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>var timerCount = 0;
var timerEl = document.querySelector("#timer");
var myResult = document.querySelector("#textResult");
var result = document.getElementById("result");
timerEl.textContent = "Time: " + timerCount;
result.style.visibility="hidden";
document.getElementById("scoreBoard").style.display="none";
document.getElementById("startQuiz").addEventListener("click", function() {
document.getElementById("startQuiz").style.display="none";
document.getElementById("sub-title").style.display="none";
document.getElementById("title").style.visibility="hidden";
document.getElementById("questionInvis").style.visibility="visible";
timerCount = 100;
timerEl.textContent = "Time: " + timerCount;
var timer = window.setInterval(function () {
timerCount--;
timerEl.textContent = "Time: " + timerCount;
if(timerCount === 0) {
clearInterval(timer);
myResult.style.visibility="visible";
myResult.textContent = "Times Up!";
result.style.visibility="visible"
setTimeout(function() {
result.style.visibility="hidden";
myResult.style.visibility="hidden";
}, 2000);
}
}, 1000);
var questions = [
{
q: "Commonly used data types DO NOT INCLUDE:",
choices: ["A. Strings", "B. Booleans", "C. Alerts", "D. Numbers"],
answer: "C"
},
{
q: "The condition in an if/else statement is encosed within ____.",
choices: ["A. Quotes", "B. Curly Brackets", "C. Parentheses", "D. Square Brackets"],
answer: "C"
},
{
q: "Array in JavaScript can be used to store ____.",
choices: ["A. Numbers and Strings", "B. Other Arrays", "C. Booleans", "D. All of the above"],
answer: "D"
},
{
q: "String values must be enclosed within ____ when being assigned to variables.",
choices: ["A. Commas", "B. Curly Brackets", "C. Quotes", "D. Parentheses"],
answer: "C"
},
{
q: "A very useful tool used during development and debugging for printing content to the debugger is: ",
choices: ["A. JavaScript", "B. Terminal/Bash", "C. For Loops", "D. Console.log"],
answer: "D"
}];
var questionsAdd = 0;
var myQuestion = document.querySelector("#question");
var optionA = document.querySelector("#answer1");
var optionB = document.querySelector("#answer2");
var optionC = document.querySelector("#answer3");
var optionD = document.querySelector("#answer4");
function questionSet() {
if (questionsAdd === questions.length || timerCount === 0) {
clearInterval(timer);
var inputForm = document.querySelector("#inputForm");
var initialText = document.querySelector("#initials");
document.getElementById("question").style.display="none";
document.getElementById("score").textContent = "Your Final Score is " + timerCount;
document.getElementById("questionInvis").style.display="none";
document.getElementById("idVisibility").style.display="block";
inputForm.addEventListener("submit", function (e) {
e.preventDefault();
var initialD = initialText.value;
document.getElementById("idVisibility").style.display="none";
document.getElementById("scoreBoard").style.display="block";
window.localStorage.setItem("timerResult", timerCount);
window.localStorage.setItem("myInitial", initialD);
});
var initialLast = window.localStorage.getItem("myInitial");
var timeResult = window.localStorage.getItem("timerResult");
console.log(initialLast);
console.log(timeResult);
if(initialLast === null) {
document.querySelector("#highScores").textContent = "Score not posted, retry quiz to see your results";
}
else {
document.querySelector("#highScores").textContent = initialLast + "-" + timeResult;
}
return;
}
myQuestion.textContent = questions[questionsAdd].q;
optionA.textContent = questions[questionsAdd].choices[0];
optionB.textContent = questions[questionsAdd].choices[1];
optionC.textContent = questions[questionsAdd].choices[2];
optionD.textContent = questions[questionsAdd].choices[3];
}
questionSet();
optionA.addEventListener("click", function () {
if (optionA.getAttribute("data-answer") === questions[questionsAdd].answer) {
questionsAdd++;
questionSet();
myResult.style.visibility="visible";
myResult.textContent = "Correct!";
result.style.visibility="visible"
setTimeout(function() {
result.style.visibility="hidden";
myResult.style.visibility="hidden";
}, 1000);
} else {
questionsAdd++;
questionSet();
timerCount -= 10;
myResult.style.visibility="visible";
myResult.textContent = "Wrong!";
result.style.visibility="visible"
setTimeout(function() {
result.style.visibility="hidden";
myResult.style.visibility="hidden";
}, 1000);
}
});
optionB.addEventListener("click", function () {
if (optionB.getAttribute("data-answer") === questions[questionsAdd].answer) {
questionsAdd++;
questionSet();
myResult.style.visibility="visible";
myResult.textContent = "Correct!";
result.style.visibility="visible"
setTimeout(function() {
result.style.visibility="hidden";
myResult.style.visibility="hidden";
}, 1000);
} else {
questionsAdd++;
questionSet();
timerCount -= 10;
myResult.style.visibility="visible";
myResult.textContent = "Wrong!";
result.style.visibility="visible"
setTimeout(function() {
result.style.visibility="hidden";
myResult.style.visibility="hidden";
}, 1000);
}
});
optionC.addEventListener("click", function () {
if (optionC.getAttribute("data-answer") === questions[questionsAdd].answer) {
questionsAdd++;
questionSet();
myResult.style.visibility="visible";
myResult.textContent = "Correct!";
result.style.visibility="visible"
setTimeout(function() {
result.style.visibility="hidden";
myResult.style.visibility="hidden";
}, 1000);
} else {
questionsAdd++;
questionSet();
timerCount -= 10;
myResult.style.visibility="visible";
myResult.textContent = "Wrong!";
result.style.visibility="visible"
setTimeout(function() {
result.style.visibility="hidden";
myResult.style.visibility="hidden";
}, 1000);
}
});
optionD.addEventListener("click", function () {
if (optionD.getAttribute("data-answer") === questions[questionsAdd].answer) {
questionsAdd++;
questionSet();
myResult.style.visibility="visible";
myResult.textContent = "Correct!";
result.style.visibility="visible"
setTimeout(function() {
result.style.visibility="hidden";
myResult.style.visibility="hidden";
}, 1000);
} else {
questionsAdd++;
questionSet();
timerCount -= 10;
myResult.style.visibility="visible";
myResult.textContent = "Wrong!";
result.style.visibility="visible"
setTimeout(function() {
result.style.visibility="hidden";
myResult.style.visibility="hidden";
}, 1000);
}
});
});<file_sep># HMW4
Code Quiz Creation with API Manipulation
## Assignment
Goal is to create a Quiz site with API Manipulation
* Must allow a start button
* When clicking starts, a timer goes on
* Must have questions including four multiple choice questions
* Getting the wrong answer will subtract time by 10 seconds
* When the user completes the quiz or when the timer runs out, the quiz is over
* The user will be able to put initial and get the scores when the quiz is over
## How it works

When you start up the website you will be greeted with the following statement in the image as well as a button to start up the quiz. The timer will be set at zero until it the
start button is clicked. If you click on "Coding Quiz" on the top left corner it will take you back to the start, this works during the quiz and after the quiz.





You will be going through 5 different questions, when you click on one of the four multiple choices only one is correct. If you get the correct answer you will immediately be taken
to the next question, notifying you that you are correct. Getting the wrong answer will do the same, except it will display wrong instead. The timer is set to 100 seconds once the
user clicks the button to start. 10 seconds will be subtracted from the timer if the user gets the question wrong.

Once the user is done with the quiz, the person will put their initials.

If it's the user's first time doing the quiz, it will not display the score and instead it will say to go back and redo it again in order to get the score from the previous quiz.
NOTE: This was made in order to compare the previous score to the current since the current has already been displayed when the user starts typing their initials.

Here is the previous score once the user does the quiz again.
| a3a3fdc823ddef5a3d15304ca388c79b9b3c9a97 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ryanstorm013/HMW4 | 721ef90dacc3fe0164340a2984af06a1f170fd98 | c17b36aeb447768c3ec0fd21621ebeb958866c30 |
refs/heads/master | <file_sep>package my_cargonaut.utility.data_classes.user;
public enum CarManufacturer {
AlfaRomeo,
AMG,
AstonMartin,
Audi,
Bentley,
Bugatti,
BMW,
Buick,
Cadillac,
Chevrolet,
Citroen,
Chrysler,
Daihatsu,
Dacia,
Dodge,
Ferrari,
Fiat,
Ford,
GeneralMotors,
GMC,
Honda,
Hummer,
Hyundai,
Infiniti,
Jaguar,
Jeep,
Kia,
Lada,
Lamborghini,
Lancia,
LandRover,
Lexus,
Lincoln,
Lotus,
Maybach,
Maserati,
Mazda,
McLaren,
MercedesBenz,
Mini,
Mitsubishi,
Nissan,
Oldsmobile,
OpelVauxhall,
Peugeot,
Plymouth,
Porsche,
Renault,
RollsRoyce,
Saab,
Seat,
Skoda,
Subaru,
Suzuki,
Tesla,
Toyota,
Volkswagen,
Volvo;
@Override
public String toString(){
return switch (this) {
case AlfaRomeo -> "Alfa-Romeo";
case AstonMartin -> "Aston-Martin";
case GeneralMotors -> "General Motors";
case LandRover -> "Land Rover";
case MercedesBenz -> "Mercedes-Benz";
case OpelVauxhall -> "Opel/Vauxhall";
case RollsRoyce -> "Rolls-Royce";
default -> super.toString();
};
}
//Found on https://stackoverflow.com/questions/7662424/how-do-i-reimplement-valueof-on-enumeration
public static CarManufacturer permissiveValueOf(String carManufacturer){
for (CarManufacturer enumValue: CarManufacturer.values()){
return switch (carManufacturer) {
case "Alfa-Romeo" -> AlfaRomeo;
case "Aston-Martin" -> AstonMartin;
case "General Motors" -> GeneralMotors;
case "Land Rover" -> LandRover;
case "Mercedes-Benz" -> MercedesBenz;
case "Opel/Vauxhall" -> OpelVauxhall;
case "Rolls-Royce" -> RollsRoyce;
default -> CarManufacturer.valueOf(carManufacturer);
};
}
return null;
}
}
<file_sep>package my_cargonaut.offer.search;
import io.javalin.http.Handler;
import my_cargonaut.login.LoginController;
import my_cargonaut.utility.FormManUtils;
import my_cargonaut.utility.data_classes.offers.Offer;
import java.text.ParseException;
import java.util.*;
public class OffersSearchController {
private static final OffersSearchService offersSearchService = OffersSearchService.getInstance();
public static Handler serveOffersSearchPage = ctx -> {
List<Offer> resultList;
Optional<Date> maybeDate1, maybeDate2;
String tmp;
OffersSearchService.OfferFilterConfigurator offerConfig = offersSearchService.getOfferFilterConfigurator();
OffersSearchPage page = new OffersSearchPage(ctx);
Map<String, String> map = FormManUtils.createQueryParamMap(ctx);
// Todo: implement filtering and saving of offers for the given query!
try{
maybeDate1 = offersSearchService.getMaybeDateFromString(map.get(page.offerSearchFormStartT));
maybeDate1.ifPresent(offerConfig::setStartDate);
maybeDate2 = offersSearchService.getMaybeDateFromString(map.get(page.offerSearchFormEndT));
maybeDate2.ifPresent(offerConfig::setEndDate);
} catch(ParseException e) {
e.printStackTrace();
}
tmp = map.get(page.offerSearchFormOrig);
if(!tmp.equals("")) {
offerConfig.setStartLocationName(tmp);
}
tmp = map.get(page.offerSearchFormDest);
if(!tmp.equals("")) {
offerConfig.setDestinationName(tmp);
}
if(map.containsKey(page.offerSearchFormCargoMaxWeight)) {
/*
Might be null if the get-request came from the landing page!
*/
if(!map.get(page.offerSearchFormCargoHeight).equals("")) {
offerConfig.setHeight(Double.parseDouble(map.get(page.offerSearchFormCargoHeight)));
}
if(!map.get(page.offerSearchFormCargoWidth).equals("")) {
offerConfig.setWidth(Double.parseDouble(map.get(page.offerSearchFormCargoWidth)));
}
if(!map.get(page.offerSearchFormCargoDepth).equals("")) {
offerConfig.setDepth(Double.parseDouble(map.get(page.offerSearchFormCargoDepth)));
}
if(!map.get(page.offerSearchFormCargoMaxWeight).equals("")) {
offerConfig.setWeight(Double.parseDouble(map.get(page.offerSearchFormCargoMaxWeight)));
}
}
resultList = offerConfig.queryOffersWithFilter();
page.markAsQueried(map, resultList);
page.render();
};
public static Handler handleOffersSearchPost = ctx -> {
// only POST-Request for now is via the Login-Form
// Todo: Watch out for further possible post requests!
OffersSearchPage page = new OffersSearchPage(ctx);
page = (OffersSearchPage)LoginController.checkLoginPost(page, ctx);
page.render();
};
}
<file_sep>package my_cargonaut.utility.data_classes;
import java.util.Objects;
public class Measurements extends Size implements java.io.Serializable {
private double weight;
public Measurements(double height, double width, double depth, double weight) {
super(height, width, depth);
this.weight = weight;
}
public double getHeight() {
return height;
}
public double getWidth() {
return width;
}
public double getDepth() {
return depth;
}
public double getWeight() { return weight; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Measurements that = (Measurements) o;
return Double.compare(that.getWeight(), getWeight()) == 0;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), getWeight());
}
}
<file_sep>/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java application project to get you started.
* For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
* User Manual available at https://docs.gradle.org/6.7.1/userguide/building_java_projects.html
*/
plugins {
// Apply the application plugin to add support for building a CLI application in Java.
id 'application'
id "org.sonarqube" version "3.1.1"
}
repositories {
// Use JCenter for resolving dependencies.
jcenter()
}
dependencies {
// Use JUnit test framework.
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.0-M1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.0-M1'
testImplementation 'org.hamcrest:hamcrest-library:2.1'
// Mockito
testImplementation 'org.mockito:mockito-core:3.7.7'
// Guava
implementation 'com.google.guava:guava:29.0-jre'
// Javalin
implementation 'io.javalin:javalin:3.12.0'
//jte
implementation 'gg.jte:jte:1.5.0'
// Java Logger
implementation 'org.slf4j:slf4j-simple:1.7.30'
// Unirest
implementation 'com.konghq:unirest-java:3.4.00'
// Selenium
implementation 'org.seleniumhq.selenium:selenium-chrome-driver:3.141.59'
//WebDriverManager
implementation 'io.github.bonigarcia:webdrivermanager:3.6.2'
}
application {
// Define the main class for the application.
mainClass = 'my_cargonaut.App'
}
task stage(dependsOn: ['build', 'clean']) {
build.mustRunAfter clean
}
task copyToLib(type: Copy) {
duplicatesStrategy = DuplicatesStrategy.INCLUDE
into "$buildDir/libs"
from(configurations.compile)
}
stage.dependsOn(copyToLib)
sonarqube {
properties {
property "sonar.projectKey", "LucasF-42_my-cargonaut-v2"
}
}
jar {
manifest {
attributes 'Main-Class': 'my_cargonaut.App'
}
archiveBaseName = 'MyCargonaut'
from {
configurations.compile.collect {it.isDirectory() ? it: zipTree(it)}
}
}
test {
useJUnitPlatform()
testLogging {
events "failed", "passed"
exceptionFormat "short"
}
}
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(15))
}
}<file_sep>package my_cargonaut.registration;
import io.javalin.http.Context;
import my_cargonaut.Page;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class RegistrationPage extends Page {
public static final String PATH = "/register";
// Registration Form
public static final String regForm = "registration";
public static final String regFormUsername = "registerName";
public static final String regFormEmail = "registerMail";
public static final String regFormPassword = "<PASSWORD>";
public static final String regFormPassword2 = "<PASSWORD>";
private boolean hasRegistrationSucceeded;
private boolean registrationAttempted;
private String registrationErrorMsg;
private String enteredUserName, enteredMail, enteredPassword, enteredPassword2;
public RegistrationPage(Context ctx) {
super(ctx);
Map<String, List<String>> params = ctx.formParamMap();
this.hideNavBarNavigation = true;
this.registrationAttempted = false;
this.hasRegistrationSucceeded = false;
}
public RegistrationPage markRegistrationFailure(Map<String, String> params, String errorMsg) {
this.registrationAttempted = true;
this.hasRegistrationSucceeded = false;
this.registrationErrorMsg = errorMsg;
addFormParamValues(params);
return this;
}
public RegistrationPage markRegistrationSuccess(Map<String, String> params) {
this.registrationAttempted = true;
this.hasRegistrationSucceeded = true;
this.registrationErrorMsg = null;
addFormParamValues(params);
return this;
}
private void addFormParamValues(Map<String, String> params) {
enteredUserName = params.get(regFormUsername);
enteredMail = params.get(regFormEmail);
enteredPassword = params.get(regFormPassword);
enteredPassword2 = params.get(regFormPassword2);
}
public boolean wasRegistrationAttempted() {
return registrationAttempted;
}
public boolean hasRegistrationSucceeded() {
return hasRegistrationSucceeded;
}
public String getEnteredUsername() { return Optional.ofNullable(enteredUserName).orElse(""); }
public String getEnteredMail() { return Optional.ofNullable(enteredMail).orElse(""); }
public String getEnteredPw() { return Optional.ofNullable(enteredPassword).orElse(""); }
public String getEnteredPw2() { return Optional.ofNullable(enteredPassword2).orElse(""); }
public String getRegistrationErrorMsg() { return Optional.ofNullable(registrationErrorMsg).orElse("Unbekannter Registrierungsfehler"); }
@Override
public String getTemplate() {
return "registration/registration.jte";
}
}
<file_sep>package my_cargonaut.utility.data_classes;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("Testing Location class")
public class LocationTest {
private final double lon = 1.0;
private final double lat = 2.0;
private final String loc = "Location";
private final String cou = "Country";
private final Location testLoc = new Location(lon, lat, loc, cou);
@Test
@DisplayName("getLongtitude() returns correct value")
public void getLongtitudeReturnsCorrectVal() {
Assertions.assertEquals(lon, testLoc.getLongtitude());
}
@Test
@DisplayName("getLatitude() returns correct value")
public void getLatitudeReturnsCorrectVal() {
Assertions.assertEquals(lat, testLoc.getLatitude());
}
@Test
@DisplayName("getLocationName() returns correct value")
public void getLocationNameReturnsCorrectVal() {
Assertions.assertEquals(loc, testLoc.getLocationName());
}
@Test
@DisplayName("getCountry() returns correct value")
public void getCountryReturnsCorrectVal() {
Assertions.assertEquals(cou, testLoc.getCountry());
}
}
<file_sep>package my_cargonaut.landing;
import io.javalin.http.Context;
import my_cargonaut.Page;
public class NotFoundPage extends Page {
private final String templateFilePath;
public NotFoundPage(Context ctx) {
super(ctx);
this.hideNavBarNavigation = true;
this.templateFilePath = "landing/notFound.jte";
}
@Override
public String getTemplate() {
return templateFilePath;
}
}
<file_sep>package my_cargonaut.utility.data_classes.offers;
import my_cargonaut.utility.FormManUtils;
import my_cargonaut.utility.data_classes.Location;
import my_cargonaut.utility.data_classes.Measurements;
import my_cargonaut.utility.data_classes.Tour;
import my_cargonaut.utility.data_classes.Vehicle;
import my_cargonaut.utility.data_classes.user.User;
import org.junit.jupiter.api.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@DisplayName("Testing OfferPool class")
public class OfferPoolTest {
private OfferPool testOfferPool;
private List<Offer> offerList;
@BeforeAll
public void fillOfferList() throws ParseException {
testOfferPool = OfferPool.getInstance();
offerList = createOfferList();
offerList.forEach(offer -> testOfferPool.addOffer(offer));
}
@Test
@DisplayName("getInstance() returns an OfferPool object")
void getInstanceReturnsOfferPool() {
Assertions.assertNotNull(OfferPool.getInstance());
}
@Test
@DisplayName("getInstance() always returns the same instance of OfferPool")
public void getInstanceReturnsSameInstance() {
OfferPool tst = OfferPool.getInstance();
Assertions.assertSame(tst, OfferPool.getInstance());
}
@Test
@DisplayName("getOfferFilter() returns a different instance each time")
public void getOfferFilterReturnsNewFilter() {
OfferPool offerPool = OfferPool.getInstance();
OfferPool.OfferFilter test = offerPool.getOfferFilter();
Assertions.assertNotSame(test, offerPool.getOfferFilter());
}
private static List<Offer> createOfferList() throws ParseException {
User u1 = new User("user1", "user1");
User u2 = new User("user2", "user2");
User u3 = new User("user3", "user3");
Location l1 = new Location(1.0, 1.0, "loc1", "country1");
Location l2 = new Location(2.0, 2.0, "loc2", "country1");
Location l3 = new Location(50.0, 51.0, "loc3", "country3");
Date d1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse("2021-3-1T12:00");
//new Date(2021, Calendar.MARCH, 1);
Date d2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse("2021-3-10T12:00");
//new Date(2021, Calendar.MARCH, 10);
Date d3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse("2021-2-10T12:00");
//new Date(2021, Calendar.FEBRUARY, 10);
Measurements m1 = new Measurements(10.0, 20.0, 30.0, 40.0);
Measurements m2 = new Measurements(100.0, 200.0, 300.0, 400.0);
Measurements m3 = new Measurements(50.0, 50.0, 50.0, 50.0);
Vehicle v1 = new Vehicle();
Vehicle v2 = new Vehicle();
Vehicle v3 = new Vehicle();
Offer o1 = new Offer(u1, new Tour(l1, l2, d1), m1, v1);
Offer o2 = new Offer(u2, new Tour(l1, l2, d1), m2, v2);
Offer o3 = new Offer(u3, new Tour(l1, l2, d3), m3, v3);
Offer o4 = new Offer(u1, new Tour(l3, l1, d2), m1, v1);
Offer o5 = new Offer(u3, new Tour(l3, l1, d3), m3, v3);
Offer o6 = new Offer(u2, new Tour(l2, l3, d3), m2, v2);
return new LinkedList<>(Arrays.asList(o1, o2, o3, o4, o5, o6));
}
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@DisplayName("Testing OfferFilter class")
public class OfferFilterTest {
Double hei = 10.0;
Double wid = 20.0;
Double dep = 30.0;
Double wei = 40.0;
OfferPool.OfferFilter testOfferFilter = testOfferPool.getOfferFilter();
Map<String, Double> nonMockitoMockMap;
Map<String, Double> mockMap = mock(Map.class);
@BeforeAll
void initMockMap() {
nonMockitoMockMap = new HashMap<>();
}
@BeforeEach
void reMockFilter() {
testOfferFilter = testOfferPool.getOfferFilter();
nonMockitoMockMap.put("height", hei);
nonMockitoMockMap.put("width", wid);
nonMockitoMockMap.put("depth", dep);
nonMockitoMockMap.put("weight", wei);
}
@Test
@DisplayName("setMeasurementsMap() sets the measurements")
void setMeasurementsMapSetsMeasurements() {
testOfferFilter.setMeasurementsMap(nonMockitoMockMap);
Assertions.assertTrue(testOfferFilter.getHeight().isPresent());
Assertions.assertEquals(hei, testOfferFilter.getHeight().get());
Assertions.assertTrue(testOfferFilter.getWidth().isPresent());
Assertions.assertEquals(wid, testOfferFilter.getWidth().get());
Assertions.assertTrue(testOfferFilter.getDepth().isPresent());
Assertions.assertEquals(dep, testOfferFilter.getDepth().get());
Assertions.assertTrue(testOfferFilter.getWeight().isPresent());
Assertions.assertEquals(wei, testOfferFilter.getWeight().get());
}
@Test
@DisplayName("getHeight() returns empty Optional if field is null")
void getHeightReturnsEmptyIfNull() {
testOfferFilter.setMeasurementsMap(mockMap);
when(mockMap.get("height")).thenReturn(null);
Assertions.assertTrue(testOfferFilter.getHeight().isEmpty());
}
@Test
@DisplayName("getHeight() returns non-empty Optional if field is null")
void getHeightReturnsValueIfNotNull() {
testOfferFilter.setMeasurementsMap(mockMap);
when(mockMap.get("height")).thenReturn(hei);
Assertions.assertFalse(testOfferFilter.getHeight().isEmpty());
}
@Test
@DisplayName("getWidth() returns empty Optional if field is null")
void getWidthReturnsEmptyIfNull() {
testOfferFilter.setMeasurementsMap(mockMap);
when(mockMap.get("width")).thenReturn(null);
Assertions.assertTrue(testOfferFilter.getWidth().isEmpty());
}
@Test
@DisplayName("getWidth() returns non-empty Optional if field is null")
void getWidthReturnsValueIfNotNull() {
testOfferFilter.setMeasurementsMap(mockMap);
when(mockMap.get("width")).thenReturn(wid);
Assertions.assertFalse(testOfferFilter.getWidth().isEmpty());
}
@Test
@DisplayName("getDepth() returns empty Optional if field is null")
void getDepthReturnsEmptyIfNull() {
testOfferFilter.setMeasurementsMap(mockMap);
when(mockMap.get("depth")).thenReturn(null);
Assertions.assertTrue(testOfferFilter.getDepth().isEmpty());
}
@Test
@DisplayName("getDepth() returns non-empty Optional if field is null")
void getDepthReturnsValueIfNotNull() {
testOfferFilter.setMeasurementsMap(mockMap);
when(mockMap.get("depth")).thenReturn(dep);
Assertions.assertFalse(testOfferFilter.getDepth().isEmpty());
}
@Test
@DisplayName("getWeight() returns empty Optional if field is null")
void getWeightReturnsEmptyIfNull() {
testOfferFilter.setMeasurementsMap(mockMap);
when(mockMap.get("weight")).thenReturn(null);
Assertions.assertTrue(testOfferFilter.getWeight().isEmpty());
}
@Test
@DisplayName("getWeight() returns non-empty Optional if field is null")
void getWeightReturnsValueIfNotNull() {
testOfferFilter.setMeasurementsMap(mockMap);
when(mockMap.get("weight")).thenReturn(wei);
Assertions.assertFalse(testOfferFilter.getWeight().isEmpty());
}
@Test
@DisplayName("filtering offers without input does return the whole list")
void applyFilterWithoutFilterArgumentsReturnsWholeList() {
List<Offer> filteredList = testOfferFilter.applyFilter();
Assertions.assertEquals(offerList, filteredList);
}
@Test
@DisplayName("filtering by a specific User only returns offers by that user")
void applyFilterWithUser() {
List<Offer> filteredList;
User u = offerList.get(0).getUser();
testOfferFilter.setUser(u);
filteredList = testOfferFilter.applyFilter();
for(Offer offer : filteredList) {
Assertions.assertEquals(u, offer.getUser());
}
}
@Test
@DisplayName("filtering by starting location does exclude offers")
void applyFilterByStartLocationExclusionTest() {
List<Offer> filteredList;
Location loc = new Location(80.0, 80.0, "notHere", "noMansLand");
testOfferFilter.setStartLoc(loc);
filteredList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, filteredList.size());
}
@Test
@DisplayName("filtering by starting location only returns offers starting from this location")
void applyFilterByStartLocationFilterTest() {
List<Offer> filteredList;
Location loc = offerList.get(0).getRoute().getStartLoc();
testOfferFilter.setStartLoc(loc);
filteredList = testOfferFilter.applyFilter();
for(Offer offer : filteredList) {
Assertions.assertEquals(loc, offer.getRoute().getStartLoc());
}
}
@Test
@DisplayName("filtering by destination does exclude offers")
void applyFilterByDestinationExclusionTest() {
List<Offer> filteredList;
Location loc = new Location(80.0, 80.0, "notHere", "noMansLand");
testOfferFilter.setDestLoc(loc);
filteredList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, filteredList.size());
}
@Test
@DisplayName("filtering by destination only returns offers starting from this location")
void applyFilterByDestinationFilterTest() {
List<Offer> filteredList;
Location loc = offerList.get(0).getRoute().getEndLoc();
testOfferFilter.setDestLoc(loc);
filteredList = testOfferFilter.applyFilter();
for(Offer offer : filteredList) {
Assertions.assertEquals(loc, offer.getRoute().getEndLoc());
}
}
@Test
@DisplayName("filtering by start date does exclude offers")
void applyFilterByStartDateExclusionTest() throws ParseException {
List<Offer> filteredList;
Date filterStartDate = FormManUtils.parseDateFromFromParam("2022-12-24T12:00");
testOfferFilter.setStartDate(filterStartDate);
filteredList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, filteredList.size());
}
@Test
@DisplayName("filtering by start date only returns offers starting afterwards")
void applyFilterByStartDateFilterTest() throws ParseException {
List<Offer> filteredList;
Date filterStartDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse("2021-02-25T12:00");
testOfferFilter.setStartDate(filterStartDate);
filteredList = testOfferFilter.applyFilter();
for(Offer offer : filteredList) {
Assertions.assertTrue(filterStartDate.before(offer.getRoute().getStartTime()));
}
}
@Test
@DisplayName("filtering by start date only returns offers starting afterwards & before its end date")
void applyFilterByStartDateFilterTestWithEndDate() throws ParseException {
List<Offer> filteredList;
Date filterStartDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse("2021-02-25T12:00");
Date filterEndDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse("2021-03-02T12:00");
testOfferFilter.setStartDate(filterStartDate);
testOfferFilter.setEndDate(filterEndDate);
filteredList = testOfferFilter.applyFilter();
for(Offer offer : filteredList) {
Assertions.assertTrue(filterStartDate.before(offer.getRoute().getStartTime()));
Assertions.assertTrue(filterEndDate.after(offer.getRoute().getStartTime()));
}
}
@Test
void applyFilterByAvailFreeSpaceHeightExclusionTest() {
List<Offer> resList;
Measurements requiredFreeSpace = new Measurements(2000.0, 0.0, 0.0, 0.0);
testOfferFilter.setFreeSpace(requiredFreeSpace);
resList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, resList.size());
}
@Test
void applyFilterByAvailFreeSpaceHeightFilterTest() {
List<Offer> resList;
double value = 80.0;
Measurements requiredFreeSpace = new Measurements(value, 0.0, 0.0, 0.0);
testOfferFilter.setFreeSpace(requiredFreeSpace);
resList = testOfferFilter.applyFilter();
for(Offer offer : resList) {
if(offer.getFreeSpace().isPresent()) {
Assertions.assertTrue(value < offer.getFreeSpace().get().getHeight());
}
}
}
@Test
void applyFilterByAvailFreeSpaceWidthExclusionTest() {
List<Offer> resList;
Measurements requiredFreeSpace = new Measurements(0.0, 2000.0, 0.0, 0.0);
testOfferFilter.setFreeSpace(requiredFreeSpace);
resList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, resList.size());
}
@Test
void applyFilterByAvailFreeSpaceWidthFilterTest() {
List<Offer> resList;
double value = 180.0;
Measurements requiredFreeSpace = new Measurements(0.0, value, 0.0, 0.0);
testOfferFilter.setFreeSpace(requiredFreeSpace);
resList = testOfferFilter.applyFilter();
for(Offer offer : resList) {
if(offer.getFreeSpace().isPresent()) {
Assertions.assertTrue(value < offer.getFreeSpace().get().getWidth());
}
}
}
@Test
void applyFilterByAvailFreeSpaceDepthExclusionTest() {
List<Offer> resList;
Measurements requiredFreeSpace = new Measurements(0.0, 0.0, 2000.0, 0.0);
testOfferFilter.setFreeSpace(requiredFreeSpace);
resList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, resList.size());
}
@Test
void applyFilterByAvailFreeSpaceDepthFilterTest() {
List<Offer> resList;
double value = 280.0;
Measurements requiredFreeSpace = new Measurements(0.0, 0.0, value, 0.0);
testOfferFilter.setFreeSpace(requiredFreeSpace);
resList = testOfferFilter.applyFilter();
for(Offer offer : resList) {
if(offer.getFreeSpace().isPresent()) {
Assertions.assertTrue(value < offer.getFreeSpace().get().getDepth());
}
}
}
@Test
void applyFilterByAvailFreeSpaceWeightExclusionTest() {
List<Offer> resList;
Measurements requiredFreeSpace = new Measurements(0.0, 0.0, 0.0, 2000.0);
testOfferFilter.setFreeSpace(requiredFreeSpace);
resList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, resList.size());
}
@Test
void applyFilterByAvailFreeSpaceWeightFilterTest() {
List<Offer> resList;
double value = 380.0;
Measurements requiredFreeSpace = new Measurements(0.0, 0.0, 0.0, value);
testOfferFilter.setFreeSpace(requiredFreeSpace);
resList = testOfferFilter.applyFilter();
for(Offer offer : resList) {
if(offer.getFreeSpace().isPresent()) {
Assertions.assertTrue(value < offer.getFreeSpace().get().getWeight());
}
}
}
@Test
@DisplayName("filter for checking whether a given cargos height fits in vehicle excludes entries")
void applyFilterWithCargoHeightExclusionTest() {
List<Offer> resList;
testOfferFilter.setMeasurementsMap(nonMockitoMockMap);
nonMockitoMockMap.replace("height", 20000.0);
resList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, resList.size());
}
@Test
@DisplayName("filter for checking whether a given cargos height fits in vehicle filters correctly")
void applyFilterWithCargoHeightTest() {
double requiredSpace = 80.0;
double freeSpace;
List<Offer> resList;
testOfferFilter.setMeasurementsMap(nonMockitoMockMap);
nonMockitoMockMap.replace("height", requiredSpace);
resList = testOfferFilter.applyFilter();
for(Offer offer : resList) {
freeSpace = offer.getFreeSpace().orElseThrow(IllegalStateException::new).getHeight();
Assertions.assertTrue(requiredSpace <= freeSpace);
}
}
@Test
@DisplayName("filter for checking whether a given cargos width fits in vehicle excludes entries")
void applyFilterWithCargoWidthExclusionTest() {
List<Offer> resList;
testOfferFilter.setMeasurementsMap(nonMockitoMockMap);
nonMockitoMockMap.replace("width", 20000.0);
resList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, resList.size());
}
@Test
@DisplayName("filter for checking whether a given cargos width fits in vehicle filters correctly")
void applyFilterWithCargoWidthTest() {
double requiredSpace = 180.0;
double freeSpace;
List<Offer> resList;
testOfferFilter.setMeasurementsMap(nonMockitoMockMap);
nonMockitoMockMap.replace("width", requiredSpace);
resList = testOfferFilter.applyFilter();
for(Offer offer : resList) {
freeSpace = offer.getFreeSpace().orElseThrow(IllegalStateException::new).getWidth();
Assertions.assertTrue(requiredSpace <= freeSpace);
}
}
@Test
@DisplayName("filter for checking whether a given cargos depth fits in vehicle excludes entries")
void applyFilterWithCargoDepthExclusionTest() {
List<Offer> resList;
testOfferFilter.setMeasurementsMap(nonMockitoMockMap);
nonMockitoMockMap.replace("depth", 20000.0);
resList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, resList.size());
}
@Test
@DisplayName("filter for checking whether a given cargos depth fits in vehicle filters correctly")
void applyFilterWithCargoDepthTest() {
double requiredSpace = 280.0;
double freeSpace;
List<Offer> resList;
testOfferFilter.setMeasurementsMap(nonMockitoMockMap);
nonMockitoMockMap.replace("depth", requiredSpace);
resList = testOfferFilter.applyFilter();
for(Offer offer : resList) {
freeSpace = offer.getFreeSpace().orElseThrow(IllegalStateException::new).getDepth();
Assertions.assertTrue(requiredSpace <= freeSpace);
}
}
@Test
@DisplayName("filter for checking whether a given cargos weight fits in vehicle excludes entries")
void applyFilterWithCargoWeightExclusionTest() {
List<Offer> resList;
testOfferFilter.setMeasurementsMap(nonMockitoMockMap);
nonMockitoMockMap.replace("weight", 20000.0);
resList = testOfferFilter.applyFilter();
Assertions.assertEquals(0, resList.size());
}
@Test
@DisplayName("filter for checking whether a given cargos weight fits in vehicle filters correctly")
void applyFilterWithCargoWeightTest() {
double requiredSpace = 280.0;
double freeSpace;
List<Offer> resList;
testOfferFilter.setMeasurementsMap(nonMockitoMockMap);
nonMockitoMockMap.replace("weight", requiredSpace);
resList = testOfferFilter.applyFilter();
for(Offer offer : resList) {
freeSpace = offer.getFreeSpace().orElseThrow(IllegalStateException::new).getWeight();
Assertions.assertTrue(requiredSpace <= freeSpace);
}
}
}
}
<file_sep>package my_cargonaut.registration;
import my_cargonaut.utility.data_classes.user.User;
import my_cargonaut.utility.data_classes.user.UserRegister;
import java.util.Optional;
// TODO: email needs to be saved for the user!
public class RegistrationService {
private static RegistrationService instance;
private final UserRegister userRegister;
private RegistrationService() {
this.userRegister = UserRegister.getInstance();
}
public boolean register(String username, String password, String email) throws IllegalArgumentException {
User user;
if(username == null || password == null) {
throw new IllegalArgumentException("Nutzername und Passwort müsssen ausgefüllt sein");
}
user = new User(username, password);
return userRegister.addNewUser(user);
}
public boolean deleteUser(String username) {
Optional<User> deletedUser = userRegister.deleteUser(username);
return deletedUser.isPresent();
}
public Optional<User> getUser(String uid) {
return userRegister.getUser(uid);
}
public static RegistrationService getInstance() {
if(RegistrationService.instance == null) {
RegistrationService.instance = new RegistrationService();
}
return RegistrationService.instance;
}
}
<file_sep>
# MyCargonaut [](https://travis-ci.com/LucasF-42/my-cargonaut-v2)
MyCargonaut is the community driven web app solution for private cargo delivering. It is a user-to-user based arangement service and works akin to an old-school black board.
In short, MyCargonaut aims to be a platform where users can offer to transport other user's cargo from point A to point B. Any monetary transactions, as well as
communication will be handled between users; MyCargonaut will not take a single cent in cuts.
MyCargonaut was created in tandem with the THM computer science lecture 'Konzepte moderner Softwareentwicklung' as the big project of the
semester 2020/2021.
## Technologies
My Cargonaut uses alot of different technologies to create a technologically interesting product.
More on that in our wiki.
One interesting fact about MyCargonaut is that we are using server sided rendering for our services by utilizing [JTE](https://github.com/casid/jte), a rather new technology.
## Prerequisites
### Host
For best results, the host machine requires a modern UNIX operating system. You will need `gradle 6.7.1` or compatible
version, as well as `openjdk15` or higher.
### Client
The client will only require a connection to the host system and any modern web browser.
## Install
MyCargonaut does not need to be installed on any client, since it's a host-rendering based web application.
We do however need to set up the host machine:
Once all prerequisites are met, you will need to build the program with `gradle`. For that, move to the `my-cargonaut`
folder via the terminal and execute the command `gradle build`.

When the project has been build, you are able to simply run MyCargonaut on your host machine via the command `gradle run`.

You can then open MyCargonaut from any client machine. On default the address for that would be `http://localhost:7777/`.
## Proof of concept
We have managed to port a version of MyCargonaut to
[Heroku](https://kms-mycargonaut.herokuapp.com/), but do the `JTE` limitations, we were forced to abandon some features,
like persistency.
The branch can be found [here](https://github.com/LucasF-42/my-cargonaut-v2/tree/herokuDeploy). This branch is only used as a proof of concept
and may not work as well as the master or development version.
## Contributing
Pull requests are welcome, but we don't plan on continuing the work on this project. The idea & icons of MyCargonaut
came from the lecturers of the THM class "Konzepte moderner Softwareentwicklung" and are not our intellectual property.
<file_sep>package my_cargonaut.offer.creation;
import io.javalin.http.Context;
import my_cargonaut.Page;
import java.util.Optional;
public class OfferCreationPage extends Page {
public static final String PATH = "/createOffer";
private final String templateFilePath;
private boolean wasOfferCreationAttempted;
private boolean hasOfferCreationSucceeded;
private String creationErrorMsg;
// Offer Creation Form
public static final String offerCForm = "offerCreate";
public static final String offerCFormStart = "offerCreateStartLoc";
public static final String offerCFormDest = "offerCreateDestinationLoc";
public static final String offerCFormStartTime = "offerCreateStartTime";
public static final String offerCFormWeight = "offerCreateWeight";
public static final String offerCFormHeight = "offerCreateHeight";
public static final String offerCFormLength = "offerCreateLength";
public static final String offerCFormDepth = "offerCreateDepth";
public static final String offerCFormDesc = "offerCreateDescription";
public OfferCreationPage(Context ctx) {
super(ctx);
pageIsNotAccessRestricted = false;
wasOfferCreationAttempted = false;
hasOfferCreationSucceeded = false;
templateFilePath = "offer/creation/createOffer.jte";
}
public OfferCreationPage markOfferCreationSuccess() {
this.wasOfferCreationAttempted = true;
this.hasOfferCreationSucceeded = true;
return this;
}
public OfferCreationPage markOfferCreationFailure(String errorMsg) {
this.wasOfferCreationAttempted = true;
this.hasOfferCreationSucceeded = false;
this.creationErrorMsg = errorMsg;
return this;
}
public boolean wasOfferCreationAttempted() {
return this.wasOfferCreationAttempted;
}
public boolean hasOfferCreationSucceeded() {
return this.wasOfferCreationAttempted && this.hasOfferCreationSucceeded;
}
public String getCreationErrorMsg() {
return Optional.ofNullable(creationErrorMsg).orElse("Unbekannter Angebotserstellungsfehler");
}
@Override
public String getTemplate() {
return templateFilePath;
}
}
<file_sep>package my_cargonaut.registration;
import io.javalin.http.Context;
import io.javalin.http.Handler;
import my_cargonaut.utility.FormManUtils;
import java.util.*;
import static my_cargonaut.utility.SessionManUtils.sessionAttributeRedirect;
import static my_cargonaut.utility.SessionManUtils.sessionAttributeRegisteredUserName;
public class RegistrationController {
private static final RegistrationService registrationService = RegistrationService.getInstance();
public static Handler handleRegistration = ctx -> {
RegistrationPage page;
Map<String, String> map = FormManUtils.createFormParamMap(ctx);
String newUsername, email, password, checkPassword;
newUsername = map.get(RegistrationPage.regFormUsername);
email = map.get(RegistrationPage.regFormEmail);
password = map.get(RegistrationPage.regFormPassword);
checkPassword = map.get(RegistrationPage.regFormPassword2);
if(!password.equals(checkPassword)) {
// Render registration page with info that passwords didn't match -> SHOULD NOT HAPPEN
page = new RegistrationPage(ctx);
page.markRegistrationFailure(map, "Die Passwoerter stimmen nicht ueberein");
page.render();
return;
}
try {
if (!registrationService.register(newUsername, password, email)) {
// Render registration page with info that username is already taken
page = new RegistrationPage(ctx);
page.markRegistrationFailure(map, "Der gewaehlte Nutzername ist bereits vergeben");
page.render();
} else {
// Render registration page with success information
page = new RegistrationPage(ctx);
page.markRegistrationSuccess(map);
page.render();
/*
ctx.sessionAttribute(sessionAttributeRegisteredUserName, newUsername);
String path = ctx.sessionAttribute(sessionAttributeRedirect);
ctx.redirect(path == null ? LandingPage.PATH : path);
*/
}
} catch(IllegalArgumentException e) {
// Render registration page with info that all fields need to be filled -> SHOULD NOT HAPPEN
page = new RegistrationPage(ctx);
page.markRegistrationFailure(map, "Bitte fuellen Sie alle Felder aus!");
page.render();
}
};
public static Handler serveRegistrationPage = ctx -> {
String path = ctx.path();
ctx.sessionAttribute(sessionAttributeRedirect, ctx.path());
RegistrationPage page = new RegistrationPage(ctx);
page.render();
};
public static void cleanSessionFromRegistrationClutter(Context ctx) {
ctx.sessionAttributeMap().remove(sessionAttributeRegisteredUserName);
ctx.sessionAttributeMap().remove(sessionAttributeRedirect);
}
}
<file_sep>package my_cargonaut.utility.data_classes;
import my_cargonaut.utility.data_classes.user.CarManufacturer;
import java.util.Objects;
public class Vehicle implements java.io.Serializable {
private CarManufacturer brand;
private String model;
private Measurements currentCargoHold;
private Measurements maxCargoHold;
public Vehicle() {
this.brand = CarManufacturer.Lancia;
this.model = "Delta HF Integrale \"Evoluzione\"";
this.currentCargoHold = new Measurements(1,1,1,1);
this.maxCargoHold = new Measurements(1,1,1,1);
}
public String getModel() {
return model;
}
public CarManufacturer getBrand() {
return brand;
}
public Measurements getCurrentCargoHold() {
return currentCargoHold;
}
public Measurements getMaxCargoHold() {
return maxCargoHold;
}
public void setCarInformation(CarManufacturer brand, String model, double curHeight, double curWidth,
double curDepth, double curWeight, double maxHeight, double maxWidth,
double maxDepth, double maxWeight){
this.brand=brand;
this.model=model;
this.currentCargoHold=new Measurements(curHeight,curWidth,curDepth,curWeight);
this.maxCargoHold=new Measurements(maxHeight,maxWidth,maxDepth,maxWeight);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vehicle vehicle = (Vehicle) o;
return getBrand() == vehicle.getBrand() && Objects.equals(getModel(), vehicle.getModel()) && Objects.equals(getCurrentCargoHold(), vehicle.getCurrentCargoHold()) && Objects.equals(getMaxCargoHold(), vehicle.getMaxCargoHold());
}
@Override
public int hashCode() {
return Objects.hash(getBrand(), getModel(), getCurrentCargoHold(), getMaxCargoHold());
}
}
<file_sep>package my_cargonaut.utility;
import io.javalin.http.Context;
import my_cargonaut.Page;
public abstract class SearchPage extends Page {
public final String offerSearchForm = "offerSearchForm";
public final String offerSearchFormOrig = "offerSearchFormOrigin";
public final String offerSearchFormDest = "offerSearchFormDestination";
public final String offerSearchFormStartT = "offerSearchFormStartTime";
public final String offerSearchFormEndT = "offerSearchFormEndTime";
public SearchPage(Context ctx) {
super(ctx);
}
}
<file_sep>package my_cargonaut;
import io.github.bonigarcia.wdm.WebDriverManager;
import io.javalin.Javalin;
import my_cargonaut.login.LoginService;
import my_cargonaut.utility.data_classes.Tour;
import my_cargonaut.utility.data_classes.offers.OfferPool;
import my_cargonaut.utility.data_classes.user.User;
import my_cargonaut.utility.data_classes.user.UserRegister;
import org.checkerframework.checker.units.qual.A;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class EndToEndTest {
static Javalin app;
static LoginService loginService;
static UserRegister trueRegister;
static OfferPool offerPool;
@AfterAll
static void exterminate(){
trueRegister.deleteUser("admin");
offerPool.purgePool("rosebuds");
app.stop();
}
@BeforeAll
static void initialize(){
trueRegister = UserRegister.getInstance();
trueRegister.addNewUser(new User("admin", "rosebuds"));
offerPool = OfferPool.getInstance();
loginService = LoginService.getInstance();
app = App.setUpCargonaut();
app.start(1234);
}
@Test
public void registerUser() throws InterruptedException {
String username = "test";
String password = "<PASSWORD>";
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.get("http://localhost:1234");
driver.findElement(By.linkText("Registrieren")).click();
Thread.sleep(500);
driver.findElement(By.id("registerName")).sendKeys("test");
assertEquals("test", driver.findElement(By.id("registerName")).getAttribute("value"));
driver.findElement(By.id("registerPw")).sendKeys("testpw");
assertEquals("testpw", driver.findElement(By.id("registerPw")).getAttribute("value"));
//driver.findElement(By.id("registerPw2")).click();
driver.findElement(By.id("registerPw2")).sendKeys("testpw");
assertEquals("testpw", driver.findElement(By.id("registerPw2")).getAttribute("value"));
Actions act = new Actions(driver);
act.moveToElement(driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div/form/div/div[4]/button"))).click().perform();
/* this can't be guaranteed to be doable for TRAVIS
hread.sleep(2000);
assertTrue(trueRegister.getUser("test").isPresent());
Thread.sleep(500);
*/
trueRegister.deleteUser("test");
driver.quit();
}
@Test
public void loginUser() throws InterruptedException{
String confirmation;
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
login(driver);
confirmation = driver.findElement(By.xpath("/html/body/div[1]/div/div/div[1]/div")).getText();
assertTrue(confirmation.contains("admin"));
driver.quit();
}
@Test
public void logoutUser() throws InterruptedException{
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
login(driver);
driver.findElement(By.xpath("/html/body/div[1]/div/div/nav/div/ul[2]/li[2]/a")).click();
assertEquals("Anmelden", driver.findElement(By.id("dropdownMenu1")).getText());
driver.quit();
}
@Test
public void profileUser() throws InterruptedException{
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
login(driver);
profile(driver);
assertEquals("Mein Profil", driver.findElement(
By.xpath("/html/body/div[1]/div/div/div/div/div/div[2]/form/div/div/h2")).getText());
driver.quit();
}
@Test
public void dealsUser() throws InterruptedException{
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
login(driver);
profile(driver);
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div/div/div[1]/div/nav/a[2]")).click();
Thread.sleep(500);
assertEquals("Meine Deals", driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div/div/div[2]/div/div/h2")).getText());
driver.quit();
}
@Test
public void carsUser() throws InterruptedException{
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
login(driver);
profile(driver);
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div/div/div[1]/div/nav/a[3]")).click();
Thread.sleep(500);
assertEquals("Mein Fahrzeug", driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div/div/div[2]/form/div/div/h2")).getText());
driver.quit();
}
//Logs in, Creates an Entry and then searches for it
@Test
public void Offer() throws InterruptedException{
Date randDate = new Date(System.currentTimeMillis());
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
WebDriver driver = new ChromeDriver(options);
Actions act = new Actions(driver);
login(driver);
driver.findElement(By.xpath("/html/body/div[1]/div/div/nav/div/ul[1]/li/a")).click();
Thread.sleep(500);
driver.findElement(By.xpath("//*[@id=\"offerCreateStartLoc\"]")).sendKeys("Test 1");
driver.findElement(By.xpath("//*[@id=\"offerCreateDestinationLoc\"]")).sendKeys("Test 2");
driver.findElement(By.xpath("//*[@id=\"offerCreateStartTime\"]")).sendKeys("02192020");
driver.findElement(By.xpath("//*[@id=\"offerCreateStartTime\"]")).sendKeys(Keys.TAB);
driver.findElement(By.xpath("//*[@id=\"offerCreateStartTime\"]")).sendKeys("1245");
driver.findElement(By.xpath("//*[@id=\"offerCreateHeight\"]")).sendKeys("15");
driver.findElement(By.xpath("//*[@id=\"offerCreateLength\"]")).sendKeys("15");
driver.findElement(By.xpath("//*[@id=\"offerCreateDepth\"]")).sendKeys("15");
driver.findElement(By.xpath("//*[@id=\"offerCreateWeight\"]")).sendKeys("45");
driver.findElement(By.xpath("//*[@id=\"offerCreateDescription\"]")).sendKeys("A description.");
act.moveToElement(driver.findElement(By.name("apply"))).click().perform();
//driver.findElement(By.name("apply")).click();
/* Can't be guaranteed to work with TRAVIS
assertEquals("Ihr Angebot wurde erstellt!",
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div[1]/div/strong")).getText());
*/
Thread.sleep(2000);
act.moveToElement( driver.findElement(By.xpath("/html/body/div[1]/div/div/nav/a"))).click().perform();
//driver.findElement(By.xpath("/html/body/div[1]/div/div/nav/a")).click();
Thread.sleep(500);
driver.findElement(By.xpath("//*[@id=\"offerSearchFormOrigin\"]")).sendKeys("Test 1");
driver.findElement(By.xpath("//*[@id=\"offerSearchFormDestination\"]")).sendKeys("Test 2");
act.moveToElement( driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div/div/div/div/nav/form/div[6]/button"))).click().perform();
//driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div/div/div/div/nav/form/div[6]/button")).click();
/* Can't be guaranteed to work with TRAVIS
assertEquals("Test 1",
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div[2]/table/tbody/tr/td[2]")).getText());
assertEquals("Test 2",
driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div[2]/table/tbody/tr/td[3]")).getText());
*/
driver.quit();
}
public void login(WebDriver driver) throws InterruptedException{
driver.get("http://localhost:1234");
driver.findElement(By.id("dropdownMenu1")).click();
Thread.sleep(100);
//driver.findElement(By.id("emailInput")).click();
driver.findElement(By.id("emailInput")).sendKeys("admin");
driver.findElement(By.id("passwordInput")).sendKeys("<PASSWORD>");
driver.findElement(By.xpath("/html/body/div[1]/div/div/nav/div/ul[2]/ul/li/ul/li/form/div[3]/button")).click();
Thread.sleep(500);
}
public void profile(WebDriver driver) throws InterruptedException{
driver.findElement(By.xpath("/html/body/div[1]/div/div/nav/div/ul[2]/li[1]/a")).click();
Thread.sleep(500);
}
}
<file_sep>package my_cargonaut.profile.deals;
import io.javalin.http.Context;
import my_cargonaut.utility.ProfileEditPage;
import my_cargonaut.utility.data_classes.offers.Offer;
import java.util.List;
import java.util.Optional;
public class DealsPage extends ProfileEditPage {
private static final String PATH_ENDING = "/deals";
public static final String PATH_STATIC = BASEPATH + PATH_ENDING;
public final String dealsPageForm = "dealsPageForm";
public final String dealsPageFormAcceptionUser = "dealsPageFormAcceptor";
public final String dealsPageFormOfferID = "dealsPageFormOfferID";
private final String templateFilePath;
private List<Offer> offerList;
public DealsPage(Context ctx){
super(ctx);
templateFilePath="profile/deals/dealsProfile.jte";
}
public static String getDynamicPath(String username) {
return Optional.ofNullable(username).map(name -> PATH_STATIC.replace(":username", name)).orElse("404error");
}
public List<Offer> getOfferList() {
return this.offerList;
}
public DealsPage addOffersList(List<Offer> list) {
this.offerList = list;
return this;
}
@Override
public String getTemplate(){
return templateFilePath;
}
}
<file_sep>package my_cargonaut;
import io.javalin.Javalin;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import my_cargonaut.registration.RegistrationPage;
import my_cargonaut.utility.FormManUtils;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.logging.Handler;
import static org.junit.jupiter.api.Assertions.assertEquals;
// See https://javalin.io/tutorials/testing
public class FunctionalTest {
@Test
public void GET_to_reach_landing_ok(){
Javalin app = App.setUpCargonaut();
app.start(1111);
HttpResponse<String> response = Unirest.get("http://localhost:1111").asString();
assertEquals(response.getStatus(),200);
app.stop();
}
@Test
public void GET_to_reach_register_ok(){
Javalin app = App.setUpCargonaut();
app.start(1112);
HttpResponse<String> response = Unirest.get("http://localhost:1112/register").asString();
assertEquals(response.getStatus(),200);
app.stop();
}
@Test
public void GET_to_reach_create_offer_ok(){
Javalin app = App.setUpCargonaut();
app.start(1113);
HttpResponse<String> response = Unirest.get("http://localhost:1113/createOffer").asString();
assertEquals(response.getStatus(),200);
app.stop();
}
@Test
public void GET_to_reach_profile_ok(){
Javalin app = App.setUpCargonaut();
app.start(1114);
HttpResponse<String> response = Unirest.get("http://localhost:1114/user/t/editProfile/profile").asString();
assertEquals(response.getStatus(),200);
app.stop();
}
@Test
public void GET_to_reach_profile_cars_ok(){
Javalin app = App.setUpCargonaut();
app.start(1115);
HttpResponse<String> response = Unirest.get("http://localhost:1115/user/t/editProfile/cars").asString();
assertEquals(response.getStatus(),200);
app.stop();
}
@Test
public void GET_to_reach_profile_deals_ok(){
Javalin app = App.setUpCargonaut();
app.start(1116);
HttpResponse<String> response = Unirest.get("http://localhost:1116/user/t/editProfile/deals").asString();
assertEquals(response.getStatus(),200);
app.stop();
}
@Test
public void GET_log_out_ok(){
Javalin app = App.setUpCargonaut();
app.start(1117);
HttpResponse<String> response = Unirest.get("http://localhost:1117/logout").asString();
assertEquals(response.getStatus(),200);
app.stop();
}
@Test
public void POST_to_get_landing_page_ok(){
Javalin app = App.setUpCargonaut();
app.start(1118);
HttpResponse<String> response = Unirest.post("http://localhost:1118").asString();
assertEquals(response.getStatus(),200);
app.stop();
}
/* Not really possible due to us relying on UI/HTML stuff we can't really access.
@Test
public void POST_register_ok(){
Javalin app = App.setUpCargonaut();
app.start(1119);
HttpResponse<String> response = Unirest.post("http://localhost:1119/register").asString();
assertEquals(response.getStatus(),200);
app.stop();
}
*/
@Test
public void POST_register_no_password(){
Javalin app = App.setUpCargonaut();
app.start(1119);
HttpResponse<String> response = Unirest.post("http://localhost:1119/register").asString();
assertEquals(response.getStatus(),500); //TODO this should actually be a 4xx status, not 5xx
app.stop();
}
}
<file_sep>package my_cargonaut.utility.data_classes.user;
public enum Pronoun {
Herr,
Frau,
Divers
}
<file_sep>package my_cargonaut.utility;
import my_cargonaut.utility.data_classes.offers.OfferPool;
import my_cargonaut.utility.data_classes.user.UserRegister;
import java.io.*;
public class Storage {
public static final String userRegisterLoc = "data/userRegister.ser";
public static final String offerPoolLoc = "data/offerPool.ser";
public static void saveData() throws IOException {
try {
UserRegister userRegister = UserRegister.getInstance();
OfferPool offerPool = OfferPool.getInstance();
writeFile(userRegisterLoc, userRegister);
writeFile(offerPoolLoc, offerPool);
} catch ( FileNotFoundException i) {
i.printStackTrace();
}
}
public static void initializeData() throws IOException, ClassNotFoundException {
UserRegister userRegister = UserRegister.getInstance();
OfferPool offerPool = OfferPool.getInstance();
UserRegister tmpUserRegister = (UserRegister) readFile(userRegisterLoc);
OfferPool tmpOfferPool = (OfferPool) readFile(offerPoolLoc);
tmpOfferPool.getOfferFilter().applyFilter().forEach(offer -> {
userRegister.addNewUser(offer.getUser());
offerPool.addOffer(offer);
});
tmpUserRegister.getUsers().forEach(userRegister::addNewUser);
}
private static void writeFile(String filename, Object obj) throws IOException {
try(FileOutputStream fileOut = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(fileOut)
) {
out.writeObject(obj);
}
}
private static Object readFile(String filename) throws IOException, ClassNotFoundException {
Object o;
try(FileInputStream fileIn = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fileIn)
) {
o = in.readObject();
return o;
}
}
}
<file_sep>package my_cargonaut.offer.search;
import my_cargonaut.utility.FormManUtils;
import my_cargonaut.utility.data_classes.Measurements;
import my_cargonaut.utility.data_classes.Vehicle;
import my_cargonaut.utility.data_classes.offers.Offer;
import my_cargonaut.utility.data_classes.offers.OfferPool;
import my_cargonaut.utility.data_classes.user.User;
import my_cargonaut.utility.data_classes.user.UserRegister;
import java.text.ParseException;
import java.util.*;
public class OffersSearchService {
private static OffersSearchService instance;
private final OfferPool offerPool;
private final UserRegister userRegister;
private OffersSearchService() {
this.offerPool = OfferPool.getInstance();
this.userRegister = UserRegister.getInstance();
}
public static OffersSearchService getInstance() {
if(OffersSearchService.instance == null) {
OffersSearchService.instance = new OffersSearchService();
}
return OffersSearchService.instance;
}
public OfferFilterConfigurator getOfferFilterConfigurator() {
return new OfferFilterConfigurator(offerPool.getOfferFilter());
}
private List<Offer> queryOffers(OfferPool.OfferFilter filter) {
return filter.applyFilter();
}
public Optional<Date> getMaybeDateFromString(String dateString) throws ParseException {
if(dateString.equals("")) return Optional.empty();
return Optional.ofNullable(FormManUtils.parseDateFromFromParam(dateString));
}
/*
provides a Builder object to map the query params to an Object
*/
public class OfferFilterConfigurator {
private final OfferPool.OfferFilter offerFilter;
/*private User user;
//private Location startLoc, destination;
private String startLocName, destinationName;
private Date startDate, endDate;
private Vehicle vehicle;*/
private final Map<String, Double> cargoMeasurements;
private OfferFilterConfigurator(OfferPool.OfferFilter offerFilter) {
this.offerFilter = offerFilter;
this.cargoMeasurements = new HashMap<>();
offerFilter.setMeasurementsMap(cargoMeasurements);
}
public List<Offer> queryOffersWithFilter() {
if(this.cargoMeasurements.size() == 4) {
this.offerFilter.setFreeSpace(new Measurements(cargoMeasurements.get("height"),
cargoMeasurements.get("width"), cargoMeasurements.get("depth"),
cargoMeasurements.get("weight")));
}
return queryOffers(this.offerFilter);
}
public OfferFilterConfigurator setStartLocationName(String startLocName) {
this.offerFilter.setStartLocName(startLocName);
return this;
}
public OfferFilterConfigurator setDestinationName(String destName) {
// If we were to use an Geocoding-API: Build a location-object from this String!
this.offerFilter.setDestLocName(destName);
return this;
}
public OfferFilterConfigurator setStartDate(Date startDate) {
this.offerFilter.setStartDate(startDate);
return this;
}
public OfferFilterConfigurator setEndDate(Date endDate) {
this.offerFilter.setEndDate(endDate);
return this;
}
public OfferFilterConfigurator setHeight(double d) {
this.cargoMeasurements.put("height", d);
return this;
}
public OfferFilterConfigurator setWidth(double d) {
this.cargoMeasurements.put("width", d);
return this;
}
public OfferFilterConfigurator setDepth(double d) {
this.cargoMeasurements.put("depth", d);
return this;
}
public OfferFilterConfigurator setWeight(double d) {
this.cargoMeasurements.put("weight", d);
return this;
}
public OfferFilterConfigurator setUser(String username) throws IllegalStateException {
this.offerFilter.setUser(userRegister.getUser(username).orElseThrow(IllegalAccessError::new));
return this;
}
public OfferFilterConfigurator setUser(User user){
this.offerFilter.setUser(user);
return this;
}
public OfferFilterConfigurator setVehicle(Vehicle vic) {
this.offerFilter.setVehicle(vic);
return this;
}
public OfferFilterConfigurator setOfferId(long id) {
this.offerFilter.setOfferID(id);
return this;
}
}
}
| bd119ab9cd606c4c5505bcf96516b9382c716a99 | [
"Markdown",
"Java",
"Gradle"
] | 20 | Java | LucasF-42/my-cargonaut-v2 | 163caae51ca88b633e33d848405fcf5b21bc9a26 | e896a427d252d6334d781c635d208773883d0670 |
refs/heads/master | <file_sep>const tag = require('./xml_generator');
const preamble = '<?xml version="1.0" encoding="UTF-8"?>';
class RSSFeed {
constructor(options) {
this.items = [];
this.options = {
title: 'default title',
link: 'https://defaulturl.com',
ttl: 60,
description: 'default description',
...options
};
}
addItem(item) {
this.items.push(item);
}
getXML() {
return preamble + tag('rss', {
version: '2.0',
children: tag('channel', {
children: [
tag('title', { children: this.options.title }),
tag('link', { children: this.options.link }),
tag('ttl', { children: this.options.ttl }),
tag('description', { children: this.options.description }),
...this.items.map(item => tag('item', {
children: [
tag('title', { children: item.title }),
tag('pubDate', { children: item.pubDate }),
tag('guid', { children: item.hash }),
tag('description', { children: item.description }),
tag('enclosure', {
url: item.torrentFileUrl,
length: item.torrentFileLength,
type: 'application/x-bittorrent'
}),
tag('link', { children: item.torrentFileUrl }),
]
}))
]
})
});
}
}
module.exports = RSSFeed;
<file_sep># bittorrent-rss-feed
Generates RSS feeds for BitTorrent files to automate downloads. This module tries to be as lightweight and quick as possible, which is why there are zero dependencies. It also tries to follow [BEP 36](http://www.bittorrent.org/beps/bep_0036.html) as close as possible.
## Usage
```
npm install bittorrent-rss-feed
```
```javascript
const RSSFeed = require('bittorrent-rss-feed');
const rssFeed = new RSSFeed({
title: 'Test Feed',
link: 'https://testlink.com',
ttl: 60,
description: 'Description of the RSS feed'
});
rssFeed.addItem({
title: 'Ubuntu Server 18.04',
pubDate: new Date(),
hash: '1da8f70c0a0503e61c3bd7b6e923783a',
description: 'New download: Ubuntu Server 18.04',
torrentFileUrl: 'https://testlink.com/ubuntu.torrent',
torrentFileLength: 342521,
});
const xml = rssFeed.getXML();
```
<file_sep>/**
* XML Generator
*
* This function generates an XML tag string. It is meant to be nested within
* eachother and tries to resemble the React JSX API. Examples:
*
* tag('item', {
* test: '123',
* children: tag('title', { children: 'Hello' })
* });
*
* <item test="123"><title>Hello</title></item>
*/
module.exports = (tag, props) => {
let propList = [];
for (let prop in props) {
if (props.hasOwnProperty(prop) && prop !== 'children') {
propList.push(`${prop}="${props[prop]}"`);
}
}
if (Array.isArray(props.children)) {
props.children = props.children.join('');
}
return `<${tag}${propList.length > 0 ? ' ' : ''}${propList.join(' ')}>${props.children || ''}</${tag}>`;
};
| 06fdd6b6b9dd0546343b2050e176c6863b3e164d | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | dislick/bittorrent-rss-feed | 5a5f0ff0cbacc39849c55ee8c01fc0c20bb85486 | 046222f97299e6382f656ccd5eac53a12e3ec6bd |
refs/heads/master | <file_sep>// m_move.c -- monster movement
#include "g_local.h"
#define STEPSIZE 18
/*
=============
M_CheckBottom
Returns false if any part of the bottom of the entity is off an edge that
is not a staircase.
=============
*/
int c_yes, c_no;
qboolean M_CheckBottom (edict_t *ent)
{
vec3_t mins, maxs, start, stop;
trace_t trace;
int x, y;
float mid, bottom;
VectorAdd (ent->s.origin, ent->mins, mins);
VectorAdd (ent->s.origin, ent->maxs, maxs);
// if all of the points under the corners are solid world, don't bother
// with the tougher checks
// the corners must be within 16 of the midpoint
start[2] = mins[2] - 1;
for (x=0 ; x<=1 ; x++)
for (y=0 ; y<=1 ; y++)
{
start[0] = x ? maxs[0] : mins[0];
start[1] = y ? maxs[1] : mins[1];
if (gi.pointcontents (start) != CONTENTS_SOLID)
goto realcheck;
}
c_yes++;
return true; // we got out easy
realcheck:
c_no++;
//
// check it for real...
//
start[2] = mins[2];
// the midpoint must be within 16 of the bottom
start[0] = stop[0] = (mins[0] + maxs[0])*0.5;
start[1] = stop[1] = (mins[1] + maxs[1])*0.5;
stop[2] = start[2] - 2*STEPSIZE;
trace = gi.trace (start, vec3_origin, vec3_origin, stop, ent,MASK_PLAYERSOLID /*MASK_MONSTERSOLID*/);
if (trace.fraction == 1.0)
return false;
mid = bottom = trace.endpos[2];
// the corners must be within 16 of the midpoint
for (x=0 ; x<=1 ; x++)
for (y=0 ; y<=1 ; y++)
{
start[0] = stop[0] = x ? maxs[0] : mins[0];
start[1] = stop[1] = y ? maxs[1] : mins[1];
trace = gi.trace (start, vec3_origin, vec3_origin, stop, ent, MASK_PLAYERSOLID /*MASK_MONSTERSOLID*/);
if (trace.fraction != 1.0 && trace.endpos[2] > bottom)
bottom = trace.endpos[2];
if (trace.fraction == 1.0 || mid - trace.endpos[2] > STEPSIZE)
return false;
}
c_yes++;
return true;
}
float distance (vec3_t p1, vec3_t p2);
qboolean CanJumpDown (edict_t *self, vec3_t neworg)
{
float dist_jump, dist_current;
vec3_t start;
trace_t tr;
edict_t *goal;
if (self->monsterinfo.jumpdn < 1)
return false; // we can't jump down!
if (self->movetarget && self->movetarget->inuse)
goal = self->movetarget;
else if (self->enemy && self->enemy->inuse)
goal = self->enemy;
else if (self->goalentity && self->goalentity->inuse)
goal = self->goalentity;
else
return false;
VectorCopy(neworg, start);
start[2] -= 8192;
tr = gi.trace(neworg, NULL, NULL, start, self, MASK_MONSTERSOLID);
// don't jump in water if we aren't already in it
if (!self->waterlevel)
{
//gi.dprintf("searching for hazards...\n");
VectorCopy(tr.endpos, start);
start[2] = tr.endpos[2] + self->mins[2] + 1;
if (gi.pointcontents(start) & (CONTENTS_LAVA|CONTENTS_SLIME))//MASK_WATER)
{
//gi.dprintf("hazard detected! jumpdown aborted.\n");
return false;
}
}
// don't jump farther than we're supposed to
if (distance(neworg, tr.endpos) > self->monsterinfo.jumpdn)
return false;
// allow monster to jump if we've been stuck for awhile
if (self->monsterinfo.stuck_frames > 50)
{
//gi.dprintf("monster got stuck and was allowed to fall\n");
self->monsterinfo.stuck_frames = 0;
return true;
}
// don't jump if the trace ends at our feet
// FIXME: check in all directions since we don't always
// walk directly off the edge
if (tr.endpos[2] == self->absmin[2])
return false;
// don't jump unless it places us closer to our goal
dist_jump = distance(tr.endpos, goal->s.origin);
dist_current = distance(self->s.origin, goal->s.origin);
if (dist_jump+STEPSIZE > dist_current)
{
/*
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_BFG_LASER);
gi.WritePosition (neworg);
gi.WritePosition (tr.endpos);
gi.multicast (self->s.origin, MULTICAST_PHS);
*/
// we'll let this go if our goal is below us
// if ((dist_jump+16 > dist_current) && (goal->absmin[2] < self->absmin[2]))
// return true;
// gi.dprintf("*** FAILED *** dist jump %d dist current %d\n", (int)dist_jump, (int)dist_current);
return false;
}
//gi.dprintf("dist jump %d dist current %d\n", (int)dist_jump, (int)dist_current);
/*
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_DEBUGTRAIL);
gi.WritePosition (neworg);
gi.WritePosition (tr.endpos);
gi.multicast (neworg, MULTICAST_ALL);
gi.dprintf("allowed monster to jump down\n");
*/
return true;
}
qboolean CanJumpUp (edict_t *self, vec3_t neworg, vec3_t end)
{
int jumpdist;
vec3_t angles, start;
trace_t tr;
if (self->monsterinfo.jumpup < 1)
return false; // we can't jump up!
VectorCopy(neworg, start);
jumpdist = STEPSIZE;
do
{
// add an additional step above the obstacle
neworg[2] = start[2]+jumpdist;
tr = gi.trace(neworg, self->mins, self->maxs, end, self, MASK_MONSTERSOLID);
// we've hit a ceiling, so we can't go any higher
if (tr.startsolid)
return false;
// try to jump a little higher
jumpdist += STEPSIZE;
// we've reached our limit
if (jumpdist > self->monsterinfo.jumpup)
return false;
}
// keep trying until we clear the obstacle OR we can't jump any higher
while (tr.allsolid);
// make sure we land on a flat plane
vectoangles(tr.plane.normal, angles);
if (angles[PITCH] > 360)
angles[PITCH] -= 360;
else if (angles[PITCH] < 0)
angles[PITCH] += 360;
if (angles[PITCH] != 270)
return false;
/*
gi.dprintf("checking for hazards...\n");
// calculate position one step beyond this obstacle
VectorAdd(self->s.origin, move, pos1);
VectorAdd(pos1, move, pos1);
// find out what's below this position
VectorCopy(pos1, pos2);
pos2[2] -= 8192;
tr = gi.trace(pos1, NULL, NULL, pos2, self, MASK_MONSTERSOLID);
// don't allow monster to jump into lava or slime!
if (self->waterlevel == 0)
{
//gi.dprintf("hazard detected!\n");
pos2[0] = tr.endpos[0];
pos2[1] = tr.endpos[1];
pos2[2] = tr.endpos[2] + self->mins[2] + 1;
if (gi.pointcontents(end) & (CONTENTS_LAVA|CONTENTS_SLIME))
return false;
}
//if (distance(tr.endpos, goal->s.origin)+16 > distance(self->s.origin, goal->s.origin))
// return false;
*/
VectorCopy(tr.endpos, self->s.origin);
//gi.dprintf("allowed monster to jump up\n");
return true;
}
// modified SV_movestep for use with player-controlled monsters
qboolean M_Move (edict_t *ent, vec3_t move, qboolean relink)
{
vec3_t oldorg, neworg, end;
trace_t trace;//, tr;
float stepsize=STEPSIZE;
// try the move
VectorCopy (ent->s.origin, oldorg);
VectorAdd (ent->s.origin, move, neworg);
neworg[2] += stepsize;
VectorCopy (neworg, end);
end[2] -= stepsize*2;
trace = gi.trace (neworg, ent->mins, ent->maxs, end, ent, MASK_MONSTERSOLID);
if (trace.allsolid)
{
// if we would have collided with a live entity, call its touch function
// this prevents player-monsters from being invulnerable to obstacles
if (G_EntIsAlive(trace.ent) && trace.ent->touch)
trace.ent->touch(trace.ent, ent, &trace.plane, trace.surface);
return false;
}
if (trace.startsolid)
{
neworg[2] -= stepsize;
trace = gi.trace (neworg, ent->mins, ent->maxs, end, ent, MASK_MONSTERSOLID);
if (trace.allsolid || trace.startsolid)
return false;
}
if (trace.fraction == 1)
{
// gi.dprintf("going to fall\n");
// if monster had the ground pulled out, go ahead and fall
// VectorSubtract(trace.endpos, oldorg, forward);
// VectorMA(oldorg, 64, forward, end);
if ( ent->flags & FL_PARTIALGROUND )
{
VectorAdd (ent->s.origin, move, ent->s.origin);
if (relink)
{
gi.linkentity (ent);
G_TouchTriggers (ent);
}
ent->groundentity = NULL;
return true;
}
}
// check point traces down for dangling corners
VectorCopy (trace.endpos, ent->s.origin);
if (!M_CheckBottom (ent))
{
if (ent->flags & FL_PARTIALGROUND)
{ // entity had floor mostly pulled out from underneath it
// and is trying to correct
if (relink)
{
gi.linkentity (ent);
G_TouchTriggers (ent);
}
return true;
}
}
if (ent->flags & FL_PARTIALGROUND)
ent->flags &= ~FL_PARTIALGROUND;
ent->groundentity = trace.ent;
if (trace.ent)
ent->groundentity_linkcount = trace.ent->linkcount;
// the move is ok
if (relink)
{
gi.linkentity (ent);
G_TouchTriggers (ent);
}
return true;
}
/*
=============
SV_movestep
Called by monster program code.
The move will be adjusted for slopes and stairs, but if the move isn't
possible, no move is done, false is returned, and
pr_global_struct->trace_normal is set to the normal of the blocking wall
=============
*/
//FIXME since we need to test end position contents here, can we avoid doing
//it again later in catagorize position?
qboolean SV_movestep (edict_t *ent, vec3_t move, qboolean relink)
{
float dz;
vec3_t oldorg, neworg, end;
trace_t trace;//, tr;
int i;
float stepsize;
vec3_t test;
int contents;
int jump=0;
// try the move
VectorCopy (ent->s.origin, oldorg);
VectorAdd (ent->s.origin, move, neworg);
// flying monsters don't step up
if ((ent->flags & (FL_SWIM|FL_FLY)) || (ent->waterlevel > 1))
{
// gi.dprintf("trying to swim\n");
// try one move with vertical motion, then one without
for (i=0 ; i<2 ; i++)
{
VectorAdd (ent->s.origin, move, neworg);
if (i == 0 && ent->enemy)
{
if (!ent->goalentity)
ent->goalentity = ent->enemy;
dz = ent->s.origin[2] - ent->goalentity->s.origin[2];
if (ent->goalentity->client)
{
if (dz > 40)
neworg[2] -= 8;
if (!((ent->flags & FL_SWIM) && (ent->waterlevel < 2)))
if (dz < 30)
neworg[2] += 8;
}
else
{
if (dz > 8)
neworg[2] -= 8;
else if (dz > 0)
neworg[2] -= dz;
else if (dz < -8)
neworg[2] += 8;
else
neworg[2] += dz;
}
}
trace = gi.trace (ent->s.origin, ent->mins, ent->maxs, neworg, ent, MASK_MONSTERSOLID);
// fly monsters don't enter water voluntarily
if (ent->flags & FL_FLY)
{
if (!ent->waterlevel)
{
test[0] = trace.endpos[0];
test[1] = trace.endpos[1];
test[2] = trace.endpos[2] + ent->mins[2] + 1;
contents = gi.pointcontents(test);
if (contents & MASK_WATER)
return false;
}
}
// swim monsters don't exit water voluntarily
if (ent->flags & FL_SWIM)
{
if (ent->waterlevel < 2)
{
test[0] = trace.endpos[0];
test[1] = trace.endpos[1];
test[2] = trace.endpos[2] + ent->mins[2] + 1;
contents = gi.pointcontents(test);
if (!(contents & MASK_WATER))
return false;
}
}
if (trace.fraction == 1)
{
VectorCopy (trace.endpos, ent->s.origin);
if (relink)
{
gi.linkentity (ent);
G_TouchTriggers (ent);
}
return true;
}
//gi.dprintf("swim move failed\n");
if (!ent->enemy)
break;
}
return false;
}
// push down from a step height above the wished position
if (!(ent->monsterinfo.aiflags & AI_NOSTEP))
stepsize = STEPSIZE;
else
stepsize = 1;
neworg[2] += stepsize;
VectorCopy (neworg, end);
end[2] -= stepsize*2;
// this trace checks from a position one step above the entity (at top of bbox)
// to one step below the entity (bottom of bbox)
trace = gi.trace (neworg, ent->mins, ent->maxs, end, ent, MASK_MONSTERSOLID);
// there is an obstruction bigger than a step
if (trace.allsolid)
//GHz START
{
// try to jump over it
if (!CanJumpUp(ent, neworg, end))
return false;
else
jump = 1;
}
//GHz END
// not enough room at this height--head of bbox intersects something solid
// so push down and just try to walk forward at floor height
else if (trace.startsolid)
{
neworg[2] -= stepsize;
trace = gi.trace (neworg, ent->mins, ent->maxs, end, ent, MASK_MONSTERSOLID);
if (trace.allsolid || trace.startsolid)
return false;
}
// don't go in to water
if (ent->waterlevel == 0)
{
test[0] = trace.endpos[0];
test[1] = trace.endpos[1];
test[2] = trace.endpos[2] + ent->mins[2] + 1;
contents = gi.pointcontents(test);
if (contents & (CONTENTS_LAVA|CONTENTS_SLIME))
return false;
}
//GHz START
// if (CanJumpDown(ent, trace.endpos))
// jump = -1;
//GHz END
// VectorSubtract(trace.endpos, oldorg, forward);
// VectorNormalize(forward);
// VectorMA(oldorg, 32, forward, end);
// VectorAdd(trace.endpos, move, end);
// VectorAdd(end, move, end);
if ((trace.fraction == 1) && (jump != 1))
{
// gi.dprintf("going to fall\n");
// if monster had the ground pulled out, go ahead and fall
// VectorSubtract(trace.endpos, oldorg, forward);
// VectorMA(oldorg, 64, forward, end);
if (!CanJumpDown(ent, trace.endpos))
{
if ( ent->flags & FL_PARTIALGROUND )
{
VectorAdd (ent->s.origin, move, ent->s.origin);
if (relink)
{
gi.linkentity (ent);
G_TouchTriggers (ent);
}
ent->groundentity = NULL;
return true;
}
return false; // walked off an edge
}
else
jump = -1;
}
// check point traces down for dangling corners
//GHz START
/*
// fix for monsters walking thru walls
tr = gi.trace(trace.endpos, ent->mins, ent->maxs, trace.endpos, ent, MASK_SOLID);
if (tr.contents & MASK_SOLID)
return false;
*/
//GHz END
if (jump != 1)
VectorCopy (trace.endpos, ent->s.origin);
if (!M_CheckBottom (ent))
{
if (ent->flags & FL_PARTIALGROUND)
{ // entity had floor mostly pulled out from underneath it
// and is trying to correct
if (relink)
{
gi.linkentity (ent);
G_TouchTriggers (ent);
}
return true;
}
if (CanJumpDown(ent, trace.endpos))
jump = -1;
if (!jump)
{
VectorCopy (oldorg, ent->s.origin);
return false;
}
}
else if (jump == -1)
jump = 0;
/*
if (jump)
{
VectorCopy(oldorg, ent->s.origin);
CanJumpDown(ent, trace.endpos, true);
VectorCopy(trace.endpos, ent->s.origin);
}
*/
if ( ent->flags & FL_PARTIALGROUND )
{
ent->flags &= ~FL_PARTIALGROUND;
}
ent->groundentity = trace.ent;
if (trace.ent)
ent->groundentity_linkcount = trace.ent->linkcount;
if (jump == -1)
{
/*
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_DEBUGTRAIL);
gi.WritePosition (oldorg);
gi.WritePosition (end);
gi.multicast (end, MULTICAST_ALL);
*/
//VectorScale(move, 10, ent->velocity);
//ent->velocity[2] = 200;
}
else if (jump == 1)
{
ent->velocity[2] = 200;
//gi.dprintf("jumped at %d\n",level.framenum);
}
// the move is ok
if (relink)
{
gi.linkentity (ent);
G_TouchTriggers (ent);
}
return true;
}
/*
======================
SV_StepDirection
Turns to the movement direction, and walks the current distance if
facing it.
======================
*/
qboolean SV_StepDirection (edict_t *ent, float yaw, float dist, qboolean try_smallstep)
{
vec3_t move, oldorigin;
//float delta;
float old_dist;
//gi.dprintf("SV_StepDirection\n");
old_dist = dist;
ent->ideal_yaw = yaw;
M_ChangeYaw (ent);
yaw = yaw*M_PI*2 / 360;
VectorCopy (ent->s.origin, oldorigin);
// loop until we can move successfully
while (dist > 0)
{
move[0] = cos(yaw)*dist;
move[1] = sin(yaw)*dist;
move[2] = 0;
if (SV_movestep (ent, move, false))
{
/*
delta = ent->s.angles[YAW] - ent->ideal_yaw;
if (delta > 45 && delta < 315)
{ // not turned far enough, so don't take the step
VectorCopy (oldorigin, ent->s.origin);
gi.dprintf("not turned far enough!\n");
}
*/
gi.linkentity (ent);
G_TouchTriggers (ent);
/*
if (old_dist != dist)
gi.dprintf("took a smaller step of %d instead of %d\n", (int)dist, (int)old_dist);
else
gi.dprintf("moved full distance\n");
*/
return true;
}
if (!try_smallstep)
break;
dist -= 5;
}
gi.linkentity (ent);
G_TouchTriggers (ent);
// gi.dprintf("Can't walk forward!\n");
return false;
}
/*
======================
SV_FixCheckBottom
======================
*/
void SV_FixCheckBottom (edict_t *ent)
{
ent->flags |= FL_PARTIALGROUND;
}
/*
================
SV_NewChaseDir
================
*/
#define DI_NODIR -1
void SV_NewChaseDir (edict_t *actor, edict_t *enemy, float dist)
{
float deltax,deltay;
float d[3];
float tdir, olddir, turnaround;
//FIXME: how did we get here with no enemy
if (!enemy)
return;
olddir = anglemod( (int)(actor->ideal_yaw/45)*45 );
turnaround = anglemod(olddir - 180);
deltax = enemy->s.origin[0] - actor->s.origin[0];
deltay = enemy->s.origin[1] - actor->s.origin[1];
if (deltax>10)
d[1]= 0;
else if (deltax<-10)
d[1]= 180;
else
d[1]= DI_NODIR;
if (deltay<-10)
d[2]= 270;
else if (deltay>10)
d[2]= 90;
else
d[2]= DI_NODIR;
// try direct route
if (d[1] != DI_NODIR && d[2] != DI_NODIR)
{
if (d[1] == 0)
tdir = d[2] == 90 ? 45 : 315;
else
tdir = d[2] == 90 ? 135 : 215;
if (tdir != turnaround && SV_StepDirection(actor, tdir, dist, true))
return;
}
// try other directions
if ( ((randomMT()&3) & 1) || abs(deltay)>abs(deltax))
{
tdir=d[1];
d[1]=d[2];
d[2]=tdir;
}
if (d[1]!=DI_NODIR && d[1]!=turnaround
&& SV_StepDirection(actor, d[1], dist, true))
return;
if (d[2]!=DI_NODIR && d[2]!=turnaround
&& SV_StepDirection(actor, d[2], dist, true))
return;
/* there is no direct path to the player, so pick another direction */
if (olddir!=DI_NODIR && SV_StepDirection(actor, olddir, dist, true))
return;
if (randomMT()&1) /*randomly determine direction of search*/
{
for (tdir=0 ; tdir<=315 ; tdir += 45)
if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist, true) )
return;
}
else
{
for (tdir=315 ; tdir >=0 ; tdir -= 45)
if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist, true) )
return;
}
if (turnaround != DI_NODIR && SV_StepDirection(actor, turnaround, dist, true) )
return;
actor->ideal_yaw = olddir; // can't move
// if a bridge was pulled out from underneath a monster, it may not have
// a valid standing position at all
if (!M_CheckBottom (actor))
SV_FixCheckBottom (actor);
}
void SV_NewChaseDir1 (edict_t *self, edict_t *goal, float dist)
{
int i, bestyaw, minyaw, maxyaw;
vec3_t v;
if (!goal)
return;
VectorSubtract(goal->s.origin, self->s.origin, v);
bestyaw = vectoyaw(v);
minyaw = bestyaw - 90;
maxyaw = bestyaw + 90;
if (minyaw < 0)
minyaw += 360;
if (maxyaw > 360)
maxyaw -= 360;
for (i=minyaw; i<maxyaw; i+=30) {
if (SV_StepDirection(self, i, dist, false))
return;
}
//gi.dprintf("couldnt find a better direction!\n");
SV_NewChaseDir(self, goal, dist);
}
/*
===============
M_ChangeYaw
===============
*/
void M_ChangeYaw (edict_t *ent)
{
float ideal;
float current;
float move;
float speed;
current = anglemod(ent->s.angles[YAW]);
ideal = ent->ideal_yaw;
if (current == ideal)
return;
move = ideal - current;
speed = ent->yaw_speed;
if (ideal > current)
{
if (move >= 180)
move = move - 360;
}
else
{
if (move <= -180)
move = move + 360;
}
if (move > 0)
{
if (move > speed)
move = speed;
}
else
{
if (move < -speed)
move = -speed;
}
ent->s.angles[YAW] = anglemod (current + move);
}
/*
======================
SV_CloseEnough
======================
*/
qboolean SV_CloseEnough (edict_t *ent, edict_t *goal, float dist)
{
int i;
for (i=0 ; i<3 ; i++)
{
if (goal->absmin[i] > ent->absmax[i] + dist)
return false;
if (goal->absmax[i] < ent->absmin[i] - dist)
return false;
}
return true;
}
/*
======================
M_MoveToGoal
======================
*/
void M_MoveToGoal (edict_t *ent, float dist)
{
edict_t *goal;
goal = ent->goalentity;
if (ent->holdtime > level.time) // stay in-place for medic healing
return;
if (!ent->groundentity && !(ent->flags & (FL_FLY|FL_SWIM)) && !ent->waterlevel)
{
//gi.dprintf("not touching ground\n");
return;
}
// if the next step hits the enemy, return immediately
if (ent->enemy && (ent->enemy->solid == SOLID_BBOX)
&& SV_CloseEnough (ent, ent->enemy, dist) )
//GHz START
{
vec3_t v;
// we need to keep turning to avoid getting stuck doing nothing
if (ent->goalentity && ent->goalentity->inuse) // 3.89 make sure the monster still has a goal!
{
VectorSubtract(ent->goalentity->s.origin, ent->s.origin, v);
VectorNormalize(v);
ent->ideal_yaw = vectoyaw(v);
M_ChangeYaw(ent);
}
return;
}
//GHz END
// dont move so fast in the water
if (!(ent->flags & (FL_FLY|FL_SWIM)) && (ent->waterlevel > 1))
dist *= 0.5;
// bump around...
// if we can't take a step, try moving in another direction
if (!SV_StepDirection (ent, ent->ideal_yaw, dist, true))
{
// if the monster hasn't moved much, then increment
// the number of frames it has been stuck
if (distance(ent->s.origin, ent->monsterinfo.stuck_org) < 64)
ent->monsterinfo.stuck_frames++;
else
ent->monsterinfo.stuck_frames = 0;
// record current position for comparison
VectorCopy(ent->s.origin, ent->monsterinfo.stuck_org);
// attempt a course-correction
if (ent->inuse && (level.time > ent->monsterinfo.bump_delay))
{
//gi.dprintf("monster stuck, attempting course-correction\n");
SV_NewChaseDir (ent, goal, dist);
ent->monsterinfo.bump_delay = level.time + FRAMETIME*GetRandom(2, 5);
return;
}
}
}
/*
===============
M_walkmove
===============
*/
qboolean M_walkmove (edict_t *ent, float yaw, float dist)
{
float original_yaw=yaw;//GHz
vec3_t move;
if (!ent->groundentity && !(ent->flags & (FL_FLY|FL_SWIM)))
return false;
yaw = yaw*M_PI*2 / 360;
move[0] = cos(yaw)*dist;
move[1] = sin(yaw)*dist;
move[2] = 0;
if (IsABoss(ent) || ent->mtype == P_TANK)
{
//return M_Move(ent, move, true);
if (!M_Move(ent, move, true))
{
float angle1, angle2, delta1, delta2, cl_yaw, ideal_yaw, mult;
vec3_t start, end, angles, right;
trace_t tr;
// get monster angles
AngleVectors(ent->s.angles, NULL, right, NULL);
//vectoangles(forward, forward);
vectoangles(right, right);
// get client yaw (FIXME: use mons yaw instead?)
cl_yaw = ent->s.angles[YAW];
AngleCheck(&cl_yaw);
// trace from monster to wall
VectorCopy(ent->s.origin, start);
VectorMA(start, 64, move, end);
tr = gi.trace(start, ent->mins, ent->maxs, end, ent, MASK_SHOT);
// get monster angles in relation to wall
VectorCopy(tr.plane.normal, angles);
vectoangles(angles, angles);
// monster is moving sideways, so use sideways vector instead
if ((int)original_yaw==(int)right[YAW])
{
cl_yaw = right[YAW];
AngleCheck(&cl_yaw);
}
// delta between monster yaw and wall yaw should be no more than 90 degrees
// else, turn wall angles around 180 degrees
if (fabs(cl_yaw-angles[YAW]) > 90)
angles[YAW]+=180;
ValidateAngles(angles);
// possible escape angle 1
angle1 = angles[YAW]+90;
AngleCheck(&angle1);
delta1 = fabs(angle1-cl_yaw);
// possible escape angle 2
angle2 = angles[YAW]-90;
AngleCheck(&angle2);
delta2 = fabs(angle2-cl_yaw);
// take the shorter route
if (delta1 > delta2)
{
ideal_yaw = angle2;
mult = 1.0-delta2/90.0;
}
else
{
ideal_yaw = angle1;
mult = 1.0-delta1/90.0;
}
// go full speed if we are turned at least half way towards ideal yaw
if (mult >= 0.5)
mult = 1.0;
// modify speed
dist*=mult;
// recalculate with new heading
yaw = ideal_yaw*M_PI*2 / 360;
move[0] = cos(yaw)*dist;
move[1] = sin(yaw)*dist;
move[2] = 0;
//gi.dprintf("can't walk wall@%.1f you@%.1f ideal@%.1f\n", angles[YAW], cl_yaw, ideal_yaw);
return M_Move(ent, move, true);
}
return true;
}
else if (level.time > ent->holdtime) // stay in-place for medic healing
return SV_movestep(ent, move, true);
else
return false;
}
<file_sep>#define MAX_LINES 21
#define LINE_SPACING 8
#define MENU_DELAY_TIME 0.2 // 3.65 delay time when cycling thru menu (in seconds)
#define MENU_WHITE_CENTERED 20001
#define MENU_GREEN_CENTERED 20002
#define MENU_GREEN_RIGHT 20003
#define MENU_GREEN_LEFT 20004
// 3.45 menu indexes, used to tell which menu we're on
// note that this isn't necessary unless there are 2 menus
// that are exactly the same (because the compiler treats
// them as the same function)
#define MENU_MASTER_PASSWORD 1
#define MENU_SPECIAL_UPGRADES 2
#define MENU_MULTI_UPGRADE 3
void addlinetomenu (edict_t *ent,char *line,int option);
void clearmenu (edict_t *ent);
void setmenuhandler (edict_t *ent,void (*optionselected)(edict_t *ent,int option));
void clearallmenus (void);
void menuup (edict_t *ent);
void menudown (edict_t *ent);
void menuselect (edict_t *ent);
void initmenu (edict_t *ent);
void showmenu (edict_t *ent);
void closemenu (edict_t *ent);
qboolean ShowMenu (edict_t *ent);
qboolean InMenu (edict_t *ent,int index, void (*optionselected)(edict_t *ent,int option));
typedef struct menumsg_s
{
char *msg;
int option;
} menumsg_t;
typedef struct menusystem_s
{
void (*optionselected)(edict_t *ent,int option);
void (*oldmenuhandler)(edict_t *ent,int option);
qboolean menu_active;
qboolean displaymsg;
int oldline;
menumsg_t messages[MAX_LINES];
int currentline;
int num_of_lines;
int menu_index;
} menusystem_t;
<file_sep>#include "g_local.h"
//Function Prototypes required for this .c file:
void PlayerBossPoints (edict_t *attacker, edict_t *target);
int mypower(int x, int y)
{
if (y > 0)
{
y--;
return (x * mypower(x,y) );
}
return (1);
}
char *LoPrint(char *text)
{
int i;
if (!text)
return NULL;
for (i=0; i<strlen(text) ; i++)
if ((byte)text[i] > 127)
text[i]=(byte)text[i]-128;
return text;
}
char *HiPrint(char *text)
{
int i;
// A copy of the string is created, static strings may only be read in linux
if (!text)
return NULL;
else {
char *s = strdup((char *)text);
for (i=0; i<strlen(text) ; i++)
if ((byte)text[i] <= 127)
s[i]=(byte)text[i]+128;
return s;
}
}
// this needs to match UpdateFreeAbilities() in v_utils.c
void NewLevel_Addons(edict_t *ent)
{
int playerLevel = ent->myskills.level;
if ((playerLevel % 5) == 0)
{
if (ent->myskills.abilities[MAX_AMMO].level < ent->myskills.abilities[MAX_AMMO].max_level)
{
ent->myskills.abilities[MAX_AMMO].level++;
ent->myskills.abilities[MAX_AMMO].current_level++;
}
else ent->myskills.speciality_points++;
if (ent->myskills.abilities[VITALITY].level < ent->myskills.abilities[VITALITY].max_level)
{
ent->myskills.abilities[VITALITY].level++;
ent->myskills.abilities[VITALITY].current_level++;
}
else ent->myskills.speciality_points++;
}
// free ID at level 0
if (playerLevel == 0)
{
if (!ent->myskills.abilities[ID].level)
{
ent->myskills.abilities[ID].level++;
ent->myskills.abilities[ID].current_level++;
}
else
ent->myskills.speciality_points += 2;
}
// free scanner at level 10
if (playerLevel == 10)
{
if (!ent->myskills.abilities[SCANNER].level)
{
ent->myskills.abilities[SCANNER].level++;
ent->myskills.abilities[SCANNER].current_level++;
}
else
ent->myskills.speciality_points += 2;
}
// Give the player talents if they are eligible.
// if(ent->myskills.level >= TALENT_MIN_LEVEL && ent->myskills.level <= TALENT_MAX_LEVEL)
// ent->myskills.talents.talentPoints++;
/**
* apple: give talent points every two levels, starting from the minimum level and stopping at max level
* note the use of the % operator, it tells you whether a number is divisible by x or not, in this case 2.
* The operator returns the residue of the division operation.
*/
if ((playerLevel >= TALENT_MIN_LEVEL) && (playerLevel <= TALENT_MAX_LEVEL) && (playerLevel%2 == 0)) {
ent->myskills.talents.talentPoints++;
}
}
void Add_credits(edict_t *ent, int targ_level)
{
int level_diff = 0;
int credit_points = 0;
float temp = 0.0;
if (!ent->client)
return;
if (targ_level > ent->myskills.level)
{
level_diff = targ_level - ent->myskills.level;
credit_points = GetRandom(CREDIT_HIGH, CREDIT_HIGH*2) + CREDIT_HIGH*level_diff;
}
else if (targ_level < ent->myskills.level)
{
level_diff = ent->myskills.level - targ_level;
credit_points = (GetRandom(CREDIT_LOW, CREDIT_LOW*2) + CREDIT_LOW)/level_diff;
}
else credit_points = GetRandom(CREDIT_SAME, CREDIT_SAME*5); //3.0 changed from: credit_points = CREDIT_SAME
if (credit_points < 0)
credit_points = 1;
if (ent->myskills.streak >= SPREE_START)//GHz
{
temp = (ent->myskills.streak + 1 - SPREE_START) * SPREE_BONUS;
if (temp > 4) temp = 4;
if (ent->myskills.streak >= SPREE_WARS_START && SPREE_WARS > 0)
temp *= SPREE_WARS_BONUS;
credit_points *= 1 + temp;
}
if (credit_points > 100)
credit_points = 100;
credit_points *= vrx_creditmult->value;
if (ent->myskills.credits+credit_points > MAX_CREDITS)
{
gi.cprintf(ent, PRINT_HIGH, "Maximum credits reached!\n");
ent->myskills.credits = MAX_CREDITS;
}
else
ent->myskills.credits += credit_points;
// gi.dprintf("%s was awarded with %d credits\n", ent->client->pers.netname, credit_points);
}
gitem_t *GetWeaponForNumber(int i)
{
switch (i)
{
case 2 :
return Fdi_SHOTGUN;
case 3 :
return Fdi_SUPERSHOTGUN;
case 4 :
return Fdi_MACHINEGUN;
case 5 :
return Fdi_CHAINGUN;
case 6 :
return Fdi_GRENADES;
case 7 :
return Fdi_GRENADELAUNCHER;
case 8 :
return Fdi_ROCKETLAUNCHER;
case 9 :
return Fdi_HYPERBLASTER;
case 10 :
return Fdi_RAILGUN;
case 11 :
return Fdi_BFG;
}
return Fdi_ROCKETLAUNCHER;
}
void check_for_levelup (edict_t *ent)
{
double points_needed;
int plateau_points = 50000;
qboolean levelup = false;
char *message;
while (ent->myskills.experience >= ent->myskills.next_level)
{
levelup = true;
// maximum level cap
if (!ent->myskills.administrator && ent->myskills.level >= 30) //decino: changed to 30 (from 25)
{
ent->myskills.next_level = ent->myskills.experience;
return;
}
//Need between 80 to 120% more points for the next level.
ent->myskills.level++;
points_needed = start_nextlevel->value * pow(nextlevel_mult->value, ent->myskills.level);
// the experience required to reach next level reaches a plateau
if (points_needed > plateau_points)
{
// determine level where plateau_points is reached
int plateau_level = (int)ceil(log(plateau_points / start_nextlevel->value) / log(nextlevel_mult->value));
// calculate next level points based
points_needed = plateau_points + 5000*(ent->myskills.level-plateau_level);
}
ent->myskills.next_level += points_needed;
ent->myskills.speciality_points += 2;
ent->myskills.weapon_points += 4;
NewLevel_Addons(ent);//Add any special addons that should be there!
modify_max(ent);
if (!ent->ai.is_bot){
message = HiPrint(va("*****%s gained a level*****", ent->client->pers.netname));
gi.bprintf(PRINT_HIGH, "%s\n", message);
message = LoPrint(message);
WriteToLogfile(ent, va("Player reached level %d\n", ent->myskills.level));}
// maximum level cap
if (!ent->myskills.administrator && ent->myskills.level >= 30)
{
ent->myskills.next_level = ent->myskills.experience;
break;
}
}
if (levelup)
{
if (!ent->ai.is_bot){
gi.centerprintf(ent, "Welcome to level %d!\n You need %d experience \nto get to the next level.\n",
ent->myskills.level, ent->myskills.next_level-ent->myskills.experience);
gi.sound(ent, CHAN_ITEM, gi.soundindex("misc/pc_up.wav"), 1, ATTN_STATIC, 0);}
}
}
int VortexAddCredits(edict_t *ent, float level_diff, int bonus, qboolean client)
{
int add_credits = 0;
int streak;
streak = ent->myskills.streak;
if (client)
add_credits = level_diff * (vrx_creditmult->value * (CREDITS_PLAYER_BASE + streak));
else
add_credits = level_diff * (vrx_creditmult->value * (CREDITS_OTHER_BASE));
if (add_credits > 500)
add_credits = 500;
add_credits += bonus;
//FIXME: remove this after allocating more space
if (ent->myskills.credits+add_credits > MAX_CREDITS)
ent->myskills.credits = MAX_CREDITS;
else
ent->myskills.credits += add_credits;
return add_credits;
}
void VortexSpreeAbilities (edict_t *attacker)
{
// NOTE: Spree MUST be incremented before calling this function
// otherwise the player will keep getting 10 seconds of quad/invuln
//New quad/invin duration variables
int base_duration = 50; //5 seconds
int kill_duration = 5; //0.5 seconds per kill
if (!attacker->client)
return;
if (attacker->myskills.streak < 6)
return;
if (HasFlag(attacker))
return;
/*
//Talent: Longer Powerups
if(getTalentSlot(attacker, TALENT_LONG_POWERUPS) != -1)
{
int level = getTalentLevel(attacker, TALENT_LONG_POWERUPS);
int baseBonus, killBonus;
switch(level)
{
case 1: baseBonus = 0; killBonus = 10; break;
case 2: baseBonus = 0; killBonus = 15; break;
case 3: baseBonus = 0; killBonus = 20; break;
default: baseBonus = 0; killBonus = 0; break;
}
base_duration += baseBonus;
kill_duration += killBonus;
}
*/
// special circumstances if they have both create quad and create invin
if ((attacker->myskills.abilities[CREATE_QUAD].current_level > 0)
&& (attacker->myskills.abilities[CREATE_INVIN].current_level > 0))
{
// if they already have it, give them another second
if (attacker->client->quad_framenum > level.framenum)
attacker->client->quad_framenum += kill_duration;
else if (attacker->client->invincible_framenum > level.framenum)
attacker->client->invincible_framenum += kill_duration;
else if (!(attacker->myskills.streak % 10))
{
// give them quad OR invin, not both!
if (random() > 0.5)
attacker->client->quad_framenum = level.framenum + base_duration;
else
// (apple)
// invincible_framenum would add up level.framenum + base_duration
attacker->client->invincible_framenum = level.framenum + base_duration;
}
}
// does the attacker have create quad?
else if (attacker->myskills.abilities[CREATE_QUAD].current_level > 0)
{
if(!attacker->myskills.abilities[CREATE_QUAD].disable)
{
// every 10 frags, give them 5 seconds of quad
if (!(attacker->myskills.streak % 10))
attacker->client->quad_framenum = level.framenum + base_duration;
// if they already have quad, give them another second
else if (attacker->client->quad_framenum > level.framenum)
attacker->client->quad_framenum += kill_duration;
}
}
// does the attacker have create invin?
else if (attacker->myskills.abilities[CREATE_INVIN].current_level > 0)
{
if(!attacker->myskills.abilities[CREATE_INVIN].disable)
{
// every 10 frags, give them 5 seconds of invin
if (!(attacker->myskills.streak % 10))
attacker->client->invincible_framenum = level.framenum + base_duration;
// if they already have invin, give them another second
else if (attacker->client->invincible_framenum > level.framenum)
attacker->client->invincible_framenum += kill_duration;
}
}
}
#define PLAYTIME_MIN_MINUTES 999.0 // minutes played before penalty begins
#define PLAYTIME_MAX_MINUTES 999.0 // minutes played before max penalty is reached
#define PLAYTIME_MAX_PENALTY 2.0 // reduce experience in half
int V_AddFinalExp (edict_t *player, int exp)
{
float mod, playtime_minutes;
// reduce experience as play time increases
playtime_minutes = player->myskills.playingtime/60.0;
if (playtime_minutes > PLAYTIME_MIN_MINUTES)
{
mod = 1.0 + playtime_minutes/PLAYTIME_MAX_MINUTES;
if (mod >= PLAYTIME_MAX_PENALTY)
mod = PLAYTIME_MAX_PENALTY;
exp /= mod;
}
// player must pay back "hole" experience first
if (player->myskills.nerfme > 0)
{
if (player->myskills.nerfme > exp)
{
player->myskills.nerfme -= exp;
return 0;
}
exp -= player->myskills.nerfme;
}
player->myskills.experience += exp;
player->client->resp.score += exp;
check_for_levelup(player);
return exp;
}
#define EXP_SHARED_FACTOR 0.5
#define PLAYER_MONSTER_MIN_PLAYERS 4
void AddMonsterExp (edict_t *player, edict_t *monster)
{
int base_exp, exp_points, max_exp, control_cost;
float level_diff, bonus;
edict_t *e;
if (!player->client)
return;
// don't award points to spectators
if (G_IsSpectator(player))
return;
// don't award points to dead players
if (player->health < 1)
return;
// don't award points to players in chat-protect mode
if (player->flags & FL_CHATPROTECT)
return;
// don't award points for monster that was just resurrected
if (monster->monsterinfo.resurrected_time > level.time)
return;
// don't award exp for player-monsters
if (PM_MonsterHasPilot(monster))
return;
// is this a world-spawned monster or a player-spawned monster?
e = G_GetClient(monster);
if (e)
{
if (total_players() < PLAYER_MONSTER_MIN_PLAYERS)
return; // don't award player-spawned monster exp if there are too few players
base_exp = EXP_PLAYER_MONSTER;
}
else
base_exp = EXP_WORLD_MONSTER;
// reduce experience for invasion mode because of secondary objective
if (INVASION_OTHERSPAWNS_REMOVED)
base_exp *= 0.5;
// increase experience for monsters in FFA since it is harder to stay alive
// if (ffa->value)
// base_exp *= 1.5;
level_diff = (float) monster->monsterinfo.level / (player->myskills.level+1);
control_cost = monster->monsterinfo.control_cost;
if (control_cost < 1)
control_cost = 1;
// calculate spree bonus
bonus = 1 + 0.04*player->myskills.streak;
if (bonus > 2)
bonus = 2;
// calculate ally bonus
if (allies->value && !numAllies(player))
{
if (e)
bonus += 0.5*(float)numAllies(e);
}
exp_points = control_cost * (level_diff*base_exp);
exp_points *= bonus;
// cap max experience at 300% normal
max_exp = 3*base_exp*control_cost;
if (exp_points > max_exp)
exp_points = max_exp;
// give your team some experience
if (/*pvm->value ||*/ ((int)(dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS)))
Add_ctfteam_exp(player, (int)(EXP_SHARED_FACTOR*exp_points));
// give your allies some experience
if (allies->value)
AddAllyExp(player, exp_points);
// add experience
/*
player->client->resp.score += exp_points;
player->myskills.experience += exp_points;
check_for_levelup(player);
*/
V_AddFinalExp(player, exp_points);
// add credits
VortexAddCredits(player, level_diff, 0, false);
//player->lastkill = level.time + 1.0;
player->client->idle_frames = 0;
// increment spree
if (pvm->value)
{
player->myskills.streak++;
VortexSpreeAbilities(player);
}
//gi.dprintf("AddMonsterExp(), %d exp, %d control_cost %d level\n", exp_points, control_cost, monster->monsterinfo.level);
}
int PVM_TotalMonsters (edict_t *monster_owner);
void VortexAddMonsterExp(edict_t *attacker, edict_t *monster)
{
int exp_points = 0;
int monsters = 0;
float level_diff = 0;
//char *message;
//int i;
//edict_t *player;
if (IsABoss(monster))
{
PlayerBossPoints(attacker, monster);
return;
}
if (IsABoss(attacker))
return; // boss-player does not get awarded points!
attacker = G_GetClient(attacker);
//GHz: Abort if we have invalid data
if (attacker == NULL || !monster->inuse /*|| !monster->activator || monster->activator->client*/)
return;
if (attacker->flags & FL_CHATPROTECT)
return;
//VortexSpreeAbilities(attacker);
//GHz: Only award experience to one person if monster is not a boss
if (monster->monsterinfo.control_cost <= 3)
{
if (INVASION_OTHERSPAWNS_REMOVED)
INV_AwardMonsterKill(attacker, monster);
else
AddMonsterExp(attacker, monster);
/*
//3.0 (If pvm was cleared of monsters, give everyone a small bonus)
// search for other drones
if(pvm->value)
{
edict_t *e = NULL;
//find the monster spawn ent
while((e = G_Find(e, FOFS(classname), "MonsterSpawn")) != NULL)
{
if (e && e->inuse)
break;
}
// get actual total world monsters
if (e && e->inuse)
monsters = PVM_TotalMonsters(e);
//If the map is clear of monsters
if ((e != NULL) && !monsters)
{
exp_points = GetRandom(25, 50);
gi.dprintf("Giving players a PvM bonus (%d) killing all monsters.\n", exp_points, e->num_monsters);
for_each_player(player, i)
{
if (player->solid == SOLID_NOT)
continue;
if (player->health < 0)
continue;
if (player->flags & FL_CHATPROTECT)
continue;
if (player->client->idle_frames > 100) //10 seconds of idling
continue;
player->client->resp.score += exp_points;
player->myskills.experience += exp_points;
check_for_levelup(player);
}
}
}
*/
}
else
{
if (monster->mtype == M_JORG)//GHz: Award exp on Makron kill instead
return;
G_PrintGreenText(va("%s puts the smackdown on a world-spawned boss!", attacker->client->pers.netname));
AwardBossKill(monster);
/*
SPREE_WAR = false;
SPREE_DUDE = NULL;
message = HiPrint(va("%s puts the smackdown on a world-spawned boss!", attacker->client->pers.netname));
gi.bprintf(PRINT_HIGH, "%s\n", message);
message = LoPrint(message);
for_each_player(player, i)
{
if (player->solid == SOLID_NOT)
continue;
//GHz: Calculate level difference modifier
level_diff = (float) (0.5*monster->monsterinfo.level) / (player->myskills.level + 1);
exp_points = GetRandom(250, 500) * level_diff;
if (exp_points > 1000)
exp_points = 1000;
V_AddFinalExp(player, exp_points);
VortexAddCredits(player, level_diff, 0, false);
}
*/
}
}
int PVP_AwardKill (edict_t *attacker, edict_t *targ, edict_t *target)
{
int max_points, clevel;
int credits = 0;
int exp_points = 0;
int break_points = 0;
float level_diff = 0;
float bonus = 1;
float dmgmod = 1;
float damage;
char *message, *name;
int minimum_points = 0;
qboolean is_mini=false;
if (IsNewbieBasher(target))
{
is_mini = true;
minimum_points = 75;
}
// calculate damage modifier
damage = GetPlayerBossDamage(attacker, target);
if (damage < 1)
return 0;
dmgmod = damage / GetTotalBossDamage(target);
// calculate level difference modifier
level_diff = (float) (target->myskills.level + 1) / (attacker->myskills.level + 1);
// calculate spree bonuses
if (attacker->myskills.streak >= SPREE_START && !SPREE_WAR)
bonus += 0.5;
else if (attacker->myskills.streak >= SPREE_WARS_START && SPREE_WARS)
bonus += 3.0;
// calculate spree-break bonuses
if (target->myskills.streak >= SPREE_START)
break_points = 100;
// you get the same bonus for killing a newbie basher as you would breaking a spree war
else if (is_mini || (target->myskills.streak >= SPREE_WARS_START && SPREE_WARS))
break_points = 200;
// players get extra points for killing an allied teammate
// if they are not allied with anyone themselves
if (allies->value && !numAllies(attacker))
bonus += (float) numAllies(target);
// award 2fer bonus
//decino: added 2fers, 3fers, 4fers, etc
//if (attacker->lastkill >= level.time)
//{
// message = HiPrint(va("%s got a 2fer.", attacker->client->pers.netname));
// gi.bprintf(PRINT_HIGH, "%s\n", message);
// message = LoPrint(message);
// bonus += 1 - ((attacker->lastkill - level.time) + 0.1);
// attacker->myskills.num_2fers++;
//}
if (attacker->nfer > 1)
{
bonus += 1 + 0.25*attacker->nfer;
}
// we killed another player
if (targ->client)
{
exp_points = dmgmod * (level_diff * (vrx_pointmult->value * (EXP_PLAYER_BASE * bonus)) + break_points);
// give extra points for FFA mode, since it is harder to spree/stay alive!
//if (ffa->value)
// exp_points *= 1.5;
// award credits for kill
if (targ->ai.is_bot)
credits *= 0.5;
credits = VortexAddCredits(attacker, level_diff, 0, true);
name = target->client->pers.netname;
clevel = target->myskills.level;
}
// we killed something else that they own
else
{
exp_points = dmgmod * (level_diff * (vrx_pointmult->value * (EXP_OTHER_BASE * bonus)));
name = V_GetMonsterName(targ->mtype);
clevel = targ->monsterinfo.level;
}
// min/max points awarded for a kill
max_points = 10 * EXP_PLAYER_BASE;
if (exp_points > max_points)
exp_points = max_points;
if (exp_points < 10)
exp_points = 10;
if (exp_points < minimum_points)
exp_points = minimum_points;
// award experience to allied players
max_points = exp_points;
if (targ->ai.is_bot)
max_points *= 0.5;
if (!allies->value || ((exp_points = AddAllyExp(attacker, max_points)) < 1))
// award experience to non-allied players
exp_points = V_AddFinalExp(attacker, max_points);
if (!attacker->ai.is_bot)
gi.cprintf(attacker, PRINT_HIGH, "You dealt %.0f damage (%.0f%c) to %s (level %d), gaining %d experience and %d credits.\n",
damage, (dmgmod * 100), '%', name, clevel, exp_points, credits);
return exp_points;
}
void VortexAddExp(edict_t *attacker, edict_t *targ)
{
int i, exp_points;
edict_t *target, *player = NULL;
// gi.dprintf("VortexAddExp()\n");
if (IsABoss(attacker))
{
AddBossExp(attacker, targ);
return;
}
if (ptr->value)
return;
if (pvm->value)
return;
if (domination->value)
{
dom_fragaward(attacker, targ);
return;
}
if (ctf->value)
{
CTF_AwardFrag(attacker, targ);
return;
}
attacker = G_GetClient(attacker);
target = G_GetClient(targ);
// sanity check
//if (attacker == target || attacker == NULL || target == NULL || !attacker->inuse || !target->inuse)
// return;
// make sure target is valid
if (!target || !target->inuse)
return;
// award experience and credits to anyone that has hurt the target
for (i=0; i<game.maxclients; i++)
{
player = g_edicts+1+i;
// award experience and credits to non-spectator clients
if (!player->inuse || G_IsSpectator(player) || player == target || player->flags & FL_CHATPROTECT)
continue;
PVP_AwardKill(player, targ, target);
}
// give your team some experience
if ((int)(dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))
{
exp_points = PVP_AwardKill(attacker, targ, target);
Add_ctfteam_exp(attacker, (int)(0.5*exp_points));
return;
}
}
void VortexDeathCleanup(edict_t *attacker, edict_t *targ)
{
int lose_points=0;
float level_diff;
char *message;
int minlevel;
//decino: dying to monsters with an owner affects your fragged stats, world spawned monsters and bosses shouldn't
if ((attacker->mtype) && (G_GetClient(attacker) != NULL) && (!IsABoss(attacker))){
// gi.dprintf("You were killed by a monster with an owner.\n");
targ->myskills.fragged++;}
//decino: make sure an enemy client killed you and not your alter ego (suicide)
if (attacker->client && (targ->client != attacker->client)){
// gi.dprintf("You were killed by a client.\n");
targ->myskills.fragged++;}
if (IsABoss(attacker))
{
targ->myskills.streak = 0;
return; // bosses don't get frags
}
attacker = G_GetClient(attacker);
targ = G_GetClient(targ);
//GHz: Ignore invalid data
if (attacker == NULL || targ == NULL)
{
if (targ)
targ->myskills.streak = 0;
return;
}
//GHz: Handle suicides
if (targ == attacker)
{
targ->myskills.streak = 0;
targ->myskills.suicides++;
// players don't lose points in PvM mode since it is easy to kill yourself
if (!pvm->value)
{
lose_points = EXP_LOSE_SUICIDE * targ->myskills.level;
// cap max exp lost at 50 points
if (lose_points > 50)
lose_points = 50;
if (targ->client->resp.score - lose_points > 0)
{
targ->client->resp.score -= lose_points;
targ->myskills.experience -= lose_points;
}
else
{
targ->myskills.experience -= targ->client->resp.score;
targ->client->resp.score = 0;
}
}
return;
}
attacker->myskills.frags++;
attacker->client->resp.frags++;
//attacker->lastkill = level.time + 1;
if (!ptr->value && !domination->value && !pvm->value && !ctf->value
&& (targ->myskills.streak >= SPREE_START))
{
//GHz: Reset spree properties for target and credit the attacker
if (SPREE_WAR == true && targ == SPREE_DUDE)
{
SPREE_WAR = false;
SPREE_DUDE = NULL;
attacker->myskills.break_spree_wars++;
}
attacker->myskills.break_sprees++;
gi.bprintf(PRINT_HIGH, "%s broke %s's %d frag killing spree!\n", attacker->client->pers.netname, targ->client->pers.netname, targ->myskills.streak);
}
targ->myskills.streak = 0;
if (IsNewbieBasher(targ))
gi.bprintf(PRINT_HIGH, "%s wasted a mini-boss!\n", attacker->client->pers.netname);
// level_diff = (float) (targ->myskills.level + 1) / (attacker->myskills.level + 1);
// don't let 'em spree off players that offer no challenge!
/* if (!(IsNewbieBasher(attacker) && (level_diff <= 0.5)))
{
attacker->myskills.streak++;
VortexSpreeAbilities(attacker);
}
else
return;*/
//determine the minimum level of the target to count towards your spree
minlevel = attacker->myskills.level / 4;
//anyone level 10 or lower can kill anyone and it counts toward sprees
if (attacker->myskills.level <= 10)
minlevel = 0;
//between 11 and 13 subtracting 10 levels is lower than dividing by 4 so do that
else if (attacker->myskills.level <= 13)
minlevel = attacker->myskills.level - 10;
//anything else should be 1/4 of the attackers level
else
minlevel = attacker->myskills.level / 4;
//if the target was below the minimum level requirement then don't count toward spree
if (targ->myskills.level < minlevel)
return;
//decino: zzz, remind me not to code when i'm half asleep, i forgot this...
++attacker->myskills.streak;
VortexSpreeAbilities(attacker);
if (ptr->value)
return;
if (domination->value)
return;
if (pvm->value)
return;
if (ctf->value)
return;
if (attacker->myskills.streak >= SPREE_START)
{
if (attacker->myskills.streak > attacker->myskills.max_streak)
attacker->myskills.max_streak = attacker->myskills.streak;
if (attacker->myskills.streak == SPREE_START)
attacker->myskills.num_sprees++;
if (attacker->myskills.streak == SPREE_WARS_START && SPREE_WARS > 0)
attacker->myskills.spree_wars++;
if ((attacker->myskills.streak >= SPREE_WARS_START) && SPREE_WARS && (!numAllies(attacker))
&& !attacker->myskills.boss && !IsNewbieBasher(attacker))
{
if (SPREE_WAR == false)
{
SPREE_DUDE = attacker;
SPREE_WAR = true;
SPREE_TIME = level.time;
gi.cprintf(attacker, PRINT_HIGH, "You have 2 minutes to war. Each kill increases your war by 10 seconds, so get as many frags as you can!\n");
}
if (attacker == SPREE_DUDE)
{
message = HiPrint(va("%s SPREE WAR: %d frag spree!", attacker->client->pers.netname, attacker->myskills.streak));
gi.bprintf(PRINT_HIGH, "%s\n", message);
message = LoPrint(message);
}
}
else if (attacker->myskills.streak >= 10 && GetRandom(1,2) == 1)
{
message = HiPrint(va("%s rampage: %d frag spree!", attacker->client->pers.netname, attacker->myskills.streak));
gi.bprintf(PRINT_HIGH, "%s\n", message);
message = LoPrint(message);
}
else if (attacker->myskills.streak >= 10)
{
message = HiPrint(va("%s is god-like: %d frag spree!", attacker->client->pers.netname, attacker->myskills.streak));
gi.bprintf(PRINT_HIGH, "%s\n", message);
message = LoPrint(message);
}
else if (attacker->myskills.streak >= SPREE_START)
{
message = HiPrint(va("%s is on a %d frag spree!", attacker->client->pers.netname, attacker->myskills.streak));
gi.bprintf(PRINT_HIGH, "%s\n", message);
message = LoPrint(message);
}
}
}
/*
===========
Add_exp_by_damage
Adds experience to attacker based on damage done to targ
CURRENTLY DISABLED
============
*/
/*
void Add_exp_by_damage (edict_t *attacker, edict_t *targ, int damage)
{
float exp_points=0;
float lose_points=0;
float level_diff=0;
float bonus=1;
edict_t *player;
attacker = GetTheClient(attacker);
player = GetTheClient(targ);
if (attacker == NULL || player == NULL || damage <= 0)
return;
// ignore invalid data
if (targ == attacker || player->deadflag || !player->takedamage)
return;
// calc level difference modifier
level_diff = (float) (player->myskills.level + 1) / (attacker->myskills.level + 1);
if (!ctf->value)
{
// calc spree bonuses
if (attacker->myskills.streak >= SPREE_START)
bonus += 0.02 * attacker->myskills.streak;
else if (attacker->myskills.streak >= SPREE_WARS_START && SPREE_WARS)
bonus += 0.03 * attacker->myskills.streak;
// calc spree break bonuses
if (player->myskills.streak >= SPREE_START && !SPREE_WAR)
bonus += 0.01 * player->myskills.streak;
else if (player->myskills.streak >= SPREE_WARS_START && SPREE_WARS)
bonus += 0.015 * player->myskills.streak;
// cap maximum points to 200%
if (bonus > 2.0)
bonus = 2.0;
}
if (targ->client)
exp_points = damage * (0.25 * (level_diff * bonus));
else
exp_points = damage * (0.025 * (level_diff * bonus));
if (targ->client)
lose_points = 0.25 * exp_points;
// gi.dprintf("attacker exp + %f, attacker cache =%f\n", exp_points, attacker->myskills.exp_cache);
// gi.dprintf("targ exp - %f, targ cache =%f\n", lose_points, targ->myskills.exp_cache);
// add non-integer values to cache
if (exp_points < 1 && attacker->myskills.exp_cache < 1)
{
attacker->myskills.exp_cache += exp_points;
return;
}
if (lose_points < 1 && player->myskills.exp_cache < 1)
{
player->myskills.exp_cache += lose_points;
return;
}
// empty cache
if (attacker->myskills.exp_cache >= 1)
{
exp_points += attacker->myskills.exp_cache;
attacker->myskills.exp_cache = 0;
}
if (player->myskills.exp_cache >= 1)
{
lose_points += player->myskills.exp_cache;
player->myskills.exp_cache = 0;
}
// give your team some experience
if (ctf->value)
Add_ctfteam_exp(attacker, (int)(0.5*exp_points));
// modify attacker's score
attacker->client->resp.score += (int) exp_points;
attacker->myskills.experience += (int) exp_points;
// reduce target's score
if (player->client->resp.score - lose_points > 0)
{
player->client->resp.score -= (int) lose_points;
player->myskills.experience -= (int) lose_points;
}
check_for_levelup(attacker);
}
*/
<file_sep>#include "g_local.h"
void OpenGeneralTalentMenu (edict_t *ent, int lastline);
//Gives the player a new talent.
void addTalent(edict_t *ent, int talentID, int maxLevel)
{
int nextEmptySlot = ent->myskills.talents.count;
int i = 0;
//Don't add too many talents.
if(!(nextEmptySlot < MAX_TALENTS))
return;
//Don't add a talent more than once.
for(i = 0; i < nextEmptySlot; ++i)
if(ent->myskills.talents.talent[nextEmptySlot].id == talentID)
return;
ent->myskills.talents.talent[nextEmptySlot].id = talentID;
ent->myskills.talents.talent[nextEmptySlot].maxLevel = maxLevel;
ent->myskills.talents.talent[nextEmptySlot].upgradeLevel = 0; //Just in case it's not already zero.
ent->myskills.talents.count++;
}
//Adds all the required talents for said class.
void setTalents(edict_t *ent)
{
switch(ent->myskills.class_num)
{
case CLASS_SOLDIER:
addTalent(ent, TALENT_IMP_STRENGTH, 3);
addTalent(ent, TALENT_IMP_RESIST, 3);
addTalent(ent, TALENT_BLOOD_OF_ARES, 3);
// addTalent(ent, TALENT_BASIC_HA, 5);
addTalent(ent, TALENT_BOMBARDIER, 3);
addTalent(ent, TALENT_RETALIATION, 3);
return;
case CLASS_POLTERGEIST:
addTalent(ent, TALENT_MORPHING, 3);
addTalent(ent, TALENT_MORE_AMMO, 3);
addTalent(ent, TALENT_SUPERIORITY, 3);
// addTalent(ent, TALENT_RETALIATION, 5);
addTalent(ent, TALENT_SECOND_CHANCE, 3);
addTalent(ent, TALENT_PACK_ANIMAL, 3);
return;
case CLASS_VAMPIRE:
addTalent(ent, TALENT_IMP_CLOAK, 3);
addTalent(ent, TALENT_ARMOR_VAMP, 3);
// addTalent(ent, TALENT_SECOND_CHANCE, 4);
addTalent(ent, TALENT_IMP_MINDABSORB, 3);
addTalent(ent, TALENT_CANNIBALISM, 3);
addTalent(ent, TALENT_FATAL_WOUND, 3);
return;
case CLASS_MAGE:
addTalent(ent, TALENT_ICE_BOLT, 3);
addTalent(ent, TALENT_FROST_NOVA, 3);
addTalent(ent, TALENT_IMP_MAGICBOLT, 3);
addTalent(ent, TALENT_MANASHIELD, 3);
addTalent(ent, TALENT_MEDITATION, 3);
// addTalent(ent, TALENT_OVERLOAD, 5);
return;
case CLASS_ENGINEER:
addTalent(ent, TALENT_LASER_PLATFORM, 3);
addTalent(ent, TALENT_ALARM, 3);
addTalent(ent, TALENT_RAPID_ASSEMBLY, 3);
addTalent(ent, TALENT_PRECISION_TUNING, 3);
addTalent(ent, TALENT_STORAGE_UPGRADE, 3);
return;
case CLASS_KNIGHT:
addTalent(ent, TALENT_REPEL, 3);
addTalent(ent, TALENT_MAG_BOOTS, 3);
addTalent(ent, TALENT_LEAP_ATTACK, 3);
addTalent(ent, TALENT_MOBILITY, 3);
addTalent(ent, TALENT_DURABILITY, 3);//lancing
return;
case CLASS_CLERIC:
addTalent(ent, TALENT_BALANCESPIRIT, 3);
addTalent(ent, TALENT_HOLY_GROUND, 3);
addTalent(ent, TALENT_UNHOLY_GROUND, 3);
addTalent(ent, TALENT_BOOMERANG, 3);
addTalent(ent, TALENT_PURGE, 3);
return;
case CLASS_WEAPONMASTER:
addTalent(ent, TALENT_BASIC_AMMO_REGEN, 3);
addTalent(ent, TALENT_COMBAT_EXP, 3);
addTalent(ent, TALENT_TACTICS, 3);//poison
addTalent(ent, TALENT_SIDEARMS, 3);
addTalent(ent, TALENT_OVERLOAD, 3);//ammo steal
return;
case CLASS_NECROMANCER:
addTalent(ent, TALENT_CHEAPER_CURSES, 3);
addTalent(ent, TALENT_CORPULENCE, 3);
addTalent(ent, TALENT_LIFE_TAP, 3);
addTalent(ent, TALENT_DIM_VISION, 3);
// addTalent(ent, TALENT_EVIL_CURSE, 5);
addTalent(ent, TALENT_FLIGHT, 3);
return;
case CLASS_SHAMAN://decino: all these talents need a replacement
addTalent(ent, TALENT_ICE, 3);
addTalent(ent, TALENT_WIND, 3);
addTalent(ent, TALENT_SHADOW, 3);
//addTalent(ent, TALENT_STONE, 3);
addTalent(ent, TALENT_PEACE, 3);
addTalent(ent, TALENT_TOTEM, 3);
//addTalent(ent, TALENT_VOLCANIC, 3);
return;
case CLASS_ALIEN:
addTalent(ent, TALENT_PHANTOM_OBSTACLE, 3);
addTalent(ent, TALENT_SUPER_HEALER, 3);
addTalent(ent, TALENT_PHANTOM_COCOON, 3);
addTalent(ent, TALENT_SWARMING, 3);
addTalent(ent, TALENT_EXPLODING_BODIES, 3);
return;
default: return;
}
}
//Erases all talent information.
void eraseTalents(edict_t *ent)
{
memset(&ent->myskills.talents, 0, sizeof(talentlist_t));
}
//Returns the talent slot with matching talentID.
//Returns -1 if there is no matching talent.
int getTalentSlot(edict_t *ent, int talentID)
{
int i;
//Make sure the ent is valid
if(!ent)
{
WriteServerMsg(va("getTalentSlot() called with a NULL entity. talentID = %d", talentID), "CRITICAL ERROR", true, true);
return -1;
}
//Make sure we are a player
if(!ent->client)
{
//gi.dprintf(va("WARNING: getTalentSlot() called with a non-player entity! talentID = %d\n", talentID));
return -1;
}
for(i = 0; i < ent->myskills.talents.count; ++i)
if(ent->myskills.talents.talent[i].id == talentID)
return i;
return -1;
}
//Returns the talent upgrade level matching talentID.
//Returns -1 if there is no matching talent.
int getTalentLevel(edict_t *ent, int talentID)
{
int slot = getTalentSlot(ent, talentID);
if(slot < 0) return 0;//-1;
return ent->myskills.talents.talent[slot].upgradeLevel;
}
//Upgrades the talent with a matching talentID
void upgradeTalent(edict_t *ent, int talentID)
{
int slot = getTalentSlot(ent, talentID);
talent_t *talent;
if(slot == -1)
return;
talent = &ent->myskills.talents.talent[slot];
// check for conflicting talents
if (talentID == TALENT_CORPULENCE && getTalentLevel(ent, TALENT_LIFE_TAP) > 0)
{
gi.cprintf(ent, PRINT_HIGH, "Corpulence can't be combined with Life Tap.\n");
return;
}
if (talentID == TALENT_LIFE_TAP && getTalentLevel(ent, TALENT_CORPULENCE) > 0)
{
gi.cprintf(ent, PRINT_HIGH, "Life Tap can't be combined with Corpulence.\n");
return;
}
if(talent->upgradeLevel == talent->maxLevel)
{
gi.cprintf(ent, PRINT_HIGH, "You can not upgrade this talent any further.\n");
return;
}
if(ent->myskills.talents.talentPoints < 1)
{
gi.cprintf(ent, PRINT_HIGH, "You do not have enough talent points.\n");
return;
}
//We can upgrade.
talent->upgradeLevel++;
ent->myskills.talents.talentPoints--;
gi.cprintf(ent, PRINT_HIGH, va("%s upgraded to level %d/%d.\n", GetTalentString(talent->id), talent->upgradeLevel, talent->maxLevel));
gi.cprintf(ent, PRINT_HIGH, va("Talent points remaining: %d\n", ent->myskills.talents.talentPoints));
savePlayer(ent);
}
//Upgrades the talent with a matching talentID
void upgradeGenTalent(edict_t *ent, int talentID)
{
int slot = getTalentSlot(ent, talentID);
talent_t *talent;
// if(slot == -1)
// return;
talent = &ent->myskills.talents.talent[slot];
if(talent->upgradeLevel == talent->maxLevel)
{
gi.cprintf(ent, PRINT_HIGH, "You can not upgrade this talent any further.\n");
return;
}
if(ent->myskills.talents.talentPoints < 1)
{
gi.cprintf(ent, PRINT_HIGH, "You do not have enough talent points.\n");
return;
}
//We can upgrade.
talent->upgradeLevel++;
ent->myskills.talents.talentPoints--;
gi.cprintf(ent, PRINT_HIGH, va("%s upgraded to level %d/%d.\n", GetTalentString(talent->id), talent->upgradeLevel, talent->maxLevel));
gi.cprintf(ent, PRINT_HIGH, va("Talent points remaining: %d\n", ent->myskills.talents.talentPoints));
savePlayer(ent);
}
//****************************************
//************* Talent Menus *************
//****************************************
void TalentUpgradeMenu_handler(edict_t *ent, int option)
{
//Not upgrading
if(option > 0)
{
OpenTalentUpgradeMenu(ent, getTalentSlot(ent, option-1)+1);
}
else //upgrading
{
upgradeTalent(ent, (option * -1)-1);
}
}
void GenTalentUpgradeMenu_handler(edict_t *ent, int option)
{
//Not upgrading
if(option > 0)
{
// OpenGeneralTalentMenu(ent, getTalentSlot(ent, option-1)+1);
}
else //upgrading
{
upgradeGenTalent(ent, (option * -1)-1);
}
}
//Adds menu lines that describe the general use of the talent.
int writeTalentDescription(edict_t *ent, int talentID)
{
switch(talentID)
{
//Soldier talents
case TALENT_IMP_STRENGTH:
addlinetomenu(ent, "Increases damage,", MENU_WHITE_CENTERED);
addlinetomenu(ent, "but reduces resist.", MENU_WHITE_CENTERED);
return 2;
case TALENT_IMP_RESIST:
addlinetomenu(ent, "Increases resist,", MENU_WHITE_CENTERED);
addlinetomenu(ent, "but reduces damage.", MENU_WHITE_CENTERED);
return 2;
case TALENT_BLOOD_OF_ARES:
addlinetomenu(ent, "Increases the damage you", MENU_WHITE_CENTERED);
addlinetomenu(ent, "give/take as you spree.", MENU_WHITE_CENTERED);
return 2;
case TALENT_BASIC_HA:
addlinetomenu(ent, "Increases ammo pickups.", MENU_WHITE_CENTERED);
return 1;
case TALENT_BOMBARDIER:
addlinetomenu(ent, "Reduces self-inflicted", MENU_WHITE_CENTERED);
addlinetomenu(ent, "grenade damage and", MENU_WHITE_CENTERED);
addlinetomenu(ent, "reduces cost.", MENU_WHITE_CENTERED);
return 3;
//Poltergeist talents
case TALENT_MORPHING:
addlinetomenu(ent, "Reduces the cost", MENU_WHITE_CENTERED);
addlinetomenu(ent, "of your morphs.", MENU_WHITE_CENTERED);
return 2;
case TALENT_MORE_AMMO:
addlinetomenu(ent, "Increases maximum ammo", MENU_WHITE_CENTERED);
addlinetomenu(ent, "capacity for", MENU_WHITE_CENTERED);
addlinetomenu(ent, "tank/caco/flyer/medic.", MENU_WHITE_CENTERED);
return 3;
case TALENT_SUPERIORITY:
addlinetomenu(ent, "Increases your damage", MENU_WHITE_CENTERED);
addlinetomenu(ent, "as you level up.", MENU_WHITE_CENTERED);
return 2;
case TALENT_RETALIATION:
addlinetomenu(ent, "Damage increases as", MENU_WHITE_CENTERED);
addlinetomenu(ent, "health is reduced.", MENU_WHITE_CENTERED);
return 2;
case TALENT_PACK_ANIMAL:
addlinetomenu(ent, "Increased damage and", MENU_WHITE_CENTERED);
addlinetomenu(ent, "resistance when near", MENU_WHITE_CENTERED);
addlinetomenu(ent, "friendly morphed", MENU_WHITE_CENTERED);
addlinetomenu(ent, "players.", MENU_WHITE_CENTERED);
return 4;
//Vampire talents
case TALENT_IMP_CLOAK:
addlinetomenu(ent, "Move while cloaked", MENU_WHITE_CENTERED);
addlinetomenu(ent, "(must be crouching).", MENU_WHITE_CENTERED);
return 2;
case TALENT_ARMOR_VAMP:
addlinetomenu(ent, "Also gain armor using", MENU_WHITE_CENTERED);
addlinetomenu(ent, "your vampire skill.", MENU_WHITE_CENTERED);
return 2;
case TALENT_FATAL_WOUND:
addlinetomenu(ent, "Adds chance for flesh", MENU_WHITE_CENTERED);
addlinetomenu(ent, "eater to cause a fatal", MENU_WHITE_CENTERED);
addlinetomenu(ent, "wound.", MENU_WHITE_CENTERED);
return 3;
case TALENT_SECOND_CHANCE:
addlinetomenu(ent, "Increases melee range of", MENU_WHITE_CENTERED);
addlinetomenu(ent, "berserker/parasite/mutant", MENU_WHITE_CENTERED);
addlinetomenu(ent, "and tank.", MENU_WHITE_CENTERED);
return 3;
case TALENT_IMP_MINDABSORB:
addlinetomenu(ent, "Increases frequency of", MENU_WHITE_CENTERED);
addlinetomenu(ent, "mind absorb attacks.", MENU_WHITE_CENTERED);
return 2;
case TALENT_CANNIBALISM:
addlinetomenu(ent, "Increases your maximum", MENU_WHITE_CENTERED);
addlinetomenu(ent, "health using corpse eater.", MENU_WHITE_CENTERED);
return 2;
//Mage talents
case TALENT_ICE_BOLT:
addlinetomenu(ent, "Special fireball spell", MENU_WHITE_CENTERED);
addlinetomenu(ent, "that chills players upon.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "hit (cmd 'icebolt').", MENU_WHITE_CENTERED);
return 3;
case TALENT_MEDITATION:
addlinetomenu(ent, "Meditate to build power", MENU_WHITE_CENTERED);
addlinetomenu(ent, "cubes (cmd 'meditate').", MENU_WHITE_CENTERED);
return 2;
/* case TALENT_OVERLOAD:
addlinetomenu(ent, "Use extra power cubes", MENU_WHITE_CENTERED);
addlinetomenu(ent, "to overload spells,", MENU_WHITE_CENTERED);
addlinetomenu(ent, "increasing their", MENU_WHITE_CENTERED);
addlinetomenu(ent, "effectiveness", MENU_WHITE_CENTERED);
addlinetomenu(ent, "(cmd 'overload').", MENU_WHITE_CENTERED);
return 5;*/
case TALENT_FROST_NOVA:
addlinetomenu(ent, "Special nova spell", MENU_WHITE_CENTERED);
addlinetomenu(ent, "that chills players.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "(cmd 'frostnova')", MENU_WHITE_CENTERED);
return 3;
case TALENT_IMP_MAGICBOLT:
addlinetomenu(ent, "Causes magic bolts to", MENU_WHITE_CENTERED);
addlinetomenu(ent, "explode.", MENU_WHITE_CENTERED);
return 2;
case TALENT_MANASHIELD:
addlinetomenu(ent, "Reduces physical damage", MENU_WHITE_CENTERED);
addlinetomenu(ent, "by 50%%. All damage", MENU_WHITE_CENTERED);
addlinetomenu(ent, "absorbed consumes power", MENU_WHITE_CENTERED);
addlinetomenu(ent, "cubes. (cmd 'manashield')", MENU_WHITE_CENTERED);
return 4;
//Engineer talents
case TALENT_LASER_PLATFORM:
addlinetomenu(ent, "Create a laser platform", MENU_WHITE_CENTERED);
addlinetomenu(ent, "(cmd 'laserplatform').", MENU_WHITE_CENTERED);
return 2;
case TALENT_ALARM:
addlinetomenu(ent, "Create a trap which attacks", MENU_WHITE_CENTERED);
addlinetomenu(ent, "enemies that get too close", MENU_WHITE_CENTERED);
addlinetomenu(ent, "(cmd 'lasertrap').", MENU_WHITE_CENTERED);
return 3;
case TALENT_RAPID_ASSEMBLY:
addlinetomenu(ent, "Reduces build time.", MENU_WHITE_CENTERED);
return 1;
case TALENT_PRECISION_TUNING:
addlinetomenu(ent, "Reduces the effect of curses", MENU_WHITE_CENTERED);
addlinetomenu(ent, "and other negative effects", MENU_WHITE_CENTERED);
addlinetomenu(ent, "on your devices.", MENU_WHITE_CENTERED);
return 3;
case TALENT_STORAGE_UPGRADE:
addlinetomenu(ent, "Increases ammunition", MENU_WHITE_CENTERED);
addlinetomenu(ent, "capacity of SS/sentry/AC.", MENU_WHITE_CENTERED);
return 2;
//Knight talents
case TALENT_REPEL:
addlinetomenu(ent, "Adds chance for projectiles", MENU_WHITE_CENTERED);
addlinetomenu(ent, "to deflect from shield.", MENU_WHITE_CENTERED);
return 2;
case TALENT_MAG_BOOTS:
addlinetomenu(ent, "Reduces effect of knockback.", MENU_WHITE_CENTERED);
return 1;
case TALENT_LEAP_ATTACK:
addlinetomenu(ent, "Adds stun/knockback effect", MENU_WHITE_CENTERED);
addlinetomenu(ent, "to boost spell when landing.", MENU_WHITE_CENTERED);
return 2;
case TALENT_MOBILITY:
addlinetomenu(ent, "Reduces boost cooldown.", MENU_WHITE_CENTERED);
return 1;
case TALENT_DURABILITY:
addlinetomenu(ent, "Increases your sword length.", MENU_WHITE_CENTERED);
return 1;
//Cleric talents
case TALENT_BALANCESPIRIT:
addlinetomenu(ent, "New spirit that can", MENU_WHITE_CENTERED);
addlinetomenu(ent, "use the skills of both", MENU_WHITE_CENTERED);
addlinetomenu(ent, "yin and yang spirits.", MENU_WHITE_CENTERED);
return 3;
case TALENT_HOLY_GROUND:
addlinetomenu(ent, "Designate an area as", MENU_WHITE_CENTERED);
addlinetomenu(ent, "holy ground to regenerate", MENU_WHITE_CENTERED);
addlinetomenu(ent, "teammates (cmd 'holyground').", MENU_WHITE_CENTERED);
return 3;
case TALENT_UNHOLY_GROUND:
addlinetomenu(ent, "Designate an area as", MENU_WHITE_CENTERED);
addlinetomenu(ent, "unholy ground to damage", MENU_WHITE_CENTERED);
addlinetomenu(ent, "enemies (cmd 'unholyground').", MENU_WHITE_CENTERED);
return 3;
case TALENT_BOOMERANG:
addlinetomenu(ent, "Turns blessed hammers", MENU_WHITE_CENTERED);
addlinetomenu(ent, "into boomerangs", MENU_WHITE_CENTERED);
addlinetomenu(ent, "(cmd 'boomerang').", MENU_WHITE_CENTERED);
return 3;
case TALENT_PURGE:
addlinetomenu(ent, "Removes curses and grants", MENU_WHITE_CENTERED);
addlinetomenu(ent, "temporary invincibility", MENU_WHITE_CENTERED);
addlinetomenu(ent, "and immunity to curses", MENU_WHITE_CENTERED);
addlinetomenu(ent, "(cmd 'purge').", MENU_WHITE_CENTERED);
return 4;
//Weaponmaster talents
case TALENT_BASIC_AMMO_REGEN:
addlinetomenu(ent, "Basic ammo regeneration.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "Regenerates one ammo pack", MENU_WHITE_CENTERED);
addlinetomenu(ent, "for the weapon in use.", MENU_WHITE_CENTERED);
return 3;
case TALENT_COMBAT_EXP:
addlinetomenu(ent, "Increases physical", MENU_WHITE_CENTERED);
addlinetomenu(ent, "damage, but reduces", MENU_WHITE_CENTERED);
addlinetomenu(ent, "resistance.", MENU_WHITE_CENTERED);
return 3;
case TALENT_TACTICS:
addlinetomenu(ent, "Adds a chance poisoning", MENU_WHITE_CENTERED);
addlinetomenu(ent, "players while dealing", MENU_WHITE_CENTERED);
addlinetomenu(ent, "damage.", MENU_WHITE_CENTERED);
return 3;
case TALENT_OVERLOAD:
addlinetomenu(ent, "Steal ammo from your", MENU_WHITE_CENTERED);
addlinetomenu(ent, "enemy while dealing damage", MENU_WHITE_CENTERED);
return 2;
case TALENT_SIDEARMS:
addlinetomenu(ent, "Gives you additional", MENU_WHITE_CENTERED);
addlinetomenu(ent, "respawn weapons. Weapon", MENU_WHITE_CENTERED);
addlinetomenu(ent, "choice is determined by", MENU_WHITE_CENTERED);
addlinetomenu(ent, "weapon upgrade level.", MENU_WHITE_CENTERED);
return 4;
//Necromancer talents
case TALENT_EVIL_CURSE:
addlinetomenu(ent, "Increases curse duration.", MENU_WHITE_CENTERED);
return 1;
case TALENT_CHEAPER_CURSES:
addlinetomenu(ent, "Reduces curse cost.", MENU_WHITE_CENTERED);
return 1;
case TALENT_CORPULENCE:
addlinetomenu(ent, "Increases hellspawn", MENU_WHITE_CENTERED);
addlinetomenu(ent, "and monster health/armor,", MENU_WHITE_CENTERED);
addlinetomenu(ent, "but reduces damage. Can't,", MENU_WHITE_CENTERED);
addlinetomenu(ent, "combine with Life Tap.", MENU_WHITE_CENTERED);
return 4;
case TALENT_LIFE_TAP:
addlinetomenu(ent, "Increases hellspawn", MENU_WHITE_CENTERED);
addlinetomenu(ent, "and monster damage,", MENU_WHITE_CENTERED);
addlinetomenu(ent, "but slowly saps life.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "Can't combine with", MENU_WHITE_CENTERED);
addlinetomenu(ent, "Corpulence.", MENU_WHITE_CENTERED);
return 5;
case TALENT_DIM_VISION:
addlinetomenu(ent, "Adds chance to", MENU_WHITE_CENTERED);
addlinetomenu(ent, "automatically curse", MENU_WHITE_CENTERED);
addlinetomenu(ent, "enemies that shoot you.", MENU_WHITE_CENTERED);
return 3;
case TALENT_FLIGHT:
addlinetomenu(ent, "Reduces jetpack cost.", MENU_WHITE_CENTERED);
return 1;
//Shaman talents
case TALENT_TOTEM:
addlinetomenu(ent, "Increases totem health.", MENU_WHITE_CENTERED);
return 1;
//decino: this is now the fury talent
case TALENT_PEACE:
addlinetomenu(ent, "Increases the chance", MENU_WHITE_CENTERED);
addlinetomenu(ent, "to activate fury.", MENU_WHITE_CENTERED);
return 2;
//decino: this talent is now water+fire
case TALENT_ICE:
addlinetomenu(ent, "Water totem will damage", MENU_WHITE_CENTERED);
addlinetomenu(ent, "nearby enemies.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "Fire totem has a chance to", MENU_WHITE_CENTERED);
addlinetomenu(ent, "shoot a fireball.", MENU_WHITE_CENTERED);
return 4;
//decino: this talent is now air+earth
case TALENT_WIND:
addlinetomenu(ent, "Air totem has a chance", MENU_WHITE_CENTERED);
addlinetomenu(ent, "to ghost attacks for you.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "Earth totem will increase", MENU_WHITE_CENTERED);
addlinetomenu(ent, "your resistance.", MENU_WHITE_CENTERED);
return 4;
//decino: this talent is now dark+nature
case TALENT_SHADOW:
addlinetomenu(ent, "Darkness totem will vamp", MENU_WHITE_CENTERED);
addlinetomenu(ent, "beyond your max health.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "Nature totem will", MENU_WHITE_CENTERED);
addlinetomenu(ent, "regenerate power cubes.", MENU_WHITE_CENTERED);
return 4;
//decino: not used
//case TALENT_STONE:
// addlinetomenu(ent, "Allows your earth totem to", MENU_WHITE_CENTERED);
// addlinetomenu(ent, "increase your resistance.", MENU_WHITE_CENTERED);
// return 2;
//decino: not used
//case TALENT_PEACE:
// addlinetomenu(ent, "Allows your nature totem to", MENU_WHITE_CENTERED);
// addlinetomenu(ent, "regenerate your power cubes.", MENU_WHITE_CENTERED);
// return 2;
//decino: not used
//case TALENT_VOLCANIC:
// addlinetomenu(ent, "Adds a chance for fire", MENU_WHITE_CENTERED);
// addlinetomenu(ent, "totem to shoot a fireball.", MENU_WHITE_CENTERED);
// return 2;
//Alien talents
case TALENT_PHANTOM_OBSTACLE:
addlinetomenu(ent, "Reduces time to cloak.", MENU_WHITE_CENTERED);
return 1;
case TALENT_SUPER_HEALER:
addlinetomenu(ent, "Adds armor regeneration", MENU_WHITE_CENTERED);
addlinetomenu(ent, "to your healer", MENU_WHITE_CENTERED);
return 2;
case TALENT_PHANTOM_COCOON:
addlinetomenu(ent, "Allows cocoon to cloak.", MENU_WHITE_CENTERED);
return 1;
case TALENT_SWARMING:
addlinetomenu(ent, "Increases spore count,", MENU_WHITE_CENTERED);
return 1;
case TALENT_EXPLODING_BODIES:
addlinetomenu(ent, "Makes alien-summons'", MENU_WHITE_CENTERED);
addlinetomenu(ent, "corpses explode.", MENU_WHITE_CENTERED);
return 2;
//General talents
case TALENT_BARTERING:
addlinetomenu(ent, "Reduces armory costs.", MENU_WHITE_CENTERED);
return 1;
default: return 0;
}
}
//Adds a menu line that tells the player what their current talent upgrade does, and
//what their next upgrade will do, if they choose to get it.
/*
void writeTalentUpgrade(edict_t *ent, int talentID, int level)
{
if(level == 0)
{
addlinetomenu(ent, "-------", MENU_WHITE_CENTERED);
return;
}
switch(talentID)
{
//Soldier talents
case TALENT_IMP_STRENGTH:
addlinetomenu(ent, va("+%d%%, -%0.2fx resist mult", level*10, (float)level*0.01f ), MENU_WHITE_CENTERED);
return;
case TALENT_IMP_RESIST:
addlinetomenu(ent, va("+%0.2fx, -%d%% damage", (float)level*0.02f, level*10 ), MENU_WHITE_CENTERED);
return;
case TALENT_BLOOD_OF_ARES:
addlinetomenu(ent, va("+%d%% per kill (max +200%%)", level*2 ), MENU_WHITE_CENTERED);
return;
case TALENT_BASIC_HA:
addlinetomenu(ent, va("+%d%%", level*20 ), MENU_WHITE_CENTERED);
return;
case TALENT_IMP_TRAPS:
addlinetomenu(ent, va("+%0.1f%%", level*6.6), MENU_WHITE_CENTERED);
return;
case TALENT_LONG_POWERUPS:
switch(level)
{
case 0: addlinetomenu(ent, " +0 seconds", MENU_WHITE_CENTERED); break;
case 1: addlinetomenu(ent, " +3 seconds", MENU_WHITE_CENTERED); break;
case 2: addlinetomenu(ent, " +5 seconds", MENU_WHITE_CENTERED); break;
case 3: addlinetomenu(ent, " +8 sec, +1sec per kill!", MENU_WHITE_CENTERED); break;
}
return;
//Poltergeist talents
case TALENT_MORPHING:
addlinetomenu(ent, va("-%d%%", level*25), MENU_WHITE_CENTERED);
return;
case TALENT_CACO_MAST:
addlinetomenu(ent, va("+%d%%", level*10), MENU_WHITE_CENTERED);
return;
case TALENT_PARA_MAST:
addlinetomenu(ent, va("+%d units", level*10), MENU_WHITE_CENTERED);
return;
case TALENT_BRAIN_MAST:
addlinetomenu(ent, va("+%d%%", level*10), MENU_WHITE_CENTERED);
return;
case TALENT_FLYER_MAST:
addlinetomenu(ent, va("+%d%%, -%d%%", level*10, level*25), MENU_WHITE_CENTERED);
return;
case TALENT_MUTANT_MAST:
addlinetomenu(ent, va("+%d%%", level*10), MENU_WHITE_CENTERED);
return;
case TALENT_MEDIC_MAST:
addlinetomenu(ent, va("+%d%%", level*5), MENU_WHITE_CENTERED);
return;
case TALENT_TANK_MAST:
addlinetomenu(ent, va("+%d%%", level*10), MENU_WHITE_CENTERED);
return;
case TALENT_BERSERK_MAST:
addlinetomenu(ent, va("+%d%%", level*11), MENU_WHITE_CENTERED);
return;
//Vampire talents
case TALENT_IMP_CLOAK:
addlinetomenu(ent, va("%dpc/frame", 6-level), MENU_WHITE_CENTERED);
return;
case TALENT_ARMOR_VAMP:
addlinetomenu(ent, va("+%d%%", level*10), MENU_WHITE_CENTERED);
return;
case TALENT_EVIL_CURSE:
addlinetomenu(ent, va("+%d%%", level*25), MENU_WHITE_CENTERED);
return;
case TALENT_SECOND_CHANCE:
addlinetomenu(ent, va("every %0.1f minutes", 3.0-level*0.5), MENU_WHITE_CENTERED);
return;
case TALENT_IMP_MINDABSORB:
addlinetomenu(ent, va("-%0.1f seconds", 0.5f * level), MENU_WHITE_CENTERED);
return;
//Mage talents
case TALENT_IMP_PCR:
addlinetomenu(ent, va(" +%d", level * 5), MENU_WHITE_CENTERED);
return;
case TALENT_ELEMENTAL_MASTERY:
addlinetomenu(ent, va("+%d%% damage", level*10), MENU_WHITE_CENTERED);
return;
case TALENT_FROST_NOVA:
addlinetomenu(ent, va("-%d%% movement", level * 5), MENU_WHITE_CENTERED);
return;
case TALENT_IMP_MAGICBOLT:
addlinetomenu(ent, va("+%d%% damage, %0.1fx cost", level * 4, 1.0 + (float)level * 0.2), MENU_WHITE_CENTERED);
return;
case TALENT_MANASHIELD:
addlinetomenu(ent, va("%0.1f PC/damage", 4.0 - (float)level * 0.5), MENU_WHITE_CENTERED);
return;
//Engineer talents
case TALENT_IMP_SUPPLY:
addlinetomenu(ent, va("+%d/%d/%d%%", level * 5, level * 10, level * 20), MENU_WHITE_CENTERED);
return;
case TALENT_IMP_SENTRY:
addlinetomenu(ent, va("+%d%% resist, -%d%% damage", level * 5, level * 2), MENU_WHITE_CENTERED);
return;
case TALENT_ATOMIC_ARMOR:
addlinetomenu(ent, va("+%d%%", 25*level), MENU_WHITE_CENTERED);
return;
//Knight talents
case TALENT_IMP_POWERSCREEN:
addlinetomenu(ent, va("-%d%%", 5*level), MENU_WHITE_CENTERED);
return;
case TALENT_IMP_REGEN:
addlinetomenu(ent, va("-%0.2f seconds", 0.05 * level), MENU_WHITE_CENTERED);
return;
case TALENT_MOBILITY:
switch(level)
{
case 3: addlinetomenu(ent, "-%0.5 seconds", MENU_WHITE_CENTERED); break;
default: addlinetomenu(ent, va("-%0.2f seconds", 0.15 * level), MENU_WHITE_CENTERED); break;
}
return;
case TALENT_DURABILITY:
addlinetomenu(ent, va("+%d", level), MENU_WHITE_CENTERED);
return;
//Cleric talents
case TALENT_BALANCESPIRIT:
addlinetomenu(ent, va("%d%% effectiveness", level*20), MENU_WHITE_CENTERED);
return;
case TALENT_SUPPORT_SKILLS:
addlinetomenu(ent, va("%d%% / %d%%", level*5, level*10), MENU_WHITE_CENTERED);
return;
case TALENT_ICY_CHILL:
addlinetomenu(ent, va("%d/clvl damage, +%d%% cost", level, level * 40), MENU_WHITE_CENTERED);
return;
case TALENT_MEDITATION:
switch(level)
{
case 1: addlinetomenu(ent, "-10%", MENU_WHITE_CENTERED); break;
case 2: addlinetomenu(ent, "-20%", MENU_WHITE_CENTERED); break;
case 3: addlinetomenu(ent, "-50%", MENU_WHITE_CENTERED); break;
default: addlinetomenu(ent, "no bonus", MENU_WHITE_CENTERED); break;
}
return;
case TALENT_HOLY_POWER:
switch(level)
{
case 1: addlinetomenu(ent, "+15%", MENU_WHITE_CENTERED); break;
case 2: addlinetomenu(ent, "+30%", MENU_WHITE_CENTERED); break;
case 3: addlinetomenu(ent, "+50%", MENU_WHITE_CENTERED); break;
}
return;
//Weaponmaster talents
case TALENT_BASIC_AMMO_REGEN:
addlinetomenu(ent, va("every %d seconds", 30 - 5 * level), MENU_WHITE_CENTERED);
return;
case TALENT_COMBAT_EXP:
addlinetomenu(ent, va("+%d%% / -%d%%",5 + level*5, 55-level*5), MENU_WHITE_CENTERED);
return;
case TALENT_IMP_HASTE:
addlinetomenu(ent, va("+%d%%", level * 25), MENU_WHITE_CENTERED);
return;
case TALENT_TACTICS:
addlinetomenu(ent, va("+%dh / +%da", level, level), MENU_WHITE_CENTERED);
return;
case TALENT_SIDEARMS:
addlinetomenu(ent, va("Addtional weapons: %d", level), MENU_WHITE_CENTERED);
return;
//Necromancer talents
case TALENT_DRONE_MASTERY:
addlinetomenu(ent, va("+%d%%", level * 4), MENU_WHITE_CENTERED);
return;
case TALENT_DRONE_POWER:
addlinetomenu(ent, va("+%d%% damage, -%d%% durability", level*3, level*3), MENU_WHITE_CENTERED);
return;
case TALENT_IMP_PLAGUE:
addlinetomenu(ent, va("+%d%%", level*10), MENU_WHITE_CENTERED);
return;
case TALENT_CANNIBALISM:
addlinetomenu(ent, va("+%0.1fx", (float)level * 0.1f), MENU_WHITE_CENTERED);
return;
//Shaman talents
//case TALENT_TOTEM:
// addlinetomenu(ent, va("%d cubes every 5 seconds", 30-level*5), MENU_WHITE_CENTERED);
// return;
case TALENT_FLAME:
addlinetomenu(ent, va("%d%% chance", level*5), MENU_WHITE_CENTERED);
return;
case TALENT_ICE:
addlinetomenu(ent, va("%d-%d damage", 10*level, 20*level), MENU_WHITE_CENTERED);
return;
case TALENT_WIND:
addlinetomenu(ent, va("%d%% chance", level*5), MENU_WHITE_CENTERED);
return;
case TALENT_STONE:
addlinetomenu(ent, va("%+d%% resist", level*5), MENU_WHITE_CENTERED);
return;
case TALENT_SHADOW:
addlinetomenu(ent, va("%+d%%", level*10), MENU_WHITE_CENTERED);
return;
case TALENT_PEACE:
addlinetomenu(ent, va("+%d% power cubes", level*10), MENU_WHITE_CENTERED);
return;
default: return;
}
}
*/
void openTalentMenu(edict_t *ent, int talentID)
{
talent_t *talent = &ent->myskills.talents.talent[getTalentSlot(ent, talentID)];
int level = talent->upgradeLevel;
int lineCount = 7;//12;
if (!ShowMenu(ent))
return;
clearmenu(ent);
addlinetomenu(ent, "Talent", MENU_GREEN_CENTERED);
addlinetomenu(ent, GetTalentString(talentID), MENU_WHITE_CENTERED);
addlinetomenu(ent, " ", 0);
lineCount += writeTalentDescription(ent, talentID);
addlinetomenu(ent, " ", 0);
//addlinetomenu(ent, "Current", MENU_GREEN_CENTERED);
//writeTalentUpgrade(ent, talentID, level);
addlinetomenu(ent, " ", 0);
/*
if(talent->upgradeLevel < talent->maxLevel)
{
level++;
addlinetomenu(ent, "Next Level", MENU_GREEN_CENTERED);
writeTalentUpgrade(ent, talentID, level);
}
else
{
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, " ", 0);
}
addlinetomenu(ent, " ", 0);
*/
if(talent->upgradeLevel < talent->maxLevel)
addlinetomenu(ent, "Upgrade this talent.", -1*(talentID+1));
else addlinetomenu(ent, " ", 0);
addlinetomenu(ent, "Previous menu.", talentID+1);
setmenuhandler(ent, TalentUpgradeMenu_handler);
ent->client->menustorage.currentline = lineCount;
showmenu(ent);
}
void generalTalentMenu(edict_t *ent, int talentID)
{
talent_t *talent = &ent->myskills.talents.talent[getTalentSlot(ent, talentID)];
int level = talent->upgradeLevel;
int lineCount = 7;//12;
if (!ShowMenu(ent))
return;
clearmenu(ent);
addlinetomenu(ent, "Talent", MENU_GREEN_CENTERED);
addlinetomenu(ent, GetTalentString(talentID), MENU_WHITE_CENTERED);
addlinetomenu(ent, " ", 0);
lineCount += writeTalentDescription(ent, talentID);
addlinetomenu(ent, " ", 0);
//addlinetomenu(ent, "Current", MENU_GREEN_CENTERED);
//writeTalentUpgrade(ent, talentID, level);
addlinetomenu(ent, " ", 0);
/*
if(talent->upgradeLevel < talent->maxLevel)
{
level++;
addlinetomenu(ent, "Next Level", MENU_GREEN_CENTERED);
writeTalentUpgrade(ent, talentID, level);
}
else
{
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, " ", 0);
}
addlinetomenu(ent, " ", 0);
*/
if(talent->upgradeLevel < talent->maxLevel)
addlinetomenu(ent, "Upgrade this talent.", -1*(talentID+1));
else addlinetomenu(ent, " ", 0);
addlinetomenu(ent, "Previous menu.", talentID+1);
setmenuhandler(ent, GenTalentUpgradeMenu_handler);
ent->client->menustorage.currentline = lineCount;
showmenu(ent);
}
//****************************************
//*********** Main Talent Menu ***********
//****************************************
void openTalentMenu_handler(edict_t *ent, int option)
{
switch(option)
{
case 9999: //Exit
{
closemenu(ent);
return;
}
default: openTalentMenu(ent, option);
}
}
void upgradingBartering_handler (edict_t *ent, int option)
{
switch(option)
{
case 1:
{
if (ent->myskills.talents.talentPoints < 1){
gi.cprintf(ent, PRINT_HIGH, "You do not have enough talent points.\n");
return;}
if (ent->myskills.talents.BarteringLevel > 2){
gi.cprintf(ent, PRINT_HIGH, "You can not upgrade this talent any further.\n");
return;}
ent->myskills.talents.BarteringLevel++;
ent->myskills.talents.talentPoints--;
gi.cprintf(ent, PRINT_HIGH, va("Bartering upgraded to level %d/3.\n", ent->myskills.talents.BarteringLevel));
gi.cprintf(ent, PRINT_HIGH, va("Talent points remaining: %d\n", ent->myskills.talents.talentPoints));
savePlayer(ent);
return;
}
default: OpenGeneralTalentMenu(ent, option);
}
}
void upgradingVital_handler (edict_t *ent, int option)
{
switch(option)
{
case 1:
{
if (ent->myskills.talents.talentPoints < 1){
gi.cprintf(ent, PRINT_HIGH, "You do not have enough talent points.\n");
return;}
if (ent->myskills.talents.VitLevel > 2){
gi.cprintf(ent, PRINT_HIGH, "You can not upgrade this talent any further.\n");
return;}
ent->myskills.talents.VitLevel++;
ent->myskills.talents.talentPoints--;
gi.cprintf(ent, PRINT_HIGH, va("Imp. Vitality upgraded to level %d/3.\n", ent->myskills.talents.VitLevel));
gi.cprintf(ent, PRINT_HIGH, va("Talent points remaining: %d\n", ent->myskills.talents.talentPoints));
savePlayer(ent);
return;
}
default: OpenGeneralTalentMenu(ent, option);
}
}
void upgradingAmmo_handler (edict_t *ent, int option)
{
switch(option)
{
case 1:
{
if (ent->myskills.talents.talentPoints < 1){
gi.cprintf(ent, PRINT_HIGH, "You do not have enough talent points.\n");
return;}
if (ent->myskills.talents.AmmoLevel > 2){
gi.cprintf(ent, PRINT_HIGH, "You can not upgrade this talent any further.\n");
return;}
ent->myskills.talents.AmmoLevel++;
ent->myskills.talents.talentPoints--;
gi.cprintf(ent, PRINT_HIGH, va("Ammo Pickups upgraded to level %d/3.\n", ent->myskills.talents.AmmoLevel));
gi.cprintf(ent, PRINT_HIGH, va("Talent points remaining: %d\n", ent->myskills.talents.talentPoints));
savePlayer(ent);
return;
}
default: OpenGeneralTalentMenu(ent, option);
}
}
void upgradingSuper_handler (edict_t *ent, int option)
{
switch(option)
{
case 1:
{
if (ent->myskills.talents.talentPoints < 1){
gi.cprintf(ent, PRINT_HIGH, "You do not have enough talent points.\n");
return;}
if (ent->myskills.talents.SuperLevel > 2){
gi.cprintf(ent, PRINT_HIGH, "You can not upgrade this talent any further.\n");
return;}
ent->myskills.talents.SuperLevel++;
ent->myskills.talents.talentPoints--;
gi.cprintf(ent, PRINT_HIGH, va("Superiority upgraded to level %d/3.\n", ent->myskills.talents.SuperLevel));
gi.cprintf(ent, PRINT_HIGH, va("Talent points remaining: %d\n", ent->myskills.talents.talentPoints));
savePlayer(ent);
return;
}
default: OpenGeneralTalentMenu(ent, option);
}
}
void upgradingGreed_handler (edict_t *ent, int option)
{
switch(option)
{
case 1:
{
if (ent->myskills.talents.talentPoints < 1){
gi.cprintf(ent, PRINT_HIGH, "You do not have enough talent points.\n");
return;}
if (ent->myskills.talents.GreedLevel > 2){
gi.cprintf(ent, PRINT_HIGH, "You can not upgrade this talent any further.\n");
return;}
ent->myskills.talents.GreedLevel++;
ent->myskills.talents.talentPoints--;
gi.cprintf(ent, PRINT_HIGH, va("Greed upgraded to level %d/3.\n", ent->myskills.talents.GreedLevel));
gi.cprintf(ent, PRINT_HIGH, va("Talent points remaining: %d\n", ent->myskills.talents.talentPoints));
savePlayer(ent);
return;
}
default: OpenGeneralTalentMenu(ent, option);
}
}
void talentDESC_Bartering (edict_t *ent)
{
// talent_t *talent;
// char buffer[30];
// int i;
// int talentLevel;
if (!ShowMenu(ent))
return;
clearmenu(ent);
// menu header
addlinetomenu(ent, "Talent", MENU_GREEN_CENTERED);
addlinetomenu(ent, "Bartering", MENU_WHITE_CENTERED);
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, "Reduces the armory cost.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "", 0);
addlinetomenu(ent, "", 0);
addlinetomenu(ent, "Upgrade this talent.", 1);
addlinetomenu(ent, "Previous Menu.", 2);
setmenuhandler(ent, upgradingBartering_handler);
ent->client->menustorage.currentline = 8;
showmenu(ent);
}
void talentDESC_Vital (edict_t *ent)
{
// talent_t *talent;
// char buffer[30];
// int i;
// int talentLevel;
if (!ShowMenu(ent))
return;
clearmenu(ent);
// menu header
addlinetomenu(ent, "Talent", MENU_GREEN_CENTERED);
addlinetomenu(ent, "Imp. Vitality", MENU_WHITE_CENTERED);
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, "Increases your levelup", MENU_WHITE_CENTERED);
addlinetomenu(ent, "health and armor bonus.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "", 0);
addlinetomenu(ent, "", 0);
addlinetomenu(ent, "Upgrade this talent.", 1);
addlinetomenu(ent, "Previous Menu.", 2);
setmenuhandler(ent, upgradingVital_handler);
ent->client->menustorage.currentline = 9;
showmenu(ent);
}
void talentDESC_Ammo (edict_t *ent)
{
// talent_t *talent;
// char buffer[30];
// int i;
// int talentLevel;
if (!ShowMenu(ent))
return;
clearmenu(ent);
// menu header
addlinetomenu(ent, "Talent", MENU_GREEN_CENTERED);
addlinetomenu(ent, "Ammo Pickups", MENU_WHITE_CENTERED);
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, "Increases the value", MENU_WHITE_CENTERED);
addlinetomenu(ent, "of ammo you pick up.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "", 0);
addlinetomenu(ent, "", 0);
addlinetomenu(ent, "Upgrade this talent.", 1);
addlinetomenu(ent, "Previous Menu.", 2);
setmenuhandler(ent, upgradingAmmo_handler);
ent->client->menustorage.currentline = 9;
showmenu(ent);
}
void talentDESC_Super (edict_t *ent)
{
// talent_t *talent;
// char buffer[30];
// int i;
// int talentLevel;
if (!ShowMenu(ent))
return;
clearmenu(ent);
// menu header
addlinetomenu(ent, "Talent", MENU_GREEN_CENTERED);
addlinetomenu(ent, "Superiority", MENU_WHITE_CENTERED);
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, "Increases damage and", MENU_WHITE_CENTERED);
addlinetomenu(ent, "resistance to monsters.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "", 0);
addlinetomenu(ent, "", 0);
addlinetomenu(ent, "Upgrade this talent.", 1);
addlinetomenu(ent, "Previous Menu.", 2);
setmenuhandler(ent, upgradingSuper_handler);
ent->client->menustorage.currentline = 9;
showmenu(ent);
}
void talentDESC_Greed (edict_t *ent)
{
// talent_t *talent;
// char buffer[30];
// int i;
// int talentLevel;
if (!ShowMenu(ent))
return;
clearmenu(ent);
// menu header
addlinetomenu(ent, "Talent", MENU_GREEN_CENTERED);
addlinetomenu(ent, "Greed", MENU_WHITE_CENTERED);
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, "Increases the chance that", MENU_WHITE_CENTERED);
addlinetomenu(ent, "the enemy you kill will.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "drop a rune.", MENU_WHITE_CENTERED);
addlinetomenu(ent, "", 0);
addlinetomenu(ent, "", 0);
addlinetomenu(ent, "Upgrade this talent.", 1);
addlinetomenu(ent, "Previous Menu.", 2);
setmenuhandler(ent, upgradingGreed_handler);
ent->client->menustorage.currentline = 10;
showmenu(ent);
}
void generalTalentMenu_handler(edict_t *ent, int option)
{
switch(option)
{
case 1://bartering
{
talentDESC_Bartering(ent);
return;
}
case 2://imp vital
{
talentDESC_Vital(ent);
return;
}
case 3://ammo pickups
{
talentDESC_Ammo(ent);
return;
}
case 4://superior
{
talentDESC_Super(ent);
return;
}
case 5://greed
{
talentDESC_Greed(ent);
return;
}
case 9999: //Exit
{
closemenu(ent);
return;
}
default: generalTalentMenu(ent, option);
}
}
void OpenTalentUpgradeMenu (edict_t *ent, int lastline)
{
talent_t *talent;
char buffer[30];
int i;
if (!ShowMenu(ent))
return;
clearmenu(ent);
// menu header
addlinetomenu(ent, "Class Talents", MENU_GREEN_CENTERED);
addlinetomenu(ent, " ", 0);
for (i = 0; i < ent->myskills.talents.count; i++)
{
talent = &ent->myskills.talents.talent[i];
//create menu string
strcpy(buffer, GetTalentString(talent->id));
strcat(buffer, ":");
padRight(buffer, 15);
addlinetomenu(ent, va("%d. %s %d/%d", i+1, buffer, talent->upgradeLevel, talent->maxLevel), talent->id);
}
// menu footer
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, va("You have %d talent points.", ent->myskills.talents.talentPoints), 0);
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, "Exit", 9999);
setmenuhandler(ent, openTalentMenu_handler);
if (!lastline) ent->client->menustorage.currentline = ent->myskills.talents.count + 6;
else ent->client->menustorage.currentline = lastline + 2;
showmenu(ent);
// try to shortcut to chat-protect mode
if (ent->client->idle_frames < CHAT_PROTECT_FRAMES-51)
ent->client->idle_frames = CHAT_PROTECT_FRAMES-51;
}
void OpenGeneralTalentMenu (edict_t *ent, int lastline)
{
talent_t *talent;
char buffer[30];
int i;
// int talentLevel;
if (!ShowMenu(ent))
return;
clearmenu(ent);
// menu header
addlinetomenu(ent, "General Talents", MENU_GREEN_CENTERED);
addlinetomenu(ent, " ", 0);
for (i = 0; i < ent->myskills.talents.count; i++)
{
talent = &ent->myskills.talents.talent[i];
//create menu string
strcpy(buffer, GetTalentString(talent->id));
strcat(buffer, ":");
padRight(buffer, 14);
}
addlinetomenu(ent, va("1. Bartering: %d/3", ent->myskills.talents.BarteringLevel), 1);
addlinetomenu(ent, va("2. Imp. Vitality: %d/3", ent->myskills.talents.VitLevel), 2);
addlinetomenu(ent, va("3. Ammo Pickups: %d/3", ent->myskills.talents.AmmoLevel), 3);
addlinetomenu(ent, va("4. Superiority: %d/3", ent->myskills.talents.SuperLevel), 4);
addlinetomenu(ent, va("5. Greed: %d/3", ent->myskills.talents.GreedLevel), 5);
// menu footer
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, va("You have %d talent points.", ent->myskills.talents.talentPoints), 0);
addlinetomenu(ent, " ", 0);
addlinetomenu(ent, "Exit", 9999);
setmenuhandler(ent, generalTalentMenu_handler);
// if (!lastline) ent->client->menustorage.currentline = ent->myskills.talents.count + 6;
ent->client->menustorage.currentline = 11;
showmenu(ent);
// try to shortcut to chat-protect mode
if (ent->client->idle_frames < CHAT_PROTECT_FRAMES-51)
ent->client->idle_frames = CHAT_PROTECT_FRAMES-51;
}<file_sep>#include "g_local.h"
#define LASER_SPAWN_DELAY 1.0 // time before emitter creates laser beam
#define LASER_INITIAL_DAMAGE 100 // beam damage per frame
#define LASER_ADDON_DAMAGE 40
#define LASER_TIMEOUT_DELAY 120
// cumulative maximum damage a laser can deal
#define LASER_INITIAL_HEALTH 0
#define LASER_ADDON_HEALTH 100
void RemoveLasers (edict_t *ent)
{
edict_t *e=NULL;
while((e = G_Find(e, FOFS(classname), "emitter")) != NULL)
{
if (e && (e->owner == ent))
{
// remove the laser beam
if (e->creator)
{
e->creator->think = G_FreeEdict;
e->creator->nextthink = level.time + FRAMETIME;
//G_FreeEdict(e->creator);
}
// remove the emitter
e->think = BecomeExplosion1;
e->nextthink = level.time + FRAMETIME;
//BecomeExplosion1(e);
}
}
// reset laser counter
ent->num_lasers = 0;
}
qboolean NearbyLasers (edict_t *ent, vec3_t org)
{
edict_t *e=NULL;
while((e = findradius(e, org, 8)) != NULL)
{
// is this a laser than we own?
if (e && e->inuse && G_EntExists(e->owner)
&& (e->owner == ent) && !strcmp(e->classname, "emitter"))
return true;
}
return false;
}
qboolean NearbyProxy (edict_t *ent, vec3_t org)
{
edict_t *e=NULL;
while((e = findradius(e, org, 8)) != NULL)
{
// is this a proxy than we own?
if (e && e->inuse && G_EntExists(e->owner)
&& (e->owner == ent) && !strcmp(e->classname, "proxygrenade"))
return true;
}
return false;
}
void laser_remove (edict_t *self)
{
// remove emitter/grenade
self->think = BecomeExplosion1;
self->nextthink = level.time+FRAMETIME;
// remove laser beam
if (self->creator && self->creator->inuse)
{
self->creator->think = G_FreeEdict;
self->creator->nextthink = level.time+FRAMETIME;
}
// decrement laser counter
if (self->owner && self->owner->inuse)
{
self->owner->num_lasers--;
gi.cprintf(self->owner, PRINT_HIGH, "Laser destroyed. %d/%d remaining.\n",
self->owner->num_lasers, MAX_LASERS);
}
}
void laser_beam_think (edict_t *self)
{
int size;
int damage = self->dmg;
vec3_t forward;
trace_t tr;
// can't have a laser beam without an emitter!
if (!self->creator)
{
G_FreeEdict(self);
return;
}
if (self->monsterinfo.level >= 10)
size = 4;
else
size = 2;
// recharge
if (self->health < self->max_health)
{
if (level.framenum > self->monsterinfo.regen_delay1)
{
self->health += 0.2*self->max_health;
if (self->health > self->max_health)
self->health = self->max_health;
self->monsterinfo.regen_delay1 = level.framenum + 10;
}
if (size > 2 && self->health < self->dmg)
size *= 0.5;
}
// set beam diameter
self->s.frame = size;
// flash yellow if the laser is about to expire
if ((level.time+10 >= self->creator->nextthink) && !(level.framenum%5) || (self->health < self->dmg))
{
self->s.skinnum = 0xdcdddedf; // yellow
}
else
{
if (self->owner->teamnum == 1)
self->s.skinnum = 0xf2f2f0f0; // red
else if (self->owner->teamnum == 2)
self->s.skinnum = 0xf3f3f1f1; // blue
else
self->s.skinnum = 0xf2f2f0f0; // red
}
// trace from beam emitter out as far as we can go
AngleVectors(self->s.angles, forward, NULL, NULL);
VectorMA(self->pos1, 8192, forward, self->pos2);
tr = gi.trace (self->pos1, NULL, NULL, self->pos2, self->creator, MASK_SHOT);
VectorCopy(tr.endpos, self->s.origin);
VectorCopy(self->pos1, self->s.old_origin);
// what is in lasers path?
if (G_EntExists(tr.ent))
{
// remove lasers near spawn positions
if (tr.ent->client && (tr.ent->client->respawn_time-1.5 > level.time))
{
gi.cprintf(self->owner, PRINT_HIGH, "Laser touched respawning player, so it was removed. (%d/%d remain)\n", self->owner->num_lasers, MAX_LASERS);
laser_remove(self->creator);
return;
}
// don't deal more damage than our health
if (damage > self->health)
damage = self->health;
// deal damage to anything in the beam's path
if (damage && T_Damage(tr.ent, self, self->owner, forward, tr.endpos,
vec3_origin, damage, 0, DAMAGE_ENERGY, MOD_LASER_DEFENSE))
{
// reduce maximum damage counter
self->health -= damage;
// if the counter reaches 0, then self-destruct
if (self->health < 1)
{
self->health = 0;
//gi.cprintf(self->owner, PRINT_HIGH, "Laser burned out. (%d/%d remain)\n", self->owner->num_lasers-1, MAX_LASERS);
//laser_remove(self->creator);
//return;
}
}
}
self->nextthink = level.time + FRAMETIME;
}
void SpawnLaser (edict_t *ent, int cost, float skill_mult, float delay_mult)
{
int talentLevel = getTalentLevel(ent, TALENT_RAPID_ASSEMBLY);//Talent: Rapid Assembly
float delay;
vec3_t forward, right, start, end, offset;
trace_t tr;
edict_t *grenade, *laser;
// get starting position and forward vector
AngleVectors (ent->client->v_angle, forward, right, NULL);
VectorSet(offset, 0, 8, ent->viewheight-8);
P_ProjectSource(ent->client, ent->s.origin, offset, forward, right, start);
// get end position
VectorMA(start, 64, forward, end);
tr = gi.trace (start, NULL, NULL, end, ent, MASK_SOLID);
// can't build a laser on sky
if (tr.surface && (tr.surface->flags & SURF_SKY))
return;
if (tr.fraction == 1)
{
gi.cprintf(ent, PRINT_HIGH, "Too far from wall.\n");
return;
}
if (NearbyLasers(ent, tr.endpos))
{
gi.cprintf(ent, PRINT_HIGH, "Too close to another laser.\n");
return;
}
if (NearbyProxy(ent, tr.endpos))
{
gi.cprintf(ent, PRINT_HIGH, "Too close to a proxy grenade.\n");
return;
}
laser = G_Spawn();
grenade = G_Spawn();
// create the laser beam
laser->monsterinfo.level = ent->myskills.abilities[BUILD_LASER].current_level * skill_mult;
laser->dmg = LASER_INITIAL_DAMAGE+LASER_ADDON_DAMAGE*laser->monsterinfo.level;
laser->health = LASER_INITIAL_HEALTH+LASER_ADDON_HEALTH*laser->monsterinfo.level;
// nerf lasers in CTF and invasion
if (ctf->value || invasion->value)
laser->health *= 0.5;
laser->max_health = laser->health;
// set beam diameter
if (laser->monsterinfo.level >= 10)
laser->s.frame = 4;
else
laser->s.frame = 2;
laser->movetype = MOVETYPE_NONE;
laser->solid = SOLID_NOT;
laser->s.renderfx = RF_BEAM|RF_TRANSLUCENT;
laser->s.modelindex = 1; // must be non-zero
laser->s.sound = gi.soundindex ("world/laser.wav");
laser->classname = "laser";
laser->owner = ent; // link to player
laser->creator = grenade; // link to grenade
laser->s.skinnum = 0xf2f2f0f0; // red beam color
laser->think = laser_beam_think;
laser->nextthink = level.time + LASER_SPAWN_DELAY * delay_mult;
VectorCopy(ent->s.origin, laser->s.origin);
VectorCopy(tr.endpos, laser->s.old_origin);
VectorCopy(tr.endpos, laser->pos1); // beam origin
vectoangles(tr.plane.normal, laser->s.angles);
gi.linkentity(laser);
delay = LASER_TIMEOUT_DELAY+GetRandom(0, (int)(0.5*LASER_TIMEOUT_DELAY));
// laser times out faster in CTF because it's too strong
if (ctf->value || invasion->value)
delay *= 0.5;
// create the laser emmitter (grenade)
VectorCopy(tr.endpos, grenade->s.origin);
vectoangles(tr.plane.normal, grenade->s.angles);
grenade->movetype = MOVETYPE_NONE;
grenade->clipmask = MASK_SHOT;
grenade->solid = SOLID_BBOX;
VectorSet(grenade->mins, -3, -3, 0);
VectorSet(grenade->maxs, 3, 3, 6);
grenade->takedamage = DAMAGE_NO;
grenade->s.modelindex = gi.modelindex("models/objects/grenade2/tris.md2");
grenade->owner = ent; // link to player
grenade->creator = laser; // link to laser
grenade->classname = "emitter";
grenade->nextthink = level.time+delay; // time before self-destruct
grenade->think = laser_remove;
gi.linkentity(grenade);
// cost is doubled if you are a flyer or cacodemon below skill level 5
if ((ent->mtype == MORPH_FLYER && ent->myskills.abilities[FLYER].current_level < 5)
|| (ent->mtype == MORPH_CACODEMON && ent->myskills.abilities[CACODEMON].current_level < 5))
cost *= 2;
ent->num_lasers++;
gi.cprintf(ent, PRINT_HIGH, "Laser built. You have %d/%d lasers.\n", ent->num_lasers, MAX_LASERS);
ent->client->pers.inventory[power_cube_index] -= cost;
ent->client->ability_delay = level.time + 0.5 * delay_mult;
ent->holdtime = level.time + 0.5 * delay_mult;
//decino: firewall talent
talentLevel = getTalentLevel(ent, TALENT_PRECISION_TUNING);
if (talentLevel == 1)
grenade->firewall_weak = true;
if (talentLevel == 2)
grenade->firewall_medium = true;
if (talentLevel == 3)
grenade->firewall_strong = true;
ent->lastsound = level.framenum;
}
void Cmd_BuildLaser (edict_t *ent)
{
int talentLevel, cost=LASER_COST;
float skill_mult=1.0, cost_mult=1.0, delay_mult=1.0;//Talent: Rapid Assembly & Precision Tuning
if(ent->myskills.abilities[BUILD_LASER].disable)
return;
if (Q_strcasecmp (gi.args(), "remove") == 0)
{
RemoveLasers(ent);
gi.cprintf(ent, PRINT_HIGH, "All lasers removed.\n");
return;
}
// cost is doubled if you are a flyer or cacodemon below skill level 5
if ((ent->mtype == MORPH_FLYER && ent->myskills.abilities[FLYER].current_level < 5)
|| (ent->mtype == MORPH_CACODEMON && ent->myskills.abilities[CACODEMON].current_level < 5))
cost *= 2;
//Talent: Rapid Assembly
talentLevel = getTalentLevel(ent, TALENT_RAPID_ASSEMBLY);
if (talentLevel > 0)
delay_mult -= 0.167 * talentLevel;
cost *= cost_mult;
if (!G_CanUseAbilities(ent, ent->myskills.abilities[BUILD_LASER].current_level, cost))
return;
if (ent->num_lasers >= MAX_LASERS)
{
gi.cprintf(ent, PRINT_HIGH, "Can't build any more lasers.\n");
return;
}
if (ctf->value && (CTF_DistanceFromBase(ent, NULL, CTF_GetEnemyTeam(ent->teamnum)) < CTF_BASE_DEFEND_RANGE))
{
gi.cprintf(ent, PRINT_HIGH, "Can't build in enemy base!\n");
return;
}
SpawnLaser(ent, cost, skill_mult, delay_mult);
}
<file_sep>//************************************************************************************************
// String functions
//************************************************************************************************
void padRight(char *String, int numChars);
char *GetWeaponString (int weapon_number);
char *GetModString (int weapon_number, int mod_number);
void V_RestoreMorphed (edict_t *ent, int refund);
void V_RegenAbilityAmmo (edict_t *ent, int ability_index, int regen_frames, int regen_delay);
void V_Touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf);
void V_UpdatePlayerAbilities (edict_t *ent);
qboolean V_HealthCache (edict_t *ent, int max_per_second, int update_frequency);
qboolean V_ArmorCache (edict_t *ent, int max_per_second, int update_frequency);
void V_ResetPlayerState (edict_t *ent);
void V_TouchSolids (edict_t *ent);
qboolean V_HasSummons (edict_t *ent);
//************************************************************************************************<file_sep>/*
==============================================================================
TANK
==============================================================================
*/
#include "g_local.h"
#include "m_tank.h"
void mytank_refire_rocket (edict_t *self);
void mytank_doattack_rocket (edict_t *self);
void mytank_reattack_blaster (edict_t *self);
void mytank_meleeattack (edict_t *self);
void mytank_restrike (edict_t *self);
qboolean TeleportNearTarget (edict_t *self, edict_t *target, float dist);
void drone_ai_stand (edict_t *self, float dist);
void drone_ai_run (edict_t *self, float dist);
void mytank_chain_refire (edict_t *self);
void mytank_attack_chain (edict_t *self);
static int sound_thud;
static int sound_pain;
static int sound_idle;
static int sound_die;
static int sound_step;
static int sound_sight;
static int sound_windup;
static int sound_strike;
//
// misc
//
void mytank_footstep (edict_t *self)
{
gi.sound (self, CHAN_BODY, sound_step, 1, ATTN_NORM, 0);
}
void mytank_thud (edict_t *self)
{
gi.sound (self, CHAN_BODY, sound_thud, 1, ATTN_NORM, 0);
}
void mytank_windup (edict_t *self)
{
gi.sound (self, CHAN_WEAPON, sound_windup, 1, ATTN_NORM, 0);
}
void mytank_idle (edict_t *self)
{
int range;
vec3_t v;
//GHz: Commanders teleport back to owner
if ((self->s.skinnum & 2) && !(self->monsterinfo.aiflags & AI_STAND_GROUND))
{
VectorSubtract(self->activator->s.origin, self->s.origin, v);
range = VectorLength (v);
if (range > 256)
{
TeleportNearTarget (self, self->activator, 16);
}
}
gi.sound (self, CHAN_VOICE, sound_idle, 1, ATTN_IDLE, 0);
self->superspeed = false; //GHz: No more sliding
}
//
// stand
//
mframe_t mytank_frames_stand []=
{
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL
};
mmove_t mytank_move_stand = {FRAME_stand01, FRAME_stand30, mytank_frames_stand, NULL};
void mytank_stand (edict_t *self)
{
self->monsterinfo.currentmove = &mytank_move_stand;
}
//
// run
//
void mytank_run (edict_t *self);
mframe_t mytank_frames_start_run [] =
{
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, mytank_footstep
};
mmove_t mytank_move_start_run = {FRAME_walk01, FRAME_walk04, mytank_frames_start_run, mytank_run};
mframe_t mytank_frames_run [] =
{
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, mytank_footstep,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, NULL,
drone_ai_run, 15, mytank_footstep
};
mmove_t mytank_move_run = {FRAME_walk05, FRAME_walk20, mytank_frames_run, NULL};
void mytank_run (edict_t *self)
{
if (self->enemy && self->enemy->client)
self->monsterinfo.aiflags |= AI_BRUTAL;
else
self->monsterinfo.aiflags &= ~AI_BRUTAL;
if (self->monsterinfo.aiflags & AI_STAND_GROUND)
{
self->monsterinfo.currentmove = &mytank_move_stand;
return;
}
if (self->monsterinfo.currentmove == &mytank_move_start_run)
{
self->monsterinfo.currentmove = &mytank_move_run;
}
else
{
self->monsterinfo.currentmove = &mytank_move_start_run;
}
}
//
// attacks
//
void myTankRail (edict_t *self)
{
int flash_number, damage;
vec3_t forward, start;
if (self->s.frame == FRAME_attak110)
flash_number = MZ2_TANK_BLASTER_1;
else if (self->s.frame == FRAME_attak113)
flash_number = MZ2_TANK_BLASTER_2;
else
flash_number = MZ2_TANK_BLASTER_3;
damage = 50 + 5*self->monsterinfo.level;
MonsterAim(self, 0.5, 0, false, flash_number, forward, start);
monster_fire_railgun(self, start, forward, damage, damage, MZ2_GLADIATOR_RAILGUN_1);
}
void myTankBlaster (edict_t *self)
{
int flash_number, min, max, damage;
vec3_t forward, start;
// alternate attack for commander
if (self->s.skinnum & 2)
{
myTankRail(self);
return;
}
if (self->s.frame == FRAME_attak110)
flash_number = MZ2_TANK_BLASTER_1;
else if (self->s.frame == FRAME_attak113)
flash_number = MZ2_TANK_BLASTER_2;
else
flash_number = MZ2_TANK_BLASTER_3;
//if (!self->activator->client)
//{
// min = 2*self->monsterinfo.level;
// max = 200 + 38*self->monsterinfo.level;
//}
//else
//{
min = self->monsterinfo.level;
max = 100 + 19*self->monsterinfo.level;
//}
damage = GetRandom(min, max);
MonsterAim(self, 0.9, 1500, false, flash_number, forward, start);
monster_fire_blaster(self, start, forward, damage, 1500, EF_BLASTER, BLASTER_PROJ_BOLT, 2.0, true, flash_number);
}
void myTankStrike (edict_t *self)
{
gi.sound (self, CHAN_WEAPON, sound_strike, 1, ATTN_NORM, 0);
}
void myTankRocket (edict_t *self)
{
int flash_number, damage, speed;
vec3_t forward, start;
// sanity check
if (!self->enemy || !self->enemy->inuse)
return;
if (self->s.frame == FRAME_attak324)
flash_number = MZ2_TANK_ROCKET_1;
else if (self->s.frame == FRAME_attak327)
flash_number = MZ2_TANK_ROCKET_2;
else
flash_number = MZ2_TANK_ROCKET_3;
damage = 50 + 10*self->monsterinfo.level;
speed = 650 + 30*self->monsterinfo.level;
MonsterAim(self, 0.9, speed, true, flash_number, forward, start);
monster_fire_rocket (self, start, forward, damage, speed, flash_number);
}
void myTankMachineGun (edict_t *self)
{
vec3_t forward, start;
int flash_number, damage;
// sanity check
if (!self->enemy || !self->enemy->inuse)
return;
flash_number = MZ2_TANK_MACHINEGUN_1 + (self->s.frame - FRAME_attak406);
damage = 20 + 2*self->monsterinfo.level;
MonsterAim(self, 0.9, 0, false, flash_number, forward, start);
monster_fire_bullet (self, start, forward, damage, damage,
DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, flash_number);
}
mframe_t mytank_frames_attack_blast [] =
{
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, myTankBlaster, // 10
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, myTankBlaster,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, myTankBlaster // 16
};
mmove_t mytank_move_attack_blast = {FRAME_attak101, FRAME_attak116, mytank_frames_attack_blast, mytank_reattack_blaster};
mframe_t mytank_frames_reattack_blast [] =
{
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, myTankBlaster,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, myTankBlaster // 16
};
mmove_t mytank_move_reattack_blast = {FRAME_attak111, FRAME_attak116, mytank_frames_reattack_blast, mytank_reattack_blaster};
void mytank_delay (edict_t *self)
{
if (!self->enemy || !self->enemy->inuse)
return;
// delay next attack if we're not standing ground, our enemy isn't within rocket range
// (we need to get closer) and we are not a tank commander/boss
if (!(self->monsterinfo.aiflags & AI_STAND_GROUND) && (entdist(self, self->enemy) > 512)
&& (self->monsterinfo.control_cost < 3))
self->monsterinfo.attack_finished = level.time + GetRandom(20, 30)*FRAMETIME;
}
mframe_t mytank_frames_attack_post_blast [] =
{
ai_move, 0, NULL, // 17
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,//mytank_delay,
ai_move, 0, mytank_footstep // 22
};
mmove_t mytank_move_attack_post_blast = {FRAME_attak117, FRAME_attak122, mytank_frames_attack_post_blast, mytank_run};
void mytank_reattack_blaster (edict_t *self)
{
if (G_ValidTarget(self, self->enemy, true) && (random() <= 0.9)
&& (entdist(self, self->enemy) <= 512))
self->monsterinfo.currentmove = &mytank_move_reattack_blast;
else
self->monsterinfo.currentmove = &mytank_move_attack_post_blast;
// don't call the attack function again for awhile!
self->monsterinfo.attack_finished = level.time + 2;
}
void mytank_poststrike (edict_t *self)
{
self->enemy = NULL;
mytank_run (self);
}
mframe_t mytank_frames_attack_strike [] =
{
ai_move, 3, NULL,
ai_move, 2, NULL,
ai_move, 2, NULL,
ai_move, 1, NULL,
ai_move, 6, NULL,
ai_move, 7, NULL,
ai_move, 9, mytank_footstep,
ai_move, 2, NULL,
ai_move, 1, NULL,
ai_move, 2, NULL,
ai_move, 2, mytank_footstep,
ai_move, 2, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, -2, NULL,
ai_move, -2, NULL,
ai_move, 0, mytank_windup,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, myTankStrike,
ai_move, 0, NULL,
ai_move, -1, NULL,
ai_move, -1, NULL,
ai_move, -1, NULL,
ai_move, -1, NULL,
ai_move, -1, NULL,
ai_move, -3, NULL,
ai_move, -10, NULL,
ai_move, -10, NULL,
ai_move, -2, NULL,
ai_move, -3, NULL,
ai_move, -2, mytank_footstep
};
mmove_t mytank_move_attack_strike = {FRAME_attak201, FRAME_attak238, mytank_frames_attack_strike, mytank_poststrike};
mframe_t mytank_frames_strike [] =
{
//ai_move, 0, mytank_windup,
//ai_move, 0, NULL,
//ai_move, 0, NULL,
ai_move, 0, mytank_windup,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, mytank_meleeattack,
};
mmove_t mytank_move_strike = {FRAME_attak222, FRAME_attak226, mytank_frames_strike, mytank_restrike};
mframe_t mytank_frames_post_strike [] =
{
ai_move, 0, NULL,
ai_move, -1, NULL,
ai_move, -1, NULL,
ai_move, -1, NULL,
ai_move, -1, NULL,
ai_move, -1, NULL,
ai_move, -3, NULL,
ai_move, -10, NULL,
ai_move, -10, NULL,
ai_move, -2, NULL,
ai_move, -3, NULL,//mytank_delay,
ai_move, -2, mytank_footstep
};
mmove_t mytank_move_post_strike = {FRAME_attak227, FRAME_attak238, mytank_frames_post_strike, mytank_run};
mframe_t mytank_frames_attack_pre_rocket [] =
{
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL, // 10
ai_charge, 0, NULL,
ai_charge, 1, NULL,
ai_charge, 2, NULL,
ai_charge, 7, NULL,
ai_charge, 7, NULL,
ai_charge, 7, mytank_footstep,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL, // 20
ai_charge, -3, NULL
};
mmove_t mytank_move_attack_pre_rocket = {FRAME_attak301, FRAME_attak321, mytank_frames_attack_pre_rocket, mytank_doattack_rocket};
mframe_t mytank_frames_attack_fire_rocket [] =
{
ai_charge, 0, NULL, // Loop Start 22
ai_charge, 0, NULL,
ai_charge, 0, myTankRocket, // 24
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, myTankRocket,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, myTankRocket // 30 Loop End
};
mmove_t mytank_move_attack_fire_rocket = {FRAME_attak322, FRAME_attak330, mytank_frames_attack_fire_rocket, mytank_refire_rocket};
mframe_t mytank_frames_attack_post_rocket [] =
{
ai_charge, 0, NULL, // 31
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL, // 40
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, mytank_footstep,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL, // 50
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, mytank_delay
};
mmove_t mytank_move_attack_post_rocket = {FRAME_attak331, FRAME_attak353, mytank_frames_attack_post_rocket, mytank_run};
mframe_t mytank_frames_attack_chain_start [] =
{
ai_charge, 0, NULL, // 168
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL // 172
};
mmove_t mytank_move_attack_chain_start = {FRAME_attak401, FRAME_attak405, mytank_frames_attack_chain_start, mytank_attack_chain};
mframe_t mytank_frames_attack_chain_end [] =
{
ai_charge, 0, NULL, // 192
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, NULL,
ai_charge, 0, mytank_delay // 196
};
mmove_t mytank_move_attack_chain_end = {FRAME_attak425, FRAME_attak429, mytank_frames_attack_chain_end, mytank_run};
mframe_t mytank_frames_attack_chain [] =
{
ai_charge, 0, myTankMachineGun, // 173
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun,
ai_charge, 0, myTankMachineGun // 191
};
mmove_t mytank_move_attack_chain = {FRAME_attak406, FRAME_attak424, mytank_frames_attack_chain, mytank_chain_refire};
void mytank_attack_chain (edict_t *self)
{
// continue attack sequence unless enemy is no longer valid
if (G_ValidTarget(self, self->enemy, true))
self->monsterinfo.currentmove = &mytank_move_attack_chain;
else
mytank_run(self);
}
void mytank_chain_refire (edict_t *self)
{
// continue firing unless enemy is no longer valid
if (G_ValidTarget(self, self->enemy, true) && (random() <= 0.8))
{
self->monsterinfo.currentmove = &mytank_move_attack_chain;
return;
}
// end attack sequence
self->monsterinfo.currentmove = &mytank_move_attack_chain_end;
}
void mytank_restrike (edict_t *self)
{
if (G_ValidTarget(self, self->enemy, true) && (random() <= 0.6)
&& (entdist(self, self->enemy) < 128))
self->monsterinfo.currentmove = &mytank_move_strike;
else
self->monsterinfo.currentmove = &mytank_move_post_strike;
}
void mytank_refire_rocket (edict_t *self)
{
if (G_ValidTarget(self, self->enemy, true) && (random() <= 0.9)
&& (entdist(self, self->enemy) <= 512))
{
self->monsterinfo.currentmove = &mytank_move_attack_fire_rocket;
return;
}
// end attack sequence
self->monsterinfo.currentmove = &mytank_move_attack_post_rocket;
}
void mytank_doattack_rocket (edict_t *self)
{
self->monsterinfo.currentmove = &mytank_move_attack_fire_rocket;
}
void mytank_melee (edict_t *self)
{
if (entdist(self, self->enemy) <= 96)
self->monsterinfo.currentmove = &mytank_move_strike;
}
void mytank_meleeattack (edict_t *self)
{
int damage;
trace_t tr;
edict_t *other=NULL;
vec3_t v;
// tank must be on the ground to punch
if (!self->groundentity)
return;
self->lastsound = level.framenum;
damage = 100+20*self->monsterinfo.level;
gi.sound (self, CHAN_AUTO, gi.soundindex ("tank/tnkatck5.wav"), 1, ATTN_NORM, 0);
while ((other = findradius(other, self->s.origin, 128)) != NULL)
{
if (!G_ValidTarget(self, other, true))
continue;
// bosses don't have to be facing their enemy, others do
//if ((self->monsterinfo.control_cost < 3) && !nearfov(self, other, 0, 60))//!infront(self, other))
// continue;
VectorSubtract(other->s.origin, self->s.origin, v);
VectorNormalize(v);
tr = gi.trace(self->s.origin, NULL, NULL, other->s.origin, self, (MASK_PLAYERSOLID | MASK_MONSTERSOLID));
T_Damage (other, self, self, v, tr.endpos, tr.plane.normal, damage, 200, 0, MOD_TANK_PUNCH);
//other->velocity[2] += 200;//damage / 2;
}
}
/*
void mytank_meleeattack (edict_t *self)
{
int damage;
vec3_t v;
edict_t *other = NULL;
trace_t tr;
if (!self->enemy)
return;
if (!self->enemy->inuse)
return;
if (self->enemy->health <= 0)
return;
damage = 100 + 20*self->monsterinfo.level;
while ((other = findradius(other, self->s.origin, 256)) != NULL)
{
if (other == self)
continue;
if (!other->inuse)
continue;
if (!other->takedamage)
continue;
if (other->solid == SOLID_NOT)
continue;
if (!other->groundentity)
continue;
if (OnSameTeam(self, other))
continue;
if (!visible(self, other))
continue;
VectorSubtract(other->s.origin, self->s.origin, v);
VectorNormalize(v);
tr = gi.trace(self->s.origin, NULL, NULL, other->s.origin, self, (MASK_PLAYERSOLID | MASK_MONSTERSOLID));
T_Damage (other, self, self, v, other->s.origin, tr.plane.normal, damage, damage, 0, MOD_UNKNOWN);
other->velocity[2] += damage / 2;
}
myTankStrike(self);
}
*/
/*
qboolean TeleportNearTarget (edict_t *self, edict_t *target)
{
int x;
vec3_t forward, right, start, point, dir;
trace_t tr;
//GHz: Get starting position and relative angles
VectorCopy(target->s.origin, start);
start[2]++;
AngleVectors(self->s.angles, forward, right, NULL);
for (x = 0; x < 4; x++)
{
//GHz: Get direction
switch (x)
{
case 0: VectorCopy(forward, dir);break;
case 1: VectorCopy(right, dir);break;
case 2: VectorInverse(forward);VectorCopy(forward, dir);break;
case 3: VectorInverse(right);VectorCopy(right, dir);break;
}
//GHz: Check target for valid spot
VectorMA(start, 75, dir, start);
tr = gi.trace(start, self->mins, self->maxs, start, target, MASK_SHOT);
if (!(tr.contents & MASK_SHOT))
{
//GHz: Check for spot for landing
VectorCopy(start, point);
point[2] -= 32;
tr = gi.trace(start, NULL, NULL, point, NULL, MASK_SHOT);
if (tr.fraction != 1.0)
{
//self->s.event = EV_PLAYER_TELEPORT;
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_BOSSTPORT);
gi.WritePosition (self->s.origin);
gi.multicast (self->s.origin, MULTICAST_PVS);
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_BOSSTPORT);
gi.WritePosition (start);
gi.multicast (start, MULTICAST_PVS);
VectorCopy(start, self->s.origin);
return true;
}
}
}
return false;
}
*/
void mytank_attack (edict_t *self)
{
float r, range;
r = random();
range = entdist(self, self->enemy);
// melee attack
if ((range < 128) && self->enemy->groundentity && (r <= 0.8))
{
self->monsterinfo.currentmove = &mytank_move_strike;
return;
}
// commander tank tries to teleport close to launch a melee attack
if ((self->s.skinnum & 2) && !(self->monsterinfo.aiflags & AI_STAND_GROUND))
{
if (TeleportNearTarget(self, self->enemy, 16))
{
if (self->enemy->groundentity && (r <= 0.8))
self->monsterinfo.currentmove = &mytank_move_strike;
else
self->monsterinfo.currentmove = &mytank_move_attack_fire_rocket;
return;
}
}
if (range <= 512)
{
if (r <= 0.2)
self->monsterinfo.currentmove = &mytank_move_attack_chain;
//else if (r <= 0.3)
// self->monsterinfo.currentmove = &mytank_move_attack_blast;
else
self->monsterinfo.currentmove = &mytank_move_attack_fire_rocket;
}
// alternate attack pattern for commander
else if (self->s.skinnum & 2)
{
if (r <= 0.1)
self->monsterinfo.currentmove = &mytank_move_attack_fire_rocket;
else if (r <= 0.3)
self->monsterinfo.currentmove = &mytank_move_attack_chain;
else
self->monsterinfo.currentmove = &mytank_move_attack_blast; // rails
}
else
{
if (r <= 0.2)
self->monsterinfo.currentmove = &mytank_move_attack_fire_rocket;
// else if (r <= 0.3)
// self->monsterinfo.currentmove = &mytank_move_attack_blast;
else
self->monsterinfo.currentmove = &mytank_move_attack_chain;
}
}
void mytank_sight (edict_t *self, edict_t *other)
{
gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
mytank_attack(self);
}
//
// death
//
void mytank_dead (edict_t *self)
{
VectorSet (self->mins, -16, -16, -16);
VectorSet (self->maxs, 16, 16, -0);
self->movetype = MOVETYPE_TOSS;
self->svflags |= SVF_DEADMONSTER;
//self->nextthink = 0;
gi.linkentity (self);
M_PrepBodyRemoval(self);
}
mframe_t mytank_frames_death1 [] =
{
ai_move, -7, NULL,
ai_move, -2, NULL,
ai_move, -2, NULL,
ai_move, 1, NULL,
ai_move, 3, NULL,
ai_move, 6, NULL,
ai_move, 1, NULL,
ai_move, 1, NULL,
ai_move, 2, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, -2, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, -3, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, -4, NULL,
ai_move, -6, NULL,
ai_move, -4, NULL,
ai_move, -5, NULL,
ai_move, -7, NULL,
ai_move, -15, mytank_thud,
ai_move, -5, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL
};
mmove_t mytank_move_death = {FRAME_death101, FRAME_death132, mytank_frames_death1, mytank_dead};
void mytank_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
{
int n;
M_Notify(self);
// reduce lag by removing the entity right away
if (nolag->value)
{
M_Remove(self, false, true);
return;
}
// check for gibbed body
if (self->health <= self->gib_health)
{
gi.sound (self, CHAN_VOICE, gi.soundindex ("misc/udeath.wav"), 1, ATTN_NORM, 0);
for (n= 0; n < 1; n++)
ThrowGib (self, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC);
for (n= 0; n < 4; n++)
ThrowGib (self, "models/objects/gibs/sm_metal/tris.md2", damage, GIB_METALLIC);
ThrowGib (self, "models/objects/gibs/chest/tris.md2", damage, GIB_ORGANIC);
//ThrowHead (self, "models/objects/gibs/gear/tris.md2", damage, GIB_METALLIC);
//self->deadflag = DEAD_DEAD;
M_Remove(self, false, false);
return;
}
if (self->deadflag == DEAD_DEAD)
return;
// begin death sequence
gi.sound (self, CHAN_VOICE, sound_die, 1, ATTN_NORM, 0);
self->deadflag = DEAD_DEAD;
self->takedamage = DAMAGE_YES;
self->monsterinfo.currentmove = &mytank_move_death;
}
//
// monster_tank
//
/*QUAKED monster_tank (1 .5 0) (-32 -32 -16) (32 32 72) Ambush Trigger_Spawn Sight
*/
/*QUAKED monster_mytank_commander (1 .5 0) (-32 -32 -16) (32 32 72) Ambush Trigger_Spawn Sight
*/
void init_drone_tank (edict_t *self)
{
// if (deathmatch->value)
// {
// G_FreeEdict (self);
// return;
// }
self->s.modelindex = gi.modelindex ("models/monsters/tank/tris.md2");
VectorSet (self->mins, -24, -24, -16);
VectorSet (self->maxs, 24, 24, 64);
self->movetype = MOVETYPE_STEP;
self->solid = SOLID_BBOX;
sound_pain = gi.soundindex ("tank/tnkpain2.wav");
sound_thud = gi.soundindex ("tank/tnkdeth2.wav");
sound_idle = gi.soundindex ("tank/tnkidle1.wav");
sound_die = gi.soundindex ("tank/death.wav");
sound_step = gi.soundindex ("tank/step.wav");
sound_windup = gi.soundindex ("tank/tnkatck4.wav");
sound_strike = gi.soundindex ("tank/tnkatck5.wav");
sound_sight = gi.soundindex ("tank/sight1.wav");
gi.soundindex ("tank/tnkatck1.wav");
gi.soundindex ("tank/tnkatk2a.wav");
gi.soundindex ("tank/tnkatk2b.wav");
gi.soundindex ("tank/tnkatk2c.wav");
gi.soundindex ("tank/tnkatk2d.wav");
gi.soundindex ("tank/tnkatk2e.wav");
gi.soundindex ("tank/tnkatck3.wav");
// if (self->activator && self->activator->client)
self->health = 100 + 65*self->monsterinfo.level;
//else self->health = 100 + 65*self->monsterinfo.level;
self->max_health = self->health;
self->gib_health = -200;
//if (self->activator && self->activator->client)
self->monsterinfo.power_armor_power = 200 + 105*self->monsterinfo.level;
//else self->monsterinfo.power_armor_power = 200 + 105*self->monsterinfo.level;
self->monsterinfo.power_armor_type = POWER_ARMOR_SHIELD;
self->monsterinfo.max_armor = self->monsterinfo.power_armor_power;
self->monsterinfo.control_cost = M_TANK_CONTROL_COST;
self->monsterinfo.cost = M_TANK_COST;
self->mtype = M_TANK;
if (random() > 0.5)
self->item = FindItemByClassname("ammo_bullets");
else
self->item = FindItemByClassname("ammo_rockets");
self->mass = 500;
//self->pain = mytank_pain;
self->die = mytank_die;
//self->touch = mytank_touch;
self->monsterinfo.stand = mytank_stand;
//self->monsterinfo.walk = mytank_walk;
self->monsterinfo.run = mytank_run;
self->monsterinfo.dodge = NULL;
self->monsterinfo.attack = mytank_attack;
//self->monsterinfo.melee = mytank_melee;
self->monsterinfo.sight = mytank_sight;
self->monsterinfo.idle = mytank_idle;
self->monsterinfo.jumpup = 64;
self->monsterinfo.jumpdn = 512;
self->monsterinfo.aiflags |= AI_NO_CIRCLE_STRAFE;
//self->monsterinfo.melee = 1;
gi.linkentity (self);
self->monsterinfo.currentmove = &mytank_move_stand;
self->monsterinfo.scale = MODEL_SCALE;
// walkmonster_start(self);
self->nextthink = level.time + FRAMETIME;
// self->activator->num_monsters += self->monsterinfo.control_cost;
}
void init_drone_commander (edict_t *self)
{
init_drone_tank(self);
// modify health and armor
self->health = 1000*self->monsterinfo.level;
self->max_health = self->health;
self->monsterinfo.power_armor_power = 1000*self->monsterinfo.level;
self->monsterinfo.max_armor = self->monsterinfo.power_armor_power;
self->monsterinfo.control_cost = 4;
self->monsterinfo.cost = M_COMMANDER_COST;
self->mtype = M_COMMANDER;
self->s.skinnum = 2;
if (!self->activator->client)
G_PrintGreenText(va("A level %d tank commander has spawned!", self->monsterinfo.level));
}
<file_sep>#include "g_local.h"
// v3.12
qboolean InMenu (edict_t *ent,int index, void (*optionselected)(edict_t *ent,int option))
{
// don't need to be here if there's no menu open!
if (!ent->client->menustorage.menu_active)
return false;
// check for index, only necessary if 2 funcs are exactly the same
if (index && (ent->client->menustorage.menu_index != index))
return false;
// check if we're using the right handler
return (ent->client->menustorage.optionselected == optionselected);
}
void addlinetomenu (edict_t *ent,char *line,int option)
{
if (ent->client->menustorage.menu_active) // checks to see if the menu is showing
return;
if (ent->client->menustorage.num_of_lines >= MAX_LINES) // checks to see if there is space
return;
ent->client->menustorage.num_of_lines++; // adds to the number of lines that can be seen
ent->client->menustorage.messages[ent->client->menustorage.num_of_lines].msg = gi.TagMalloc (strlen(line)+1, TAG_GAME);
strcpy(ent->client->menustorage.messages[ent->client->menustorage.num_of_lines].msg, line);
ent->client->menustorage.messages[ent->client->menustorage.num_of_lines].option = option;
}
void clearmenu(edict_t *ent)
{
int i = 0;
if (ent->client->menustorage.menu_active) // checks to see if the menu is showing
return;
for (i = 0; i < MAX_LINES; i++){
ent->client->menustorage.messages[i].option = 0;
if (ent->client->menustorage.messages[i].msg != NULL){
gi.TagFree (ent->client->menustorage.messages[i].msg);
//GHz START
ent->client->menustorage.messages[i].msg = NULL;
//GHz END
}
}
//GHz START
// keep record of last known menu for multi-purpose menus that have more than one handler
if (ent->client->menustorage.optionselected)
ent->client->menustorage.oldmenuhandler = ent->client->menustorage.optionselected;
if (ent->client->menustorage.currentline)
ent->client->menustorage.oldline = ent->client->menustorage.currentline;
//GHz END
ent->client->menustorage.optionselected = NULL;
ent->client->menustorage.currentline = 0;
ent->client->menustorage.num_of_lines = 0;
ent->client->menustorage.menu_index = 0; // 3.45
}
void tradeconfirmation_handler (edict_t *ent, int option);
void itemmenu_handler (edict_t *ent, int option);
void setmenuhandler(edict_t *ent, void (*optionselected)(edict_t *ent,int option))
{
ent->client->menustorage.optionselected=optionselected;
}
//GHz START
int topofmenu (edict_t *ent)
{
int i, option;
for (i = 0; i < MAX_LINES; i++){
option = ent->client->menustorage.messages[i].option;
if (option != 0 && option != MENU_GREEN_CENTERED && option != MENU_WHITE_CENTERED && option != MENU_GREEN_LEFT)
break;
}
return i;
}
int bottomofmenu (edict_t *ent)
{
int i, option;
for (i = MAX_LINES-1; i > 0; i--){
option = ent->client->menustorage.messages[i].option;
if (option != 0 && option != MENU_GREEN_CENTERED && option != MENU_WHITE_CENTERED && option != MENU_GREEN_LEFT)
break;
}
return i;
}
//GHz END
void menudown(edict_t *ent)
{
int option;
// 3.65 avoid menu overflows
if (ent->client->menu_delay > level.time)
return;
ent->client->menu_delay = level.time + MENU_DELAY_TIME;
do
{
if (ent->client->menustorage.currentline < ent->client->menustorage.num_of_lines)
ent->client->menustorage.currentline++;
else
ent->client->menustorage.currentline = topofmenu(ent);
option = ent->client->menustorage.messages[ent->client->menustorage.currentline].option;
}
while (option == 0 || option == MENU_WHITE_CENTERED || option == MENU_GREEN_CENTERED
|| option == MENU_GREEN_RIGHT || option == MENU_GREEN_LEFT);
showmenu(ent);
}
void menuup(edict_t *ent)
{
int option;
// 3.65 avoid menu overflows
if (ent->client->menu_delay > level.time)
return;
ent->client->menu_delay = level.time + MENU_DELAY_TIME;
do
{
if (ent->client->menustorage.currentline > topofmenu(ent))
ent->client->menustorage.currentline--;
else
ent->client->menustorage.currentline = bottomofmenu(ent);
option = ent->client->menustorage.messages[ent->client->menustorage.currentline].option;
}
while (option == 0 || option == MENU_WHITE_CENTERED || option == MENU_GREEN_CENTERED
|| option == MENU_GREEN_RIGHT || option == MENU_GREEN_LEFT);
showmenu(ent);
}
/*
=============
menuselect
calls the menu handler with the currently selected option
=============
*/
void menuselect(edict_t *ent)
{
int i;
//GHz START
if (debuginfo->value)
gi.dprintf("DEBUG: menuselect()\n");
//GHz END
i = ent->client->menustorage.messages[ent->client->menustorage.currentline].option;
closemenu(ent); // close the menu as a selection has been made
// call the menu handler with the current option value
ent->client->menustorage.optionselected(ent, i);
// gi.dprintf("menuselect() at line %d\n", ent->client->menustorage.currentline);
}
/*
=============
initmenu
clears all menus for this client
=============
*/
void initmenu (edict_t *ent)
{
int i;
for (i = 0;i < MAX_LINES;i++){
ent->client->menustorage.messages[i].msg = NULL;
ent->client->menustorage.messages[i].option = 0;
}
ent->client->menustorage.menu_active = false;
ent->client->menustorage.displaymsg = false;
ent->client->menustorage.optionselected = NULL;
ent->client->menustorage.currentline = 0;
ent->client->menustorage.num_of_lines = 0;
ent->client->menustorage.menu_index = 0; // 3.45
}
/*
=============
ShowMenu
used every frame to display a player's menu
=============
*/
void showmenu(edict_t *ent)
{
int i, j; // general purpose integer for temporary use :)
char finalmenu[1024]; // where the control strings for the menu are assembled.
char tmp[80]; // temporary storage strings
int center;
if (debuginfo->value)
gi.dprintf("DEBUG: showmenu()\n");
if ((ent->client->menustorage.num_of_lines < 1) || (ent->client->menustorage.num_of_lines > MAX_LINES))
{
gi.dprintf("WARNING: showmenu() called with %d lines\n", ent->client->menustorage.num_of_lines);
return;
}
// copy menu bg control strings to our final menu
sprintf (finalmenu, "xv 32 yv 8 picn inventory ");
// get y coord of text based on the number of lines we want to create
// this keeps the text vertically centered on our screen
j = 24 + LINE_SPACING*(ceil((float)(20-ent->client->menustorage.num_of_lines) / 2));
// cycle through all lines and add their control codes to our final menu
// nothing is actually displayed until the very end
for (i = 1;i < (ent->client->menustorage.num_of_lines + 1); i++)
{
// get x coord of screen based on the length of the string for
// text that should be centered
center = 216/2 - strlen(ent->client->menustorage.messages[i].msg)*4 + 52;
if (ent->client->menustorage.messages[i].option == 0)// print white text
{
sprintf(tmp,"xv 52 yv %i string \"%s\" ",j,ent->client->menustorage.messages[i].msg);
}
else if (ent->client->menustorage.messages[i].option == MENU_GREEN_LEFT)// print green text
{
sprintf(tmp,"xv 52 yv %i string2 \"%s\" ",j,ent->client->menustorage.messages[i].msg);
}
else if (ent->client->menustorage.messages[i].option == MENU_GREEN_CENTERED)// print centered green text
{
sprintf(tmp,"xv %d yv %i string2 \"%s\" ", center, j, ent->client->menustorage.messages[i].msg);
}
else if (ent->client->menustorage.messages[i].option == MENU_WHITE_CENTERED)// print centered white text
{
sprintf(tmp,"xv %d yv %i string \"%s\" ", center, j, ent->client->menustorage.messages[i].msg);
}
else if (ent->client->menustorage.messages[i].option == MENU_GREEN_RIGHT)// print right-aligned green text
{
center = 216 - strlen(ent->client->menustorage.messages[i].msg)*8 + 52;
sprintf(tmp,"xv %d yv %i string2 \"%s\" ", center, j, ent->client->menustorage.messages[i].msg);
}
else if (i == ent->client->menustorage.currentline)
{
sprintf(tmp,"xv 52 yv %i string2 \">> %s\" ",j,ent->client->menustorage.messages[i].msg);
}
else
sprintf(tmp,"xv 52 yv %i string \" %s\" ",j,ent->client->menustorage.messages[i].msg);
// add the control string to our final menu space
strcat(finalmenu, tmp);
j += LINE_SPACING;
}
// actually display the final menu
ent->client->menustorage.menu_active = true;
ent->client->menustorage.displaymsg = false;
ent->client->showinventory = false;
ent->client->showscores = true;
gi.WriteByte (svc_layout);
gi.WriteString (finalmenu);
gi.unicast (ent, true);
//gi.dprintf("showmenu() at line %d\n", ent->client->menustorage.currentline);
}
void closemenu (edict_t *ent)
{
if (debuginfo->value)
gi.dprintf("DEBUG: closemenu()\n");
clearmenu(ent); // reset all menu variables and strings
ent->client->showscores = false;
ent->client->menustorage.menu_active = false;
ent->client->menustorage.displaymsg = false;
ent->client->showinventory = false;
ent->client->trading = false; // done trading
}
/*
=============
clearallmenus
cycles thru all clients and resets their menus
=============
*/
void clearallmenus (void)
{
int i;
edict_t *ent;
for (i=0 ; i < game.maxclients ; i++)
{
ent = g_edicts + 1 + i;
closemenu(ent);
}
}
/*
=============
ShowMenu
returns false if the client has another menu open
=============
*/
qboolean ShowMenu (edict_t *ent)
{
if (ent->client->showscores || ent->client->showinventory || ent->client->showbuffs
|| ent->client->menustorage.menu_active || ent->client->pers.scanner_active)
return false;
return true;
}
<file_sep>#ifndef SHAMAN_H
#define SHAMAN_H
#define SHAMAN_CURSE_RADIUS_BASE 512
#define SHAMAN_CURSE_RADIUS_BONUS 0
#define CURSE_DEFAULT_INITIAL_RADIUS 256
#define CURSE_DEFAULT_ADDON_RADIUS 0
#define CURSE_DEFAULT_INITIAL_RANGE 512
#define CURSE_DEFAULT_ADDON_RANGE 0
//************************************************************
// Mind Absorb (passive skill)
//************************************************************
#define MIND_ABSORB_RADIUS_BASE 256
#define MIND_ABSORB_RADIUS_BONUS 0
#define MIND_ABSORB_AMOUNT_BASE 0
#define MIND_ABSORB_AMOUNT_BONUS 10
//************************************************************
// Lower Resist (Curse)
//************************************************************
#define LOWER_RESIST_INITIAL_RANGE 512
#define LOWER_RESIST_ADDON_RANGE 0
#define LOWER_RESIST_INITIAL_RADIUS 256
#define LOWER_RESIST_ADDON_RADIUS 0
#define LOWER_RESIST_INITIAL_DURATION 0
#define LOWER_RESIST_ADDON_DURATION 1.0
#define LOWER_RESIST_COST 50
#define LOWER_RESIST_DELAY 1.0
#define LOWER_RESIST_INITIAL_FACTOR 0.25
#define LOWER_RESIST_ADDON_FACTOR 0.025
//************************************************************
// Amp Damage (Curse)
//************************************************************
#define AMP_DAMAGE_DELAY 2
#define AMP_DAMAGE_DURATION_BASE 0
#define AMP_DAMAGE_DURATION_BONUS 1.0
#define AMP_DAMAGE_COST 50
#define AMP_DAMAGE_MULT_BASE 1.5
#define AMP_DAMAGE_MULT_BONUS 0.1
//************************************************************
// Weaken (Curse)
// Weaken causes target to take extra damage, deal less damage
// and slows them down
//************************************************************
#define WEAKEN_DELAY 2
#define WEAKEN_DURATION_BASE 0
#define WEAKEN_DURATION_BONUS 1.0
#define WEAKEN_COST 50
#define WEAKEN_MULT_BASE 1.25
#define WEAKEN_MULT_BONUS 0.025
#define WEAKEN_SLOW_BASE 0
#define WEAKEN_SLOW_BONUS 0.1
//************************************************************
// Iron Maiden (Curse)
//************************************************************
//#define IRON_MAIDEN_DELAY 2
//#define IRON_MAIDEN_DURATION_BASE 2
//#define IRON_MAIDEN_DURATION_BONUS 0.5
//#define IRON_MAIDEN_COST 50
//#define IRON_MAIDEN_BONUS 0.66 //damage multiplier
//************************************************************
// Life Drain (Curse)
//************************************************************
#define LIFE_DRAIN_DELAY 2
#define LIFE_DRAIN_COST 50
#define LIFE_DRAIN_HEALTH 1 //this was 10
#define LIFE_DRAIN_DURATION_BASE 0
#define LIFE_DRAIN_DURATION_BONUS 1.0
#define LIFE_DRAIN_RANGE 256
#define LIFE_DRAIN_UPDATETIME 0.1 //this was 0.1
//************************************************************
// Amnesia (Curse)
//************************************************************
#define AMNESIA_DELAY 2
#define AMNESIA_DURATION_BASE 0
#define AMNESIA_DURATION_BONUS 2
#define AMNESIA_COST 50
//************************************************************
// Curse (Curse)
//************************************************************
#define CURSE_DELAY 2
#define CURSE_DURATION_BASE 0
#define CURSE_DURATION_BONUS 1
#define CURSE_COST 25
//************************************************************
// Healing (Blessing)
//************************************************************
#define HEALING_DELAY 2
#define HEALING_DURATION_BASE 10.5 //allow for 10 "ticks"
#define HEALING_DURATION_BONUS 0
#define HEALING_COST 50
#define HEALING_HEAL_BASE 0
#define HEALING_HEAL_BONUS 1
//************************************************************
// Bless (Blessing)
//************************************************************
#define BLESS_DELAY 0
#define BLESS_DURATION_BASE 0
#define BLESS_DURATION_BONUS 0.5
#define BLESS_COST 50
#define BLESS_BONUS 1.5 //Damage / Defense
#define BLESS_MAGIC_BONUS 1.5
//************************************************************
// Deflect (Blessing)
//************************************************************
#define DEFLECT_INITIAL_DURATION 0
#define DEFLECT_ADDON_DURATION 1.0
#define DEFLECT_COST 50
#define DEFLECT_DELAY 2.0
#define DEFLECT_INITIAL_HITSCAN_CHANCE 0.1
#define DEFLECT_ADDON_HITSCAN_CHANCE 0.023
#define DEFLECT_INITIAL_PROJECTILE_CHANCE 0.1
#define DEFLECT_ADDON_PROJECTILE_CHANCE 0.023
#define DEFLECT_MAX_PROJECTILE_CHANCE 0.33
#define DEFLECT_MAX_HITSCAN_CHANCE 0.33
#define DEFLECT_HITSCAN_ABSORB_BASE 1.0
#define DEFLECT_HITSCAN_ABSORB_ADDON 0
#define DEFLECT_HITSCAN_ABSORB_MAX 1.0
//************************************************************
void Cmd_AmpDamage(edict_t *ent);
void Cmd_Weaken(edict_t *ent);
void Cmd_Slave(edict_t *ent);
void Cmd_Amnesia(edict_t *ent);
void Cmd_Curse(edict_t *ent);
void Cmd_Bless(edict_t *ent);
void Cmd_Healing(edict_t *ent);
void MindAbsorb(edict_t *ent);
void CursedPlayer (edict_t *ent);
void CurseEffects (edict_t *self, int num, int color);
void Cmd_LifeDrain(edict_t *ent);
void LifeDrain (edict_t *ent);
void Bleed (edict_t *curse);
void Cmd_LowerResist (edict_t *ent);
#endif<file_sep>#define CACODEMON_SKULL_REGEN_FRAMES 250
#define CACODEMON_SKULL_REGEN_DELAY 50
#define MELEE_HIT_NOTHING 0
#define MELEE_HIT_ENT 1
#define MELEE_HIT_WORLDSPAWN 2
void RunFlyerFrames (edict_t *ent, usercmd_t *ucmd);
void Cmd_PlayerToFlyer_f (edict_t *ent);
void RunParasiteFrames (edict_t *ent, usercmd_t *ucmd);
void Cmd_PlayerToParasite_f (edict_t *ent);
void RunCacodemonFrames (edict_t *ent, usercmd_t *ucmd);
void Cmd_PlayerToCacodemon_f (edict_t *ent);
void Cmd_PlayerToMutant_f (edict_t *ent);
void RunMutantFrames (edict_t *ent, usercmd_t *ucmd);
void Cmd_PlayerToBrain_f (edict_t *ent);
void mutant_boost (edict_t *ent);
void boss_makron_spawn (edict_t *ent);
void MorphRegenerate (edict_t *ent, int regen_delay, int regen_frames);
void Cmd_PlayerToMedic_f (edict_t *ent);
void RunMedicFrames (edict_t *ent, usercmd_t *ucmd);
void RunBerserkFrames (edict_t *ent, usercmd_t *ucmd);
void Cmd_PlayerToBerserk_f (edict_t *ent);
<file_sep>#include "g_local.h"
#include "bot.h"
#include "mysql/mysql.h"
#define DEFALT_SQL_STMT "select * from deathmatch"
MYSQL myData;
qboolean connected_to_gds=true;
int mysql_processes=0;
void Print_ConnectionGDS(edict_t *ent)
{
//if (!(ent->svflags & SVF_MONSTER) && gds_uselocal->value != 1)
//gi.cprintf(ent, PRINT_HIGH, "GDS CONNECTION: %s\n", (connected_to_gds == true) ? "CONNECTED" : "DISCONNECTED");
//else if (!(ent->svflags & SVF_MONSTER))
gi.cprintf(ent, PRINT_HIGH, "GDS CONNECTION: LOCAL\n");
}
<file_sep>#ifndef V_MAPLIST_H
#define V_MAPLIST_H
#define MAX_VOTERS (MAX_CLIENTS * 2)
#define MAX_MAPS 64
#define MAX_MAPNAME_LEN 16
#define MAPMODE_PVP 1
#define MAPMODE_PVM 2
#define MAPMODE_DOM 3
#define MAPMODE_CTF 4
#define MAPMODE_FFA 5
#define MAPMODE_INV 6
#define ML_ROTATE_SEQ 0
#define ML_ROTATE_RANDOM 1
#define ML_ROTATE_NUM_CHOICES 2
//***************************************************************************************
//***************************************************************************************
typedef struct v_maplist_s
{
int nummaps; // number of maps in list
char mapnames[MAX_MAPS][MAX_MAPNAME_LEN];
} v_maplist_t;
//***************************************************************************************
//***************************************************************************************
typedef struct votes_s
{
qboolean used; // Paril: in "new" system, this means in progress.
int mode;
int mapindex;
char name[24];
char ip[16];
} votes_t;
//***************************************************************************************
//***************************************************************************************
#endif<file_sep>CC=gcc
COCKBAGS_MAKEFILE=makefile
SHARED_FLAGS:=
RELEASE_CFLAGS=-Isource/ -I./ -I../ $(SHARED_FLAGS) -O3
DEBUG_CFLAGS=-g -Isource/ -I./ -I../ $(SHARED_FLAGS) -DC_ONLY
LDFLAGS=-lm -shared
#DED_LDFLAGS=-ldl -lm -lz
#MODULE_LDFLAGS=-lm
#X11_LDFLAGS=-L/usr/X11R6/lib -lX11 -lXext
SHLIBCFLAGS=
SHLIBLDFLAGS=-shared
DO_SHLIB_CC=$(CC) $(CFLAGS) $(SHLIBCFLAGS) -o $@ -c $<
# this nice line comes from the linux kernel makefile
#ARCH := $(shell uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc/ -e s/sparc64/sparc/ -e s/arm.*/arm/ -e s/sa110/arm/ -e s/alpha/axp/)
ARCH =i386
SHLIBEXT =so
BUILD_DEBUG_DIR=debug$(ARCH)
BUILD_RELEASE_DIR=release$(ARCH)
TARGETS=$(BUILDDIR)/game.so
all: release
debug:
@-mkdir -p $(BUILD_DEBUG_DIR)
$(MAKE) -f $(COCKBAGS_MAKEFILE) targets BUILDDIR=$(BUILD_DEBUG_DIR) SOURCEDIR=. CFLAGS="$(DEBUG_CFLAGS) -DLINUX_VERSION='\"$(VERSION) Debug\"'"
release:
@-mkdir -p $(BUILD_RELEASE_DIR)
$(MAKE) -f $(COCKBAGS_MAKEFILE) targets BUILDDIR=$(BUILD_RELEASE_DIR) SOURCEDIR=. CFLAGS="$(RELEASE_CFLAGS) -g -fPIC -std=c99 -shared"
targets: $(TARGETS)
#
# Game object files
#
OBJS_GAME=\
$(BUILDDIR)/ally.o \
$(BUILDDIR)/armory.o \
$(BUILDDIR)/auras.o \
$(BUILDDIR)/backpack.o \
$(BUILDDIR)/bombspell.o \
$(BUILDDIR)/boss_general.o \
$(BUILDDIR)/boss_makron.o \
$(BUILDDIR)/boss_tank.o \
$(BUILDDIR)/class_brain.o \
$(BUILDDIR)/class_demon.o \
$(BUILDDIR)/cloak.o \
$(BUILDDIR)/ctf.o \
$(BUILDDIR)/damage.o \
$(BUILDDIR)/domination.o \
$(BUILDDIR)/drone_ai.o \
$(BUILDDIR)/drone_bitch.o \
$(BUILDDIR)/drone_brain.o \
$(BUILDDIR)/drone_decoy.o \
$(BUILDDIR)/drone_gladiator.o \
$(BUILDDIR)/drone_gunner.o \
$(BUILDDIR)/drone_medic.o \
$(BUILDDIR)/drone_misc.o \
$(BUILDDIR)/drone_move.o \
$(BUILDDIR)/drone_mutant.o \
$(BUILDDIR)/drone_parasite.o \
$(BUILDDIR)/drone_retard.o \
$(BUILDDIR)/drone_soldier.o \
$(BUILDDIR)/drone_tank.o \
$(BUILDDIR)/ents.o \
$(BUILDDIR)/file_output.o \
$(BUILDDIR)/flying_skull.o \
$(BUILDDIR)/forcewall.o \
$(BUILDDIR)/g_chase.o \
$(BUILDDIR)/g_cmds.o \
$(BUILDDIR)/g_combat.o \
$(BUILDDIR)/gds.o \
$(BUILDDIR)/g_flame.o \
$(BUILDDIR)/g_func.o \
$(BUILDDIR)/g_items.o \
$(BUILDDIR)/g_lasers.o \
$(BUILDDIR)/g_main.o \
$(BUILDDIR)/g_misc.o \
$(BUILDDIR)/g_monster.o \
$(BUILDDIR)/g_phys.o \
$(BUILDDIR)/g_save.o \
$(BUILDDIR)/g_spawn.o \
$(BUILDDIR)/g_svcmds.o \
$(BUILDDIR)/g_sword.o \
$(BUILDDIR)/g_target.o \
$(BUILDDIR)/g_trigger.o \
$(BUILDDIR)/g_utils.o \
$(BUILDDIR)/g_weapon.o \
$(BUILDDIR)/help.o \
$(BUILDDIR)/invasion.o \
$(BUILDDIR)/item_menu.o \
$(BUILDDIR)/jetpack.o \
$(BUILDDIR)/lasers.o \
$(BUILDDIR)/lasersight.o \
$(BUILDDIR)/laserstuff.o \
$(BUILDDIR)/magic.o \
$(BUILDDIR)/maplist.o \
$(BUILDDIR)/menu.o \
$(BUILDDIR)/mersennetwister.o \
$(BUILDDIR)/m_flash.o \
$(BUILDDIR)/minisentry.o \
$(BUILDDIR)/misc_stuff.o \
$(BUILDDIR)/p_client.o \
$(BUILDDIR)/p_hook.o \
$(BUILDDIR)/p_hud.o \
$(BUILDDIR)/player.o \
$(BUILDDIR)/playerlog.o \
$(BUILDDIR)/player_points.o \
$(BUILDDIR)/playertoberserk.o \
$(BUILDDIR)/playertoflyer.o \
$(BUILDDIR)/playertomedic.o \
$(BUILDDIR)/playertomutant.o \
$(BUILDDIR)/playertoparasite.o \
$(BUILDDIR)/playertotank.o \
$(BUILDDIR)/p_menu.o \
$(BUILDDIR)/p_parasite.o \
$(BUILDDIR)/p_trail.o \
$(BUILDDIR)/pvb.o \
$(BUILDDIR)/p_view.o \
$(BUILDDIR)/p_weapon.o \
$(BUILDDIR)/q_shared.o \
$(BUILDDIR)/repairstation.o \
$(BUILDDIR)/runes.o \
$(BUILDDIR)/scanner.o \
$(BUILDDIR)/sentrygun2.o \
$(BUILDDIR)/shaman.o \
$(BUILDDIR)/special_items.o \
$(BUILDDIR)/spirit.o \
$(BUILDDIR)/supplystation.o \
$(BUILDDIR)/talents.o \
$(BUILDDIR)/teamplay.o \
$(BUILDDIR)/totems.o \
$(BUILDDIR)/trade.o \
$(BUILDDIR)/upgrades.o \
$(BUILDDIR)/v_file_io.o \
$(BUILDDIR)/v_items.o \
$(BUILDDIR)/v_maplist.o \
$(BUILDDIR)/vote.o \
$(BUILDDIR)/v_utils.o \
$(BUILDDIR)/weapons.o \
$(BUILDDIR)/weapon_upgrades.o
$(BUILDDIR)/game.so: $(OBJS_GAME)
@echo Linking...;
$(CC) $(CFLAGS) -o $@ $(OBJS_GAME) $(LDFLAGS) $(MODULE_LDFLAGS)
$(BUILDDIR)/ally.o: $(SOURCEDIR)/ally.c; $(DO_SHLIB_CC)
$(BUILDDIR)/armory.o: $(SOURCEDIR)/armory.c; $(DO_SHLIB_CC)
$(BUILDDIR)/auras.o: $(SOURCEDIR)/auras.c; $(DO_SHLIB_CC)
$(BUILDDIR)/backpack.o: $(SOURCEDIR)/backpack.c; $(DO_SHLIB_CC)
$(BUILDDIR)/bombspell.o: $(SOURCEDIR)/bombspell.c; $(DO_SHLIB_CC)
$(BUILDDIR)/boss_general.o: $(SOURCEDIR)/boss_general.c; $(DO_SHLIB_CC)
$(BUILDDIR)/boss_makron.o: $(SOURCEDIR)/boss_makron.c; $(DO_SHLIB_CC)
$(BUILDDIR)/boss_tank.o: $(SOURCEDIR)/boss_tank.c; $(DO_SHLIB_CC)
$(BUILDDIR)/class_brain.o: $(SOURCEDIR)/class_brain.c; $(DO_SHLIB_CC)
$(BUILDDIR)/class_demon.o: $(SOURCEDIR)/class_demon.c; $(DO_SHLIB_CC)
$(BUILDDIR)/cloak.o: $(SOURCEDIR)/cloak.c; $(DO_SHLIB_CC)
$(BUILDDIR)/ctf.o: $(SOURCEDIR)/ctf.c; $(DO_SHLIB_CC)
$(BUILDDIR)/damage.o: $(SOURCEDIR)/damage.c; $(DO_SHLIB_CC)
$(BUILDDIR)/domination.o: $(SOURCEDIR)/domination.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_ai.o: $(SOURCEDIR)/drone_ai.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_bitch.o: $(SOURCEDIR)/drone_bitch.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_brain.o: $(SOURCEDIR)/drone_brain.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_decoy.o: $(SOURCEDIR)/drone_decoy.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_gladiator.o: $(SOURCEDIR)/drone_gladiator.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_gunner.o: $(SOURCEDIR)/drone_gunner.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_medic.o: $(SOURCEDIR)/drone_medic.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_misc.o: $(SOURCEDIR)/drone_misc.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_move.o: $(SOURCEDIR)/drone_move.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_mutant.o: $(SOURCEDIR)/drone_mutant.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_parasite.o: $(SOURCEDIR)/drone_parasite.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_retard.o: $(SOURCEDIR)/drone_retard.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_soldier.o: $(SOURCEDIR)/drone_soldier.c; $(DO_SHLIB_CC)
$(BUILDDIR)/drone_tank.o: $(SOURCEDIR)/drone_tank.c; $(DO_SHLIB_CC)
$(BUILDDIR)/ents.o: $(SOURCEDIR)/ents.c; $(DO_SHLIB_CC)
$(BUILDDIR)/file_output.o: $(SOURCEDIR)/file_output.c; $(DO_SHLIB_CC)
$(BUILDDIR)/flying_skull.o: $(SOURCEDIR)/flying_skull.c; $(DO_SHLIB_CC)
$(BUILDDIR)/forcewall.o: $(SOURCEDIR)/forcewall.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_chase.o: $(SOURCEDIR)/g_chase.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_cmds.o: $(SOURCEDIR)/g_cmds.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_combat.o: $(SOURCEDIR)/g_combat.c; $(DO_SHLIB_CC)
$(BUILDDIR)/gds.o: $(SOURCEDIR)/gds.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_flame.o: $(SOURCEDIR)/g_flame.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_func.o: $(SOURCEDIR)/g_func.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_items.o: $(SOURCEDIR)/g_items.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_lasers.o: $(SOURCEDIR)/g_lasers.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_main.o: $(SOURCEDIR)/g_main.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_misc.o: $(SOURCEDIR)/g_misc.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_monster.o: $(SOURCEDIR)/g_monster.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_phys.o: $(SOURCEDIR)/g_phys.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_save.o: $(SOURCEDIR)/g_save.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_spawn.o: $(SOURCEDIR)/g_spawn.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_svcmds.o: $(SOURCEDIR)/g_svcmds.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_sword.o: $(SOURCEDIR)/g_sword.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_target.o: $(SOURCEDIR)/g_target.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_trigger.o: $(SOURCEDIR)/g_trigger.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_utils.o: $(SOURCEDIR)/g_utils.c; $(DO_SHLIB_CC)
$(BUILDDIR)/g_weapon.o: $(SOURCEDIR)/g_weapon.c; $(DO_SHLIB_CC)
$(BUILDDIR)/help.o: $(SOURCEDIR)/help.c; $(DO_SHLIB_CC)
$(BUILDDIR)/invasion.o: $(SOURCEDIR)/invasion.c; $(DO_SHLIB_CC)
$(BUILDDIR)/item_menu.o: $(SOURCEDIR)/item_menu.c; $(DO_SHLIB_CC)
$(BUILDDIR)/jetpack.o: $(SOURCEDIR)/jetpack.c; $(DO_SHLIB_CC)
$(BUILDDIR)/lasers.o: $(SOURCEDIR)/lasers.c; $(DO_SHLIB_CC)
$(BUILDDIR)/lasersight.o: $(SOURCEDIR)/lasersight.c; $(DO_SHLIB_CC)
$(BUILDDIR)/laserstuff.o: $(SOURCEDIR)/laserstuff.c; $(DO_SHLIB_CC)
$(BUILDDIR)/magic.o: $(SOURCEDIR)/magic.c; $(DO_SHLIB_CC)
$(BUILDDIR)/maplist.o: $(SOURCEDIR)/maplist.c; $(DO_SHLIB_CC)
$(BUILDDIR)/menu.o: $(SOURCEDIR)/menu.c; $(DO_SHLIB_CC)
$(BUILDDIR)/mersennetwister.o: $(SOURCEDIR)/mersennetwister.c; $(DO_SHLIB_CC)
$(BUILDDIR)/m_flash.o: $(SOURCEDIR)/m_flash.c; $(DO_SHLIB_CC)
$(BUILDDIR)/minisentry.o: $(SOURCEDIR)/minisentry.c; $(DO_SHLIB_CC)
$(BUILDDIR)/misc_stuff.o: $(SOURCEDIR)/misc_stuff.c; $(DO_SHLIB_CC)
$(BUILDDIR)/p_client.o: $(SOURCEDIR)/p_client.c; $(DO_SHLIB_CC)
$(BUILDDIR)/p_hook.o: $(SOURCEDIR)/p_hook.c; $(DO_SHLIB_CC)
$(BUILDDIR)/p_hud.o: $(SOURCEDIR)/p_hud.c; $(DO_SHLIB_CC)
$(BUILDDIR)/player.o: $(SOURCEDIR)/player.c; $(DO_SHLIB_CC)
$(BUILDDIR)/playerlog.o: $(SOURCEDIR)/playerlog.c; $(DO_SHLIB_CC)
$(BUILDDIR)/player_points.o: $(SOURCEDIR)/player_points.c; $(DO_SHLIB_CC)
$(BUILDDIR)/playertoberserk.o: $(SOURCEDIR)/playertoberserk.c; $(DO_SHLIB_CC)
$(BUILDDIR)/playertoflyer.o: $(SOURCEDIR)/playertoflyer.c; $(DO_SHLIB_CC)
$(BUILDDIR)/playertomedic.o: $(SOURCEDIR)/playertomedic.c; $(DO_SHLIB_CC)
$(BUILDDIR)/playertomutant.o: $(SOURCEDIR)/playertomutant.c; $(DO_SHLIB_CC)
$(BUILDDIR)/playertoparasite.o: $(SOURCEDIR)/playertoparasite.c; $(DO_SHLIB_CC)
$(BUILDDIR)/playertotank.o: $(SOURCEDIR)/playertotank.c; $(DO_SHLIB_CC)
$(BUILDDIR)/p_menu.o: $(SOURCEDIR)/p_menu.c; $(DO_SHLIB_CC)
$(BUILDDIR)/p_parasite.o: $(SOURCEDIR)/p_parasite.c; $(DO_SHLIB_CC)
$(BUILDDIR)/p_trail.o: $(SOURCEDIR)/p_trail.c; $(DO_SHLIB_CC)
$(BUILDDIR)/pvb.o: $(SOURCEDIR)/pvb.c; $(DO_SHLIB_CC)
$(BUILDDIR)/p_view.o: $(SOURCEDIR)/p_view.c; $(DO_SHLIB_CC)
$(BUILDDIR)/p_weapon.o: $(SOURCEDIR)/p_weapon.c; $(DO_SHLIB_CC)
$(BUILDDIR)/q_shared.o: $(SOURCEDIR)/q_shared.c; $(DO_SHLIB_CC)
$(BUILDDIR)/repairstation.o: $(SOURCEDIR)/repairstation.c; $(DO_SHLIB_CC)
$(BUILDDIR)/runes.o: $(SOURCEDIR)/runes.c; $(DO_SHLIB_CC)
$(BUILDDIR)/scanner.o: $(SOURCEDIR)/scanner.c; $(DO_SHLIB_CC)
$(BUILDDIR)/sentrygun2.o: $(SOURCEDIR)/sentrygun2.c; $(DO_SHLIB_CC)
$(BUILDDIR)/shaman.o: $(SOURCEDIR)/shaman.c; $(DO_SHLIB_CC)
$(BUILDDIR)/special_items.o: $(SOURCEDIR)/special_items.c; $(DO_SHLIB_CC)
$(BUILDDIR)/spirit.o: $(SOURCEDIR)/spirit.c; $(DO_SHLIB_CC)
$(BUILDDIR)/supplystation.o: $(SOURCEDIR)/supplystation.c; $(DO_SHLIB_CC)
$(BUILDDIR)/talents.o: $(SOURCEDIR)/talents.c; $(DO_SHLIB_CC)
$(BUILDDIR)/teamplay.o: $(SOURCEDIR)/teamplay.c; $(DO_SHLIB_CC)
$(BUILDDIR)/totems.o: $(SOURCEDIR)/totems.c; $(DO_SHLIB_CC)
$(BUILDDIR)/trade.o: $(SOURCEDIR)/trade.c; $(DO_SHLIB_CC)
$(BUILDDIR)/upgrades.o: $(SOURCEDIR)/upgrades.c; $(DO_SHLIB_CC)
$(BUILDDIR)/v_file_io.o: $(SOURCEDIR)/v_file_io.c; $(DO_SHLIB_CC)
$(BUILDDIR)/v_items.o: $(SOURCEDIR)/v_items.c; $(DO_SHLIB_CC)
$(BUILDDIR)/v_maplist.o: $(SOURCEDIR)/v_maplist.c; $(DO_SHLIB_CC)
$(BUILDDIR)/vote.o: $(SOURCEDIR)/vote.c; $(DO_SHLIB_CC)
$(BUILDDIR)/v_utils.o: $(SOURCEDIR)/v_utils.c; $(DO_SHLIB_CC)
$(BUILDDIR)/weapons.o: $(SOURCEDIR)/weapons.c; $(DO_SHLIB_CC)
$(BUILDDIR)/weapon_upgrades.o: $(SOURCEDIR)/weapon_upgrades.c; $(DO_SHLIB_CC)
#
# Parameters
#
clean: clean-debug clean-release
clean-debug:
$(MAKE) -f $(COCKBAGS_MAKEFILE) clean2 BUILDDIR=$(BUILD_DEBUG_DIR)
clean-release:
$(MAKE) -f $(COCKBAGS_MAKEFILE) clean2 BUILDDIR=$(BUILD_RELEASE_DIR)
clean2:
@-rm -f \
$(OBJS_GAME)
distclean:
@-rm -rf $(BUILD_DEBUG_DIR) $(BUILD_RELEASE_DIR)
<file_sep>#include "g_local.h"
//************************************************************************************************
// Indexing functions
//************************************************************************************************
//Takes the class string and returns the index
int getClassNum(char *newclass)
{
if (Q_strcasecmp(newclass, "Soldier") == 0)
return CLASS_SOLDIER;
else if (Q_strcasecmp(newclass, "Mage") == 0)
return CLASS_MAGE;
else if (Q_strcasecmp(newclass, "Necromancer") == 0)
return CLASS_NECROMANCER;
else if (Q_strcasecmp(newclass, "Vampire") == 0)
return CLASS_VAMPIRE;
else if (Q_strcasecmp(newclass, "Engineer") == 0)
return CLASS_ENGINEER;
else if (Q_strcasecmp(newclass, "Poltergeist") == 0)
return CLASS_POLTERGEIST;
else if (Q_strcasecmp(newclass, "Knight") == 0)
return CLASS_KNIGHT;
else if (Q_strcasecmp(newclass, "Cleric") == 0)
return CLASS_CLERIC;
else if (Q_strcasecmp(newclass, "Shaman") == 0)
return CLASS_SHAMAN;
else if (Q_strcasecmp(newclass, "Alien") == 0)
return CLASS_ALIEN;
else if ((Q_strcasecmp(newclass, "Weapon Master") == 0) || (Q_strcasecmp(newclass, "WeaponMaster") == 0))
return CLASS_WEAPONMASTER;
return 0;
}
//************************************************************************************************
// String functions
//************************************************************************************************
void padRight(char *String, int numChars)
{
//Pads a string with spaces at the end, until the length of the string is 'numChars'
int i;
for (i = strlen(String); i < numChars; ++i)
String[i] = ' ';
String[numChars] = 0;
}
//************************************************************************************************
char GetRandomChar (void)
{
switch (GetRandom(1, 3))
{
case 1: return (GetRandom(48, 57));
case 2: return (GetRandom(65, 90));
case 3: return (GetRandom(97, 113));
}
return ' ';
}
//************************************************************************************************
char *GetRandomString (int len)
{
int i;
char *s;
s = (char *) gi.TagMalloc (len*sizeof(char), TAG_GAME);
for (i=0; i<len-1; i++) {
s[i] = GetRandomChar();
}
s[i] = '\0'; // terminating char
return s;
}
//************************************************************************************************
// Command list (help menu)
//************************************************************************************************
void PrintCommands(edict_t *ent)
{
//Spam the user with a huge amount of text :)
gi.cprintf(ent, PRINT_HIGH, "Vortex Command List:\n\n");
gi.cprintf(ent, PRINT_HIGH, va("Version %s\n\n", VRX_VERSION));
gi.cprintf(ent, PRINT_HIGH, "*** Skills ***\n\n");
gi.cprintf(ent, PRINT_HIGH, "aura_holyfreeze\naura_shock\naura_salvation\nbless [self]\ncacodemon\ncripple\ncurse\nampdamage\nironmaiden\nweaken\namnesia\ndecoy\ndetpipes\nforcewall [solid]\ngravjump\nguardian\n+hook\nheal [self]\nlaser[s] [remove]\nmagicbolt\nmagmine\nminisentry [remove]\nmonster [help/hunt/remove/select/stand]\nnova\n+parasite\nsentry [remove/rotate]\nspell_boost\nspell_bomb [area/forward]\nspell_corpseexplode\nspell_stealammo\n+superspeed\nsupplystation\nteleport_fwd\n+thrust\nuse [power screen/holywater/potion/gravityboots]\n\n");
gi.cprintf(ent, PRINT_HIGH, "*** Standard Commands ***\n\n");
gi.cprintf(ent, PRINT_HIGH, "owner <name>\nwhois <playername>\nflashlight\nrune\nteam\ntrade\ntogglesecondary\nuse tball [self]\nupgrade_ability\nupgrade_weapon\nvote\nvrx_password\nvrxarmory\nvrxhelp\nvrxid\nvrxinfo\nvrxrespawn\n\n");
}
//************************************************************************************************
// Armoury Strings (stuff you can buy at the armory)
//************************************************************************************************
char *GetArmoryItemString (int purchase_number)
{
switch(purchase_number)
{
case 1: return "Shotgun";
case 2: return "Super Shotgun";
case 3: return "Machinegun";
case 4: return "Chaingun";
case 5: return "Grenade Launcher";
case 6: return "Rocket Launcher";
case 7: return "Hyperblaster";
case 8: return "Railgun";
case 9: return "BFG10K";
case 10: return "20mm Cannon";
case 11: return "Bullets";
case 12: return "Shells";
case 13: return "Cells";
case 14: return "Grenades";
case 15: return "Rockets";
case 16: return "Slugs";
case 17: return "T-Balls";
case 18: return "Power Cubes";
case 19: return "Body Armor";
case 20: return "Health Potions";
case 21: return "Holy Water";
case 22: return "Anti-grav Boots";
case 23: return "Fire Resistant Clothing";
case 24: return "Auto-Tball";
case 25: return "Ability Rune";
case 26: return "Weapon Rune";
case 27: return "Combo Rune";
case 28: return "Reset Abilities/Weapons";
default: return "<BAD ITEM NUMBER>";
}
}
//************************************************************************************************
// Weapon Strings (mods and weapon names)
//************************************************************************************************
char *GetShortWeaponString (int weapon_number)
{
//Returns a shorter form of a weapon, for the rune menu
switch(weapon_number)
{
case WEAPON_BLASTER: return "Blaster";
case WEAPON_SHOTGUN: return "SG";
case WEAPON_SUPERSHOTGUN: return "SSG";
case WEAPON_MACHINEGUN: return "MG";
case WEAPON_CHAINGUN: return "CG";
case WEAPON_GRENADELAUNCHER: return "GL";
case WEAPON_ROCKETLAUNCHER: return "RL";
case WEAPON_HYPERBLASTER: return "HB";
case WEAPON_RAILGUN: return "RG";
case WEAPON_BFG10K: return "BFG10K";
case WEAPON_SWORD: return "Sword";
case WEAPON_20MM: return "20mm";
case WEAPON_HANDGRENADE: return "HG";
default: return "<BAD WEAPON NUMBER>";
}
}
//************************************************************************************************
char *GetWeaponString (int weapon_number)
{
switch(weapon_number)
{
case WEAPON_BLASTER: return "Blaster";
case WEAPON_SHOTGUN: return "Shotgun";
case WEAPON_SUPERSHOTGUN: return "Super Shotgun";
case WEAPON_MACHINEGUN: return "Machinegun";
case WEAPON_CHAINGUN: return "Chaingun";
case WEAPON_GRENADELAUNCHER: return "Grenade Launcher";
case WEAPON_ROCKETLAUNCHER: return "Rocket Launcher";
case WEAPON_HYPERBLASTER: return "Hyperblaster";
case WEAPON_RAILGUN: return "Railgun";
case WEAPON_BFG10K: return "BFG10K";
case WEAPON_SWORD: return "Sword";
case WEAPON_20MM: return "20mm Cannon";
case WEAPON_HANDGRENADE: return "Hand Grenade";
default: return "<BAD WEAPON NUMBER>";
}
}
//************************************************************************************************
char *GetModString (int weapon_number, int mod_number)
{
switch(mod_number)
{
case 0: return "Damage";
case 1:
switch(weapon_number)
{
case WEAPON_BLASTER: return "Stun";
case WEAPON_SHOTGUN: return "Strike";
case WEAPON_SUPERSHOTGUN: return "Range";
case WEAPON_MACHINEGUN: return "Pierce";
case WEAPON_CHAINGUN: return "Spin";
case WEAPON_GRENADELAUNCHER: return "Radius";
case WEAPON_ROCKETLAUNCHER: return "Radius";
case WEAPON_HYPERBLASTER: return "Stun";
case WEAPON_RAILGUN: return "Pierce";
case WEAPON_BFG10K: return "Duration";
case WEAPON_SWORD: return "Forging";
case WEAPON_20MM: return "Range";
case WEAPON_HANDGRENADE: return "Range";
default: return "<BAD WEAPON NUMBER>";
}
case 2:
switch(weapon_number)
{
case WEAPON_BLASTER: return "Speed";
case WEAPON_SHOTGUN: return "Pellets";
case WEAPON_SUPERSHOTGUN: return "Pellets";
case WEAPON_MACHINEGUN: return "Tracers";
case WEAPON_CHAINGUN: return "Tracers";
case WEAPON_GRENADELAUNCHER: return "Range";
case WEAPON_ROCKETLAUNCHER: return "Speed";
case WEAPON_HYPERBLASTER: return "Speed";
case WEAPON_RAILGUN: return "Burn";
case WEAPON_BFG10K: return "Speed";
case WEAPON_SWORD: return "Length";
case WEAPON_20MM: return "Recoil";
case WEAPON_HANDGRENADE: return "Radius";
default: return "<BAD WEAPON NUMBER>";
}
case 3:
switch(weapon_number)
{
case WEAPON_BLASTER: return "Trails";
case WEAPON_SHOTGUN: return "Spread";
case WEAPON_SUPERSHOTGUN: return "Spread";
case WEAPON_MACHINEGUN: return "Spread";
case WEAPON_CHAINGUN: return "Spread";
case WEAPON_GRENADELAUNCHER: return "Trails";
case WEAPON_ROCKETLAUNCHER: return "Trails";
case WEAPON_HYPERBLASTER: return "Light";
case WEAPON_RAILGUN: return "Trails";
case WEAPON_BFG10K: return "Slide";
case WEAPON_SWORD: return "Burn";
case WEAPON_20MM: return "Caliber";
case WEAPON_HANDGRENADE: return "Trails";
default: return "<BAD WEAPON NUMBER>";
}
case 4: return "Noise/Flash";
default: return "<BAD WEAPON MOD NUMBER>";
}
}
//************************************************************************************************
// Class Strings
//************************************************************************************************
char *GetClassString (int class_num)
{
switch (class_num)
{
case CLASS_SOLDIER: return "Soldier";
case CLASS_MAGE: return "Mage";
case CLASS_NECROMANCER: return "Necromancer";
case CLASS_VAMPIRE: return "Vampire";
case CLASS_ENGINEER: return "Engineer";
case CLASS_POLTERGEIST: return "Poltergeist";
case CLASS_KNIGHT: return "Knight";
case CLASS_CLERIC: return "Cleric";
case CLASS_WEAPONMASTER:return "Weapon Master";
case CLASS_SHAMAN: return "Shaman";
case CLASS_ALIEN: return "Alien";
default: return "Unknown";
}
}
//************************************************************************************************
// "Talent Name" Strings
//************************************************************************************************
char *GeneralTalentString(int talent_ID)
{
switch(talent_ID)
{
//Soldier Talents
case TALENT_BARTERING: return "Bartering";
case TALENT_TACTICS: return "Imp. Vit";
case TALENT_BASIC_HA: return "Ammo Efficiency";
case TALENT_SUPERIORITY: return "Superiority";
case TALENT_RETALIATION: return "Retaliation";
default: return va("talent ID = %d", talent_ID);
}
}
char *GetTalentString(int talent_ID)
{
switch(talent_ID)
{
//Soldier Talents
case TALENT_IMP_STRENGTH: return "Imp. Strength";
case TALENT_IMP_RESIST: return "Imp. Resist";
case TALENT_BLOOD_OF_ARES: return "Blood of Ares";
case TALENT_BOMBARDIER: return "Bombardier";
case TALENT_RETALIATION: return "Retaliation";
//Poltergeist Talents
case TALENT_MORPHING: return "Morphing";//decino: change to longer slash range for para/mutant/tank/berserker
case TALENT_MORE_AMMO: return "More Ammo";//decino: not sure if this is usefull with polt ammo regen
case TALENT_SUPERIORITY: return "Imp. Metabolism";//decino: don't get confused, this is now a different talent than orig. superiority
case TALENT_PACK_ANIMAL: return "Pack Animal";
case TALENT_SECOND_CHANCE: return "Imp. Appendage";
//Vampire Talents
case TALENT_IMP_CLOAK: return "Imp. Cloak";//decino: sucks, needs a replacement or removal
case TALENT_ARMOR_VAMP: return "Armor Vampire";
case TALENT_IMP_MINDABSORB: return "Mind Control";
case TALENT_CANNIBALISM: return "Cannibalism";
case TALENT_FATAL_WOUND: return "Fatal Wound";
//Mage Talents
case TALENT_ICE_BOLT: return "Ice Bolt";//decino: replace, add ice bolt to ability list
case TALENT_MEDITATION: return "Meditation";
case TALENT_FROST_NOVA: return "Frost Nova";
case TALENT_IMP_MAGICBOLT: return "Imp. Magicbolt";//decino: too simple
case TALENT_MANASHIELD: return "Mana Shield";
//Engineer Talents
case TALENT_LASER_PLATFORM: return "Laser Platform";//decino: worthless, improve or replace
case TALENT_ALARM: return "Laser Trap";
case TALENT_RAPID_ASSEMBLY: return "Rapid Assembly";
case TALENT_PRECISION_TUNING: return "Fire Wall";
case TALENT_STORAGE_UPGRADE: return "Storage Upgrade";
//Knight Talents
case TALENT_REPEL: return "Repel";
case TALENT_MAG_BOOTS: return "Mag Boots";
case TALENT_LEAP_ATTACK: return "Leap Attack";
case TALENT_MOBILITY: return "Mobility";
case TALENT_DURABILITY: return "Lancing";
//Cleric Talents
case TALENT_BALANCESPIRIT: return "Balance Spirit";//decino: too shitty, make it combine spirits without having the opposite one upgraded; lv 3: same level as opposite spirit
case TALENT_HOLY_GROUND: return "Holy Ground";
case TALENT_UNHOLY_GROUND: return "Unholy Ground";
case TALENT_PURGE: return "Purge";
case TALENT_BOOMERANG: return "Boomerang";
//Weapon Master Talents
case TALENT_BASIC_AMMO_REGEN: return "Ammo Regen";
case TALENT_COMBAT_EXP: return "Combat Exp.";
case TALENT_SIDEARMS: return "Sidearms";
case TALENT_TACTICS: return "Poison Rounds";
case TALENT_OVERLOAD: return "Ammo Thief";
//Necromancer Talents
case TALENT_CHEAPER_CURSES: return "Cheaper Curses";
case TALENT_CORPULENCE: return "Corpulence";
case TALENT_LIFE_TAP: return "Life Tap";
case TALENT_DIM_VISION: return "Dim Vision";
case TALENT_FLIGHT: return "Flight";//decino: replace with something usefull?
//Shaman Talents
case TALENT_PEACE: return "Short Temper";
case TALENT_ICE: return "Obsidian";//decino: replace with erosion talent (earth+air)
case TALENT_WIND: return "Erosion";//decino: replace with obsidian talent (fire+water)
case TALENT_SHADOW: return "Twilight";//decino: replace, fury talent?
case TALENT_TOTEM: return "Totemic Focus";
//Alien Talents
case TALENT_PHANTOM_OBSTACLE: return "Hidden Obstacle";
case TALENT_SUPER_HEALER: return "Super Healer";//decino: should heal armor and healer should always heal 150% health w/o talent
case TALENT_PHANTOM_COCOON: return "Phantom Cocoon";
case TALENT_SWARMING: return "Swarming";//decino: shouldn't reduce damage, spores suck already
case TALENT_EXPLODING_BODIES: return "Exploding Body";
//General talents
case TALENT_BARTERING: return "Bartering";
default: return va("talent ID = %d", talent_ID);
}
}
//************************************************************************************************
// Ability Strings
//************************************************************************************************
char *GetAbilityString (int ability_number)
{
switch (ability_number)
{
case VITALITY: return "Vitality";
case REGENERATION: return "Regen";
case RESISTANCE: return "Resist";
case STRENGTH: return "Strength";
case HASTE: return "Haste";
case VAMPIRE: return "Life Steal";
case JETPACK: return "Jetpack";
case CLOAK: return "Cloak";
case WEAPON_KNOCK: return "Knock Weapon";
case ARMOR_UPGRADE: return "Armor Upgrade";
case AMMO_STEAL: return "Aftermath";
case ID: return "ID";
case MAX_AMMO: return "Max Ammo";
case GRAPPLE_HOOK: return "Grapple Hook";
case SUPPLY_STATION: return "Supply Station";
case CREATE_QUAD: return "Auto-Quad";
case CREATE_INVIN: return "Auto-Invin";
case POWER_SHIELD: return "Power Shield";
case CORPSE_EXPLODE: return "Detonate Body";
case GHOST: return "Ghost";
case SALVATION: return "Salvation Aura";
case FORCE_WALL: return "Force Wall";
case AMMO_REGEN: return "Ammo Regen";
case POWER_REGEN: return "PC Regen";
case BUILD_LASER: return "Lasers";
case HA_PICKUP: return "H/A Pickup";
case BUILD_SENTRY: return "Sentry Guns";
case BOOST_SPELL: return "Boost Spell";
case BLOOD_SUCKER: return "Parasite";
case PROXY: return "Proxy Grenade";
case MONSTER_SUMMON: return "Monster Summon";
case SUPER_SPEED: return "Sprint";
case ARMOR_REGEN: return "Armor Regen";
case BOMB_SPELL: return "Bomb Spell";
case LIGHTNING: return "Chain Lightning";
case DECOY: return "Mirror";
case HOLY_FREEZE: return "HolyFreeze Aura";
case WORLD_RESIST: return "World Resist";
case BULLET_RESIST: return "Bullet Resist";
case SHELL_RESIST: return "Shell Resist";
case ENERGY_RESIST: return "Energy Resist";
case PIERCING_RESIST: return "Piercing Resist";
case SPLASH_RESIST: return "Splash Resist";
case CACODEMON: return "Cacodemon";
case PLAGUE: return "Plague";
case FLESH_EATER: return "Corpse Eater";
case HELLSPAWN: return "Hell Spawn";
case BRAIN: return "Brain";
case BEAM: return "Beam";
case MAGMINE: return "Mag Mine";
case CRIPPLE: return "Cripple";
case MAGICBOLT: return "Magic Bolt";
case TELEPORT: return "Teleport";
case NOVA: return "Nova";
case EXPLODING_ARMOR: return "Exploding Armor";
case MIND_ABSORB: return "Mind Absorb";
case LIFE_DRAIN: return "Life Drain";
case AMP_DAMAGE: return "Amp Damage";
case CURSE: return "Curse";
case WEAKEN: return "Weaken";
case AMNESIA: return "Amnesia";
case BLESS: return "Bless";
case HEALING: return "Healing";
case AMMO_UPGRADE: return "Ammo Efficiency";
case YIN: return "Yin Spirit";
case YANG: return "Yang Spirit";
case FLYER: return "Flyer";
case SPIKE: return "Spike";
case MUTANT: return "Mutant";
case MORPH_MASTERY: return "Morph Mastery";
case NAPALM: return "Napalm";
case TANK: return "Tank";
case MEDIC: return "Medic";
case BERSERK: return "Berserker";
case METEOR: return "Meteor";
case AUTOCANNON: return "Auto Cannon";
case HAMMER: return "Blessed Hammer";
case BLACKHOLE: return "Wormhole";
case FIRE_TOTEM: return "Fire Totem";
case WATER_TOTEM: return "Water Totem";
case AIR_TOTEM: return "Air Totem";
case EARTH_TOTEM: return "Earth Totem";
case DARK_TOTEM: return "Darkness Totem";
case NATURE_TOTEM: return "Nature Totem";
case FURY: return "Fury";
case TOTEM_MASTERY: return "Totem Mastery";
case SHIELD: return "Shield";
case CALTROPS: return "Caltrops";
case SPIKE_GRENADE: return "Spike Grenade";
case DETECTOR: return "Detector";
case CONVERSION: return "Conversion";
case DEFLECT: return "Deflect";
case SCANNER: return "Scanner";
case EMP: return "EMP";
case DOUBLE_JUMP: return "Double Jump";
case LOWER_RESIST: return "Lower Resist";
case FIREBALL: return "Fireball";
case PLASMA_BOLT: return "Plasma Bolt";
case LIGHTNING_STORM: return "Lightning Storm";
case MIRV: return "Mirv Grenade";
case SPIKER: return "Spiker";
case OBSTACLE: return "Obstacle";
case HEALER: return "Healer";
case GASSER: return "Gasser";
case SPORE: return "Spore";
case ACID: return "Acid";
case COCOON: return "Cocoon";
default: return ":)";
}
}
//************************************************************************************************
// Rune Strings
//************************************************************************************************
char *GetRuneValString(item_t *rune)
{
int level = rune->itemLevel;
switch(rune->itemtype)
{
case ITEM_WEAPON:
{
switch(level / 2)
{
case 0: return "Worthless";
case 1: return "Cracked";
case 2: return "Chipped";
case 3: return "Flawed";
case 4: return "Normal";
case 5: return "Good";
case 6: return "Great";
case 7: return "Exceptional";
case 8: return "Flawless";
case 9: return "Perfect";
case 10: return "Godly";
default: return "Cheater's";
}
}
break;
case ITEM_ABILITY:
{
switch(level / 3)
{
case 0: return "Worthless";
case 1: return "Cracked";
case 2: return "Normal";
case 3: return "Good";
case 4: return "Flawless";
case 5: return "Perfect";
case 6: return "Godly";
default: return "Cheater's";
}
}
break;
case ITEM_COMBO:
{
switch(level / 2)
{
case 0: return "Worthless";
case 1: return "Cracked";
case 2: return "Normal";
case 3: return "Good";
case 4: return "Flawless";
case 5: return "Perfect";
case 6: return "Godly";
default: return "Cheater's";
}
}
break;
case ITEM_CLASSRUNE:
{
switch (rune->classNum)
{
case CLASS_ENGINEER:
{
switch(level / 2)
{
case 0: return "Student's";
case 1: return "Assistant's";
case 2: return "Technician's";
case 3: return "Mechanic's";
case 4: return "Scientist's";
case 5: return "Physicist's";
case 6: return "Engineer's";
default: return "Cheater's";
}
}
break;
case CLASS_SOLDIER:
{
switch(level / 2)
{
case 0: return "Newbie's";
case 1: return "Greenhorn's";
case 2: return "Sergent's";
case 3: return "Soldier's";
case 4: return "Warrior's";
case 5: return "Veteran's";
case 6: return "Master's";
default: return "Cheater's";
}
}
break;
case CLASS_MAGE:
{
switch(level / 2)
{
case 0: return "Apprentice's";
case 1: return "Illusionist's";
case 2: return "Sage's";
case 3: return "Mage's";
case 4: return "Wizard's";
case 5: return "Sorcerer's";
case 6: return "Archimage's";
default: return "Cheater's";
}
}
break;
case CLASS_NECROMANCER:
{
switch(level / 2)
{
case 0: return "Excorcist's";
case 1: return "Theurgist's";
case 2: return "Curser's";
case 3: return "Necromancer's";
case 4: return "Warlock's";
case 5: return "Demi-Lich's";
case 6: return "Lich's";
default: return "Cheater's";
}
}
break;
case CLASS_VAMPIRE:
{
switch(level / 2)
{
case 0: return "Ghoul's";
case 1: return "Geist's";
case 2: return "Wraith's";
case 3: return "Vampire's";
case 4: return "Revenant's";
case 5: return "Nosferatu's";
case 6: return "Dracula's";
default: return "Cheater's";
}
}
break;
case CLASS_POLTERGEIST:
{
switch(level / 2)
{
case 0: return "Spook's";
case 1: return "Spirit's";
case 2: return "Phantom's";
case 3: return "Poltergeist's";
case 4: return "Apparition's";
case 5: return "Ghost's";
case 6: return "Monster's";
default: return "Cheater's";
}
}
break;
case CLASS_KNIGHT:
{
switch(level / 2)
{
case 0: return "Commoner's";
case 1: return "Squire's";
case 2: return "Guard's";
case 3: return "Knight's";
case 4: return "Baron's";
case 5: return "Lord's";
case 6: return "King's";
default: return "Cheater's";
}
}
break;
case CLASS_CLERIC:
{
switch(level / 2)
{
case 0: return "Follower's";
case 1: return "Acolyte's";
case 2: return "Preacher's";
case 3: return "Cleric's";
case 4: return "Pastor's";
case 5: return "Bishop's";
case 6: return "Pope's";
default: return "Cheater's";
}
}
break;
case CLASS_WEAPONMASTER:
{
switch(level / 2)
{
case 0: return "Amateur's";
case 1: return "Neophyte's";
case 2: return "Novice's";
case 3: return "Weapon Master's";
case 4: return "Guru's";
case 5: return "Expert's";
case 6: return "Elite's'";
default: return "Cheater's";
}
}
break;
case CLASS_ALIEN: //decino: no more unknown class shit
{
switch(level / 2)
{
case 0: return "Breeder's";
case 1: return "Hatchling's";
case 2: return "Drone's";
case 3: return "Alien's";
case 4: return "Stinger's";
case 5: return "Guardian's";
case 6: return "Stalker's'";
default: return "Cheater's";
}
}
break;
case CLASS_SHAMAN: //decino: ditto
{
switch(level / 2)
{
case 0: return "Guide's";
case 1: return "Mediator's";
case 2: return "Healer's";
case 3: return "Shaman's";
case 4: return "Machi's";
case 5: return "Shi Yi's";
case 6: return "Yaskomo's'";
default: return "Cheater's";
}
}
break;
default: return "<Unknown Class>";
}
break;
default: return "Strange";
}
}
}
//************************************************************************************************
// CLASS RUNE ARRAYS
//************************************************************************************************
int getClassRuneStat(int cIndex)
{
int index;
switch (cIndex)
{
case CLASS_SOLDIER:
{
index = GetRandom(0, 6);
switch(index)
{
case 0: return STRENGTH;
case 1: return RESISTANCE;
case 2: return HA_PICKUP;
case 3: return NAPALM;
case 4: return SPIKE_GRENADE;
case 5: return EMP;
case 6: return MIRV;
}
}
break;
case CLASS_KNIGHT:
{
index = GetRandom(0, 6);
switch(index)
{
case 0: return ARMOR_UPGRADE;
case 1: return REGENERATION;
case 2: return POWER_SHIELD;
case 3: return ARMOR_REGEN;
case 4: return EXPLODING_ARMOR;
case 5: return BEAM;
case 6: return PLASMA_BOLT;
}
}
break;
case CLASS_VAMPIRE:
{
index = GetRandom(0, 7);
switch(index)
{
case 0: return VAMPIRE;
case 1: return GHOST;
case 2: return LIFE_DRAIN;
case 3: return FLESH_EATER;
case 4: return CORPSE_EXPLODE;
case 5: return MIND_ABSORB;
case 6: return AMMO_STEAL;
case 7: return CONVERSION;
}
}
break;
case CLASS_NECROMANCER:
{
index = GetRandom(0, 7);
switch(index)
{
case 0: return MONSTER_SUMMON;
case 1: return HELLSPAWN;
case 2: return PLAGUE;
case 3: return AMP_DAMAGE;
case 4: return CRIPPLE;
case 5: return CURSE;
case 6: return WEAKEN;
case 7: return LOWER_RESIST;
}
}
break;
case CLASS_ENGINEER:
{
index = GetRandom(0, 7);
switch(index)
{
case 0: return PROXY;
case 1: return BUILD_SENTRY;
case 2: return SUPPLY_STATION;
case 3: return BUILD_LASER;
case 4: return MAGMINE;
case 5: return CALTROPS;
case 6: return AUTOCANNON;
case 7: return DETECTOR;
}
}
break;
case CLASS_MAGE:
{
index = GetRandom(0, 7);
switch(index)
{
case 0: return MAGICBOLT;
case 1: return NOVA;
case 2: return BOMB_SPELL;
case 3: return FIREBALL;
case 4: return FORCE_WALL;
case 5: return LIGHTNING;
case 6: return METEOR;
case 7: return LIGHTNING_STORM;
}
}
break;
case CLASS_CLERIC:
{
index = GetRandom(0, 7);
switch(index)
{
case 0: return SALVATION;
case 1: return HOLY_FREEZE;
case 2: return HEALING;
case 3: return BLESS;
case 4: return YIN;
case 5: return YANG;
case 6: return HAMMER;
case 7: return DEFLECT;
}
}
break;
case CLASS_POLTERGEIST:
{
index = GetRandom(0, 8);
switch(index)
{
case 0: return CACODEMON;
case 1: return BLOOD_SUCKER;
case 2: return BRAIN;
case 3: return FLYER;
case 4: return MUTANT;
case 5: return TANK;
case 6: return MEDIC;
case 7: return MORPH_MASTERY;
case 8: return BERSERK;
}
}
break;
case CLASS_SHAMAN:
{
index = GetRandom(0, 8);
switch(index)
{
case 0: return FIRE_TOTEM;
case 1: return WATER_TOTEM;
case 2: return AIR_TOTEM;
case 3: return EARTH_TOTEM;
case 4: return DARK_TOTEM;
case 5: return NATURE_TOTEM;
case 6: return FURY;
case 7: return TOTEM_MASTERY;
case 8: return HASTE;
}
}
break;
case CLASS_WEAPONMASTER:
{
index = GetRandom(0, 7);
switch(index)
{
case 0: return SUPER_SPEED;
case 1: return CREATE_QUAD;
case 2: return CREATE_INVIN;
case 3: return AMMO_REGEN;
case 4: return WEAPON_KNOCK;
case 5: return VITALITY;
case 6: return POWER_REGEN;
case 7: return WORLD_RESIST;
}
}
break;
case CLASS_ALIEN:
{
index = GetRandom(0, 7);
switch(index)
{
case 0: return SPIKER;
case 1: return OBSTACLE;
case 2: return GASSER;
case 3: return HEALER;
case 4: return SPORE;
case 5: return ACID;
case 6: return SPIKE;
case 7: return COCOON;
}
}
break;
}
return -1;
}
//************************************************************************************************
int CountRuneMods(item_t *rune)
{
int i;
int count = 0;
for(i = 0; i < MAX_VRXITEMMODS; ++i)
if(rune->modifiers[i].type != TYPE_NONE && rune->modifiers[i].value > 0)
++count;
return count;
}
//************************************************************************************************
// Physical functions
//************************************************************************************************
float V_EntDistance(edict_t *ent1, edict_t *ent2)
//Gets the absolute vector distance between 2 entities
{
vec3_t dist;
dist[0] = ent1->s.origin[0] - ent2->s.origin[0];
dist[1] = ent1->s.origin[1] - ent2->s.origin[1];
dist[2] = ent1->s.origin[2] - ent2->s.origin[2];
return sqrt((dist[0] * dist[0]) + (dist[1] * dist[1]) + (dist[2] * dist[2]));
}
//************************************************************************************************
void V_ResetAbilityDelays(edict_t *ent)
//Resets all of the selected ent's ability delays
{
int i;
//Reset ability cooldowns, even though almost none of them are used.
for (i = 0; i < MAX_ABILITIES; ++i)
ent->myskills.abilities[i].delay = 0.0f;
//Reset talent cooldowns as well.
for (i = 0; i < ent->myskills.talents.count; ++i)
ent->myskills.talents.talent[i].delay = 0.0f;
}
//************************************************************************************************
qboolean V_CanUseAbilities (edict_t *ent, int ability_index, int ability_cost, qboolean print_msg)
{
if (!ent->client)
return false;
if (!G_EntIsAlive(ent))
return false;
if (ent->myskills.abilities[ability_index].disable)
return false;
if (ent->owner && ent->owner->mtype == BOSS_TANK)
return false;
if (ent->owner && G_EntIsAlive(ent->owner) && IsABoss(ent->owner))
return false;
//4.2 can't use abilities in wormhole/noclip
if (ent->flags & FL_WORMHOLE)
return false;
// poltergeist cannot use abilities in human form
if (ent->myskills.class_num == CLASS_POLTERGEIST && !ent->mtype)
{
// allow them to morph
if (!PM_PlayerHasMonster(ent) && (ability_index != CACODEMON) && (ability_index != MUTANT) && (ability_index != BRAIN) && (ability_index != FLYER)
&& (ability_index != MEDIC) && (ability_index != BLOOD_SUCKER) && (ability_index != TANK) && (ability_index != BERSERK))
{
if (print_msg && !ent->ai.is_bot)
safe_cprintf(ent, PRINT_HIGH, "You can't use abilities in human form!\n");
return false;
}
}
if (ent->myskills.abilities[ability_index].current_level < 1)
{
if (print_msg && !ent->ai.is_bot)
safe_cprintf(ent, PRINT_HIGH, "You have to upgrade to use this ability!\n");
return false;
}
// enforce special rules on flag carrier in CTF mode
if (ctf->value && ctf_enable_balanced_fc->value && HasFlag(ent))
{
if (print_msg && !ent->ai.is_bot)
safe_cprintf(ent, PRINT_HIGH, "Flag carrier cannot use abilities.\n");
return false;
}
if (que_typeexists(ent->curses, CURSE_FROZEN))
return false;
if (level.time < pregame_time->value)
{
// gi.cprintf(ent, PRINT_HIGH, "You can't use abilities during pre-game.\n");
return false;
}
// can't use abilities immediately after a re-spawn
if (ent->client->respawn_time > level.time)
{
if (print_msg && !ent->ai.is_bot)
safe_cprintf (ent, PRINT_HIGH, "You can't use abilities for another %2.1f seconds.\n",
ent->client->respawn_time-level.time);
return false;
}
if (ent->client->ability_delay > level.time)
{
if (print_msg && !ent->ai.is_bot)
safe_cprintf (ent, PRINT_HIGH, "You can't use abilities for another %2.1f seconds.\n",
ent->client->ability_delay-level.time);
return false;
}
if (ent->myskills.abilities[ability_index].delay > level.time)
{
if (print_msg && !ent->ai.is_bot)
safe_cprintf(ent, PRINT_HIGH, "You can't use this ability for another %2.1f seconds.\n",
ent->myskills.abilities[ability_index].delay-level.time);
return false;
}
// can't use abilities if you don't have enough power cubes
if (ability_cost && (ent->client->pers.inventory[power_cube_index] < ability_cost))
{
if (print_msg && !ent->ai.is_bot)
safe_cprintf(ent, PRINT_HIGH, "You need more %d power cubes to use this ability.\n",
ability_cost-ent->client->pers.inventory[power_cube_index]);
return false;
}
// players cursed by amnesia can't use abilities
if (que_findtype(ent->curses, NULL, AMNESIA) != NULL)
{
if (print_msg)
safe_cprintf(ent, PRINT_HIGH, "You have been cursed with amnesia and can't use any abilities!!\n");
return false;
}
return true;
}
//************************************************************************************************
//Gives the player packs of ammo
qboolean V_GiveAmmoClip(edict_t *ent, float qty, int ammotype)
{
int amount;
int *max;
int *current;
switch(ammotype)
{
case AMMO_SHELLS:
amount = SHELLS_PICKUP;
current = &ent->client->pers.inventory[shell_index];
max = &ent->client->pers.max_shells;
break;
case AMMO_BULLETS:
amount = BULLETS_PICKUP;
current = &ent->client->pers.inventory[bullet_index];
max = &ent->client->pers.max_bullets;
break;
case AMMO_GRENADES:
amount = GRENADES_PICKUP;
current = &ent->client->pers.inventory[grenade_index];
max = &ent->client->pers.max_grenades;
break;
case AMMO_ROCKETS:
amount = ROCKETS_PICKUP;
current = &ent->client->pers.inventory[rocket_index];
max = &ent->client->pers.max_rockets;
break;
case AMMO_SLUGS:
amount = SLUGS_PICKUP;
current = &ent->client->pers.inventory[slug_index];
max = &ent->client->pers.max_slugs;
break;
case AMMO_CELLS:
amount = CELLS_PICKUP;
current = &ent->client->pers.inventory[cell_index];
max = &ent->client->pers.max_cells;
break;
default: return false;
}
//don't pick up ammo if you are full already
//if (*current >= *max) return false;
if (*current >= *max && qty > 0.0) return false;
//Multiply by the item quantity
amount *= qty;
//Multiply by the ammo efficiency skill
//if (!ent->myskills.abilities[AMMO_UPGRADE].disable)
// amount *= AMMO_UP_BASE + (AMMO_UP_MULT * ent->myskills.abilities[AMMO_UPGRADE].current_level);
//Talent: Improved HA Pickup
// if (getTalentSlot(ent, TALENT_BASIC_HA) != -1)
// amount *= 1.0 + (0.2 * getTalentLevel(ent, TALENT_BASIC_HA));
if(ent->myskills.talents.AmmoLevel > 0)
amount *= 1.0 + (0.33 * ent->myskills.talents.AmmoLevel);
//Give them the ammo
*current += amount;
if (*current > *max)
*current = *max;
if (*current < 0)
*current = 0;
return true;
}
//************************************************************************************************
//Returns an ammo type based on the player's respawn weapon.
int V_GetRespawnAmmoType(edict_t *ent)
{
switch (ent->myskills.respawn_weapon)
{
case 2: //sg
case 3: //ssg
case 12: //20mm
return AMMO_SHELLS;
case 4: //mg
case 5: //cg
return AMMO_BULLETS;
case 6: //gl
case 11: //hg
return AMMO_GRENADES;
case 7: //rl
return AMMO_ROCKETS;
case 9: //rg
return AMMO_SLUGS;
case 8: //hb
case 10: //bfg
return AMMO_CELLS;
default: //blaster/sword
return 0; //nothing
}
}
//************************************************************************************************
int GetClientNumber(edict_t *ent)
//Returns zero if a client was not found
{
edict_t *temp;
int i;
for (i = 1; i <= game.maxclients; i++)
{
temp = &g_edicts[i];
//Copied from id. do not crash
if (!temp->inuse)
continue;
if (!temp->client)
continue;
//More checking
if (strlen(temp->myskills.player_name) < 1)
continue;
if (Q_strcasecmp(ent->myskills.player_name, temp->myskills.player_name) == 0) //same name
return i+1;
}
return 0;
}
//************************************************************************************************
edict_t *V_getClientByNumber(int index)
//Gets client through an index number used in GetClientNumber()
{
return &g_edicts[index];
}
//************************************************************************************************
//************************************************************************************************
// New File I/O functions
//************************************************************************************************
//************************************************************************************************
char ReadChar(FILE *fptr)
{
char Value;
fread(&Value, sizeof(char), 1, fptr);
return Value;
}
//************************************************************************************************
void WriteChar(FILE *fptr, char Value)
{
fwrite(&Value, sizeof(char), 1, fptr);
}
//************************************************************************************************
void ReadString(char *buf, FILE *fptr)
{
int Length;
//get the string length
Length = ReadChar(fptr);
//If string is empty, abort
if (Length == 0)
{
buf[0] = 0;
//return buf;
}
fread(buf, Length, 1, fptr);
//Null terminate the string just read
buf[Length] = 0;
}
//************************************************************************************************
void WriteString(FILE *fptr, char *String)
{
int Length = strlen(String);
WriteChar(fptr, (char)Length);
fwrite(String, Length, 1, fptr);
}
//************************************************************************************************
int ReadInteger(FILE *fptr)
{
int Value;
fread(&Value, sizeof(int), 1, fptr);
return Value;
}
//************************************************************************************************
void WriteInteger(FILE *fptr, int Value)
{
fwrite(&Value, sizeof(int), 1, fptr);
}
//************************************************************************************************
long ReadLong(FILE *fptr)
{
long Value;
fread(&Value, sizeof(long), 1, fptr);
return Value;
}
//************************************************************************************************
void WriteLong(FILE *fptr, long Value)
{
fwrite(&Value, sizeof(long), 1, fptr);
}
//************************************************************************************************
char *V_FormatFileName(char *name)
{
char filename[64];
char buffer[64];
int i, j = 0;
//This bit of code formats invalid filename chars, like the '?' and
//reformats them into a saveable format.
Q_strncpy (buffer, name, sizeof(buffer)-1);
for (i = 0; i < strlen(buffer); ++i)
{
char tmp;
switch (buffer[i])
{
case '\\': tmp = '1'; break;
case '/': tmp = '2'; break;
case '?': tmp = '3'; break;
case '|': tmp = '4'; break;
case '"': tmp = '5'; break;
case ':': tmp = '6'; break;
case '*': tmp = '7'; break;
case '<': tmp = '8'; break;
case '>': tmp = '9'; break;
case '_': tmp = '_'; break;
default: tmp = '0'; break;
}
if (tmp != '0')
{
filename[j++] = '_';
filename[j++] = tmp;
}
else
{
filename[j++] = buffer[i];
}
}
//make sure string is null-terminated
filename[j] = 0;
return va("%s", filename);
}
//************************************************************************************************
//************************************************************************************************
// New File I/O functions (for parsing text files)
//************************************************************************************************
//************************************************************************************************
int V_tFileCountLines(FILE *fptr, long size)
{
int count = 0;
char temp;
int i = 0;
do
{
temp = getc(fptr);
if (temp == '\n')
count++;
}
while (++i < size);
rewind(fptr);
return count - 1; //Last line is always empty
}
//************************************************************************************************
void V_tFileGotoLine(FILE *fptr, int linenumber, long size)
{
int count = 0;
char temp;
int i = 0;
do
{
temp = fgetc(fptr);
if (temp == '\n')
count++;
if (count == linenumber)
return;
}
while (++i < size);
return;
}
//************************************************************************************************
// this needs to match NewLevel_Addons() in player_points.c
// NOTE: this function can't/won't award refunds if the ability was already upgraded
void UpdateFreeAbilities (edict_t *ent)
{
if (ent->myskills.level >= 0)
{
// free ID at level 0
if (!ent->myskills.abilities[ID].level)
{
ent->myskills.abilities[ID].level++;
ent->myskills.abilities[ID].current_level++;
}
// free scanner at level 10
if (ent->myskills.level >= 10)
{
if (!ent->myskills.abilities[SCANNER].level)
{
ent->myskills.abilities[SCANNER].level++;
ent->myskills.abilities[SCANNER].current_level++;
}
}
}
// free max ammo and vitality upgrade every 5 levels
ent->myskills.abilities[MAX_AMMO].level = ent->myskills.abilities[VITALITY].level = ent->myskills.level / 5;
}
#define CHANGECLASS_MSG_CHANGE 1
#define CHANGECLASS_MSG_RESET 2
void ChangeClass (char *playername, int newclass, int msgtype)
{
int i = 0;
edict_t *player;
float tempTalentPoints = 0;
if (!newclass)
return;
for (i = 1; i <= maxclients->value; i++)
{
player = &g_edicts[i];
if (!player->inuse)
continue;
if (Q_strcasecmp(playername, player->myskills.player_name) != 0)
continue;
if (newclass == CLASS_KNIGHT)
player->myskills.respawn_weapon = 1; //sword only
//Reset player's skills and change their class
memset(player->myskills.abilities, 0, sizeof(upgrade_t) * MAX_ABILITIES);
memset(player->myskills.weapons, 0, sizeof(weapon_t) * MAX_WEAPONS);
player->myskills.class_num = newclass;
//Give them some upgrade points.
player->myskills.speciality_points = 2 * player->myskills.level;
//if(player->myskills.class_num == CLASS_WEAPONMASTER)
// player->myskills.weapon_points = 6 * player->myskills.level;
//else
player->myskills.weapon_points = 4 * player->myskills.level;
//Weapon masters get double the weapon points of other classes.
//if(player->myskills.class_num == CLASS_WEAPONMASTER)
// player->myskills.weapon_points *= 2;
//Initialize their upgrades
disableAbilities(player);
setGeneralAbilities(player);
setClassAbilities(player);
resetWeapons(player);
//Check for special level-up bonuses
//max ammo and vit
UpdateFreeAbilities(player);
//player->myskills.abilities[MAX_AMMO].level = player->myskills.abilities[VITALITY].level = player->myskills.level / 5;
//if (player->myskills.level > 9)
// player->myskills.abilities[ID].level = 1;
//Reset talents, and give them their talent points
eraseTalents(player);
setTalents(player);
/*if(player->myskills.level < TALENT_MAX_LEVEL)
player->myskills.talents.talentPoints = player->myskills.level - TALENT_MIN_LEVEL + 1;
else player->myskills.talents.talentPoints = TALENT_MAX_LEVEL - TALENT_MIN_LEVEL + 1;*/
if (player->myskills.level < TALENT_MAX_LEVEL)
{
tempTalentPoints = player->myskills.level - TALENT_MIN_LEVEL + 1;
tempTalentPoints = ceil(tempTalentPoints/2.f);
player->myskills.talents.talentPoints = (int)tempTalentPoints;
}
else
{
tempTalentPoints = TALENT_MAX_LEVEL - TALENT_MIN_LEVEL + 1;
tempTalentPoints = ceil(tempTalentPoints/2.f);
player->myskills.talents.talentPoints = (int)tempTalentPoints;
}
if(player->myskills.talents.talentPoints < 0)
player->myskills.talents.talentPoints = 0;
//Re-apply equipment
V_ResetAllStats(player);
for (i = 0; i < 3; ++i)
V_ApplyRune(player, &player->myskills.items[i]);
if (msgtype == CHANGECLASS_MSG_CHANGE)
{
//Notify everyone
gi.cprintf(NULL, PRINT_HIGH, "%s's class was changed to %s (%d).\n", playername, GetClassString(newclass), newclass);
WriteToLogfile(player, va("Class was changed to %s (%d).\n", gi.argv(3), newclass));
gi.dprintf("%s's class was changed to %s (%d).\n", playername, gi.argv(3), newclass);
}
else if (msgtype == CHANGECLASS_MSG_RESET)
{
gi.cprintf(player, PRINT_HIGH, "Your ability and weapon upgrades have been reset!\n");
WriteToLogfile(player, "Character data was reset.\n");
gi.dprintf("%s's character data was reset.\n", playername);
}
//Reset max health/armor/ammo
modify_max(player);
//Save the player.
savePlayer(player);
return;
}
gi.dprintf("Can't find player: %s\n", playername);
}
void V_TruncateString (char *string, int newStringLength, char *dest)
{
// char buf[512];
if (!newStringLength || (newStringLength > 512))
return;
// it's already short enough
if (strlen(string) <= newStringLength)
return;
strncpy(dest,string,newStringLength);
dest[newStringLength] = '\0';
}
void V_RegenAbilityAmmo (edict_t *ent, int ability_index, int regen_frames, int regen_delay)
{
int ammo;
int max = ent->myskills.abilities[ability_index].max_ammo;
int *current = &ent->myskills.abilities[ability_index].ammo;
int *delay = &ent->myskills.abilities[ability_index].ammo_regenframe;
if (*current > max)
return;
// don't regenerate ammo if player is firing
// if (ent->client->buttons & BUTTON_ATTACK) decino: uhh, no :)
// return;
if (regen_delay > 0)
{
if (level.framenum < *delay)
return;
*delay = level.framenum + regen_delay;
}
else
regen_delay = 1;
ammo = floattoint((float)max / ((float)regen_frames / regen_delay));
//gi.dprintf("ammo=%d, max=%d, frames=%d, delay=%d\n", ammo, max, regen_frames, regen_delay);
if (ammo < 1)
ammo = 1;
//decino: only regenerate 20% of the ammo if we're firing
if (ent->client->buttons & BUTTON_ATTACK)
ammo *= 0.2;
*current += ammo;
if (*current > max)
*current = max;
}
void V_RestoreMorphed (edict_t *ent, int refund)
{
//gi.dprintf("V_RestoreMorphed()\n");
if (ent->myskills.class_num == CLASS_POLTERGEIST)
VortexRemovePlayerSummonables(ent);
if (PM_PlayerHasMonster(ent))
{
if (refund > 0)
ent->client->pers.inventory[power_cube_index] += refund;
// player's chasing this monster should now chase the player instead
PM_UpdateChasePlayers(ent->owner);
// remove the tank entity
M_Remove(ent->owner, false, false);
PM_RestorePlayer(ent);
return;
}
if (ent->mtype && (refund > 0))
ent->client->pers.inventory[power_cube_index] += refund;
ent->viewheight = 22;
ent->mtype = 0;
ent->s.modelindex = 255;
ent->s.skinnum = ent-g_edicts-1;
ShowGun(ent);
//decino: show cool morph fx!!!1!1!
ent->morph_blendtime = level.time + 0.1;
gi.sound(ent, CHAN_ITEM, gi.soundindex("misc/itembreak.wav"), 1, ATTN_NORM, 0);
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_BFG_BIGEXPLOSION);
gi.WritePosition (ent->s.origin);
gi.multicast (ent->s.origin, MULTICAST_PVS);
ent->client->lock_frames = 0;//4.2 reset smart-rocket lock-on counter
}
void mutant_checkattack (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf);
void V_Touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
{
// made a sound
if (other && other->inuse)
other->lastsound = level.framenum;
mutant_checkattack(self, other, plane, surf);
}
//FIXME: this doesn't work with 2-4 point abilities
void V_UpdatePlayerAbilities (edict_t *ent)
{
int i, refunded = 0;
upgrade_t old_abilities[MAX_ABILITIES];
qboolean points_refunded = false;
UpdateFreeAbilities(ent);
// make a copy of old abilities that we can use as a reference for comparison
for (i=0; i<MAX_ABILITIES; ++i)
memcpy(&old_abilities, ent->myskills.abilities, sizeof(upgrade_t) * MAX_ABILITIES);
// reset all ability upgrades
memset(ent->myskills.abilities, 0, sizeof(upgrade_t) * MAX_ABILITIES);
disableAbilities(ent);
// set general abilities
setGeneralAbilities(ent);
// set class-specific abilities
setClassAbilities(ent);
for (i=0; i<MAX_ABILITIES; ++i)
{
// if this ability was previously enabled, restore the upgrade level
if ((ent->myskills.abilities[i].disable == false) && (old_abilities[i].disable == false))
{
// restore previous upgrade level if our new max_level is greater or equal to the old one
if (ent->myskills.abilities[i].max_level >= old_abilities[i].max_level)
ent->myskills.abilities[i].level = old_abilities[i].level;
// otherwise set new upgrade level to soft max and refund unused points
else
{
refunded = old_abilities[i].level - ent->myskills.abilities[i].max_level;
ent->myskills.abilities[i].level = ent->myskills.abilities[i].max_level;
}
}
// if this upgrade was previously disabled, refund them points
else if ((ent->myskills.abilities[i].disable == true) && (old_abilities[i].disable == false))
refunded = old_abilities[i].level;
}
// re-apply equipment
V_ResetAllStats(ent);
for (i = 0; i < 3; ++i)
V_ApplyRune(ent, &ent->myskills.items[i]);
gi.cprintf(ent, PRINT_HIGH, "Your abilities have been updated.\n");
// have points been refunded?
if (refunded > 0)
{
ent->myskills.speciality_points += old_abilities[i].level;
gi.cprintf(ent, PRINT_HIGH, "%d ability points have been refunded.\n", refunded);
}
}
char *V_GetMonsterName (int mtype)
{
switch (mtype)
{
case M_SOLDIER:
case M_SOLDIERLT:
case M_SOLDIERSS:
return "soldier";
case M_FLIPPER:
return "flipper";
case M_FLYER:
return "flyer";
case M_INFANTRY:
return "infantry";
case M_INSANE:
case M_RETARD:
return "retard";
case M_GUNNER:
return "gunner";
case M_CHICK:
return "bitch";
case M_PARASITE:
return "parasite";
case M_FLOATER:
return "floater";
case M_HOVER:
return "hover";
case M_BERSERK:
return "berserker";
case M_MEDIC:
return "medic";
case M_MUTANT:
return "mutant";
case M_BRAIN:
return "brain";
case M_GLADIATOR:
return "gladiator";
case M_TANK:
case P_TANK:
return "tank";
case M_SUPERTANK:
return "supertank";
case M_JORG:
return "jorg";
case M_MAKRON:
return "makron";
case M_COMMANDER:
return "commander";
case M_MINISENTRY:
return "mini-sentry";
case M_SENTRY:
return "sentry";
case M_FORCEWALL:
return "force wall";
case M_DECOY:
return "admin clone";
case M_SKULL:
return "hellspawn";
case M_YINSPIRIT:
return "yin spirit";
case M_YANGSPIRIT:
return "yang spirit";
case M_BALANCESPIRIT:
return "balance spirit";
case M_AUTOCANNON:
return "autocannon";
case M_DETECTOR:
return "detector";
case TOTEM_FIRE:
return "fire totem";
case TOTEM_WATER:
return "water totem";
case TOTEM_AIR:
return "air totem";
case TOTEM_EARTH:
return "earth totem";
case TOTEM_NATURE:
return "nature totem";
case TOTEM_DARKNESS:
return "darkness totem";
case M_SPIKER:
return "spiker";
case M_OBSTACLE:
return "obstacle";
case M_GASSER:
return "gasser";
case M_SPIKEBALL:
return "spore";
case M_HEALER:
return "healer";
case M_COCOON:
return "cocoon";
case M_LASERPLATFORM:
return "laser platform";
case INVASION_PLAYERSPAWN:
case CTF_PLAYERSPAWN:
return "spawn";
default:
return "<unknown>";
}
}
qboolean V_IsPVP (void)
{
return (!pvm->value && !ctf->value && !ffa->value && !invasion->value && !ctf->value && !ptr->value);
}
qboolean V_HealthCache (edict_t *ent, int max_per_second, int update_frequency)
{
int heal, delta, max;
if (ent->health_cache_nextframe > level.framenum)
return false;
ent->health_cache_nextframe = level.framenum + update_frequency;
if (ent->health_cache > 0 && ent->health < ent->max_health)
{
if (update_frequency <= 10)
max = max_per_second / (10 / update_frequency);
else
max = max_per_second;
if (max > ent->health_cache)
max = ent->health_cache;
delta = ent->max_health - ent->health;
if (delta > max)
heal = max;
else
heal = delta;
ent->health += heal;
ent->health_cache -= heal;
// gi.dprintf("healed %d / %d (max %d) at %d\n", heal, ent->health_cache, max, level.framenum);
return true;
}
ent->health_cache = 0;
return false;
}
qboolean V_ArmorCache (edict_t *ent, int max_per_second, int update_frequency)
{
int heal, delta, max, max_armor;
int *armor;
if (ent->armor_cache_nextframe > level.framenum)
return false;
if (ent->client)
{
armor = &ent->client->pers.inventory[body_armor_index];
max_armor = MAX_ARMOR(ent);
}
else
{
armor = &ent->monsterinfo.power_armor_power;
max_armor = ent->monsterinfo.max_armor;
}
ent->armor_cache_nextframe = level.framenum + update_frequency;
if (ent->armor_cache > 0 && *armor < max_armor)
{
if (update_frequency <= 10)
max = max_per_second / (10 / update_frequency);
else
max = max_per_second;
if (max > ent->armor_cache)
max = ent->armor_cache;
delta = max_armor - *armor;
if (delta > max)
heal = max;
else
heal = delta;
*armor += heal;
ent->armor_cache -= heal;
return true;
}
ent->armor_cache = 0;
return false;
}
void V_ResetPlayerState (edict_t *ent)
{
if (PM_PlayerHasMonster(ent))
{
// player's chasing this monster should now chase the player instead
PM_UpdateChasePlayers(ent->owner);
// remove the monster entity
M_Remove(ent->owner, true, false);
// restore the player to original state
PM_RestorePlayer(ent);
}
// restore morphed player state
if (ent->mtype)
{
ent->viewheight = 22;
ent->mtype = 0;
ent->s.modelindex = 255;
ent->s.skinnum = ent-g_edicts-1;
ShowGun(ent);
// reset flyer rocket lock-on frames
ent->client->lock_frames = 0;
}
// reset railgun sniper frames
ent->client->refire_frames = 0;
// reset h/a cache
ent->health_cache = 0;
ent->health_cache_nextframe = 0;
ent->armor_cache = 0;
ent->armor_cache_nextframe = 0;
// boot them out of a wormhole, but don't forget to teleport them to a valid location!
ent->flags &= ~FL_WORMHOLE;
ent->svflags &= ~SVF_NOCLIENT;
ent->movetype = MOVETYPE_WALK;
// reset detected state
ent->flags &= ~FL_DETECTED;
ent->detected_time = 0;
// reset cocooned state
ent->cocoon_time = 0;
ent->cocoon_factor = 0;
// disble fury
ent->fury_time = 0;
// disable movement abilities
//jetpack
ent->client->thrusting = 0;
//grapple hook
ent->client->hook_state = HOOK_READY;
// super speed
ent->superspeed = false;
// mana shield
ent->manashield = false;
// reset holdtime
ent->holdtime = 0;
// powerups
ent->client->invincible_framenum = 0;
ent->client->quad_framenum = 0;
// reset ability delay
ent->client->ability_delay = 0;
V_ResetAbilityDelays(ent);
// reset their velocity
VectorClear(ent->velocity);
// remove curses
CurseRemove(ent, 0);
if (ent->client)
ent->client->is_poisoned = false;
// remove auras
AuraRemove(ent, 0);
// remove movement penalty
ent->Slower = 0;
ent->slowed_factor = 1.0;
ent->slowed_time = 0;
ent->chill_level = 0;
ent->chill_time = 0;
// remove all summonables
VortexRemovePlayerSummonables(ent);
// if teamplay mode, set team skin
if (ctf->value || domination->value)
{
char *s = Info_ValueForKey(ent->client->pers.userinfo, "skin");
AssignTeamSkin(ent, s);
// drop the flag
dom_dropflag(ent, FindItem("Flag"));
CTF_DropFlag(ent, FindItem("Red Flag"));
CTF_DropFlag(ent, FindItem("Blue Flag"));
}
// drop all techs
tech_dropall(ent);
// disable scanner
ClearScanner(ent->client);
// stop trading
EndTrade(ent);
}
/*
============
V_TouchSolids
A modified version of G_TouchTriggers that will call the touch function
of any valid intersecting entities
============
*/
void V_TouchSolids (edict_t *ent)
{
int i, num;
edict_t *touch[MAX_EDICTS], *hit;
// sanity check
if (!ent || !ent->inuse || !ent->takedamage)
return;
num = gi.BoxEdicts (ent->absmin, ent->absmax, touch, MAX_EDICTS, AREA_SOLID);
// be careful, it is possible to have an entity in this
// list removed before we get to it (killtriggered)
for (i=0 ; i<num ; i++)
{
hit = touch[i];
if (!hit->inuse || !hit->touch || !hit->takedamage || hit == ent)
continue;
hit->touch (hit, ent, NULL, NULL);
}
}
// returns true if an entity has any offensive
// (meaning they can do damage) deployed
qboolean V_HasSummons (edict_t *ent)
{
return (ent->num_sentries || ent->num_monsters || ent->skull || ent->num_spikers
|| ent->num_autocannon || ent->num_gasser || ent->num_caltrops || ent->num_proxy
|| ent->num_obstacle || ent->num_armor || ent->num_spikeball || ent->num_lasers);
}<file_sep>#include "g_local.h"
extern qboolean is_quad;
#define SWORD_DEATHMATCH_DAMAGE sabre_damage_initial->value//130
#define SWORD_KICK sabre_kick->value//400
#define SWORD_RANGE sabre_range->value//60
extern byte is_silenced;//K03
/*
=============
fire_sword
attacks with the beloved sword of the highlander
edict_t *self - entity producing it, yourself
vec3_t start - The place you are
vec3_t aimdir - Where you are looking at in this case
int damage - the damage the sword inflicts
int kick - how much you want that bitch to be thrown back
=============
*/
void Laser_PreThink(edict_t *self)
{
VectorCopy(self->moveinfo.start_origin, self->s.origin);
VectorCopy(self->moveinfo.end_origin, self->s.old_origin);
//VectorCreateVelocity(self->s.old_origin, self->s.origin, self->velocity);
VectorSubtract(self->s.old_origin, self->s.origin, self->velocity);
VectorScale(self->velocity, 10, self->velocity);
//if the radius isn't the final length then adjust it
if (self->s.frame != self->health)
{
int difference = self->health - self->max_health;
float total_time = self->delay - self->wait;
float time_ellapsed = level.time - self->wait;
self->s.frame = self->max_health + (int)((difference / total_time) * time_ellapsed);
}
if (level.time >= self->delay)
{
G_FreeEdict(self);
return;
}
self->nextthink = level.time + FRAMETIME;
gi.linkentity(self);
}
/*
colors
The way laser colors work is based on color palette indexes found in pak0 pics/colormap.pcx
Each byte of the long represents 1 stage of the laser and each of the 4 bytes get cycled through in order
0xf2f2f0f0 - red
0xd0d1d2d3 - green
0xf3f3f1f1 - blue
0xdcdddedf - yellow
0xe0e1e2e3 - orange
0x80818283 - dark purple
0x70717273 - light blue
0x90919293 - different green
0xb0b1b2b3 - purple
0x40414243 - different red
0xe2e5e3e6 - orange
0xd0f1d3f3 - blue and green
0xf2f3f0f1 - inner = red, outer = blue
0xf3f2f1f0 - inner = blue, outer = red
0xdad0dcd2 - inner = green, outer = yellow
0xd0dad2dc - inner = yellow, outer = green
*/
edict_t *CreateLaser(edict_t *owner, vec3_t start, vec3_t end, int effects, int color, int diameter, int final_diameter, float time)
{
edict_t *laser = G_Spawn();
laser->classname = "laser";
laser->owner = owner;
laser->think = Laser_PreThink;
laser->nextthink = level.time + FRAMETIME;
laser->s.frame = diameter;
laser->s.skinnum = color;
laser->s.renderfx = RF_BEAM | RF_TRANSLUCENT;
laser->s.effects = effects;
laser->movetype = MOVETYPE_NOCLIP;
laser->clipmask = MASK_ALL;
laser->model = NULL;
laser->s.modelindex = 1;
laser->max_health = diameter; //store original diameter here
laser->health = final_diameter; //store final diameter here
laser->wait = level.time; //store original time created here for calculating final size
laser->delay = level.time + time;
//store the start and end points between frames
VectorCopy(start, laser->moveinfo.start_origin);
VectorCopy(end, laser->moveinfo.end_origin);
//kick off the lasers movement
laser->think(laser);
return laser;
}
void fire_sword_old ( edict_t *self, vec3_t start, vec3_t aimdir, int damage, int kick)
{
trace_t tr; //detect whats in front of you up to range "vec3_t end"
vec3_t end;
vec3_t begin;
vec3_t begin_offset;
int sword_bonus = 1;
int swordrange;
// calling entity made a sound, used to alert monsters
self->lastsound = level.framenum;
// if (self->myskills.class_num == CLASS_KNIGHT) //doomie
// sword_bonus = 1.5;
swordrange = SABRE_INITIAL_RANGE + (SABRE_ADDON_RANGE * self->myskills.weapons[WEAPON_SWORD].mods[2].current_level * sword_bonus);
VectorSet( begin_offset,0,0,self->viewheight-8);
VectorAdd( self->s.origin, begin_offset, begin);
// Figure out what we hit, if anything:
VectorMA (start, swordrange, aimdir, end); //calculates the range vector
tr = gi.trace (begin, NULL, NULL, end, self, MASK_SHOT);
// figuers out what in front of the player up till "end"
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_BFG_LASER);
gi.WritePosition (begin);
gi.WritePosition (tr.endpos);
gi.multicast (begin, MULTICAST_PHS);
// Figure out what to do about what we hit, if anything
if (!((tr.surface) && (tr.surface->flags & SURF_SKY)))
{
if (tr.fraction < 1.0)
{
if (tr.ent->takedamage)
{
if (self->myskills.weapons[WEAPON_SWORD].mods[4].current_level < 1)
gi.sound (self, CHAN_WEAPON, gi.soundindex("misc/fhit3.wav") , 1, ATTN_NORM, 0);
if (T_Damage (tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal, damage, kick, 0, MOD_SWORD))
{
if (self->myskills.weapons[WEAPON_SWORD].mods[3].current_level >= 1)
burn_person(tr.ent, self, (int)(SABRE_ADDON_HEATDAMAGE * self->myskills.weapons[WEAPON_SWORD].mods[3].current_level * sword_bonus));
}
}
//else gi.multicast(begin,MULTICAST_PHS);
}
if (self->myskills.weapons[WEAPON_SWORD].mods[4].current_level < 1)
{
gi.WriteByte (svc_muzzleflash);
gi.WriteShort (self-g_edicts);
gi.WriteByte (MZ_IONRIPPER|MZ_SILENCED);
gi.multicast (self->s.origin, MULTICAST_PVS);
}
}
}
void fire_sword (edict_t *self, vec3_t start, vec3_t dir, int damage, int length, int color)
{
edict_t *ignore;
trace_t tr, tr2;
vec3_t from, end;
vec3_t mins, maxs;
qboolean water;
int mask;
int kick = 100;
int count = 0;
int swordrange;
int talentLevel;
talentLevel = getTalentLevel(self, TALENT_DURABILITY);
VectorSet(mins, -2, -2, -2);
VectorSet(maxs, 2, 2, 2);
// calling entity made a sound, used to alert monsters
self->lastsound = level.framenum;
swordrange = SABRE_INITIAL_RANGE + (SABRE_ADDON_RANGE * self->myskills.weapons[WEAPON_SWORD].mods[2].current_level) * (1 + 0.33*talentLevel);
//decino: special for decoys
if (self->mtype == M_DECOY)
swordrange = SABRE_INITIAL_RANGE + (SABRE_ADDON_RANGE * self->activator->myskills.weapons[WEAPON_SWORD].mods[2].current_level);
//create starting and ending positions for trace
VectorCopy(start, from);
VectorMA(start, swordrange, dir, end);
// gi.dprintf("Sword range: %d\n", swordrange);
//taken from railgun fire code
ignore = self;
water = false;
mask = MASK_SHOT;
while (ignore)
{
tr = gi.trace (from, mins, maxs, end, ignore, mask);
//ZOID--added so rail goes through SOLID_BBOX entities (gibs, etc)
if ((tr.ent->svflags & SVF_MONSTER) || (tr.ent->client) ||
(tr.ent->solid == SOLID_BBOX))
ignore = NULL;//decino: no pierce
else
ignore = NULL;
if ((tr.ent != self) && (tr.ent->takedamage))
{
if (self->myskills.weapons[WEAPON_SWORD].mods[4].current_level < 1)
gi.sound (self, CHAN_WEAPON, gi.soundindex("misc/fhit3.wav") , 1, ATTN_NORM, 0);
if (T_Damage (tr.ent, self, self, dir, tr.endpos, tr.plane.normal, damage, kick, 0, MOD_SWORD))
{
if (self->myskills.weapons[WEAPON_SWORD].mods[3].current_level >= 1)
burn_person(tr.ent, self, (int)(SABRE_ADDON_HEATDAMAGE * self->myskills.weapons[WEAPON_SWORD].mods[3].current_level));
}
}
VectorCopy (tr.endpos, from);
if (++count >= MAX_EDICTS)
break;
}
//trace forward and back to find water
tr2 = gi.trace(tr.endpos, NULL, NULL, start, tr.ent, MASK_WATER);
if (tr2.contents & MASK_WATER)
water = true;
else //water not found going backwards so try forwards
{
tr2 = gi.trace(start, NULL, NULL, tr.endpos, self, MASK_WATER);
if (tr2.contents & MASK_WATER)
water = true;
}
CreateLaser(self, start, tr.endpos, 0, color, 4, 4, 0.1);
if (water) //create a laser in the reverse direction so it shows up in and out of water
CreateLaser(self, tr.endpos, start, 0, color, 4, 4, 0.1);
}
void lance_touch (edict_t *ent, edict_t *other, cplane_t *plane, csurface_t *surf)
{
vec3_t origin;
int n;
if (!G_EntExists(ent->owner))
{
G_FreeEdict(ent);
return;
}
if (other == ent->owner)
return;
if (surf && (surf->flags & SURF_SKY))
{
G_FreeEdict (ent);
return;
}
if (ent->owner->client)
PlayerNoise(ent->owner, ent->s.origin, PNOISE_IMPACT);
// calculate position for the explosion entity
VectorMA (ent->s.origin, -0.02, ent->velocity, origin);
if (other->takedamage){
T_Damage (other, ent, ent->owner, ent->velocity, ent->s.origin, plane->normal, ent->dmg, 0, 0, MOD_SWORD);
if (ent->owner->myskills.weapons[WEAPON_SWORD].mods[4].current_level < 1)
gi.sound (other, CHAN_WEAPON, gi.soundindex("misc/fhit3.wav") , 1, ATTN_NORM, 0);}
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_BFG_EXPLOSION);
gi.WritePosition (origin);
gi.multicast (ent->s.origin, MULTICAST_PHS);
G_FreeEdict (ent);
}
void lance_think (edict_t *self)
{
int i;
int color;
vec3_t start, forward;
vec3_t dir;
// remove lance if owner dies or becomes invalid
// or the lance times out
if (!G_EntIsAlive(self->owner) || (level.time >= self->delay))
{
G_FreeEdict(self);
return;
}
VectorNormalize2(self->velocity, dir);
vectoangles(dir, self->s.angles);
// 0 = black, 8 = grey, 15 = white, 16 = light brown, 20 = brown, 57 = light orange, 66 = orange/red, 73 = maroon
// 106 = pink, 113 = light blue, 119 = blue, 123 = dark blue, 200 = pale green, 205 = dark green, 209 = bright green
// 217 = white, 220 = yellow, 226 = orange, 231 = red/orange, 240 = red, 243 = dark blue
if (self->owner->myskills.sword_red)
color = 240;
else if (self->owner->myskills.sword_yellow)
color = 220;
else if (self->owner->myskills.sword_green)
color = 209;
else if (self->owner->myskills.sword_blue)
color = 117;
else if (self->owner->myskills.sword_orange)
color = 223;
else if (self->owner->myskills.sword_purple)
color = 105;
else
color = 0;
VectorCopy(self->s.origin, start);
VectorCopy(self->velocity, forward);
VectorNormalize(forward);
// create a trail behind the lance
for (i=0; i<6; i++)
{
gi.WriteByte(svc_temp_entity);
gi.WriteByte(TE_LASER_SPARKS);
gi.WriteByte(1); // number of sparks
gi.WritePosition(start);
gi.WriteDir(forward);
gi.WriteByte(color); // color
gi.multicast(start, MULTICAST_PVS);
VectorMA(start, -2, forward, start);
}
self->nextthink = level.time + FRAMETIME;
}
void fire_lance (edict_t *self, vec3_t start, vec3_t dir, int damage, int speed)
{
edict_t *lance;
// calling entity made a sound, used to alert monsters
self->lastsound = level.framenum;
lance = G_Spawn();
VectorCopy (start, lance->s.origin);
VectorCopy (dir, lance->movedir);
vectoangles (dir, lance->s.angles);
VectorScale (dir, speed, lance->velocity);
lance->movetype = MOVETYPE_TOSS;
lance->clipmask = MASK_SHOT;
lance->solid = SOLID_BBOX;
VectorClear (lance->mins);
VectorClear (lance->maxs);
lance->s.modelindex = gi.modelindex ("models/objects/laser/tris.md2");
lance->owner = self;
lance->s.effects = (EF_COLOR_SHELL|EF_SPHERETRANS);
if (self->myskills.sword_red)
lance->s.renderfx = RF_SHELL_RED;
else if (self->myskills.sword_yellow)
lance->s.renderfx = RF_SHELL_YELLOW;
else if (self->myskills.sword_green)
lance->s.renderfx = RF_SHELL_GREEN;
else if (self->myskills.sword_blue)
lance->s.renderfx = RF_SHELL_BLUE;
else if (self->myskills.sword_orange)
lance->s.renderfx = (RF_SHELL_RED|RF_SHELL_YELLOW);
else if (self->myskills.sword_purple)
lance->s.renderfx = (RF_SHELL_RED|RF_SHELL_BLUE);
else
lance->s.renderfx = 0;
lance->touch = lance_touch;
lance->nextthink = level.time + FRAMETIME;
lance->think = lance_think;
lance->delay = level.time + 8000/speed;
lance->dmg = damage;
lance->classname = "lance";
gi.linkentity (lance);
}
void sword_attack (edict_t *ent, vec3_t g_offset, int damage)
{
vec3_t forward, right;
vec3_t start;
vec3_t offset;
int color;
int swordrange = SABRE_INITIAL_RANGE + SABRE_ADDON_RANGE * ent->myskills.weapons[WEAPON_SWORD].mods[2].current_level;
if (is_quad)
damage *= 4;
AngleVectors (ent->client->v_angle, forward, right, NULL);
VectorSet(offset, 8, 8, ent->viewheight-8);
P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start);
//FIXME: would be better to have 1 sword value like myskills.sword_color instead of having
//every color individually, would also prevent data corruption if you ever add a new color.
if (ent->myskills.sword_red)
color = 0xf2f2f0f0;
else if (ent->myskills.sword_yellow)
color = 0xdcdddedf;
else if (ent->myskills.sword_green)
color = 0xd0d1d2d3;
else if (ent->myskills.sword_blue)
color = 0xf3f3f1f1;
else if (ent->myskills.sword_orange)
color = 0xe0e1e2e3;
else if (ent->myskills.sword_purple)
color = 0xf3f2f1f0;
else
color = 0; //black
if (ent->client->weapon_mode && ent->swordtimer <= level.time)
{
swordrange *= 10;
damage *= 1.5;
fire_lance (ent, start, forward, damage, swordrange);
ent->swordtimer = level.time + 1.4;
return;
}
if (ent->swordtimer >= level.time)
return;
fire_sword (ent, start, forward, damage, SABRE_INITIAL_KICK + SABRE_ADDON_KICK * ent->myskills.weapons[WEAPON_SWORD].mods[0].current_level, color);
}
void Weapon_Sword_Fire (edict_t *ent)
{
int sword_bonus = 1;
int damage;
float temp;
// special rules; flag carrier can't use weapons
if (ctf->value && ctf_enable_balanced_fc->value && HasFlag(ent))
return;
if (ent->myskills.class_num == CLASS_KNIGHT)
sword_bonus = 1;//decino: 1.5, no use for bonus now
damage = SABRE_INITIAL_DAMAGE + (SABRE_ADDON_DAMAGE * ent->myskills.weapons[WEAPON_SWORD].mods[0].current_level * sword_bonus);
// sword forging reduces the per-frame damage penalty
temp = 0.8 + 0.007 * ent->myskills.weapons[WEAPON_SWORD].mods[1].current_level;
if ((temp < 1.0) && (ent->client->ps.gunframe - 5 > 0))
damage *= pow(temp, ent->client->ps.gunframe - 5);
//gi.dprintf("damage=%d\n", damage);
if ((ent->client->ps.gunframe == 5) && (ent->myskills.weapons[WEAPON_SWORD].mods[4].current_level < 1))
gi.sound (ent, CHAN_WEAPON, gi.soundindex("misc/power1.wav") , 1, ATTN_NORM, 0);
if ( ent->client->buttons & BUTTON_ATTACK )
sword_attack (ent, vec3_origin, damage);
ent->client->ps.gunframe++;
}
void Weapon_Sword (edict_t *ent)
{
static int pause_frames[] = {19, 32, 0};
static int fire_frames[] = {5, 6, 7, 8, 9, 10, 11, 12, 13, 0};//was 5, 0
int fire_last=20;
//K03 Begin
//if (ent->myskills.weapons[WEAPON_SWORD].mods[1].current_level > 9)
// fire_last = 16;
//else if (ent->myskills.weapons[WEAPON_SWORD].mods[1].current_level > 4)
// fire_last = 18;
Weapon_Generic (ent, 4, fire_last, 52, 55, pause_frames, fire_frames, Weapon_Sword_Fire);
}<file_sep>#ifndef SETTINGS
#define SETTINGS
#define VRX_VERSION "1.0 BETA"
#define RUNE_PICKUP_DELAY 2.0 // time before another rune can be picked up
#define SENTRY_MAXIMUM 1 //Maximum number of sentry guns allowed
// berserker sprint
#define SPRINT_COST 4 // per frame ability charge cost
#define SPRINT_MAX_CHARGE 100 // maximum charge
#define SPRINT_CHARGE_RATE 10 // rate of charge per second while ability is unused
#define SHIELD_COST 2 // per frame ability charge cost
#define SHIELD_MAX_CHARGE 100 // maximum charge
#define SHIELD_CHARGE_RATE 10 // rate of charge per second while ability is unused
#define SHIELD_FRONT_PROTECTION 1.0 // damage absorbed for front (power screen) protection
#define SHIELD_BODY_PROTECTION 0.8 // damage absorbed for full-body protection
#define SHIELD_ABILITY_DELAY 0.3 // seconds before shield can be re-activated
#define SMARTROCKET_LOCKFRAMES 3 // frames required for smart rocket to lock-on to a target
#define DAMAGE_ESCAPE_DELAY 0.2 // seconds before player can use tball/jetpack/boost/teleport/superspeed after being damaged
#define EXP_PLAYER_MONSTER 20
#define EXP_WORLD_MONSTER 20
#define AMMO_REGEN_DELAY 5.0 // seconds until next ammo regen tick
#define MAX_KNOCKBACK 300 // maximum knockback allowed for some attacks (e.g. rocket explosion)
#define CHAT_PROTECT_FRAMES 200
#define MAX_HOURS 24 //Maximum playing time per day (hours)
#define NEWBIE_BASHER_MAX 3 * AveragePlayerLevel() //maximum level a newbie basher can be
#define MAX_MINISENTRIES 2// number of minisentries you can have out at a time
#define MAX_CREDITS 1000000 // max credits someone can have; update this on next reset to unsigned long!
// General settings
#define CLOAK_DRAIN_TIME 1 //10 frames = 1 second
#define CLOAK_DRAIN_AMMO 1.0
#define CLOAK_COST 50
#define CLOAK_ACTIVATE_TIME 2 // cloak after 3 seconds
#define LASER_TIMEUP 60
#define LASER_COST 25
#define LASER_CUTDAMAGE 15 // damage per frame
#define MAX_LASERS 6
#define LASER_SPAWN 3
#define SUPERSPEED_DRAIN_COST 3
#define RESPAWN_INVIN_TIME 20 //2.0 seconds
// force wall
#define FORCEWALL_WIDTH 256
#define FORCEWALL_HEIGHT 128
#define FORCEWALL_THICKNESS 16
#define FORCEWALL_DELAY 2.0
#define FORCEWALL_SOLID_COST 20
#define FORCEWALL_NOTSOLID_COST 50
#define MAX_PIPES 8
#define PTR_MAX_IDLE_FRAMES 600
#define MAX_IDLE_FRAMES 1800
// Sprees
#define SPREE_WARS 1
#define SPREE_START 6
#define SPREE_WARS_START 25
#define SPREE_WARS_BONUS 2
#define SPREE_BONUS 0.5
#define SPREE_BREAKBONUS 25
// Health and armor settings
#define INITIAL_HEALTH_SOLDIER 100
#define INITIAL_HEALTH_NECROMANCER 100
#define INITIAL_HEALTH_ENGINEER 100
#define INITIAL_HEALTH_VAMPIRE 100
#define INITIAL_HEALTH_POLTERGEIST 100
#define INITIAL_HEALTH_KNIGHT 100
#define INITIAL_HEALTH_CLERIC 100
#define INITIAL_HEALTH_MAGE 100
#define INITIAL_HEALTH_WEAPONMASTER 100
#define INITIAL_HEALTH_SHAMAN 100
#define INITIAL_HEALTH_ALIEN 100
#define LEVELUP_HEALTH_SOLDIER 1
#define LEVELUP_HEALTH_NECROMANCER 1
#define LEVELUP_HEALTH_ENGINEER 2
#define LEVELUP_HEALTH_VAMPIRE 5
#define LEVELUP_HEALTH_POLTERGEIST 5
#define LEVELUP_HEALTH_KNIGHT 1
#define LEVELUP_HEALTH_CLERIC 5
#define LEVELUP_HEALTH_MAGE 1
#define LEVELUP_HEALTH_WEAPONMASTER 1
#define LEVELUP_HEALTH_SHAMAN 5
#define LEVELUP_HEALTH_ALIEN 1
#define INITIAL_ARMOR_SOLDIER 50
#define INITIAL_ARMOR_NECROMANCER 50
#define INITIAL_ARMOR_ENGINEER 100
#define INITIAL_ARMOR_VAMPIRE 50
#define INITIAL_ARMOR_POLTERGEIST 50
#define INITIAL_ARMOR_KNIGHT 100
#define INITIAL_ARMOR_CLERIC 50
#define INITIAL_ARMOR_MAGE 50
#define INITIAL_ARMOR_WEAPONMASTER 50
#define INITIAL_ARMOR_SHAMAN 50
#define INITIAL_ARMOR_ALIEN 50
#define LEVELUP_ARMOR_SOLDIER 1
#define LEVELUP_ARMOR_NECROMANCER 0
#define LEVELUP_ARMOR_ENGINEER 5
#define LEVELUP_ARMOR_VAMPIRE 0
#define LEVELUP_ARMOR_POLTERGEIST 0
#define LEVELUP_ARMOR_KNIGHT 10
#define LEVELUP_ARMOR_CLERIC 2
#define LEVELUP_ARMOR_MAGE 0
#define LEVELUP_ARMOR_WEAPONMASTER 1
#define LEVELUP_ARMOR_SHAMAN 0
#define LEVELUP_ARMOR_ALIEN 0
// Respawning
#define TBALLS_RESPAWN 1
#define POWERCUBES_RESPAWN 25
//Ammo pickups (also handled during respawning)
#define SHELLS_PICKUP 10
#define BULLETS_PICKUP 50
#define GRENADES_PICKUP 5
#define ROCKETS_PICKUP 5
#define CELLS_PICKUP 50
#define SLUGS_PICKUP 5
// Ammo upgrade skill
#define AMMO_UP_BASE 1.0
#define AMMO_UP_MULT 0.1 //10%
// CTF
#define CTF_CAPTURE_BASE ctf_capture_base->value
#define CTF_CAPTURE_BONUS 0.5
#define CTF_TEAM_BONUS 1
#define CTF_RETURN_FLAG_ASSIST_BONUS 1.2
#define CTF_FRAG_CARRIER_ASSIST_BONUS 1.2
#define CTF_MIN_CAPTEAM ctf_min_capteam->value
#define CTF_RECOVERY_BONUS 5
#define CTF_FLAG_BONUS 0
#define CTF_FRAG_MODIFIER ctf_frag_modifier->value
#define CTF_TEAMMATE_FRAGAWARD ctf_teammate_fragaward->value
#define CTF_FRAG_CARRIER_BONUS 1.3
#define CTF_CARRIER_DANGER_PROTECT_BONUS 1.2
#define CTF_CARRIER_PROTECT_BONUS 1.1
#define CTF_FLAG_DEFENSE_BONUS 1.2
#define CTF_TARGET_PROTECT_RADIUS 400
#define CTF_ATTACKER_PROTECT_RADIUS 400
#define CTF_CARRIER_DANGER_PROTECT_TIMEOUT 8
#define CTF_FRAG_CARRIER_ASSIST_TIMEOUT 10
#define CTF_RETURN_FLAG_ASSIST_TIMEOUT 10
#define CTF_AUTO_FLAG_RETURN_TIMEOUT 30
#define CTF_FORCE_EVENTEAMS ctf_force_eventeams->value
#define CTF_TECH_TIMEOUT 30
#define CTF_FLAG_HOLDTIME 300
// Points
#define START_NEXTLEVEL 500
#define NEXTLEVEL_MULT 1.5
#define BONUS_2FER 4
#define BONUS_ACCURACY 0
#define BONUS_ACCURACY_START 100
#define EXP_PLAYER_BASE 30
#define EXP_OTHER_BASE 5
#define EXP_INIT 2
#define EXP_MONSTER 5
#define EXP_LOW 4
#define EXP_SAME 6
#define EXP_HIGH 8
#define EXP_LOSE_LOW 0
#define EXP_LOSE_SAME 1
#define EXP_LOSE_HIGH 2
#define EXP_LOSE_SUICIDE 5
#define EXP_MINIBOSS 100
#define CREDITS_PLAYER_BASE 10
#define CREDITS_OTHER_BASE 10
#define CREDIT_LOW 1
#define CREDIT_SAME 2
#define CREDIT_HIGH 3
// Weapons
#define SABRE_INITIAL_DAMAGE 100
#define SABRE_ADDON_DAMAGE 5
#define SABRE_ADDON_HEATDAMAGE 2
#define SABRE_INITIAL_RANGE 64
#define SABRE_ADDON_RANGE 3.2
#define SABRE_INITIAL_KICK 100
#define SABRE_ADDON_KICK 0
#define BLASTER_INITIAL_DAMAGE_MIN 10
#define BLASTER_INITIAL_DAMAGE_MAX 40
#define BLASTER_ADDON_DAMAGE_MIN 2
#define BLASTER_ADDON_DAMAGE_MAX 3
#define BLASTER_INITIAL_HASTE 50
#define BLASTER_ADDON_HASTE 14
#define BLASTER_INITIAL_SPEED 1000
#define BLASTER_ADDON_SPEED 50
// 20mm cannon
#define WEAPON_20MM_INITIAL_DMG_MIN 30
#define WEAPON_20MM_INITIAL_DMG_MAX 50
#define WEAPON_20MM_ADDON_DMG_MIN 1.5
#define WEAPON_20MM_ADDON_DMG_MAX 2.5
// fires every 1.0 seconds
#define SHOTGUN_INITIAL_DAMAGE 8
#define SHOTGUN_ADDON_DAMAGE 0.2//0.3
#define SHOTGUN_INITIAL_BULLETS 10
#define SHOTGUN_ADDON_BULLETS 0.5
// fires every 1.2 seconds
#define SUPERSHOTGUN_INITIAL_DAMAGE 10
#define SUPERSHOTGUN_ADDON_DAMAGE 0.4//0.3
#define SUPERSHOTGUN_INITIAL_BULLETS 15
#define SUPERSHOTGUN_ADDON_BULLETS 0.5
#define MACHINEGUN_INITIAL_DAMAGE 10
#define MACHINEGUN_ADDON_DAMAGE 0.5
#define MACHINEGUN_ADDON_TRACERDAMAGE 3
// note: CG fires 40 bullets/sec
#define CHAINGUN_INITIAL_DAMAGE 5
#define CHAINGUN_ADDON_DAMAGE 0.2
#define CHAINGUN_ADDON_TRACERDAMAGE 5
#define GRENADE_INITIAL_DAMAGE 200
#define GRENADE_ADDON_DAMAGE 10
#define GRENADE_INITIAL_RADIUS_DAMAGE 200
#define GRENADE_ADDON_RADIUS_DAMAGE 10
#define GRENADE_INITIAL_RADIUS 100
#define GRENADE_ADDON_RADIUS 5.0 //7.5 was too much, let's try 5?
// fires every 7-8 frames
#define GRENADELAUNCHER_INITIAL_DAMAGE 100
#define GRENADELAUNCHER_ADDON_DAMAGE 5
#define GRENADELAUNCHER_INITIAL_RADIUS_DAMAGE 100
#define GRENADELAUNCHER_ADDON_RADIUS_DAMAGE 5
#define GRENADELAUNCHER_INITIAL_RADIUS 100
#define GRENADELAUNCHER_ADDON_RADIUS 2.5
#define GRENADELAUNCHER_INITIAL_SPEED 600
#define GRENADELAUNCHER_ADDON_SPEED 30
// fires every 7-8 frames
#define ROCKETLAUNCHER_INITIAL_DAMAGE 100
#define ROCKETLAUNCHER_ADDON_DAMAGE 3.5//2.5
#define ROCKETLAUNCHER_INITIAL_SPEED 650
#define ROCKETLAUNCHER_ADDON_SPEED 25
#define ROCKETLAUNCHER_INITIAL_RADIUS_DAMAGE 100
#define ROCKETLAUNCHER_ADDON_RADIUS_DAMAGE 2.5
#define ROCKETLAUNCHER_INITIAL_DAMAGE_RADIUS 100
#define ROCKETLAUNCHER_ADDON_DAMAGE_RADIUS 2.5
// hyperblaster fires every other frame, 5 bolts/sec
#define HYPERBLASTER_INITIAL_DAMAGE 30
#define HYPERBLASTER_ADDON_DAMAGE 1.5 //1
#define HYPERBLASTER_INITIAL_SPEED 1500
#define HYPERBLASTER_ADDON_SPEED 50
// fires every 13-14 frames
#define RAILGUN_INITIAL_DAMAGE 100
#define RAILGUN_ADDON_DAMAGE 8//10
#define RAILGUN_ADDON_HEATDAMAGE 1.0
#define BFG10K_INITIAL_DAMAGE 30
#define BFG10K_ADDON_DAMAGE 2.0
#define BFG10K_INITIAL_SPEED 650
#define BFG10K_ADDON_SPEED 35
#define BFG10K_RADIUS 150
#define BFG10K_INITIAL_DURATION 1.0
#define BFG10K_ADDON_DURATION 0.05
#define BFG10K_DEFAULT_DURATION 1.5
#define BFG10K_DEFAULT_SLIDE 0
//4.1 (new ability constants)
//Totems (general)
#define TOTEM_MAX_RANGE 512
#define TOTEM_COST 25
#define TOTEM_HEALTH_BASE 75
#define TOTEM_HEALTH_MULT 10
#define TOTEM_REGEN_BASE 10
#define TOTEM_REGEN_MULT 0
#define TOTEM_MASTERY_MULT 2
#define TOTEM_REGEN_FRAMES 100
#define TOTEM_REGEN_DELAY 10
//Fury
#define FURY_INITIAL_REGEN 0.05
#define FURY_ADDON_REGEN 0.005
#define FURY_MAX_REGEN 0.1
#define FURY_INITIAL_FACTOR 1.5
#define FURY_ADDON_FACTOR 0.05
#define FURY_FACTOR_MAX 2.0
#define FURY_DURATION_BASE 0
#define FURY_DURATION_BONUS 1.0
//Fire totem
#define FIRETOTEM_DAMAGE_BASE 0
#define FIRETOTEM_DAMAGE_MULT 3
#define FIRETOTEM_REFIRE_BASE 2.0
#define FIRETOTEM_REFIRE_MULT 0.0 //make this negative to reduce the "cooldown".
//Water totem
//Don't make this duration too short. The ice talent will do too much damage if you do.
#define WATERTOTEM_DURATION_BASE 3.0
#define WATERTOTEM_DURATION_MULT 0.0
#define WATERTOTEM_REFIRE_BASE 1.0
#define WATERTOTEM_REFIRE_MULT 0.0 //make this negative to reduce the "cooldown".
//Air totem
#define AIRTOTEM_RESIST_BASE 1.0
#define AIRTOTEM_RESIST_MULT 0.2
//Earth totem
#define EARTHTOTEM_RESIST_MULT 0.05
#define EARTHTOTEM_DAMAGE_MULT 0.1
//Nature totem
#define NATURETOTEM_HEALTH_BASE 0
#define NATURETOTEM_HEALTH_MULT 5
#define NATURETOTEM_ARMOR_BASE 0
#define NATURETOTEM_ARMOR_MULT 2.5
#define NATURETOTEM_REFIRE_BASE 5.0
#define NATURETOTEM_REFIRE_MULT 0.0 //make this negative to reduce the "cooldown".
//Darkness totem
#define DARKNESSTOTEM_VAMP_MULT 0.020 //0.033
#define DARKNESSTOTEM_MAX_MULT 0.1
// Sentries
#define SENTRY_INITIAL_HEALTH 100
#define SENTRY_ADDON_HEALTH 10
#define SENTRY_INITIAL_ARMOR 150
#define SENTRY_ADDON_ARMOR 15
#define SENTRY_INITIAL_AMMO 100
#define SENTRY_ADDON_AMMO 10
#define MINISENTRY_INITIAL_HEALTH 50
#define MINISENTRY_ADDON_HEALTH 10
#define MINISENTRY_INITIAL_ARMOR 50
#define MINISENTRY_ADDON_ARMOR 30
#define MINISENTRY_MAX_HEALTH 200
#define MINISENTRY_MAX_ARMOR 350
#define MINISENTRY_INITIAL_AMMO 50
#define MINISENTRY_ADDON_AMMO 5
#define MINISENTRY_INITIAL_BULLET 10
#define MINISENTRY_ADDON_BULLET 1
#define MINISENTRY_INITIAL_ROCKET 50
#define MINISENTRY_ADDON_ROCKET 10
#define MINISENTRY_MAX_BULLET 100
#define MINISENTRY_MAX_ROCKET 1000
//GHz: Changed to damage multiplier
#define SENTRY_LEVEL1_DAMAGE 0.5
#define SENTRY_LEVEL2_DAMAGE 0.75
#define SENTRY_LEVEL3_DAMAGE 1.0
#define SENTRY_INITIAL_BULLETDAMAGE 10
#define SENTRY_ADDON_BULLETDAMAGE 1
#define SENTRY_INITIAL_ROCKETDAMAGE 50
#define SENTRY_ADDON_ROCKETDAMAGE 15
#define SENTRY_INITIAL_ROCKETSPEED 650
#define SENTRY_ADDON_ROCKETSPEED 35
#define SENTRY_COST 50
#define SENTRY_MAX 1
#define SENTRY_UPGRADE 100
#define DELAY_SENTRY_SCAN 3
#define DELAY_SENTRY 3
#define SPIKER_MAX_COUNT 4
#define GASSER_MAX_COUNT 4
#define OBSTACLE_MAX_COUNT 6
#define SPIKEBALL_MAX_COUNT 3
#define MAX_MONSTERS 3
#define DELAY_MONSTER_THINK 3
#define DELAY_MONSTER 3
// Monster cost
#define M_FLYER_COST 25
#define M_INSANE_COST 25
#define M_SOLDIERLT_COST 25
#define M_SOLDIER_COST 25
#define M_GUNNER_COST 25
#define M_CHICK_COST 25
#define M_PARASITE_COST 25
#define M_MEDIC_COST 25
#define M_BRAIN_COST 25
#define M_TANK_COST 50
#define M_HOVER_COST 25
#define M_SUPERTANK_COST 300
#define M_COMMANDER_COST 300
#define M_MUTANT_COST 25
#define M_DEFAULT_COST 25
// Monster control cost
#define M_FLYER_CONTROL_COST 1
#define M_INSANE_CONTROL_COST 1
#define M_SOLDIERLT_CONTROL_COST 1
#define M_SOLDIER_CONTROL_COST 1
#define M_GUNNER_CONTROL_COST 1
#define M_CHICK_CONTROL_COST 1
#define M_PARASITE_CONTROL_COST 1
#define M_MEDIC_CONTROL_COST 1
#define M_TANK_CONTROL_COST 2
#define M_BRAIN_CONTROL_COST 1
#define M_HOVER_CONTROL_COST 1
#define M_SUPERTANK_CONTROL_COST 3
#define M_COMMANDER_CONTROL_COST 3
#define M_MUTANT_CONTROL_COST 1
#define M_DEFAULT_CONTROL_COST 1
// Misc Delays
#define DELAY_QUAD 10
#define DELAY_INVULN 10
#define DELAY_AMMOSTEAL 2.0
#define DELAY_FREEZE 5
#define DELAY_BOOST 3.0
#define DELAY_BLOODSUCKER 3
#define DELAY_SALVATION 1
#define DELAY_CORPSEEXPLODE 0.5
#define DELAY_LASER 1
#define DELAY_DECOY 2
#define DELAY_BOMB 1
#define DELAY_THORNS 1
#define DELAY_HOLYFREEZE 1
// Spell Stuff
#define COST_FOR_QUAD 400
#define QUAD_TIME 50 //in frames 10 frames = 1 second
#define COST_FOR_INVIN 400
#define INVIN_TIME 50//in frames 10 frames = 1 second
#define COST_FOR_STEALER 25
#define COST_FOR_FREEZER 50
#define FREEZE_DURATION 5
#define BURN_DAMAGE 2
#define COST_FOR_BOOST 0
#define COST_FOR_BLOODSUCKER 100
#define COST_FOR_SALVATION 1
#define COST_FOR_CORPSEEXPLODE 20
#define COST_FOR_DECOY 100
#define COST_FOR_HOLYSHOCK 1
#define COST_FOR_HOLYFREEZE 1
#define COST_FOR_HOOK 10
#define MAX_BOMB_RANGE 768
#define COST_FOR_BOMB 25
#define METEOR_COST 25
#define ICEBOLT_COST 25
#define FIREBALL_COST 25
#define NOVA_COST 25
#define BOLT_COST 25
#define CLIGHTNING_COST 25
#define LIGHTNING_COST 25
// Spell Radii
#define RADIUS_AMMOSTEAL 512
#define RADIUS_FREEZE 512
#define RADIUS_BLOODSUCKER 512
#define RADIUS_CORPSEEXPLODE 1024
#define RADIUS_BOMB 512
//3.0 Armoury
#define ARMORY_ITEMS 28 //Number of available items
#define ARMORY_RUNE_UNIQUE_PRICE 150000
#define ARMORY_RUNE_APOINT_PRICE 5000
#define ARMORY_RUNE_WPOINT_PRICE 2500
#define ARMORY_MAX_RUNES 10
#define ARMORY_PRICE_WEAPON 5
#define ARMORY_PRICE_AMMO 5
#define ARMORY_PRICE_TBALLS 10
#define ARMORY_PRICE_POWERCUBE 2
#define ARMORY_PRICE_RESPAWNS 100
#define ARMORY_PRICE_ARMOR 15
#define ARMORY_PRICE_POTIONS 50
#define ARMORY_PRICE_ANTIDOTES 100
#define ARMORY_PRICE_GRAVITYBOOTS 150
#define ARMORY_PRICE_FIRE_RESIST 75
#define ARMORY_PRICE_AUTO_TBALL 250
#define ARMORY_PRICE_RESET 2500 // per level price (so level 10 would be 25k)
#define ARMORY_QTY_RESPAWNS 1000
#define ARMORY_QTY_POTIONS 5
#define ARMORY_QTY_ANTIDOTES 10
#define ARMORY_QTY_GRAVITYBOOTS 25
#define ARMORY_QTY_FIRE_RESIST 25
#define ARMORY_QTY_AUTO_TBALL 3
//4.5 player combat preferences
#define HOSTILE_PLAYERS 0x00000001
#define HOSTILE_MONSTERS 0x00000002
//3.0 Special Flags
#define SFLG_NONE 0x00000000
#define SFLG_MATRIXJUMP 0x00000001
#define SFLG_UNDERWATER 0x00000002
#define SFLG_PARTIAL_INWATER 0x00000004
#define SFLG_AUTO_TBALLED 0x00000008
#define SFLG_DOUBLEJUMP 0x00000010
//Other flag combinations
#define SFLG_TOUCHING_WATER SFLG_UNDERWATER | SFLG_PARTIAL_INWATER
//Matrix jump
#define MJUMP_VELOCITY 350
#define MJUMP_GRAVITY_MULT 2.5
// Cheat Stuff
#define CLIENT_GL_MODULATE 1
#define CLIENT_GL_DYNAMIC 2
#define CLIENT_SW_DRAWFLAT 3
#define CLIENT_GL_SHOWTRIS 4
#define CLIENT_R_FULLBRIGHT 5
#define CLIENT_TIMESCALE 6
#define CLIENT_GL_LIGHTMAP 7
#define CLIENT_GL_SATURATELIGHTING 8
#define CLIENT_R_DRAWFLAT 9
#define CLIENT_CL_TESTLIGHTS 10
#define CLIENT_FIXEDTIME 11
// class numbers
#define CLASS_SOLDIER 1
#define CLASS_POLTERGEIST 2
#define CLASS_VAMPIRE 3
#define CLASS_MAGE 4
#define CLASS_ENGINEER 5
#define CLASS_KNIGHT 6
#define CLASS_CLERIC 7
#define CLASS_NECROMANCER 8
#define CLASS_SHAMAN 9
#define CLASS_ALIEN 10
#define CLASS_WEAPONMASTER 11 //decino: change CLASS_MAX to 11 to enable WM
#define CLASS_MAX 11 //Number of classes to choose from
//Trade stuff
#define TRADE_MAX_DISTANCE 512 //Trade distance
#define TRADE_MAX_PLAYERS 5 //Max # of players to choose when trading
#endif
<file_sep>#include "g_local.h"
#include "m_player.h"
void drone_ai_stand (edict_t *self, float dist);
void drone_ai_run (edict_t *self, float dist);
mframe_t decoy_frames_stand1 [] =
{
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL,
drone_ai_stand, 0, NULL
};
mmove_t decoy_move_stand = {FRAME_stand01, FRAME_stand40, decoy_frames_stand1, NULL};
void decoy_stand (edict_t *self)
{
self->monsterinfo.currentmove = &decoy_move_stand;
}
mframe_t decoy_frames_run [] =
{
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL
};
mmove_t decoy_move_run = {FRAME_run1, FRAME_run6, decoy_frames_run, NULL};
void actor_run (edict_t *self);
mframe_t decoy_frames_runandtaunt [] =
{
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL
};
mmove_t decoy_move_runandtaunt = {FRAME_taunt01, FRAME_taunt17, decoy_frames_runandtaunt, actor_run};
mframe_t decoy_frames_runandflipoff [] =
{
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL,
drone_ai_run, 30, NULL
};
mmove_t decoy_move_runandflipoff = {FRAME_flip01, FRAME_flip12, decoy_frames_runandflipoff, actor_run};
void actor_run (edict_t *self)
{
// gi.dprintf("actor_run()\n");
if (self->monsterinfo.aiflags & AI_STAND_GROUND)
decoy_stand(self);
else
self->monsterinfo.currentmove = &decoy_move_run;
}
char *player_msg[] =
{
"Watch it",
"Lmao, you fail",
"Get off me",
"Rofl, keep failing"
};
char *other_msg[] =
{
"Even Ivan is better than you",
"Nice shot",
"Haha, that was a close one",
"Not bad"
};
void drone_pain (edict_t *self, edict_t *other, float kick, int damage);
void actor_pain (edict_t *self, edict_t *other, float kick, int damage)
{
// char *s;
// gi.dprintf("actor_pain()\n");
//if (self->health < (self->max_health / 2))
// self->s.skinnum = 1;
if ((level.time < self->pain_debounce_time) && (random() > 0.2))
return;
// gi.sound (self, CHAN_VOICE, actor.sound_pain, 1, ATTN_NORM, 0);
if (self->health > 40)
gi.sound(self, CHAN_VOICE, gi.soundindex("player/male/pain50_1.wav"), 1, ATTN_NORM, 0);
// if (random () < 0.5)
// s = HiPrint(va("%s's decoy: %s %s", self->activator->client->pers.netname,
// player_msg[GetRandom(0, 3)], other->client->pers.netname));
// else
// s = HiPrint(va("%s's decoy: %s %s", self->activator->client->pers.netname,
// other_msg[GetRandom(0, 3)], other->client->pers.netname));
// gi.bprintf(PRINT_HIGH, "%s\n", s);
// if (random() < 0.5)
// self->monsterinfo.currentmove = &decoy_move_runandflipoff;
// else
// self->monsterinfo.currentmove = &decoy_move_runandtaunt;
drone_pain(self, other, kick, damage);
self->pain_debounce_time = level.time + GetRandom(6, 10);
}
void decoy_rocket_old (edict_t *self)
{
//int damage, speed ;
//vec3_t forward, start;
//speed = 650 + 30*self->activator->myskills.level;
//if (speed > 950)
//speed = 950;
//if (random() <= 0.1)
// damage = 50 + 10*self->activator->myskills.level;
//else
// damage = 1;
//MonsterAim(self, damage, speed, true, 0, forward, start);
//monster_fire_rocket (self, start, forward, damage, speed, 0);
//gi.WriteByte (svc_muzzleflash);
//gi.WriteShort (self-g_edicts);
//gi.WriteByte (MZ_ROCKET);
//gi.multicast (self->s.origin, MULTICAST_PVS);
}
void decoy_sword (edict_t *self)
{
int damage, kick;
vec3_t forward, start;
if (self->decoy_next <= level.time){
damage = SABRE_INITIAL_DAMAGE + (SABRE_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_SWORD].mods[0].current_level);
kick = 100;
MonsterAim(self, 1, 0, false, 0, forward, start);
monster_fire_sword (self, start, forward, damage, kick, 0);
self->decoy_next = level.time + 0.1;}
}
void decoy_blaster (edict_t *self)
{
int damage, speed, max, min;
vec3_t forward, start;
if (self->decoy_next <= level.time){
speed = BLASTER_INITIAL_SPEED + BLASTER_ADDON_SPEED * self->activator->myskills.weapons[WEAPON_BLASTER].mods[2].current_level;
min = BLASTER_INITIAL_DAMAGE_MIN + (BLASTER_ADDON_DAMAGE_MIN * self->activator->myskills.weapons[WEAPON_BLASTER].mods[0].current_level);
max = BLASTER_INITIAL_DAMAGE_MAX + (BLASTER_ADDON_DAMAGE_MAX * self->activator->myskills.weapons[WEAPON_BLASTER].mods[0].current_level);
damage = GetRandom(min, max);
MonsterAim(self, 1, speed, false, 0, forward, start);
monster_fire_blaster (self, start, forward, damage, speed, EF_BLASTER, BLASTER_PROJ_BOLT, 2.0, true, 0);
gi.WriteByte (svc_muzzleflash);
gi.WriteShort (self-g_edicts);
gi.WriteByte (MZ_BLASTER);
gi.multicast (self->s.origin, MULTICAST_PVS);
self->decoy_next = level.time + 0.3;}
}
void decoy_shotgun (edict_t *self)
{
int damage, pellets;
vec3_t forward, start;
if (self->decoy_next <= level.time){
damage = SHOTGUN_INITIAL_DAMAGE + SHOTGUN_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_SHOTGUN].mods[0].current_level;
pellets = SHOTGUN_INITIAL_BULLETS + SHOTGUN_ADDON_BULLETS * self->activator->myskills.weapons[WEAPON_SHOTGUN].mods[2].current_level;
MonsterAim(self, 1, 0, false, 0, forward, start);
monster_fire_shotgun (self, start, forward, damage, damage, 500, 500, pellets, 0);
gi.WriteByte (svc_muzzleflash);
gi.WriteShort (self-g_edicts);
gi.WriteByte (MZ_SHOTGUN);
gi.multicast (self->s.origin, MULTICAST_PVS);
self->decoy_next = level.time + 0.8;}
}
void decoy_supershotgun (edict_t *self)
{
int damage, pellets;
vec3_t forward, start;
if (self->decoy_next <= level.time){
damage = SUPERSHOTGUN_INITIAL_DAMAGE + SUPERSHOTGUN_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_SUPERSHOTGUN].mods[0].current_level;
pellets = SUPERSHOTGUN_INITIAL_BULLETS + SUPERSHOTGUN_ADDON_BULLETS * self->activator->myskills.weapons[WEAPON_SUPERSHOTGUN].mods[2].current_level;
MonsterAim(self, 1, 0, false, 0, forward, start);
monster_fire_shotgun (self, start, forward, damage, damage, 500, 1000, pellets, 0);
gi.WriteByte (svc_muzzleflash);
gi.WriteShort (self-g_edicts);
gi.WriteByte (MZ_SSHOTGUN);
gi.multicast (self->s.origin, MULTICAST_PVS);
self->decoy_next = level.time + 1.0;}
}
void decoy_machinegun (edict_t *self)
{
int damage;
vec3_t forward, start;
damage = MACHINEGUN_INITIAL_DAMAGE + MACHINEGUN_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_MACHINEGUN].mods[0].current_level;
MonsterAim(self, 1, 0, false, 0, forward, start);
monster_fire_bullet (self, start, forward, damage, damage, DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, 0);
gi.WriteByte (svc_muzzleflash);
gi.WriteShort (self-g_edicts);
gi.WriteByte (MZ_MACHINEGUN);
gi.multicast (self->s.origin, MULTICAST_PVS);
}
void decoy_chaingun (edict_t *self)
{
int damage;
vec3_t forward, start;
damage = CHAINGUN_INITIAL_DAMAGE + CHAINGUN_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_CHAINGUN].mods[0].current_level;
MonsterAim(self, 1, 0, false, 0, forward, start);
monster_fire_bullet (self, start, forward, damage, damage, DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, 0);
monster_fire_bullet (self, start, forward, damage, damage, DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, 0);
monster_fire_bullet (self, start, forward, damage, damage, DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, 0);
}
void decoy_grenades (edict_t *self)
{
float radius;
vec3_t forward, start;
if (self->decoy_next <= level.time){
int damage = GRENADE_INITIAL_DAMAGE + GRENADE_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_HANDGRENADE].mods[0].current_level;
int radius_damage = GRENADE_INITIAL_RADIUS_DAMAGE + GRENADE_ADDON_RADIUS_DAMAGE * self->activator->myskills.weapons[WEAPON_HANDGRENADE].mods[0].current_level;
int speed = 800 + 40 * self->activator->myskills.weapons[WEAPON_HANDGRENADE].mods[1].current_level;
radius = 100;
MonsterAim(self, 1, 0, false, 0, forward, start);
fire_grenade2 (self, start, forward, damage, speed, 2.0, radius, radius_damage, 0);
self->decoy_next = level.time + 2.0;}
}
void decoy_grenadelauncher (edict_t *self)
{
// float radius;
vec3_t forward, start;
if (self->decoy_next <= level.time){
int damage = GRENADELAUNCHER_INITIAL_DAMAGE + GRENADELAUNCHER_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_GRENADELAUNCHER].mods[0].current_level;
float radius = GRENADELAUNCHER_INITIAL_RADIUS + GRENADELAUNCHER_ADDON_RADIUS * self->activator->myskills.weapons[WEAPON_GRENADELAUNCHER].mods[1].current_level;
int speed = GRENADELAUNCHER_INITIAL_SPEED + (GRENADELAUNCHER_ADDON_SPEED * self->activator->myskills.weapons[WEAPON_GRENADELAUNCHER].mods[2].current_level);
int radius_damage = GRENADELAUNCHER_INITIAL_RADIUS_DAMAGE + GRENADELAUNCHER_ADDON_RADIUS_DAMAGE * self->activator->myskills.weapons[WEAPON_GRENADELAUNCHER].mods[0].current_level;
MonsterAim(self, 1, 0, false, 0, forward, start);
fire_grenade (self, start, forward, damage, speed, 2.5, radius, radius_damage);
gi.WriteByte (svc_muzzleflash);
gi.WriteShort (self-g_edicts);
gi.WriteByte (MZ_GRENADE);
gi.multicast (self->s.origin, MULTICAST_PVS);
self->decoy_next = level.time + 0.7;}
}
void decoy_rocketlauncher (edict_t *self)
{
vec3_t forward, start;
if (self->decoy_next <= level.time){
int speed = ROCKETLAUNCHER_INITIAL_SPEED + ROCKETLAUNCHER_ADDON_SPEED * self->activator->myskills.weapons[WEAPON_ROCKETLAUNCHER].mods[2].current_level;
int damage = ROCKETLAUNCHER_INITIAL_DAMAGE + ROCKETLAUNCHER_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_ROCKETLAUNCHER].mods[0].current_level;
int radius_damage = ROCKETLAUNCHER_INITIAL_RADIUS_DAMAGE + ROCKETLAUNCHER_ADDON_RADIUS_DAMAGE * self->activator->myskills.weapons[WEAPON_ROCKETLAUNCHER].mods[0].current_level;
int damage_radius = ROCKETLAUNCHER_INITIAL_DAMAGE_RADIUS + ROCKETLAUNCHER_ADDON_DAMAGE_RADIUS * self->activator->myskills.weapons[WEAPON_ROCKETLAUNCHER].mods[1].current_level;
MonsterAim(self, 1, 0, true, 0, forward, start);
fire_rocket (self, start, forward, damage, speed, damage_radius, radius_damage);
gi.WriteByte (svc_muzzleflash);
gi.WriteShort (self-g_edicts);
gi.WriteByte (MZ_ROCKET);
gi.multicast (self->s.origin, MULTICAST_PVS);
self->decoy_next = level.time + 0.7;}
}
void decoy_hyperblaster (edict_t *self)
{
int damage;
int speed;
vec3_t forward, start;
if (self->decoy_next <= level.time){
damage = HYPERBLASTER_INITIAL_DAMAGE + HYPERBLASTER_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_HYPERBLASTER].mods[0].current_level;
speed = HYPERBLASTER_INITIAL_SPEED + HYPERBLASTER_ADDON_SPEED * self->activator->myskills.weapons[WEAPON_HYPERBLASTER].mods[2].current_level;
MonsterAim(self, 1, 0, false, 0, forward, start);
monster_fire_blaster (self, start, forward, damage, speed, EF_HYPERBLASTER, BLASTER_PROJ_BOLT, 10.0, false, 0);
gi.WriteByte (svc_muzzleflash);
gi.WriteShort (self-g_edicts);
gi.WriteByte (MZ_HYPERBLASTER);
gi.multicast (self->s.origin, MULTICAST_PVS);
self->decoy_next = level.time + 0.2;}
}
void decoy_railgun (edict_t *self)
{
int damage;
int kick = 200;
vec3_t forward, start;
if (self->decoy_next <= level.time){
damage = RAILGUN_INITIAL_DAMAGE + RAILGUN_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_RAILGUN].mods[0].current_level;
MonsterAim(self, 1, 0, false, 0, forward, start);
fire_rail (self, start, forward, damage, kick);
gi.WriteByte (svc_muzzleflash);
gi.WriteShort (self-g_edicts);
gi.WriteByte (MZ_RAILGUN);
gi.multicast (self->s.origin, MULTICAST_PVS);
self->decoy_next = level.time + 1.4;}
}
void decoy_bfg10k (edict_t *self)
{
int dmg;
int speed;
float range;
vec3_t forward, start;
if (self->decoy_next <= level.time){
speed = BFG10K_INITIAL_SPEED + BFG10K_ADDON_SPEED * self->activator->myskills.weapons[WEAPON_BFG10K].mods[2].current_level;
range = BFG10K_RADIUS;
dmg = BFG10K_INITIAL_DAMAGE + BFG10K_ADDON_DAMAGE * self->activator->myskills.weapons[WEAPON_BFG10K].mods[0].current_level;
MonsterAim(self, 1, 0, false, 0, forward, start);
fire_bfg (self, start, forward, dmg, speed, range);
gi.WriteByte (svc_muzzleflash);
gi.WriteShort (self-g_edicts);
gi.WriteByte (MZ_BFG);
gi.multicast (self->s.origin, MULTICAST_PVS);
self->decoy_next = level.time + 2.3;}
}
void decoy_20mm (edict_t *self)
{
int damage, min, max;
int kick;
vec3_t forward, start;
if (self->decoy_next <= level.time){
min = WEAPON_20MM_INITIAL_DMG_MIN + WEAPON_20MM_ADDON_DMG_MIN*self->activator->myskills.weapons[WEAPON_20MM].mods[0].current_level;
max = WEAPON_20MM_INITIAL_DMG_MAX + WEAPON_20MM_ADDON_DMG_MAX*self->activator->myskills.weapons[WEAPON_20MM].mods[0].current_level;
damage = GetRandom(min, max);
kick = damage;
MonsterAim(self, 1, 0, false, 0, forward, start);
fire_20mm (self, start, forward, damage, kick);
gi.sound (self, CHAN_WEAPON, gi.soundindex("weapons/sgun1.wav"), 1, ATTN_NORM, 0);
self->decoy_next = level.time + 0.2;}
}
void decoy_weapon (edict_t *self)
{
if (self->activator->client->pers.weapon == FindItem("Sword"))
decoy_sword(self);
if (self->activator->client->pers.weapon == FindItem("Blaster"))
decoy_blaster(self);
if (self->activator->client->pers.weapon == FindItem("Shotgun"))
decoy_shotgun(self);
if (self->activator->client->pers.weapon == FindItem("Super Shotgun"))
decoy_supershotgun(self);
if (self->activator->client->pers.weapon == FindItem("Machinegun"))
decoy_machinegun(self);
if (self->activator->client->pers.weapon == FindItem("Chaingun"))
decoy_chaingun(self);
if (self->activator->client->pers.weapon == FindItem("Grenades"))
decoy_grenades(self);
if (self->activator->client->pers.weapon == FindItem("Grenade Launcher"))
decoy_grenadelauncher(self);
if (self->activator->client->pers.weapon == FindItem("Rocket Launcher"))
decoy_rocketlauncher(self);
if (self->activator->client->pers.weapon == FindItem("HyperBlaster"))
decoy_hyperblaster(self);
if (self->activator->client->pers.weapon == FindItem("Railgun"))
decoy_railgun(self);
if (self->activator->client->pers.weapon == FindItem("BFG10K"))
decoy_bfg10k(self);
if (self->activator->client->pers.weapon == FindItem("20MM Cannon"))
decoy_20mm(self);
}
void actor_dead (edict_t *self)
{
VectorSet (self->mins, -16, -16, -24);
VectorSet (self->maxs, 16, 16, -8);
self->movetype = MOVETYPE_TOSS;
self->svflags |= SVF_DEADMONSTER;
self->nextthink = 0;
gi.linkentity (self);
}
mframe_t actor_frames_death1 [] =
{
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
};
mmove_t actor_move_death1 = {FRAME_death101, FRAME_death106, actor_frames_death1, actor_dead};
mframe_t actor_frames_death2 [] =
{
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, 0, NULL,
};
mmove_t actor_move_death2 = {FRAME_death201, FRAME_death206, actor_frames_death2, actor_dead};
void decoy_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
{
int n;
M_Notify(self);
// check for gib
if (self->health <= self->gib_health)
{
for (n= 0; n < 2; n++)
ThrowGib (self, "models/objects/gibs/bone/tris.md2", damage, GIB_ORGANIC);
for (n= 0; n < 4; n++)
ThrowGib (self, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC);
//ThrowHead (self, "models/objects/gibs/head2/tris.md2", damage, GIB_ORGANIC);
//self->deadflag = DEAD_DEAD;
M_Remove(self, false, false);
return;
}
if (self->deadflag == DEAD_DEAD)
return;
self->deadflag = DEAD_DEAD;
//Talent: Exploding Decoy
/*
if(damage > 0 && self->activator && getTalentLevel(self->activator, TALENT_EXPLODING_DECOY) != -1)
{
int talentLevel = getTalentLevel(self->activator, TALENT_EXPLODING_DECOY);
int decoyDamage = 100 + talentLevel * 50;
int decoyRadius = 100 + talentLevel * 25;
T_RadiusDamage(self, self->activator, decoyDamage, self, decoyRadius, MOD_EXPLODING_DECOY);
self->takedamage = DAMAGE_NO;
self->think = BecomeExplosion1;
self->nextthink = level.time + FRAMETIME;
return;
}*/
// regular death
self->takedamage = DAMAGE_YES;
self->s.modelindex2 = 0;
if (random() < 0.5)
gi.sound(self, CHAN_VOICE, gi.soundindex("player/male/death1.wav"), 1, ATTN_NORM, 0);
else
gi.sound(self, CHAN_VOICE, gi.soundindex("player/male/death2.wav"), 1, ATTN_NORM, 0);
// gi.bprintf(PRINT_HIGH, "%s's decoy was killed by %s.\n", self->activator->client->pers.netname, attacker->client->pers.netname);
n = randomMT() % 2;
if (n == 0) self->monsterinfo.currentmove = &actor_move_death1;
else self->monsterinfo.currentmove = &actor_move_death2;
}
mframe_t actor_frames_attack [] =
{
drone_ai_run, 30, decoy_weapon,
drone_ai_run, 30, decoy_weapon,
drone_ai_run, 30, decoy_weapon,
drone_ai_run, 30, decoy_weapon,
drone_ai_run, 30, decoy_weapon,
drone_ai_run, 30, decoy_weapon,
drone_ai_run, 30, decoy_weapon,
drone_ai_run, 30, decoy_weapon
};
mmove_t actor_move_attack = {FRAME_attack1, FRAME_attack8, actor_frames_attack, actor_run};
void actor_attack(edict_t *self)
{
// int n;
// gi.dprintf("actor_attack()\n");
self->monsterinfo.currentmove = &actor_move_attack;
if (self->activator->client->pers.weapon == FindItem("Blaster"))
self->monsterinfo.attack_finished = level.time + 0.3;
if (self->activator->client->pers.weapon == FindItem("Sword"))
self->monsterinfo.attack_finished = level.time + 1.5;
if (self->activator->client->pers.weapon == FindItem("Shotgun"))
self->monsterinfo.attack_finished = level.time + 0.3;
if (self->activator->client->pers.weapon == FindItem("Super Shotgun"))
self->monsterinfo.attack_finished = level.time + 1.0;
if (self->activator->client->pers.weapon == FindItem("Machinegun"))
self->monsterinfo.attack_finished = level.time + 0;
if (self->activator->client->pers.weapon == FindItem("Chaingun"))
self->monsterinfo.attack_finished = level.time + 0;
if (self->activator->client->pers.weapon == FindItem("Grenades"))
self->monsterinfo.attack_finished = level.time + 2;
if (self->activator->client->pers.weapon == FindItem("Grenade Launcher"))
self->monsterinfo.attack_finished = level.time + 0.7;
if (self->activator->client->pers.weapon == FindItem("Rocket Launcher"))
self->monsterinfo.attack_finished = level.time + 0.7;
if (self->activator->client->pers.weapon == FindItem("Hyperblaster"))
self->monsterinfo.attack_finished = level.time + 0;
if (self->activator->client->pers.weapon == FindItem("Railgun"))
self->monsterinfo.attack_finished = level.time + 1.4;
if (self->activator->client->pers.weapon == FindItem("BFG10k"))
self->monsterinfo.attack_finished = level.time + 2.3;
if (self->activator->client->pers.weapon == FindItem("20MM Cannon"))
self->monsterinfo.attack_finished = level.time + 0;
// n = (rand() & 15) + 3 + 7;
// self->monsterinfo.pausetime = level.time + n * FRAMETIME;
}
/*QUAKED misc_actor (1 .5 0) (-16 -16 -24) (16 16 32)
*/
void decoy_copy (edict_t *self)
{
edict_t *target = self->activator;
// if (self->mtype != M_DECOY)
// return;
// if (PM_PlayerHasMonster(self->activator))
// target = self->activator->owner;
// copy everything from our owner
self->model = target->model;
self->s.skinnum = target->s.skinnum;
self->s.modelindex = target->s.modelindex;
self->s.modelindex2 = target->s.modelindex2;
self->s.effects = target->s.effects;
self->s.renderfx = target->s.renderfx;
// try to copy target's bounding box if there's room
if (!VectorCompare(self->mins, target->mins) || !VectorCompare(self->maxs, target->maxs))
{
trace_t tr = gi.trace(self->s.origin, target->mins, target->maxs, self->s.origin, self, MASK_SHOT);
if (tr.fraction == 1.0)
{
VectorCopy(target->mins, self->mins);
VectorCopy(target->maxs, self->maxs);
gi.linkentity(self);
}
}
}
void init_drone_decoy (edict_t *self)
{
self->movetype = MOVETYPE_STEP;
self->solid = SOLID_BBOX;
VectorSet (self->mins, -16, -16, -24);
VectorSet (self->maxs, 16, 16, 32);
decoy_copy(self);
self->health = 7500;
//Limit decoy health to 1000
// if(self->health > 7500) self->health = 1000;
self->max_health = self->health;
self->gib_health = -40;
self->mass = 200;
self->mtype = M_DECOY;
self->pain = actor_pain;
self->die = decoy_die;
self->monsterinfo.level = 99;
self->monsterinfo.stand = decoy_stand;
self->monsterinfo.run = actor_run;
self->monsterinfo.attack = actor_attack;
self->monsterinfo.control_cost = 0;
self->monsterinfo.cost = 0;
self->monsterinfo.jumpup = 64;
self->monsterinfo.jumpdn = 512;
//K03 Begin
// self->monsterinfo.power_armor_type = POWER_ARMOR_SHIELD;
// self->monsterinfo.power_armor_power = 400;
//K03 End
//decino: if using sword try to get close
if (self->activator->client->pers.weapon == FindItem("Sword"))
{
self->monsterinfo.aiflags |= AI_NO_CIRCLE_STRAFE;
}
// self->monsterinfo.aiflags |= AI_GOOD_GUY;
gi.linkentity (self);
self->monsterinfo.currentmove = &decoy_move_stand;
self->monsterinfo.scale = MODEL_SCALE;
}
qboolean MirroredEntitiesExist (edict_t *ent);
void Cmd_Decoy_f (edict_t *ent)
{
if (ent->myskills.administrator < 90)
return;
if (ent->client->ability_delay > level.time)
return;
// if (level.time < pregame_time->value)
// {
// gi.cprintf(ent, PRINT_HIGH, "You can't use abilities during pre-game.\n");
// return;
// }
// if (ent->client->pers.inventory[power_cube_index] < 50)
// {
// gi.cprintf(ent, PRINT_HIGH, "You must have at least 50 cubes to spawn a Decoy!\n");
// return;
// }
SpawnDrone(ent, 20, false);
}
<file_sep>#include "g_local.h"
#define DRONE_GOAL_TIMEOUT 3 // seconds before a movement goal times out
void drone_think (edict_t *self);
void drone_wakeallies (edict_t *self);
qboolean drone_findtarget (edict_t *self);
void init_drone_gunner (edict_t *self);
void init_drone_parasite (edict_t *self);
void init_drone_bitch (edict_t *self);
void init_drone_brain (edict_t *self);
void init_drone_medic (edict_t *self);
void init_drone_tank (edict_t *self);
void init_drone_mutant (edict_t *self);
void init_drone_decoy (edict_t *self);
void init_drone_commander (edict_t *self);
void init_drone_soldier (edict_t *self);
void init_drone_gladiator (edict_t *self);
int crand (void);
qboolean drone_ValidChaseTarget (edict_t *self, edict_t *target)
{
//if (target && target->inuse && target->classname)
// gi.dprintf("drone_ValidChaseTarget() is checking %s\n", target->classname);
//else
// gi.dprintf("drone_ValidChaseTarget() is checking <unknown>\n");
if (!target || !target->inuse)
return false;
// chasing a combat point/goal
if ((self->monsterinfo.aiflags & AI_COMBAT_POINT) && target->inuse
&& ((target->mtype == INVASION_NAVI) || (target->mtype == PLAYER_NAVI)))
return true;
if (!target->takedamage || (target->solid == SOLID_NOT))
return false;
//if (!G_EntExists(target))
// return false;
if ((self->monsterinfo.aiflags & AI_MEDIC) && M_ValidMedicTarget(self, self->enemy))
return true;
// ignore players that are in chat-protect
if (target->flags & FL_CHATPROTECT)
return false;
if (target->flags & FL_GODMODE)
return false;
// if we're standing ground and have a limited sight range
// ignore enemies that move outside of this range (since we can't attack them)
if ((self->monsterinfo.aiflags & AI_STAND_GROUND)
&& (entdist(self, target) > self->monsterinfo.sight_range))
return false;
if (target->client)
{
if (target->client->respawn_time > level.time)
return false; // don't pursue respawning players
if (target->client->cloaking && (target->client->idle_frames >= 100))
return false; // don't pursue cloaked targets
}
return ((target->health>0) && (target->deadflag!=DEAD_DEAD)
&& !que_typeexists(target->curses, CURSE_FROZEN) && !OnSameTeam(self, target));
}
qboolean drone_isclearshot (edict_t *self, edict_t *target)
{
vec3_t forward, start, end;
trace_t tr;
// get muzzle origin (roughly)
AngleVectors(self->s.angles, forward, NULL, NULL);
VectorMA(self->s.origin, self->maxs[1], forward, start);
start[2] += self->viewheight;
// get target position
VectorCopy(target->s.origin, end);
if (target->client)
end[2] += target->viewheight;
tr = gi.trace(start, NULL, NULL, self->enemy->s.origin, self, MASK_SHOT);
if (!tr.ent || (tr.ent != target))
return false;
return true;
}
/*
qboolean CanStep (edict_t *self, float yaw, float dist)
{
int stepsize;
vec3_t start, end, test, move;
trace_t trace;
yaw = yaw*M_PI*2 / 360;
move[0] = cos(yaw)*dist;
move[1] = sin(yaw)*dist;
move[2] = 0;
// try the move
VectorAdd (self->s.origin, move, start);
// push down from a step height above the wished position
if (!(self->monsterinfo.aiflags & AI_NOSTEP))
stepsize = STEPHEIGHT;
else
stepsize = 1;
start[2] += stepsize;
VectorCopy (start, end);
end[2] -= stepsize*2;
trace = gi.trace (start, self->mins, self->maxs, end, self, MASK_MONSTERSOLID);
if (trace.allsolid)
return false;
if (trace.startsolid)
{
start[2] -= stepsize;
trace = gi.trace (start, self->mins, self->maxs, end, self, MASK_MONSTERSOLID);
if (trace.allsolid || trace.startsolid)
return false;
}
// don't go in to water
if (!self->waterlevel)
{
test[0] = trace.endpos[0];
test[1] = trace.endpos[1];
test[2] = trace.endpos[2] + self->mins[2] + 1;
if (gi.pointcontents(test) & MASK_WATER)
return false;
}
if (trace.fraction == 1.0)
return false; // walked off an edge
return true;
}
*/
void drone_ai_checkattack (edict_t *self)
{
vec3_t start, end;
trace_t tr;
if (!self->monsterinfo.attack)
return;
if (!G_EntExists(self->enemy))
return; // enemy is invalid or a combat point
//if (self->monsterinfo.aiflags & AI_COMBAT_POINT)
// return; // we're busy reaching a combat point
// don't change attacks if we're busy with the last one
if (level.time < self->monsterinfo.attack_finished)
{
if (!self->monsterinfo.melee)
return;
if (level.time < self->monsterinfo.melee_finished)
return;
self->monsterinfo.melee(self);
return;
}
// if we see an easier target, go for it
if (!visible(self, self->enemy))
{
self->oldenemy = self->enemy;
if (!drone_findtarget(self))
return;
//gi.dprintf("%d going for an easier target\n", self->mtype);
}
//if (!infront(self, self->enemy))
if (!nearfov(self, self->enemy, 0, 60))
{
//gi.dprintf("target is not in front\n");
return;
}
// check for blocked shot
// if the entity blocking us is a valid target, attack them instead!
G_EntMidPoint(self, start);
G_EntMidPoint(self->enemy, end);
tr = gi.trace(start, NULL, NULL, end, self, MASK_SHOT);
if (!tr.ent || tr.ent != self->enemy)
{
if (G_ValidTarget(self, tr.ent, false))
self->enemy = tr.ent;
else
return;
}
//AngleVectors(self->s.angles, forward, NULL, NULL);
//VectorMA(self->s.origin, self->maxs[1]+8, forward , start);
// our shot is blocked
//if (!G_IsClearPath(self->enemy, MASK_SHOT, start, self->enemy->s.origin)/*!drone_isclearshot(self, self->enemy)*/)
//if (!G_ClearPath(self, self->enemy, MASK_SHOT, self->s.origin, self->enemy->s.origin))
//{
// gi.dprintf("shot is blocked\n");
// return;
//}
self->monsterinfo.attack(self);
}
void goalentity_think (edict_t *self)
{
if (level.time > self->delay)
{
if (self->owner)
self->owner->movetarget = NULL;
G_FreeEdict(self);
return;
}
self->nextthink = level.time + FRAMETIME;
}
edict_t *SpawnGoalEntity (edict_t *ent, vec3_t org)
{
edict_t *goal;
goal = G_Spawn();
goal->think = goalentity_think;
// goal->touch = goalentity_touch;
goal->delay = level.time + DRONE_GOAL_TIMEOUT;
goal->owner = ent;
goal->classname = "drone_goal";
goal->svflags |= SVF_NOCLIENT; // comment this for debugging
// goal->solid = SOLID_TRIGGER;
// goal->s.modelindex = gi.modelindex("models/items/c_head/tris.md2");
// goal->s.effects |= EF_BLASTER;
VectorCopy(org, goal->s.origin);
goal->nextthink = level.time + FRAMETIME;
// gi.linkentity(goal);
ent->movetarget = goal; // pointer to goal
return goal;
}
//void AddDmgList (edict_t *self, edict_t *other, int damage);//4.05
void drone_pain (edict_t *self, edict_t *other, float kick, int damage)
{
//vec3_t forward, start;
if ((self->s.modelindex != 255) && (self->health < (0.5*self->max_health)))
self->s.skinnum |= 1;
// keep track of damage by players in invasion mode
// if (INVASION_OTHERSPAWNS_REMOVED)
// AddDmgList(self, other, damage);
// ignore non-living objects
if (!G_EntIsAlive(other))
return;
// ignore teammates
if (OnSameTeam(self, other))
return;
//4.05 make monsters fight nearer targets
if (self->enemy && self->enemy->inuse)
{
// attack if current enemy can't take damage (a node/goal?) OR our current enemy
// isn't visible OR if new enemy is closer than the old one
if (!self->enemy->takedamage || !visible(self, self->enemy)
|| (entdist(self, other) < entdist(self, self->enemy)))
{
self->oldenemy = self->enemy;
self->enemy = other;
drone_wakeallies(self);
}
}
else
{
// we don't already have an enemy, so attack this one
self->enemy = other;
drone_wakeallies(self);
}
// if this is a boss, then add attacker dmg to a list
// this list will be used to calculate exp for killing this monster
// if (self->monsterinfo.control_cost > 3)
// AddDmgList(self, other, damage);
}
void drone_death (edict_t *self, edict_t *attacker)
{
//gi.dprintf("drone_death()\n");
//try to spawn a rune
if (pvm->value)
{
SpawnRune(self, attacker, false);
}
//4.2 commander can drop up to 5 runes
if (self->mtype == M_COMMANDER)
{
edict_t *e;
if ((e = V_SpawnRune(self, attacker, 0.25, 0)) != NULL)
V_TossRune(e, (float)GetRandom(200, 1000), (float)GetRandom(200, 1000));
if ((e = V_SpawnRune(self, attacker, 0.25, 0)) != NULL)
V_TossRune(e, (float)GetRandom(200, 1000), (float)GetRandom(200, 1000));
if ((e = V_SpawnRune(self, attacker, 0.25, 0)) != NULL)
V_TossRune(e, (float)GetRandom(200, 1000), (float)GetRandom(200, 1000));
if ((e = V_SpawnRune(self, attacker, 0.25, 0)) != NULL)
V_TossRune(e, (float)GetRandom(200, 1000), (float)GetRandom(200, 1000));
}
// world monsters sometimes drop ammo
if (self->activator && !self->activator->client
&& self->item && (random() >= 0.8))
Drop_Item(self, self->item);
}
void drone_heal (edict_t *self, edict_t *other)
{
if ((self->health > 0) && (level.time > self->lasthurt + 0.5) && (level.framenum > self->monsterinfo.regen_delay1))
{
// check health
if (self->health < self->max_health && other->client->pers.inventory[power_cube_index] >= 5)
{
self->health_cache += (int)(0.50 * self->max_health) + 1;
self->monsterinfo.regen_delay1 = level.framenum + 10;
other->client->pers.inventory[power_cube_index] -= 5;
}
// check armor
if (self->monsterinfo.power_armor_power < self->monsterinfo.max_armor
&& other->client->pers.inventory[power_cube_index] >= 5)
{
self->armor_cache += (int)(0.50 * self->monsterinfo.max_armor) + 1;
self->monsterinfo.regen_delay1 = level.framenum + 10;
other->client->pers.inventory[power_cube_index] -= 5;
}
}
}
void drone_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
{
vec3_t forward, right, start, offset;
V_Touch(self, other, plane, surf);
// the monster's owner or allies can push him around
//if (G_EntIsAlive(other) && self->activator
// && ((other == self->activator) || IsAlly(self->activator, other)))
// if this is player-monster, look at the owner/activator
// FIXME: this doesn't work well because M_Move() doesn't get you close enough
if (PM_MonsterHasPilot(other) && ((other->activator == self->activator) || IsAlly(self->activator, other->activator)))
{
AngleVectors(other->s.angles, forward, NULL, NULL);
self->velocity[0] += forward[0] * 200;
self->velocity[1] += forward[1] * 200;
self->velocity[2] += 200;
drone_heal(self, other->activator);
return;
}
if (other && other->inuse && other->client && self->activator
&& (other == self->activator || IsAlly(self->activator, other)))
{
AngleVectors (other->client->v_angle, forward, right, NULL);
VectorScale (forward, -3, other->client->kick_origin);
VectorSet(offset, 0, 7, other->viewheight-8);
P_ProjectSource (other->client, other->s.origin, offset, forward, right, start);
self->velocity[0] += forward[0] * 50;
self->velocity[1] += forward[1] * 50;
self->velocity[2] += forward[2] * 50;
drone_heal(self, other);
}
}
void drone_grow (edict_t *self)
{
V_HealthCache(self, (int)(0.2 * self->max_health), 1);
V_ArmorCache(self, (int)(0.2 * self->monsterinfo.max_armor), 1);
// done growing
if (self->health >= self->max_health)
self->think = drone_think;
// check for heal
else if (self->health >= 0.3*self->max_health)
self->s.skinnum &= ~1;
// if position has been updated, check for ground entity
if (self->linkcount != self->monsterinfo.linkcount)
{
self->monsterinfo.linkcount = self->linkcount;
M_CheckGround (self);
}
// don't slide
if (self->groundentity)
VectorClear(self->velocity);
M_CatagorizePosition (self);
M_WorldEffects (self);
M_SetEffects (self);
if (self->health <= 0)
M_MoveFrame(self);
else
self->s.effects |= EF_PLASMA;
self->nextthink = level.time + FRAMETIME;
}
edict_t *SpawnDrone (edict_t *ent, int drone_type, qboolean worldspawn)
{
vec3_t forward, right, start, end, offset;
trace_t tr;
edict_t *drone;
float mult;
int talentLevel;
drone = G_Spawn();
drone->classname = "drone";
// set monster level
if (worldspawn)
{
if (drone_type == 30)// tank commander
drone->monsterinfo.level = HighestLevelPlayer();
else if (INVASION_OTHERSPAWNS_REMOVED)
drone->monsterinfo.level = GetRandom(LowestLevelPlayer(), HighestLevelPlayer())+invasion_difficulty_level-1;
else
drone->monsterinfo.level = GetRandom(LowestLevelPlayer(), HighestLevelPlayer());
}
else
{
// calling entity made a sound, used to alert monsters
ent->lastsound = level.framenum;
drone->monsterinfo.level = ent->myskills.abilities[MONSTER_SUMMON].current_level;
}
if (drone->monsterinfo.level < 1)
drone->monsterinfo.level = 1;
drone->activator = ent;
drone->svflags |= SVF_MONSTER;
drone->pain = drone_pain;
drone->yaw_speed = 20;
drone->takedamage = DAMAGE_AIM;
drone->clipmask = MASK_MONSTERSOLID;
drone->movetype = MOVETYPE_STEP;
drone->s.skinnum = 0;
drone->deadflag = DEAD_NO;
drone->svflags &= ~SVF_DEADMONSTER;
drone->svflags |= SVF_MONSTER;
drone->flags |= FL_CHASEABLE; // 3.65 indicates entity can be chase-cammed
drone->s.effects |= EF_PLASMA;
drone->s.renderfx |= (RF_FRAMELERP|RF_IR_VISIBLE);
drone->solid = SOLID_BBOX;
//decino: fun stuff for admins
if (ent->client && drone_type == 30 && drone->activator == ent)
drone->monsterinfo.level = 99;
// use normal think for worldspawned monsters
if (worldspawn || !ent->client)
drone->think = drone_think;
else
// use pre-think for player-spawn monsters
drone->think = drone_grow;
drone->touch = drone_touch;
drone->monsterinfo.control_cost = M_DEFAULT_CONTROL_COST;
drone->monsterinfo.cost = M_DEFAULT_COST;
drone->monsterinfo.sight_range = 1024; // 3.56 default sight range for finding targets
switch(drone_type)
{
case 1: init_drone_gunner(drone); break;
case 2: init_drone_parasite(drone); break;
case 3: init_drone_bitch(drone); break;
case 4: init_drone_brain(drone); break;
case 5: init_drone_medic(drone); break;
case 6: init_drone_tank(drone); break;
case 7: init_drone_mutant(drone); break;
case 8: init_drone_gladiator(drone); break;
case 9: init_drone_soldier(drone); break;
case 20: init_drone_decoy(drone); break;
case 30: init_drone_commander(drone); break;
default: init_drone_gunner(drone); break;
}
//4.0 gib health based on monster control cost
if (drone_type != 30)
drone->gib_health = -drone->monsterinfo.control_cost*200;
else
drone->gib_health = 0;//gib boss immediately
mult = 1.0;
if (!worldspawn)
{
//Talent: Corpulence (also in M_Initialize)
talentLevel = getTalentLevel(ent, TALENT_CORPULENCE);
if(talentLevel > 0) mult += 0.167 * talentLevel; //+10% per upgrade
//Talent: Drone Power (durability penalty)
// talentLevel = getTalentLevel(ent, TALENT_DRONE_POWER);
// if(talentLevel > 0) mult -= 0.03 * talentLevel; //-3% per upgrade
}
drone->health *= mult;
drone->max_health *= mult;
drone->monsterinfo.power_armor_power *= mult;
drone->monsterinfo.max_armor *= mult;
if (worldspawn)
{
if (!INVASION_OTHERSPAWNS_REMOVED || (drone_type == 30 && !drone->activator)) // only use designated spawns in invasion mode
{
if (!FindValidSpawnPoint(drone, false))
{
G_FreeEdict(drone);
return NULL; // couldn't find a spawn point
}
// gives players some time to react to newly spawned monsters
drone->nextthink = level.time + 1 + random();
// trigger spree war if a boss successfully spawns in PvP mode
if (deathmatch->value && !domination->value && !ctf->value && !invasion->value && !pvm->value
&& !ptr->value && !ffa->value && (drone->mtype == M_COMMANDER))
{
SPREE_WAR = true;
SPREE_TIME = level.time;
SPREE_DUDE = world;
}
}
else
drone->nextthink = level.time + FRAMETIME;
}
else if (ent->client)
{
// 3.9 double monster cost if there are too many monsters in CTF
if (ctf->value && (CTF_GetNumSummonable("drone", ent->teamnum) > MAX_MONSTERS))
drone->monsterinfo.cost *= 2;
// cost is doubled if you are a flyer or cacodemon below skill level 5
if ((ent->mtype == MORPH_FLYER && ent->myskills.abilities[FLYER].current_level < 5)
|| (ent->mtype == MORPH_CACODEMON && ent->myskills.abilities[CACODEMON].current_level < 5))
drone->monsterinfo.cost *= 2;
if (ent->client->pers.inventory[power_cube_index] < drone->monsterinfo.cost)
{
safe_cprintf(ent, PRINT_HIGH, "You need more power cubes to use this ability.\n");
G_FreeEdict(drone);
return NULL;
}
if (ent->myskills.administrator < 90 && ent->num_monsters+drone->monsterinfo.control_cost > MAX_MONSTERS)
{
if (ent->num_monsters == MAX_MONSTERS)
safe_cprintf(ent, PRINT_HIGH, "All available monster slots in use.\n");
else
safe_cprintf(ent, PRINT_HIGH, "Insufficient monster slots.\n");
G_FreeEdict(drone);
return NULL;
}
// get muzzle origin
AngleVectors (ent->client->v_angle, forward, right, NULL);
VectorSet(offset, 0, 7, ent->viewheight-8);
P_ProjectSource(ent->client, ent->s.origin, offset, forward, right, start);
// trace
VectorMA(start, 96, forward, end);
tr = gi.trace(start, NULL, NULL, end, ent, MASK_MONSTERSOLID);
if (tr.fraction < 1)
{
if (tr.endpos[2] <= ent->s.origin[2])
tr.endpos[2] += abs(drone->mins[2]); // spawned below us
else
tr.endpos[2] -= drone->maxs[2]; // spawned above
}
// is this a valid spot?
tr = gi.trace(tr.endpos, drone->mins, drone->maxs, tr.endpos, NULL, MASK_MONSTERSOLID);
if (tr.contents & MASK_MONSTERSOLID)
{
G_FreeEdict(drone);
return NULL;
}
VectorCopy(tr.endpos, drone->s.origin);
drone->s.angles[YAW] = ent->s.angles[YAW];
ent->client->ability_delay = level.time + 2*drone->monsterinfo.control_cost;
//ent->holdtime = level.time + 2*drone->monsterinfo.control_cost;
ent->client->pers.inventory[power_cube_index] -= drone->monsterinfo.cost;
drone->health = 0.5*drone->max_health;
drone->monsterinfo.power_armor_power = 0.5*drone->monsterinfo.max_armor;
drone->nextthink = level.time + FRAMETIME;//2*drone->monsterinfo.control_cost;
//drone->monsterinfo.upkeep_delay = drone->nextthink*10 + 10; // 3.2 upkeep begins 1 second after monster spawn
}
else
{
gi.dprintf("WARNING: SpawnDrone() called without a valid spawner!\n");
G_FreeEdict(drone);
return NULL;
}
if (!ent->client && drone_type == 30) // boss
ent->num_sentries++;
else
ent->num_monsters += drone->monsterinfo.control_cost;
VectorCopy (drone->s.origin, drone->s.old_origin);
gi.linkentity(drone);
return drone;
}
void RemoveAllDrones (edict_t *ent, qboolean refund_player)
{
edict_t *e=NULL;
DroneRemoveSelected(ent, NULL);
// search for other drones
while((e = G_Find(e, FOFS(classname), "drone")) != NULL)
{
// try to restore previous owner
if (e && e->activator && (e->activator == ent) && !RestorePreviousOwner(e))
M_Remove(e, refund_player, true);
}
}
void RemoveDrone (edict_t *ent)
{
vec3_t forward, right, start, end, offset;
trace_t tr;
edict_t *e=NULL;
// get muzzle origin
AngleVectors (ent->client->v_angle, forward, right, NULL);
VectorSet(offset, 0, 7, ent->viewheight-8);
P_ProjectSource(ent->client, ent->s.origin, offset, forward, right, start);
// trace
VectorMA(start, 8192, forward, end);
tr = gi.trace(start, NULL, NULL, end, ent, MASK_MONSTERSOLID);
// are we pointing at a drone of ours?
if (tr.ent && tr.ent->activator && (tr.ent->activator == ent)
&& !strcmp(tr.ent->classname, "drone"))
{
// try to convert back to previous owner
if (RestorePreviousOwner(tr.ent))
{
safe_cprintf(ent, PRINT_HIGH, "Conversion removed.\n");
return;
}
safe_cprintf(ent, PRINT_HIGH, "Monster removed.\n");
DroneRemoveSelected(ent, tr.ent);
M_Remove(tr.ent, true, true);
return;
}
// search for other drones
while((e = G_Find(e, FOFS(classname), "drone")) != NULL)
{
if (e && e->activator && (e->activator == ent))
{
// try to convert back to previous owner
if (RestorePreviousOwner(e))
continue;
M_Remove(e, true, true);
}
}
// clear all slots
DroneRemoveSelected(ent, NULL);
ent->num_monsters = 0;
safe_cprintf(ent, PRINT_HIGH, "All monsters removed.\n");
}
void combatpoint_think (edict_t *self)
{
edict_t *e=NULL;
qboolean q=false;;
// if the goal times-out, then reset all drones
if (!G_EntExists(self->owner) || (level.time > self->delay)
|| (self->owner->selectedsentry != self))
{
G_FreeEdict(self);
return;
}
self->nextthink = level.time + FRAMETIME;
}
edict_t *SpawnCombatPoint (edict_t *ent, vec3_t org)
{
edict_t *goal;
goal = G_Spawn();
goal->think = combatpoint_think;
goal->delay = level.time + 30;
goal->owner = ent;
goal->classname = "drone_goal";
// goal->clipmask = MASK_MONSTERSOLID;
// goal->movetype = MOVETYPE_NONE;
// goal->takedamage = DAMAGE_NO;
// goal->svflags |= SVF_NOCLIENT; // comment this for debugging
goal->mtype = PLAYER_NAVI;
goal->solid = SOLID_TRIGGER;
goal->s.modelindex = gi.modelindex("models/items/c_head/tris.md2");
// goal->s.effects |= EF_BLASTER;
org[2] += 8;
VectorCopy(org, goal->s.origin);
goal->nextthink = level.time + FRAMETIME;
VectorSet (goal->mins, -8, -8, -8);
VectorSet (goal->maxs, 8, 8, 8);
gi.linkentity(goal);
// ent->movetarget = goal; // pointer to goal
return goal;
}
void DroneBlink (edict_t *ent)
{
int i;
for (i=0; i<3; i++) {
if (G_EntIsAlive(ent->selected[i]))
ent->selected[i]->monsterinfo.selected_time = level.time + 3;
}
}
edict_t *SelectDrone (edict_t *ent)
{
int i=0;
edict_t *e=NULL;
while ((e = findclosestreticle(e, ent, 1024)) != NULL)
{
i++;
if (i > 100000)
{
WriteServerMsg("SelectDrone() aborted infinite loop.", "ERROR", true, true);
break;
}
if (!G_EntIsAlive(e))
continue;
if (!visible(ent, e))
continue;
if (!infront(ent, e))
continue;
if (!(e->svflags & SVF_MONSTER))
continue;
if (e->activator && (e->activator == ent))
return e;
}
return NULL;
}
void DroneRemoveSelected (edict_t *ent, edict_t *drone)
{
int i;
for (i=0; i<3; i++)
{
if (drone)
{
// if this monster was previously selected, remove it from the list
if (drone == ent->selected[i])
ent->selected[i] = NULL;
}
else
// remove all monsters from the list
ent->selected[i] = NULL;
}
}
edict_t **DroneAlreadySelected (edict_t *ent, edict_t *drone)
{
int i;
for (i=0; i<3; i++)
{
// is this drone already selected?
if (drone == ent->selected[i])
return &ent->selected[i];
}
return NULL;
}
edict_t **GetFreeSelectSlot (edict_t *ent)
{
int i;
for (i=0; i<3; i++)
{
// is this slot available?
if (!G_EntIsAlive(ent->selected[i]))
return &ent->selected[i];
}
return NULL;
}
void DroneSelect (edict_t *ent)
{
edict_t *drone;
edict_t **slot;
// are we pointing at a drone of ours?
if ((drone = SelectDrone(ent)) != NULL)
{
if ((slot = DroneAlreadySelected(ent, drone)) != NULL)
{
gi.centerprintf(ent, "Drone standing down.\n");
*slot = NULL;
drone->monsterinfo.selected_time = 0;
DroneBlink(ent);
return;
}
if ((slot = GetFreeSelectSlot(ent)) != NULL)
{
gi.centerprintf(ent, "Drone awaiting orders.\n");
*slot = drone;
DroneBlink(ent);
return;
}
// the queue is full, so bump one of our already selected monsters
gi.centerprintf(ent, "Drone awaiting orders.\n");
ent->selected[0] = drone;
DroneBlink(ent);
}
else
{
safe_cprintf(ent, PRINT_HIGH, "You must be looking at a monster to select it.\n");
safe_cprintf(ent, PRINT_HIGH, "Once selected, you can give a monster orders.\n");
}
}
static edict_t *FindMoveTarget (edict_t *ent)
{
int i;
edict_t *e=NULL;
qboolean q=false;
while ((e = findclosestreticle(e, ent, 1024)) != NULL)
{
// don't chase the owner
if (e == ent)
continue;
if (!G_EntIsAlive(e))
continue;
for (i=0; i<3; i++)
{
// is this a selected drone?
if (e == ent->selected[i])
{
q = true;
break;
}
}
if (q)
continue;
if (!visible(ent, e))
continue;
if (!infront(ent, e))
continue;
//gi.dprintf("found %s\n", e->classname);
return e;
}
return NULL;
}
void DroneMove (edict_t *ent)
{
int i;
vec3_t forward, right, start, end, offset;
trace_t tr;
edict_t *e, *target;
// are we pointing at someone?
if ((target = FindMoveTarget(ent)) != NULL)
{
if (OnSameTeam(target, ent))
{
if (target->client)
gi.centerprintf(ent, "Drones will follow %s.\n", target->client->pers.netname);
else
gi.centerprintf(ent, "Drones will follow target.\n");
for (i=0; i<3; i++) {
if (G_EntIsAlive(ent->selected[i])
&& !(ent->selected[i]->spawnflags & AI_STAND_GROUND))
{
ent->selected[i]->enemy = target;
ent->selected[i]->monsterinfo.aiflags |= (AI_NO_CIRCLE_STRAFE|AI_COMBAT_POINT);
}
}
}
else
{
if (target->client)
gi.centerprintf(ent, "Drones will attack %s.\n", target->client->pers.netname);
else
gi.centerprintf(ent, "Drones will attack target.\n");
for (i=0; i<3; i++) {
if (G_EntIsAlive(ent->selected[i])
&& !(ent->selected[i]->spawnflags & AI_STAND_GROUND))
ent->selected[i]->enemy = target;
}
}
ent->selectedsentry = NULL; // we no longer need any combat point
return;
}
// get muzzle origin
AngleVectors (ent->client->v_angle, forward, right, NULL);
VectorSet(offset, 0, 7, ent->viewheight-8);
P_ProjectSource(ent->client, ent->s.origin, offset, forward, right, start);
// trace
VectorMA(start, 8192, forward, end);
tr = gi.trace(start, NULL, NULL, end, ent, MASK_SHOT);
// we're pointing at a spot
if (ent->selectedsentry)
{
ent->selectedsentry = NULL; // reset the combat point
return;
}
gi.centerprintf(ent, "Drones changing position.\n");
e = SpawnCombatPoint(ent, tr.endpos);
ent->selectedsentry = e;
for (i=0; i<3; i++) {
if (G_EntIsAlive(ent->selected[i]))
{
ent->selected[i]->monsterinfo.aiflags |= (AI_NO_CIRCLE_STRAFE|AI_COMBAT_POINT);
ent->selected[i]->enemy = e;
}
}
}
/*
=============
infront
returns 1 if the entity is in front (in sight) of self
=============
*/
qboolean infront (edict_t *self, edict_t *other)
{
vec3_t vec;
float dot;
vec3_t forward;
AngleVectors (self->s.angles, forward, NULL, NULL);
VectorSubtract (other->s.origin, self->s.origin, vec);
VectorNormalize (vec);
dot = DotProduct (vec, forward);
if (dot > 0.3)
return true;
return false;
}
qboolean infov (edict_t *self, edict_t *other, int degrees)
{
vec3_t vec;
float dot, value;
vec3_t forward;
AngleVectors (self->s.angles, forward, NULL, NULL);
VectorSubtract (other->s.origin, self->s.origin, vec);
VectorNormalize (vec);
dot = DotProduct (vec, forward);
value = 1.0-(float)degrees/180.0;
if (dot > value)
return true;
return false;
}
void MonsterAim (edict_t *self, float accuracy, int projectile_speed, qboolean rocket,
int flash_number, vec3_t forward, vec3_t start)
{
float velocity, dist;
vec3_t target, end;
vec3_t right, offset;
trace_t tr;
// determine muzzle origin
AngleVectors (self->s.angles, forward, right, NULL);
if (self->client && !flash_number)
{
VectorSet(offset, 0, 8, self->viewheight-8);
P_ProjectSource (self->client, self->s.origin, offset, forward, right, start);
}
else if (flash_number)
{
// monsters have special offsets that determine their exact firing origin
G_ProjectSource (self->s.origin, monster_flash_offset[flash_number], forward, right, start);
// fix for retarded chick muzzle location
if ((self->svflags & SVF_MONSTER) && (start[2] < self->absmin[2]+32))
start[2] += 32;
}
else
{
// can't determine the muzzle origin, so assume we fire directly ahead of our bbox
VectorCopy(self->s.origin, start);
VectorMA(start, self->maxs[1]+8, forward, start);
}
// fire ahead if our enemy is invalid or out of our FOV
if (!G_EntExists(self->enemy) || !nearfov(self, self->enemy, 0, 60))
{
AngleVectors(self->s.angles, forward, right, NULL);
return;
}
// detected entities are easy targets
if (self->enemy->flags & FL_DETECTED && self->enemy->detected_time > level.time)
accuracy = 1.0;
dist = entdist(self, self->enemy);
// reduce accuracy further based on target's velocity
if ((accuracy < 1.0) && (dist > 128))
{
velocity = VectorLength(self->enemy->velocity);
if (velocity <= 210) // highest walking speed
accuracy *= 0.9;
else if (velocity <= 310) // highest running speed
accuracy *= 0.8;
else if (velocity > 310)
accuracy *= 0.7;
}
// curse reduces accuracy of monsters dramatically
if ((accuracy < 1.0) && que_findtype(self->curses, NULL, CURSE))
accuracy *= 0.2;
G_EntMidPoint(self->enemy, target); // 3.58 aim at the ent's actual mid point
//VectorCopy(self->enemy->s.origin, target);
// miss the shot
if (random() > accuracy)
{
// aim above or below the bbox
//if (random() > 0.5)
target[2] += GetRandom(0, self->enemy->maxs[2]+16);
//else
// target[2] += -GetRandom(0, abs(self->enemy->mins[2])+16);
// aim to the left or right of the bbox
VectorMA(target, ((self->enemy->maxs[1]+GetRandom(12, 24))*crand()), right, target);
VectorSubtract(target, start, forward);
VectorNormalize(forward);
return;
}
// lead shots if our enemy is alive and not too close
if ((self->enemy->health > 0) && (dist > 64) && (projectile_speed > 0))
{
// move our target point based on projectile and enemy velocity
VectorMA(target, (float)dist/projectile_speed, self->enemy->velocity, end);
tr = gi.trace(target, NULL, NULL, end, self->enemy, MASK_SOLID);
VectorCopy(tr.endpos, target);
if (rocket)
{
// if our enemy's feet are within 100 units of the ground
// then we should aim at the ground and cause radius damage
VectorCopy(target, end);
end[2] = self->enemy->absmin[2]-100;
// FIXME: we should probably be tracing without the verticle prediction
tr = gi.trace(target, NULL, NULL, end, self->enemy, MASK_SOLID);
// is there is ground below our target point ?
if (tr.fraction < 1)
VectorCopy(tr.endpos, target);
}
// if we dont have a clear shot to our predicted target
if (!G_IsClearPath(self, MASK_SOLID, start, target))
G_EntMidPoint(self->enemy, target); // 3.58
//VectorCopy(self->enemy->s.origin, target); // fire directly at our enemy
}
VectorSubtract(target, start, forward);
VectorNormalize (forward);
}
qboolean M_MeleeAttack (edict_t *self, float range, int damage, int knockback)
{
vec3_t start, forward, end;
trace_t tr;
self->lastsound = level.framenum;
// get starting and ending positions
G_EntMidPoint(self, start);
G_EntMidPoint(self->enemy, end);
// get vector to target
VectorSubtract(end, start, forward);
tr = gi.trace(start, NULL, NULL, end, self, MASK_SHOT);
if (G_EntExists(tr.ent))
{
T_Damage(tr.ent, self, self, forward, tr.endpos, tr.plane.normal, damage, knockback, 0, MOD_HIT);
return true; // hit a damageable ent
}
return false;
}
qboolean M_NeedRegen (edict_t *ent)
{
if (!ent || !ent->inuse)
return false;
// if they are dead, they can't be regenerated
if (ent->deadflag == DEAD_DEAD)
return false;
// check for health
if (ent->health < ent->max_health)
return true;
// check for armor
if (ent->client)
{
// client check
if (ent->client->pers.inventory[body_armor_index] < MAX_ARMOR(ent))
return true;
}
else
{
// non-client check
if (ent->monsterinfo.max_armor && (ent->monsterinfo.power_armor_power < ent->monsterinfo.max_armor))
return true;
}
return false;
}
qboolean M_Regenerate (edict_t *self, int regen_frames, int delay, qboolean regen_health, qboolean regen_armor, qboolean regen_ammo, int *nextframe)
{
int health, armor, ammo;
qboolean regenerate=false;
if (!self || !self->inuse)
return false;
if (delay > 0)
{
if (level.framenum < *nextframe)
return false;
*nextframe = level.framenum + delay;
}
else
delay = 1;
if (regen_health)
{
health = floattoint( (float)self->max_health / ((float)regen_frames / delay) );
if (health < 1)
health = 1;
// heal them if they are weakened
if (self->health < self->max_health)
{
self->health += health;
if (self->health > self->max_health)
self->health = self->max_health;
// switch to normal monster skin when it's healed
if (!self->client && (self->svflags & SVF_MONSTER)
&& (self->health >= 0.3*self->max_health))
self->s.skinnum &= ~1;
regenerate = true;
}
}
if (regen_armor)
{
if (self->client)
{
if (self->client->pers.inventory[body_armor_index] < MAX_ARMOR(self))
{
armor = MAX_ARMOR(self) / (regen_frames / delay);
if (armor < 1)
armor = 1;
// repair player armor
self->client->pers.inventory[body_armor_index] += armor;
if (self->client->pers.inventory[body_armor_index] > MAX_ARMOR(self))
self->client->pers.inventory[body_armor_index] = MAX_ARMOR(self);
regenerate = true;
}
}
if (self->monsterinfo.power_armor_type && self->monsterinfo.max_armor
&& (self->monsterinfo.power_armor_power < self->monsterinfo.max_armor))
{
//decino: divide by 0? wut. dunno what's causing it
armor = self->monsterinfo.max_armor / (regen_frames / delay);
if (armor < 1)
armor = 1;
self->monsterinfo.power_armor_power += armor;
if (self->monsterinfo.power_armor_power > self->monsterinfo.max_armor)
self->monsterinfo.power_armor_power = self->monsterinfo.max_armor;
regenerate = true;
}
}
if (regen_ammo)
{
if (self->client)
{
int ammoIndex = G_GetAmmoIndexByWeaponIndex(G_GetRespawnWeaponIndex(self));
int maxAmmo = MaxAmmoType(self, ammoIndex);
if (AmmoLevel(self, ammoIndex) < 1.0)
{
ammo = maxAmmo / (regen_frames / delay);
if (ammo < 1)
ammo = 1;
self->client->pers.inventory[ammoIndex] += ammo;
if (self->client->pers.inventory[ammoIndex] > maxAmmo)
self->client->pers.inventory[ammoIndex] = maxAmmo;
regenerate = true;
}
}
}
return regenerate;
}
void M_Remove (edict_t *self, qboolean refund, qboolean effect)
{
// monster is already being removed
if (!self->inuse || (self->solid == SOLID_NOT))
return;
// additional steps must be taken if we have an owner/activator
if (PM_MonsterHasPilot(self)) // for player-monsters
{
if (refund)
self->owner->client->pers.inventory[power_cube_index]+=self->monsterinfo.cost;
}
else if (self->activator && self->activator->inuse
&& !self->monsterinfo.slots_freed) // for all other monsters
{
if (self->activator->client)
{
// refund player's power cubes used if the monster has full health
if (refund && !M_NeedRegen(self))
self->activator->client->pers.inventory[power_cube_index]
+= self->monsterinfo.cost;
}
else
{
// invasion defender spawns hold a pointer to this monster which must be cleared
if (self->activator->enemy && (self->activator->enemy == self))
self->activator->enemy = NULL;
// reduce boss count
if (self->monsterinfo.control_cost > 2)
self->activator->num_sentries--;
// end spree war if there are no more bosses remaining
if (SPREE_WAR && (SPREE_DUDE == world) && world->num_sentries < 1)
{
SPREE_WAR = false;
SPREE_DUDE = NULL;
}
}
// reduce monster count
self->activator->num_monsters -= self->monsterinfo.control_cost;
if (self->activator->num_monsters < 0)
self->activator->num_monsters = 0;
// mark the player slots as being refunded, so it can't happen again
self->monsterinfo.slots_freed = true;
}
// mark this entity for removal
if (effect)
self->think = BecomeTE;
else
self->think = G_FreeEdict;
self->takedamage = DAMAGE_NO;
self->solid = SOLID_NOT; //4.0 to keep killbox() happy
self->deadflag = DEAD_DEAD;
self->nextthink = level.time + FRAMETIME;
gi.unlinkentity(self); //4.0 B15 another attempt to make killbox() happy
}
void M_PrepBodyRemoval (edict_t *self)
{
self->think = M_BodyThink;
self->delay = level.time + 30; // time until body is auto-removed
self->activator = NULL; // no longer owned by anyone
self->nextthink = level.time + FRAMETIME;
}
void M_BodyThink (edict_t *self)
{
// sanity check
if (!self || !self->inuse)
return;
// already in the process of being removed
if (self->solid == SOLID_NOT)
return;
// body becomes transparent before removal
if (level.time == self->delay-5.0)
self->s.effects = EF_PLASMA;
else if (level.time == self->delay-2.0)
self->s.effects = EF_SPHERETRANS;
// remove the body
if (level.time >= self->delay)
{
M_Remove(self, false, false);
return;
}
self->nextthink = level.time + FRAMETIME;
}
qboolean M_Upkeep (edict_t *self, int delay, int upkeep_cost)
{
int *cubes;
edict_t *e;
if (delay > 0)
{
if (level.framenum < self->monsterinfo.upkeep_delay)
return true;
self->monsterinfo.upkeep_delay = level.framenum + delay;
}
else
delay = 1;
e = G_GetClient(self);
if (!e)
return true; // probably owned by world; doesn't pay upkeep
cubes = &e->client->pers.inventory[power_cube_index];
if (*cubes < upkeep_cost)
{
// owner can't pay upkeep, so we're dead :(
T_Damage(self, world, world, vec3_origin, self->s.origin, vec3_origin, 100000, 0, 0, 0);
return false;
}
*cubes -= upkeep_cost;
return true;
}
qboolean M_Initialize (edict_t *ent, edict_t *monster)
{
int talentLevel;
float mult = 1.0;
switch (monster->mtype)
{
case M_GUNNER: init_drone_gunner(monster); break;
case M_CHICK: init_drone_bitch(monster); break;
case M_BRAIN: init_drone_brain(monster); break;
case M_MEDIC: init_drone_medic(monster); break;
case M_MUTANT: init_drone_mutant(monster); break;
case M_PARASITE: init_drone_parasite(monster); break;
case M_TANK: init_drone_tank(monster); break;
case M_SOLDIER: case M_SOLDIERLT: case M_SOLDIERSS: init_drone_soldier(monster); break;
case M_GLADIATOR: init_drone_gladiator(monster); break;
default: return false;
}
if (ent && ent->inuse && ent->client)
{
//Talent: Corpulence
talentLevel = getTalentLevel(ent, TALENT_CORPULENCE);
if(talentLevel > 0) mult += 0.1 * talentLevel; //+10% per upgrade
}
monster->health *= mult;
monster->max_health *= mult;
monster->monsterinfo.power_armor_power *= mult;
monster->monsterinfo.max_armor *= mult;
// set shared monster properties
monster->classname = "drone";
monster->svflags |= SVF_MONSTER;
monster->svflags &= ~SVF_DEADMONSTER;
monster->yaw_speed = 20;
monster->monsterinfo.sight_range = 1024;
monster->flags |= FL_CHASEABLE;
monster->deadflag = DEAD_NO;
monster->movetype = MOVETYPE_STEP;
monster->solid = SOLID_BBOX;
monster->clipmask = MASK_MONSTERSOLID;
monster->takedamage = DAMAGE_AIM;
monster->s.renderfx |= RF_FRAMELERP|RF_IR_VISIBLE;
monster->enemy = NULL;
monster->oldenemy = NULL;
monster->goalentity = NULL;
monster->monsterinfo.aiflags &= ~AI_COMBAT_POINT;
// set shared monster functions
monster->pain = drone_pain;
monster->touch = drone_touch;
monster->think = drone_think;
return true;
}
qboolean M_SetBoundingBox (int mtype, vec3_t boxmin, vec3_t boxmax)
{
switch (mtype)
{
case M_SOLDIER:
case M_SOLDIERLT:
case M_SOLDIERSS:
case M_GUNNER:
case M_BRAIN:
VectorSet (boxmin, -16, -16, -24);
VectorSet (boxmax, 16, 16, 32);
break;
case M_PARASITE:
VectorSet (boxmin, -16, -16, -24);
VectorSet (boxmax, 16, 16, 0);
break;
case M_CHICK:
VectorSet (boxmin, -16, -16, 0);
VectorSet (boxmax, 16, 16, 56);
break;
case M_TANK:
VectorSet (boxmin, -24, -24, -16);
VectorSet (boxmax, 24, 24, 64);
break;
case M_MEDIC:
case M_MUTANT:
VectorSet (boxmin, -24, -24, -24);
VectorSet (boxmax, 24, 24, 32);
break;
default:
//gi.dprintf("failed to set bbox\n");
return false;
}
//gi.dprintf("set bounding box for mtype %d\n", mtype);
return true;
}
char *GetMonsterKindString (int mtype)
{
switch (mtype)
{
case M_BRAIN: return "Brain";
case M_DECOY: return "Admin Clone";
case M_GLADIATOR: return "Gladiator";
case M_CHICK: return "Chick";
case M_MEDIC: return "Medic";
case M_MUTANT: return "Mutant";
case M_PARASITE: return "Parasite";
case M_SOLDIER: case M_SOLDIERLT: case M_SOLDIERSS: return "Soldier";
case M_TANK: return "Tank";
case M_GUNNER: return "Gunner";
case M_YANGSPIRIT: return "Yang Spirit";
case M_BALANCESPIRIT: return "Balance Spirit";
case BOSS_TANK:
case M_COMMANDER:
return "Tank Commander";
case BOSS_MAKRON: return "Makron";
case P_TANK: return "Tank";
case M_SKULL: return "Hellspawn";
case M_SPIKER: return "Spiker";
case M_GASSER: return "Gasser";
case M_SPIKEBALL: return "Spore";
case M_OBSTACLE: return "Obstacle";
case M_COCOON: return "Cocoon";
case M_HEALER: return "Healer";
case TOTEM_FIRE: return "Fire Totem";
case TOTEM_WATER: return "Water Totem";
case M_ALARM: return "Laser Trap";
default: return "Monster";
}
}
void M_Notify (edict_t *monster)
{
if (!monster || !monster->inuse)
return;
if (!monster->activator || !monster->activator->inuse || !monster->activator->client)
return;
// don't call this more than once
if (monster->monsterinfo.slots_freed)
return;
monster->activator->num_monsters -= monster->monsterinfo.control_cost;
if (monster->activator->num_monsters < 0)
monster->activator->num_monsters = 0;
safe_cprintf(monster->activator, PRINT_HIGH, "You lost a %s! (%d/%d)\n",
GetMonsterKindString(monster->mtype), monster->activator->num_monsters, MAX_MONSTERS);
monster->monsterinfo.slots_freed = true;
DroneRemoveSelected(monster->activator, monster);//4.2 remove from selection list
}
void Cmd_Drone_f (edict_t *ent)
{
int i=0;
char *s;
edict_t *e=NULL;
if (debuginfo->value)
gi.dprintf("DEBUG: %s just called Cmd_Drone_f()\n", ent->client->pers.netname);
if (ent->deadflag == DEAD_DEAD)
return;
s = gi.args();
if (!Q_strcasecmp(s, "remove"))
{
RemoveDrone(ent);
return;
}
if (!Q_strcasecmp(s, "follow"))
{
gi.centerprintf(ent, "Drones will follow you.\n");
for (i=0; i<3; i++) {
// search queue for drones
if (G_EntIsAlive(ent->selected[i]))
{
ent->selected[i]->monsterinfo.aiflags |= (AI_NO_CIRCLE_STRAFE|AI_COMBAT_POINT);
ent->selected[i]->monsterinfo.aiflags &= ~AI_STAND_GROUND;
ent->selected[i]->enemy = ent;
}
}
return;
}
if (!Q_strcasecmp(s, "stand"))
{
gi.centerprintf(ent, "Drones will hold position.\n");
for (i=0; i<3; i++) {
// search queue for drones
if (G_EntIsAlive(ent->selected[i]))
{
ent->selected[i]->monsterinfo.aiflags |= AI_STAND_GROUND;
ent->selected[i]->yaw_speed = 40; // faster turn rate while standing ground
// some drones have limited sight range while standing ground
if (ent->selected[i]->mtype == M_BRAIN)
ent->selected[i]->monsterinfo.sight_range = 256;
if (ent->selected[i]->mtype == M_PARASITE)
ent->selected[i]->monsterinfo.sight_range = 128;
}
}
return;
}
if (!Q_strcasecmp(s, "count"))
{
// search for other drones
while((e = G_Find(e, FOFS(classname), "drone")) != NULL)
{
if (e && e->activator && (e->activator == ent)
&& (e->deadflag != DEAD_DEAD))
i++;
}
gi.centerprintf(ent, "You have %d drones.\n%d/%d slots used.", i, ent->num_monsters, MAX_MONSTERS);
return;
}
if (!Q_strcasecmp(s, "hunt"))
{
gi.centerprintf(ent, "Drones will hunt.\n");
for (i=0; i<3; i++) {
// search queue for drones
if (G_EntIsAlive(ent->selected[i]))
{
ent->selected[i]->monsterinfo.aiflags &= ~AI_STAND_GROUND;
ent->selected[i]->monsterinfo.sight_range = 1024; // reset back to default
ent->selected[i]->yaw_speed = 40; // reset back to default
}
}
return;
}
if (!Q_strcasecmp(s, "select"))
{
DroneSelect(ent);
return;
}
if (!Q_strcasecmp(s, "move"))
{
DroneMove(ent);
return;
}
if (!Q_strcasecmp(s, "help"))
{
safe_cprintf(ent, PRINT_HIGH, "Available monster commands:\n");
safe_cprintf(ent, PRINT_HIGH, "monster gunner\nmonster parasite\nmonster brain\nmonster bitch\nmonster medic\nmonster tank\nmonster mutant\nmonster gladiator\nmonster select\nmonster move\nmonster remove\nmonster hunt\nmonster count\n");
return;
}
if (ent->myskills.abilities[MONSTER_SUMMON].disable)
return;
if (!G_CanUseAbilities(ent, ent->myskills.abilities[MONSTER_SUMMON].current_level, 0))
return;
if (ctf->value && (CTF_DistanceFromBase(ent, NULL, CTF_GetEnemyTeam(ent->teamnum)) < CTF_BASE_DEFEND_RANGE))
{
safe_cprintf(ent, PRINT_HIGH, "Can't build in enemy base!\n");
return;
}
if (!Q_strcasecmp(s, "gunner"))
SpawnDrone(ent, 1, false);
else if (!Q_strcasecmp(s, "parasite"))
SpawnDrone(ent, 2, false);
else if (!Q_strcasecmp(s, "brain"))
SpawnDrone(ent, 4, false);
else if (!Q_strcasecmp(s, "bitch"))
SpawnDrone(ent, 3, false);
else if (!Q_strcasecmp(s, "medic"))
SpawnDrone(ent, 5, false);
else if (!Q_strcasecmp(s, "tank"))
SpawnDrone(ent, 6, false);
else if (!Q_strcasecmp(s, "mutant"))
SpawnDrone(ent, 7, false);
else if (!Q_strcasecmp(s, "gladiator"))// && ent->myskills.administrator)
SpawnDrone(ent, 8, false);
else if (!Q_strcasecmp(s, "soldier") && ent->myskills.administrator)
SpawnDrone(ent, 9, false);
else if (!Q_strcasecmp(s, "commander") && ent->myskills.administrator)
SpawnDrone(ent, 30, false);
// if (ent->myskills.administrator < 90)
// gi.cprintf(ent, PRINT_HIGH, "Additional parameters required.\nType 'monster help' for a list of commands.\n");
//gi.dprintf("%d\n", CTF_GetNumSummonable("drone", ent->teamnum));
}
<file_sep>#define MONSTERSPAWN_STATUS_WORKING 0 // spawning a wave of monsters
#define MONSTERSPAWN_STATUS_IDLE 1 // waiting for current wave to be killed
#define PLAYERSPAWN_REGEN_FRAMES 1200
#define PLAYERSPAWN_REGEN_DELAY 10
#define PLAYERSPAWN_HEALTH 2000
#define INVASION_BONUS_EXP 1000
#define INVASION_BONUS_CREDITS 1000
<file_sep>#include "g_local.h"
#define DRONE_TARGET_RANGE 1024 // maximum range for finding targets
#define DRONE_ALLY_RANGE 512 // range allied units can be called for assistance
#define DRONE_FOV 90 // viewing fov used by drone
#define DRONE_MIN_GOAL_DIST 32 // goals are tagged as being reached at this distance
#define DRONE_FINDTARGET_FRAMES 2 // drones search for targets every few frames
#define DRONE_TELEPORT_DELAY 30 // delay in seconds before a drone can teleport
#define DRONE_SLEEP_FRAMES 100 // frames before drone becomes less alert
#define DRONE_SEARCH_TIMEOUT 300 // frames before drone gives up trying to reach an enemy
#define DRONE_SUICIDE_FRAMES 1800 // idle frames before a world monster suicides
#define STEPHEIGHT 18 // standard quake2 step size
#ifdef max
#undef max
#endif
qboolean drone_ValidChaseTarget (edict_t *self, edict_t *target);
float distance (vec3_t p1, vec3_t p2);
edict_t *SpawnGoalEntity (edict_t *ent, vec3_t org);
void drone_ai_checkattack (edict_t *self);
qboolean drone_findtarget (edict_t *self);
int max(int a, int b);
int max(int a, int b) {
return a > b ? a : b;
}
/*
=============
ai_move
Move the specified distance at current facing.
This replaces the QC functions: ai_forward, ai_back, ai_pain, and ai_painforward
==============
*/
void ai_move (edict_t *self, float dist)
{
M_walkmove (self, self->s.angles[YAW], dist);
}
/*
=============
ai_charge
Turns towards target and advances
Use this call with a distance of 0 to replace ai_face
==============
*/
void ai_charge (edict_t *self, float dist)
{
vec3_t v;
if (!self || !self->inuse)
return;
// if our enemy is invalid, try to find a new one
if (!G_ValidTarget(self, self->enemy, true) && !drone_findtarget(self))
return;
VectorSubtract (self->enemy->s.origin, self->s.origin, v);
self->ideal_yaw = vectoyaw(v);
M_ChangeYaw (self);
}
/*
=============
ai_run_slide
Strafe sideways, but stay at aproximately the same range
=============
*/
void ai_run_slide(edict_t *self, float distance)
{
float ofs;
if (!self->enemy)
return;
self->ideal_yaw = self->enemy->s.angles[YAW];
M_ChangeYaw (self);
if (self->monsterinfo.lefty)
ofs = 90;
else
ofs = -90;
if (M_walkmove (self, self->ideal_yaw + ofs, distance))
return;
self->monsterinfo.lefty = 1 - self->monsterinfo.lefty;
M_walkmove (self, self->ideal_yaw - ofs, distance);
// walk backwards to maintain distance
if (entdist(self, self->enemy)+distance < 256)
M_walkmove(self, self->s.angles[YAW], -distance);
}
/*
=============
drone_wakeallies
Makes allied drones chase our enemy if they aren't busy
=============
*/
void drone_wakeallies (edict_t *self)
{
edict_t *e=NULL;
if (!self->enemy)
return; // what are we doing here?
// if allied monsters arent chasing a visible enemy
// then enlist their help
while ((e = findradius (e, self->s.origin, DRONE_ALLY_RANGE)) != NULL)
{
if (!G_EntExists(e))
continue;
if (e->client)
continue;
if (!(e->svflags & SVF_MONSTER))
continue;
if (strcmp(e->classname, "drone"))
continue;
if (!OnSameTeam(self, e))
continue;
if (!visible(self, e))
continue;
if (e->enemy && visible(e, e->enemy))
continue;
// gi.dprintf("ally found!\n");
e->enemy = self->enemy;
}
}
qboolean M_ValidMedicTarget (edict_t *self, edict_t *target)
{
if (target == self)
return false;
if (!G_EntExists(target))
return false;
//gi.dprintf("looking for medic target\n");
// don't target players with invulnerability
if (target->client && (target->client->invincible_framenum > level.framenum))
return false;
// don't target spawning players
if (target->client && (target->client->respawn_time > level.time))
return false;
// don't target players in chat-protect
if (target->client && ((target->flags & FL_CHATPROTECT) || (target->flags & FL_GODMODE)))
return false;
// don't target frozen players
if (que_typeexists(target->curses, CURSE_FROZEN))
return false;
// invasion medics shouldn't try to heal base defenders
if (invasion->value && (self->monsterinfo.aiflags & AI_FIND_NAVI) && !(target->monsterinfo.aiflags & AI_FIND_NAVI))
return false;
// the target is dead
if ((target->health < 1) || (target->deadflag == DEAD_DEAD))
{
// don't target player or non-monster corpses
if (target->client || strcmp(target->classname, "drone"))
{
//gi.dprintf("invalid corpse\n");
return false;
}
// if we're owned by a player, don't spawn more monsters than our limit
if (self->activator && self->activator->client && (self->activator->num_monsters
+ target->monsterinfo.control_cost > MAX_MONSTERS))
return false;
}
// target must be on our team and require healing
else if (!OnSameTeam(self, target) || !M_NeedRegen(target))
return false;
if (!visible(self, target))
return false;
//gi.dprintf("found medic target\n");
return true;
}
qboolean drone_validnavi (edict_t *self, edict_t *other, qboolean visibility_check)
{
// only world-spawn monsters should search for invasion mode navi
// don't bother if they are not mobile
if (self->activator->client || (self->monsterinfo.aiflags & AI_STAND_GROUND))
return false;
// make sure this is actually a beacon
if (!other || !other->inuse || (other->mtype != INVASION_NAVI))
return false;
// do a visibility check if required
if (visibility_check && !visible(self, other))
return false;
return true;
}
qboolean drone_heartarget (edict_t *target)
{
// monster always senses other AI
if (!target->client)
return true;
// target made a sound (necessary mostly for weapon firing)
if (target->lastsound + 4 >= level.framenum)
return true;
// target used an ability
if (target->client->ability_delay + 0.4 >= level.time)
return true;
return false;
}
/*
=============
drone_findtarget
Searches a spherical area for enemies and
returns true if one is found within range
=============
*/
qboolean drone_findtarget (edict_t *self)
{
int frames, range=self->monsterinfo.sight_range;
edict_t *target=NULL;
qboolean foundnavi=false;
if (level.time < pregame_time->value)
return false; // pre-game time
// if a monster hasn't found a target for awhile, it becomes less alert
// and searches less often, freeing up CPU cycles
if (!(self->monsterinfo.aiflags & AI_STAND_GROUND)
&& self->monsterinfo.idle_frames > DRONE_SLEEP_FRAMES)
frames = 4;
else
frames = DRONE_FINDTARGET_FRAMES;
if (level.framenum % frames)
return false;
// if we're a medic, do a sweep for those with medical need!
if (self->monsterinfo.aiflags & AI_MEDIC)
{
// don't bother finding targets out of our range
if (self->monsterinfo.aiflags & AI_STAND_GROUND)
range = 256;
while ((target = findclosestradius (target, self->s.origin, range)) != NULL)
{
if (!M_ValidMedicTarget(self, target))
continue;
self->enemy = target;
return true;
}
}
// find an enemy
while ((target = findclosestradius (target, self->s.origin,
self->monsterinfo.sight_range)) != NULL)
{
if (!G_ValidTarget(self, target, true))
continue;
// limit drone/monster FOV, but check for recent sounds
if (!nearfov(self, target, 0, DRONE_FOV) && !drone_heartarget(target))//(level.framenum > target->lastsound + 5))
continue;
//4.4 if this is an invasion player spawn (base), then clear goal AI flags
if (target->mtype == INVASION_PLAYERSPAWN)
{
self->monsterinfo.aiflags &= ~AI_FIND_NAVI;
if (!self->monsterinfo.melee)
self->monsterinfo.aiflags &= ~AI_NO_CIRCLE_STRAFE;
}
self->enemy = target;
// trigger sight
if (self->monsterinfo.sight)
self->monsterinfo.sight(self, self->enemy);
// alert nearby monsters and make them chase our enemy
drone_wakeallies(self);
//gi.dprintf("found an enemy\n");
return true;
}
// find a navigational beacon IF we're not already chasing something
// monster must be owned by world and not instructed to ignore navi
if (!self->enemy && (self->monsterinfo.aiflags & AI_FIND_NAVI))
{
while ((target = findclosestradius1 (target, self->s.origin,
self->monsterinfo.sight_range)) != NULL)
{
if (!drone_validnavi(self, target, true))
continue;
// set ai flags to chase goal and turn off circle strafing
self->monsterinfo.aiflags |= (AI_COMBAT_POINT|AI_NO_CIRCLE_STRAFE);
//gi.dprintf("found navi\n");
self->enemy = target;
return true;
}
}
return false;
}
/*
=============
drone_ai_stand
Called when the drone isn't chasing an enemy or goal
It is also called when the drone is holding position
=============
*/
void drone_ai_stand (edict_t *self, float dist)
{
vec3_t v;
if (self->deadflag == DEAD_DEAD)
return;
if (self->monsterinfo.pausetime > level.time)
return;
//gi.dprintf("drone_ai_stand\n");
// used for slight position adjustments for animations
if (dist)
M_walkmove(self, self->s.angles[YAW], dist);
if (!self->enemy)
{
// if we had a previous enemy, go after him
if (G_EntExists(self->oldenemy))
{
if (drone_ValidChaseTarget(self, self->oldenemy))
{
self->enemy = self->oldenemy;
self->monsterinfo.run(self);
}
else
{
// no longer valid, so forget about him
self->oldenemy = NULL;
return;
}
}
else if (drone_findtarget(self))
{
self->monsterinfo.run(self);
//if (self->monsterinfo.sight)
// self->monsterinfo.sight(self, self->enemy);
}
else // didn't find anything to get mad at
{
// regenerate to full in 30 seconds
//if (self->monsterinfo.control_cost < 3) // non-boss
if (self->mtype == M_MEDIC)
M_Regenerate(self, 300, 10, true, true, false, &self->monsterinfo.regen_delay1);
else if (self->health >= 0.3*self->max_health)
// change skin if we are being healed by someone else
self->s.skinnum &= ~1;
// call idle func every so often
if (self->monsterinfo.idle && (level.time > self->monsterinfo.idle_delay))
{
self->monsterinfo.idle(self);
self->monsterinfo.idle_delay = level.time + GetRandom(15, 30);
}
self->monsterinfo.idle_frames++;
// world monsters suicide if they haven't found an enemy in awhile
if (self->activator && !self->activator->client && !(self->monsterinfo.aiflags & AI_STAND_GROUND)
&& (self->monsterinfo.idle_frames > DRONE_SUICIDE_FRAMES))
{
if (self->monsterinfo.control_cost > 2) // we're a boss
self->activator->num_sentries--;
if (self->activator)
self->activator->num_monsters -= self->monsterinfo.control_cost;
if (self->activator->num_monsters < 0)
self->activator->num_monsters = 0;
BecomeTE(self);
return;
}
}
}
else
{
// we're not going anywhere
if (self->monsterinfo.aiflags & AI_STAND_GROUND)
{
// if enemy isn't visible, ignore him
if (!visible(self, self->enemy))
{
self->enemy = NULL;
return;
}
if (drone_ValidChaseTarget(self, self->enemy))
{
// turn towards our enemy
VectorSubtract(self->enemy->s.origin, self->s.origin, v);
self->ideal_yaw = vectoyaw(v);
M_ChangeYaw(self);
drone_ai_checkattack(self);
return;
}
else
{
self->enemy = NULL;
return;
}
}
if (drone_ValidChaseTarget(self, self->enemy))
self->monsterinfo.run(self);
else if (drone_findtarget(self))
self->monsterinfo.run(self);
else
self->enemy = NULL;
}
}
#define STATE_TOP 0
#define STATE_BOTTOM 1
#define STATE_UP 2
#define STATE_DOWN 3
qboolean G_IsClearPath (edict_t *ignore, int mask, vec3_t spot1, vec3_t spot2);
/*
=============
FindPlat
returns true if a nearby platform/elevator is found
self the entity searching for the platform
plat_pos the position of the platform (if found)
=============
*/
qboolean FindPlat (edict_t *self, vec3_t plat_pos)
{
vec3_t start, end;
edict_t *e=NULL;
trace_t tr;
if (!self->enemy)
return false; // what are we doing here?
while((e = G_Find(e, FOFS(classname), "func_plat")) != NULL)
{
// this is an ugly hack, but it's the only way to test the distance
// or visiblity of a plat, since the origin and bbox yield no useful
// information
tr = gi.trace(self->s.origin, NULL, NULL, e->absmax, self, MASK_SOLID);
VectorCopy(tr.endpos, start);
VectorCopy(tr.endpos, end);
end[2] -= 8192;
tr = gi.trace(start, NULL, NULL, end, self, MASK_SOLID);
VectorCopy(tr.endpos, start);
VectorCopy(tr.endpos, plat_pos);
if (!tr.ent || (tr.ent && (tr.ent != e)))
continue; // we can't see this plat
if (distance(start, self->s.origin) > 512)
continue; // too far
if (e->moveinfo.state != STATE_BOTTOM)
continue; // plat must be down
if (start[2] > self->absmin[2]+2*STEPHEIGHT)
continue;
VectorCopy(start, end);
end[2] += abs(e->s.origin[2]);
if (distance(end, self->enemy->s.origin)
> distance(self->s.origin, self->enemy->s.origin))
continue; // plat must bring us closer to our goal
self->goalentity = e;
self->monsterinfo.aiflags |= AI_PURSUE_PLAT_GOAL;
return true;
}
return false;
}
/*
=============
FindHigherGoal
finds a goal higher than our current position and moves to it
self the drone searching for the goal
dist the distance the drone wants to move
=============
*/
void FindHigherGoal (edict_t *self, float dist)
{
int i;
float yaw, range=128;
vec3_t forward, start, end, best, angles;
trace_t tr;
// gi.dprintf("finding a higher goal\n");
VectorCopy(self->absmin, best);
// try to run forward first
VectorCopy(self->s.origin, start);
start[2] = self->absmin[2]+2*STEPHEIGHT;
AngleVectors(self->s.angles, forward, NULL, NULL);
VectorMA(start, 128, forward, end);
tr = gi.trace(start, NULL, NULL, end, self, MASK_SOLID);
vectoangles(tr.plane.normal, angles);
AngleCheck(&angles[PITCH]);
if (angles[PITCH] != 0)
{
self->ideal_yaw = vectoyaw(forward);
M_MoveToGoal(self, dist);
return;
}
while (range <= 512)
{
// check 8 angles at 45 degree intervals
for(i=0; i<8; i++)
{
yaw = anglemod(i*45);
forward[0] = cos(DEG2RAD(yaw));
forward[1] = sin(DEG2RAD(yaw));
forward[2] = 0;
// start scanning above step height
VectorCopy(self->s.origin, start);
if (self->waterlevel > 1)
start[2] = self->absmax[2];//VectorCopy(self->absmax, start);
else
start[2] = self->absmin[2];//VectorCopy(self->absmin, start);
start[2] += 2*STEPHEIGHT;
// dont trace too far forward, or you will find multiple paths!
VectorMA(start, range, forward, end);
tr = gi.trace(start, NULL, NULL, end, self, MASK_SOLID);
// trace down
VectorCopy(tr.endpos, start);
VectorCopy(tr.endpos, end);
end[2] -= 8192;
tr = gi.trace(start, NULL, NULL, end, self, MASK_SOLID);
if (distance(self->absmin, tr.endpos) < DRONE_MIN_GOAL_DIST)
continue; // too close
// if we can still see our enemy, dont take a path that will
// put him out of sight
if (self->enemy && !(self->monsterinfo.aiflags & AI_LOST_SIGHT)
&& !G_IsClearPath(self, MASK_SOLID, tr.endpos, self->enemy->s.origin))
continue;
vectoangles(tr.plane.normal, angles);
if (angles[PITCH] > 360)
angles[PITCH] -= 360;
if (angles[PITCH] < 360)
angles[PITCH] += 360;
if (angles[PITCH] != 270)
continue; // must be flat ground, or we risk getting stuck
// is this point higher than the last?
if (tr.endpos[2] > best[2])
VectorCopy(tr.endpos, best);
// we may find more than one position at the same height
// so take it if it's farther from us
else if ((tr.endpos[2] == best[2]) && (distance(self->absmin,
tr.endpos) > distance(self->absmin, best)))
VectorCopy(tr.endpos, best);
}
// were we able to find anything?
if (best[2] <= self->absmin[2]+1)
range *= 2;
else
break;
}
if (range > 512)
{
// gi.dprintf("couldnt find a higher goal!!!\n");
self->goalentity = self->enemy;
M_MoveToGoal(self, dist);
return;
}
// gi.dprintf("found higher goal at %d, current %d\n", (int)best[2], (int)self->absmin[2]);
self->goalentity = SpawnGoalEntity(self, best);
VectorSubtract(self->goalentity->s.origin, self->s.origin, forward);
self->ideal_yaw = vectoyaw(forward);
M_MoveToGoal(self, dist);
}
/*
=============
FindLowerGoal
finds a goal lower than our current position and moves to it
self the drone searching for the goal
dist the distance the drone wants to move
=============
*/
void FindLowerGoal (edict_t *self, float dist)
{
int i;
float yaw, range=128;
vec3_t forward, start, end, best;
trace_t tr;
// gi.dprintf("finding a lower goal\n");
VectorCopy(self->absmin, best);
while (range <= 512)
{
// check 8 angles at 45 degree intervals
for(i=0; i<8; i++)
{
yaw = anglemod(i*45);
forward[0] = cos(DEG2RAD(yaw));
forward[1] = sin(DEG2RAD(yaw));
forward[2] = 0;
// start scanning above step height
VectorCopy(self->s.origin, start);
//VectorCopy(self->absmin, start);
//start[2] += STEPHEIGHT;
start[2] = self->absmin[2] + STEPHEIGHT;
// dont trace too far forward, or you will find multiple paths!
VectorMA(start, range, forward, end);
tr = gi.trace(start, NULL, NULL, end, self, MASK_SOLID);
// trace down
VectorCopy(tr.endpos, start);
VectorCopy(tr.endpos, end);
end[2] -= 64;
tr = gi.trace(start, NULL, NULL, end, self, MASK_SOLID);
if ((tr.fraction == 1) && (self->monsterinfo.jumpdn < 1))
continue; // don't fall off an edge
if (distance(self->absmin, tr.endpos) < DRONE_MIN_GOAL_DIST)
continue; // too close
// is this point lower than the last?
if ((tr.endpos[2] < best[2]))
VectorCopy(tr.endpos, best);
// we may find more than one position at the same height
// so take it if it's farther from us
else if ((tr.endpos[2] == best[2]) && (distance(self->absmin,
tr.endpos) > distance(self->absmin, best)))
VectorCopy(tr.endpos, best);
}
// were we able to find anything?
if (VectorEmpty(best) || (best[2] >= self->absmin[2]))
range *= 2;
else
break;
}
if (range > 512)
{
// gi.dprintf("couldn't find a goal!!!\n");
self->goalentity = self->enemy;
M_MoveToGoal(self, dist);
return;
}
self->goalentity = SpawnGoalEntity(self, best);
VectorSubtract(self->goalentity->s.origin, self->s.origin, forward);
self->ideal_yaw = vectoyaw(forward);
M_MoveToGoal(self, dist);
}
/*
qboolean FollowWall (edict_t *self, vec3_t endpos, vec3_t wall_normal, float dist)
{
int i;
vec3_t forward, start, end, angles;
trace_t tr;
if (self->monsterinfo.aiflags & AI_PURSUIT_LAST_SEEN)
return false; // give a chance for the regular AI to work
for (i=90; i<180; i*=2)
{
vectoangles(wall_normal, angles);
angles[YAW] += i;
if (angles[YAW] > 360)
angles[YAW] -= 360;
if (angles[YAW] < 360)
angles[YAW] += 360;
forward[0] = cos(DEG2RAD(angles[YAW]));
forward[1] = sin(DEG2RAD(angles[YAW]));
forward[2] = 0;
VectorCopy(endpos, start);
VectorMA(start, 64, forward, end);
tr = gi.trace(start, NULL, NULL, end, self, MASK_SHOT);
if (tr.fraction < 1)
continue;
VectorCopy(tr.endpos, start);
VectorCopy(tr.endpos, end);
end[2] -= 64;
tr = gi.trace(start, NULL, NULL, end, self, MASK_SOLID);
if (tr.fraction == 1) // don't fall
continue;
self->goalentity = SpawnGoalEntity(self, tr.endpos);
VectorSubtract(self->goalentity->s.origin, self->s.origin, forwa
rd);
self->ideal_yaw = vectoyaw(forward);
M_MoveToGoal(self, dist);
gi.dprintf("following wall at %d degrees...\n", i);
return true;
}
gi.dprintf("*** FAILED at %d degrees ***\n", i);
return false;
}
*/
void FindCloserGoal (edict_t *self, vec3_t target_origin, float dist)
{
int i;
float yaw, best_dist=8192;
vec3_t forward, start, end, best;
trace_t tr;
// gi.dprintf("finding a closer goal\n");
VectorCopy(self->s.origin, best);
// check 8 angles at 45 degree intervals
for(i=0; i<8; i++)
{
yaw = anglemod(i*45);
forward[0] = cos(DEG2RAD(yaw));
forward[1] = sin(DEG2RAD(yaw));
forward[2] = 0;
// start scanning above step height
VectorCopy(self->absmin, start);
start[2] += STEPHEIGHT;
// trace forward
VectorMA(start, 64, forward, end);
tr = gi.trace(start, NULL, NULL, end, self, MASK_SHOT);
// trace down
VectorCopy(tr.endpos, start);
VectorCopy(tr.endpos, end);
end[2] -= 64;
tr = gi.trace(start, NULL, NULL, end, self, MASK_SOLID);
if (tr.fraction == 1) // don't fall
continue;
if (distance(self->absmin, tr.endpos) < DRONE_MIN_GOAL_DIST)
continue; // too close
// is this point closer?
if (distance(target_origin, tr.endpos) < best_dist)
{
best_dist = distance(target_origin, tr.endpos);
VectorCopy(tr.endpos, best);
}
}
if (distance(best, target_origin) >= distance(tr.endpos, target_origin))
{
self->goalentity = self->enemy;
M_MoveToGoal(self, dist);
// gi.dprintf("couldnt find a closer goal!!!\n");
return;
}
self->goalentity = SpawnGoalEntity(self, best);
VectorSubtract(self->goalentity->s.origin, self->s.origin, forward);
self->ideal_yaw = vectoyaw(forward);
M_MoveToGoal(self, dist);
}
void drone_unstuck (edict_t *self)
{
int i, yaw;
vec3_t forward, start;
trace_t tr;
// check 8 angles at 45 degree intervals
for(i=0; i<8; i++)
{
// get new vector
yaw = anglemod(i*45);
forward[0] = cos(DEG2RAD(yaw));
forward[1] = sin(DEG2RAD(yaw));
forward[2] = 0;
// trace from current position
VectorMA(self->s.origin, 64, forward, start);
tr = gi.trace(self->s.origin, self->mins, self->maxs, start, self, MASK_SHOT);
if ((tr.fraction == 1) && !(gi.pointcontents(start) & CONTENTS_SOLID))
{
VectorCopy(tr.endpos, self->s.origin);
gi.linkentity(self);
self->monsterinfo.air_frames = 0;
//gi.dprintf("freed stuck monster!\n");
return;
}
}
// gi.dprintf("couldnt fix\n");
}
void drone_pursue_goal (edict_t *self, float dist)
{
float goal_elevation;
vec3_t goal_origin, v;
vec3_t forward, start, end;
trace_t tr;
// if we are not on the ground and we can see our goal
// then turn towards it
if (!self->groundentity && !self->waterlevel && visible(self, self->goalentity))
{
//gi.dprintf("off ground %d\n", level.framenum);
VectorSubtract(self->goalentity->s.origin, self->s.origin, v);
self->ideal_yaw = vectoyaw(v);
M_ChangeYaw(self);
if (!self->waterlevel)
self->monsterinfo.air_frames++;
if (self->monsterinfo.air_frames > 20)
drone_unstuck(self);
return;
}
self->monsterinfo.air_frames = 0;
// don't bother pursuing an enemy that isn't on the ground
if (self->goalentity->groundentity || !self->goalentity->takedamage
|| (self->waterlevel != self->goalentity->waterlevel))
{
// try to find a plat first
if (FindPlat(self, goal_origin))
{
// top of plat
goal_elevation = goal_origin[2];
}
else
{
goal_elevation = self->goalentity->absmin[2]; // ent's feet
VectorCopy(self->goalentity->s.origin, goal_origin);
}
// can we see our enemy?
if (self->monsterinfo.aiflags & AI_LOST_SIGHT)
{
// is our enemy higher?
if (goal_elevation > self->absmin[2]+2*STEPHEIGHT)
FindHigherGoal(self, dist);
// is our enemy lower?
else if (goal_elevation < self->absmin[2]-2*STEPHEIGHT)
FindLowerGoal(self, dist);
else
FindCloserGoal(self, goal_origin, dist);
}
else
{
// is our enemy higher?
if (goal_elevation > self->absmin[2]+max(self->monsterinfo.jumpup, 2*STEPHEIGHT)+1)
FindHigherGoal(self, dist);
// is our enemy lower?
else if (goal_elevation < self->absmin[2]-max(self->monsterinfo.jumpdn, 2*STEPHEIGHT))
FindLowerGoal(self, dist);
// is anyone standing in our way?
else
{
VectorCopy(self->s.origin, start);
AngleVectors(self->s.angles, forward, NULL, NULL);
VectorMA(self->s.origin, self->maxs[1]+dist, forward, start);
VectorCopy(start, end);
end[2] -= 2*STEPHEIGHT;
tr = gi.trace(start, NULL, NULL, end, self, MASK_SOLID);
// did we fall off an edge?
if (tr.fraction == 1.0)
{
M_MoveToGoal(self, dist);
return;
}
tr = gi.trace(self->s.origin, NULL, NULL, goal_origin, self, MASK_SOLID);
// is anyone in our way?
//if (!tr.ent || (tr.ent != self->goalentity))
// is the path clear of obstruction?
if (tr.fraction < 1)
{
M_MoveToGoal(self, dist);
return;
}
VectorSubtract(goal_origin, self->s.origin, v);
self->ideal_yaw = vectoyaw(v);
M_MoveToGoal(self, dist);
}
}
}
else
{
if (self->monsterinfo.aiflags & AI_LOST_SIGHT)
FindCloserGoal(self, self->goalentity->s.origin, dist);
else if (self->waterlevel && self->goalentity->waterlevel)
{
VectorSubtract(self->goalentity->s.origin, self->s.origin, v);
self->ideal_yaw = vectoyaw(v);
M_MoveToGoal(self, dist);
}
else
M_MoveToGoal(self, dist);
}
}
void drone_ai_run_slide (edict_t *self, float dist)
{
float ofs, range;
vec3_t v;
VectorSubtract(self->enemy->s.origin, self->s.origin, v);
self->ideal_yaw = vectoyaw(v);
M_ChangeYaw (self);
//4.4 try to maintain ideal range/distance to target
range = VectorLength(v) - 196;
if (fabs(range) >= dist)
{
if (range > dist)
range = dist;
else if (range < -dist)
range = -dist;
M_walkmove (self, self->ideal_yaw, range);
//gi.dprintf("moved %.0f units\n", range);
}
if (self->monsterinfo.lefty)
ofs = 90;
else
ofs = -90;
if (M_walkmove (self, self->ideal_yaw + ofs, dist))
return;
// change direction and try strafing in the opposite direction
self->monsterinfo.lefty = 1 - self->monsterinfo.lefty;
M_walkmove (self, self->ideal_yaw - ofs, dist);
}
void TeleportForward (edict_t *ent, vec3_t vec, float dist);
void drone_cleargoal (edict_t *self)
{
self->enemy = NULL;
self->oldenemy = NULL;
self->goalentity = NULL;
// clear ai flags
self->monsterinfo.aiflags &= ~AI_COMBAT_POINT;
if (!self->monsterinfo.melee)
self->monsterinfo.aiflags &= ~AI_NO_CIRCLE_STRAFE;
self->monsterinfo.search_frames = 0;
self->monsterinfo.stand(self);
}
edict_t *drone_findnavi (edict_t *self)
{
edict_t *e=NULL;
while ((e = findclosestradius1 (e, self->s.origin,
self->monsterinfo.sight_range)) != NULL)
{
if (!drone_validnavi(self, e, true))
continue;
return e;
}
return NULL;
}
/*
=============
drone_ai_run
Called when the monster is chasing an enemy or goal
=============
*/
void drone_ai_run (edict_t *self, float dist)
{
float time;
vec3_t start, end, v;
trace_t tr;
edict_t *tempgoal=NULL;
qboolean enemy_vis=false;
// if we're dead, we shouldn't be here
if (self->deadflag == DEAD_DEAD)
return;
// decoys make step sounds
if ((self->mtype == M_DECOY) && (level.time > self->wait))
{
gi.sound (self, CHAN_BODY, gi.soundindex(va("player/step%i.wav", (randomMT()%4)+1)), 1, ATTN_NORM, 0);
self->wait = level.time + 0.3;
}
// monster is no longer idle
self->monsterinfo.idle_frames = 0;
// if the drone is standing, we shouldn't be here
if (self->monsterinfo.aiflags & AI_STAND_GROUND)
{
self->monsterinfo.stand(self);
return;
}
if (drone_ValidChaseTarget(self, self->enemy))
{
if ((self->monsterinfo.aiflags & AI_COMBAT_POINT) && !self->enemy->takedamage)
{
if (!drone_findtarget(self) && (entdist(self, self->enemy) <= 64))
{
// the goal is a navi
if (self->enemy->mtype == INVASION_NAVI)
{
edict_t *e;
// we're close enough to this navi; follow the next one in the chain
if (self->enemy->target && self->enemy->targetname &&
((e = G_Find(NULL, FOFS(targetname), self->enemy->target)) != NULL))
{
//gi.dprintf("following next navi in chain\n");
self->enemy = e;
}
else
{
//FIXME: this never happens because monsters usually see the player/bases and begin attacking before they reach the last navi
// we've reached our final destination
drone_cleargoal(self);
self->monsterinfo.aiflags &= ~AI_FIND_NAVI;
//gi.dprintf("reached final destination\n");
return;
}
}
else
{
// the goal is a combat point
//gi.dprintf("cleared combat point\n");
drone_cleargoal(self);
return;
}
}
}
drone_ai_checkattack(self); // try attacking
// constantly update the last place we remember
// seeing our enemy
if (visible(self, self->enemy))
{
VectorCopy(self->enemy->s.origin, self->monsterinfo.last_sighting);
self->monsterinfo.aiflags &= ~(AI_LOST_SIGHT|AI_PURSUIT_LAST_SEEN);
self->monsterinfo.teleport_delay = level.time + DRONE_TELEPORT_DELAY; // teleport delay
self->monsterinfo.search_frames = 0;
enemy_vis = true;
// circle-strafe our target if we are close
if ((entdist(self, self->enemy) < 256)
&& !(self->monsterinfo.aiflags & AI_NO_CIRCLE_STRAFE))
{
drone_ai_run_slide(self, dist);
return;
}
}
else
{
// drone should try to find a navi if enemy isn't visible
if ((self->monsterinfo.aiflags & AI_FIND_NAVI) && self->enemy->takedamage)
{
//gi.dprintf("can't see %s, trying another target...", self->enemy->classname);
// save current target
self->oldenemy = self->enemy;
self->enemy = NULL; // must be cleared to find navi
// try to find a new target
if (drone_findtarget(self))
{
//gi.dprintf("found %s!\n", self->enemy->classname);
drone_ai_checkattack(self);
}
else
{
// restore current target
self->enemy = self->oldenemy;
self->oldenemy = NULL;
//gi.dprintf("no target.\n");
}
}
// drones give up if they can't reach their enemy
if (!self->enemy || (self->monsterinfo.search_frames > DRONE_SEARCH_TIMEOUT))
{
//gi.dprintf("drone gave up\n");
self->enemy = NULL;
self->oldenemy = NULL;
self->goalentity = NULL;
//self->monsterinfo.aiflags &= ~AI_COMBAT_POINT;
if (!self->monsterinfo.melee)
self->monsterinfo.aiflags &= ~AI_NO_CIRCLE_STRAFE;
self->monsterinfo.stand(self);
self->monsterinfo.search_frames = 0;
return;
}
self->monsterinfo.search_frames++;
//gi.dprintf("%d\n", self->monsterinfo.search_frames);
}
if (dist < 1)
{
VectorSubtract(self->enemy->s.origin, self->s.origin, v);
self->ideal_yaw = vectoyaw(v);
M_ChangeYaw(self);
return;
}
// if we are on a platform going up, wait around until we've reached the top
if (self->groundentity && (self->monsterinfo.aiflags & AI_PURSUE_PLAT_GOAL)
&& (self->groundentity->style == FUNC_PLAT)
&& (self->groundentity->moveinfo.state == STATE_UP))
{
// gi.dprintf("standing on plat!\n");
// divide by speed to get time to reach destination
time = 0.1 * (abs(self->groundentity->s.origin[2]) / self->groundentity->moveinfo.speed);
self->monsterinfo.pausetime = level.time + time;
self->monsterinfo.stand(self);
self->monsterinfo.aiflags &= ~AI_PURSUE_PLAT_GOAL;
return;
}
// if we're stuck, then follow new course
if (self->monsterinfo.bump_delay > level.time)
{
M_ChangeYaw(self);
M_MoveToGoal(self, dist);
return;
}
// we're following a temporary goal
if (self->movetarget && self->movetarget->inuse)
{
/*
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_BFG_LASER);
gi.WritePosition (self->s.origin);
gi.WritePosition (self->movetarget->s.origin);
gi.multicast (self->s.origin, MULTICAST_PHS);
*/
// pursue the movetarget
M_MoveToGoal(self, dist);
// occasionally, a monster will bump to a better course
// than the one he was previously following
if ((self->enemy->absmin[2] > self->absmin[2]+2*STEPHEIGHT) &&
(self->movetarget->s.origin[2] < self->absmin[2]))
{
// we are higher than our current goal
G_FreeEdict(self->movetarget);
self->movetarget = NULL;
}
else if ((self->enemy->absmin[2] < self->absmin[2]-2*STEPHEIGHT) &&
(self->movetarget->s.origin[2] > self->absmin[2]))
{
// we are lower than our current goal
G_FreeEdict(self->movetarget);
self->movetarget = NULL;
}
else if (entdist(self, self->movetarget) <= DRONE_MIN_GOAL_DIST)
{
// we are close 'nuff to our goal
G_FreeEdict(self->movetarget);
self->movetarget = NULL;
}
}
else
{
/*
// we're following a goal
if (self->goalentity && self->goalentity->inuse)
{
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_BFG_LASER);
gi.WritePosition (self->s.origin);
gi.WritePosition (self->goalentity->s.origin);
gi.multicast (self->s.origin, MULTICAST_PHS);
drone_pursue_goal(self, dist);
return;
}
else
*/
// we don't already have a goal, make the enemy our goal
self->goalentity = self->enemy;
// pursue enemy if he's visible, otherwise pursue the last place
// he was seen if we haven't already been there
if (!enemy_vis)
{
/*
if (level.time > self->monsterinfo.teleport_delay)
{
VectorSubtract(self->enemy->s.origin, self->s.origin, v);
VectorNormalize(v);
TeleportForward(self, v, 512);
self->monsterinfo.teleport_delay = level.time + DRONE_TELEPORT_DELAY;
}
*/
if (!(self->monsterinfo.aiflags & AI_LOST_SIGHT))
self->monsterinfo.aiflags |= (AI_LOST_SIGHT|AI_PURSUIT_LAST_SEEN);
if (self->monsterinfo.aiflags & AI_PURSUIT_LAST_SEEN)
{
VectorCopy(self->monsterinfo.last_sighting, start);
VectorCopy(start, end);
end[2] -= 64;
tr = gi.trace(start, NULL, NULL, end, self, MASK_SOLID);
// we are done chasing player last sighting if we're close to it
// or it's hanging in mid-air
if ((tr.fraction == 1) || (distance(self->monsterinfo.last_sighting, self->s.origin) < DRONE_MIN_GOAL_DIST))
{
self->monsterinfo.aiflags &= ~AI_PURSUIT_LAST_SEEN;
}
else
{
tempgoal = G_Spawn();
VectorCopy(self->monsterinfo.last_sighting, tempgoal->s.origin);
VectorCopy(self->monsterinfo.last_sighting, tempgoal->absmin);
self->goalentity = tempgoal;
}
}
}
// go get him!
drone_pursue_goal(self, dist);
if (tempgoal)
G_FreeEdict(tempgoal);
}
}
else
{
// gi.dprintf("stand was called because monster has no valid target!\n");
self->monsterinfo.stand(self);
}
}
void drone_togglelight (edict_t *self)
{
if (self->health > 0)
{
if (level.daytime && self->flashlight)
{
// turn light off
G_FreeEdict(self->flashlight);
self->flashlight = NULL;
return;;
}
else if (!level.daytime && !self->flashlight)
{
FL_make(self);
}
}
else
{
// turn off the flashlight if we're dead!
if (self->flashlight)
{
G_FreeEdict(self->flashlight);
self->flashlight = NULL;
return;
}
}
}
void drone_dodgeprojectiles (edict_t *self)
{
// dodge incoming projectiles
if (self->health > 0 && self->monsterinfo.dodge && (self->monsterinfo.aiflags & AI_DODGE)
&& !(self->monsterinfo.aiflags & AI_STAND_GROUND)) // don't dodge if we are holding position
{
if (((self->monsterinfo.radius > 0) && ((level.time + 0.3) > self->monsterinfo.eta))
|| (level.time + FRAMETIME) > self->monsterinfo.eta)
{
self->monsterinfo.dodge(self, self->monsterinfo.attacker, self->monsterinfo.dir, self->monsterinfo.radius);
self->monsterinfo.aiflags &= ~AI_DODGE;
}
}
}
/*
=============
drone_validposition
Returns false if the monster gets stuck in a solid object
and cannot be re-spawned
=============
*/
qboolean drone_validposition (edict_t *self)
{
//trace_t tr;
qboolean respawned = false;
if (gi.pointcontents(self->s.origin) & CONTENTS_SOLID)
{
if (self->activator && self->activator->inuse && !self->activator->client)
respawned = FindValidSpawnPoint(self, false);
if (!respawned)
{
WriteServerMsg("A drone was removed from a solid object.", "Info", true, false);
M_Remove(self, true, false);
return false;
}
}
return true;
}
qboolean drone_boss_stuff (edict_t *self)
{
if (self->deadflag == DEAD_DEAD)
return true; // we're dead
//4.05 boss always regenerates
if (self->monsterinfo.control_cost > 2)
{
if (self->enemy)
M_Regenerate(self, 900, 10, true, true, false, &self->monsterinfo.regen_delay1);
else // idle
M_Regenerate(self, 600, 10, true, true, false, &self->monsterinfo.regen_delay1);
}
// bosses teleport away from danger when they are weakened
if (self->activator && !self->activator->client && (self->monsterinfo.control_cost >= 3)
&& (level.time > self->sentrydelay) && (self->health < (0.3*self->max_health))
&& self->enemy && visible(self, self->enemy))
{
gi.bprintf(PRINT_HIGH, "Boss teleported away.\n");
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_BOSSTPORT);
gi.WritePosition (self->s.origin);
gi.multicast (self->s.origin, MULTICAST_PVS);
if(!FindValidSpawnPoint(self, false))
{
// boss failed to re-spawn
/*
if (self->activator)
self->activator->num_sentries--;
G_FreeEdict(self);
*/
M_Remove(self, false, false);
gi.dprintf("WARNING: Boss failed to re-spawn!\n");
return false;
}
self->enemy = NULL; // find a new target
self->oldenemy = NULL;
self->monsterinfo.stand(self);
self->sentrydelay = level.time + GetRandom(10, 30);
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_BOSSTPORT);
gi.WritePosition (self->s.origin);
gi.multicast (self->s.origin, MULTICAST_PVS);
}
return true;
}
void decoy_copy (edict_t *self);
void drone_think (edict_t *self)
{
//gi.dprintf("drone_think()\n");
if (!drone_validposition(self))
return;
if (!drone_boss_stuff(self))
return;
// decoy_copy(self);
CTF_SummonableCheck(self);
// monster will auto-remove if it is asked to
if (self->removetime > 0)
{
qboolean converted=false;
if (self->flags & FL_CONVERTED)
converted = true;
if (level.time > self->removetime)
{
// if we were converted, try to convert back to previous owner
if (!RestorePreviousOwner(self))
{
M_Remove(self, false, true);
return;
}
}
// warn the converted monster's current owner
else if (converted && self->activator && self->activator->inuse && self->activator->client
&& (level.time > self->removetime-5) && !(level.framenum%10))
safe_cprintf(self->activator, PRINT_HIGH, "%s conversion will expire in %.0f seconds\n",
V_GetMonsterName(self->mtype), self->removetime-level.time);
}
// if owner can't pay upkeep, monster dies
if (!M_Upkeep(self, 10, self->monsterinfo.control_cost))
return;
V_HealthCache(self, (int)(0.2 * self->max_health), 1);
V_ArmorCache(self, (int)(0.2 * self->monsterinfo.max_armor), 1);
//Talent: Life Tap
if (self->activator && self->activator->inuse && self->activator->client && !(level.framenum % 10))
{
if (getTalentLevel(self->activator, TALENT_LIFE_TAP) > 0)
{
int damage = 0.01 * self->max_health;
if (damage < 1)
damage = 1;
T_Damage(self, world, world, vec3_origin, self->s.origin, vec3_origin, damage, 0, DAMAGE_NO_ABILITIES, 0);
}
}
if (self->linkcount != self->monsterinfo.linkcount)
{
self->monsterinfo.linkcount = self->linkcount;
M_CheckGround (self);
}
if (self->groundentity)
VectorClear(self->velocity); // don't slide
drone_togglelight(self);
drone_dodgeprojectiles(self);
// this must come before M_MoveFrame() because a monster's dead
// function may set the nextthink to 0
self->nextthink = level.time + FRAMETIME;
M_MoveFrame (self);
M_CatagorizePosition (self);
M_WorldEffects (self);
M_SetEffects (self);
}
<file_sep>#include "g_local.h"
#define STATION_TARGET_RADIUS 256
#define STATION_COST 50
#define STATION_DELAY 2
#define STATION_BUILD_TIME 2
qboolean ValidStationTarget (edict_t *self, edict_t *targ) {
return (G_EntExists(targ) && (targ->health>0)
&& targ->client && visible(self, targ));
}
qboolean station_findtarget (edict_t *self)
{
edict_t *e=NULL;
while ((e = findclosestradius(e, self->s.origin, STATION_TARGET_RADIUS)) != NULL)
{
if (!ValidStationTarget(self, e))
continue;
if (!OnSameTeam(self, e))
{
gi.centerprintf(self->creator, "%s is using\nyour supply station!\n",
e->client->pers.netname);
continue;
}
self->enemy = e;
return true;
}
self->enemy = NULL;
return false;
}
qboolean NeedHealth (edict_t *player) {
return (player->health < player->max_health);
}
qboolean NeedArmor (edict_t *player) {
return (player->client->pers.inventory[body_armor_index] < MAX_ARMOR(player));
}
float HealthLevel (edict_t *ent) {
return ((float)ent->health/ent->max_health);
}
float ArmorLevel (edict_t *ent) {
return ((float)ent->client->pers.inventory[body_armor_index]/MAX_ARMOR(ent));
}
edict_t *DropRandomAmmo (edict_t *self)
{
gitem_t *item;
switch (GetRandom(1, 6))
{
case 1: item = FindItemByClassname("ammo_shells"); break;
case 2: item = FindItemByClassname("ammo_bullets"); break;
case 3: item = FindItemByClassname("ammo_grenades"); break;
case 4: item = FindItemByClassname("ammo_rockets"); break;
case 5: item = FindItemByClassname("ammo_cells"); break;
case 6: item = FindItemByClassname("ammo_slugs"); break;
}
return Drop_Item(self, item);
}
#define HEALTHBOX_SMALL 1
#define HEALTHBOX_LARGE 2
void healthbox_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
{
float temp = 1.0;
if (G_EntExists(other) && other->client && (other->health > 0)
&& (NeedHealth(other) || (self->style == HEALTHBOX_SMALL)))
{
// special rules disable flag carrier abilities
if(!(ctf->value && ctf_enable_balanced_fc->value && HasFlag(other)))
{
if(!other->myskills.abilities[HA_PICKUP].disable)
temp += 0.3*other->myskills.abilities[HA_PICKUP].current_level;
//Talent: Basic HA Pickup
//if(getTalentSlot(other, TALENT_BASIC_HA) != -1)
// temp += 0.2 * getTalentLevel(other, TALENT_BASIC_HA);
}
other->health += self->count*temp;
// check for maximum health cap
if ((other->health > other->max_health) && (self->style != HEALTHBOX_SMALL))
other->health = other->max_health;
// play appropriate sound
if (self->style == HEALTHBOX_LARGE)
gi.sound(self, CHAN_ITEM, gi.soundindex("items/l_health.wav"), 1, ATTN_NORM, 0);
else if (self->style == HEALTHBOX_SMALL)
gi.sound(self, CHAN_ITEM, gi.soundindex("items/s_health.wav"), 1, ATTN_NORM, 0);
// remove the ent
G_FreeEdict(self);
}
}
void healthbox_think (edict_t *self)
{
if (level.time > self->delay)
{
G_FreeEdict(self);
return;
}
self->nextthink = level.time + FRAMETIME;
}
edict_t *SpawnHealthBox (edict_t *ent, int type)
{
vec3_t forward;
edict_t *health;
health = G_Spawn();
if (type == HEALTHBOX_LARGE)
{
health->model = "models/items/healing/large/tris.md2";
health->s.modelindex = gi.modelindex("models/items/healing/large/tris.md2");
health->count = 25;
health->style = HEALTHBOX_LARGE;
}
else if (type == HEALTHBOX_SMALL)
{
health->model = "models/items/healing/stimpack/tris.md2";
health->s.modelindex = gi.modelindex("models/items/healing/stimpack/tris.md2");
health->count = 2;
health->style = HEALTHBOX_SMALL;
}
else
{
gi.dprintf("WARNING: SpawnHealthBox() called without a valid type.\n");
return NULL;
}
health->touch = healthbox_touch;
health->think = healthbox_think;
health->nextthink = level.time + FRAMETIME;
health->delay = level.time + 30;
health->s.renderfx = (RF_GLOW|RF_IR_VISIBLE);
health->solid = SOLID_TRIGGER;
health->movetype = MOVETYPE_TOSS;
VectorSet(health->mins, -15, -15, -15);
VectorSet(health->maxs, 15, 15, 15);
// toss the item
VectorCopy(ent->s.angles, forward);
forward[YAW] = GetRandom(0, 360);
health->s.angles[YAW] = GetRandom(0, 360);
AngleVectors(forward, forward, NULL, NULL);
VectorCopy (ent->s.origin, health->s.origin);
gi.linkentity(health);
VectorScale (forward, GetRandom(50, 150), health->velocity);
health->velocity[2] = 300;
return health;
}
int MaxAmmoType (edict_t *ent, int ammo_index)
{
if (!ammo_index)
return 0;
else if (ammo_index == ITEM_INDEX(FindItemByClassname("ammo_shells")))
return ent->client->pers.max_shells;
else if (ammo_index == ITEM_INDEX(FindItemByClassname("ammo_bullets")))
return ent->client->pers.max_bullets;
else if (ammo_index ==ITEM_INDEX(FindItemByClassname("ammo_grenades")))
return ent->client->pers.max_grenades;
else if (ammo_index == ITEM_INDEX(FindItemByClassname("ammo_rockets")))
return ent->client->pers.max_rockets;
else if (ammo_index == ITEM_INDEX(FindItemByClassname("ammo_cells")))
return ent->client->pers.max_cells;
else if (ammo_index == ITEM_INDEX(FindItemByClassname("ammo_slugs")))
return ent->client->pers.max_slugs;
else return 0;
}
int G_GetRespawnWeaponIndex (edict_t *ent)
{
switch (ent->myskills.respawn_weapon)
{
case 2: return ITEM_INDEX(Fdi_SHOTGUN);
case 3: return ITEM_INDEX(Fdi_SUPERSHOTGUN);
case 4: return ITEM_INDEX(Fdi_MACHINEGUN);
case 5: return ITEM_INDEX(Fdi_CHAINGUN);
case 6: return ITEM_INDEX(Fdi_GRENADELAUNCHER);
case 7: return ITEM_INDEX(Fdi_ROCKETLAUNCHER);
case 8: return ITEM_INDEX(Fdi_HYPERBLASTER);
case 9: return ITEM_INDEX(Fdi_RAILGUN);
case 10: return ITEM_INDEX(Fdi_BFG);
case 11: return grenade_index;
case 12: return ITEM_INDEX(Fdi_20MM);
default: return 0;
}
}
int G_GetAmmoIndexByWeaponIndex (int weapon_index)
{
//gi.dprintf("weapon_index=%d\n", weapon_index);
if (!weapon_index)
return 0;
else if (weapon_index == ITEM_INDEX(Fdi_SHOTGUN))
return shell_index;
else if (weapon_index == ITEM_INDEX(Fdi_SUPERSHOTGUN))
return shell_index;
else if (weapon_index == ITEM_INDEX(Fdi_MACHINEGUN))
return bullet_index;
else if (weapon_index == ITEM_INDEX(Fdi_CHAINGUN))
return bullet_index;
else if (weapon_index == ITEM_INDEX(Fdi_GRENADELAUNCHER))
return grenade_index;
else if (weapon_index == ITEM_INDEX(Fdi_ROCKETLAUNCHER))
return rocket_index;
else if (weapon_index == ITEM_INDEX(Fdi_HYPERBLASTER))
return cell_index;
else if (weapon_index == ITEM_INDEX(Fdi_RAILGUN))
return slug_index;
else if (weapon_index == ITEM_INDEX(Fdi_BFG))
return cell_index;
else if (weapon_index == ITEM_INDEX(Fdi_20MM))
return shell_index;
else if (weapon_index == grenade_index)
return grenade_index;
return 0;
}
float AmmoLevel (edict_t *ent, int ammo_index)
{
int max;
// unknown weapon, return full ammo status
if (!ammo_index)
return 1.0;
// check for max ammo of current weapon
max = MaxAmmoType(ent, ammo_index);
// can't determine max ammo, so return full ammo status
if (!max)
return 1.0;
// return ratio of current ammo to max
return ((float)ent->client->pers.inventory[ammo_index]/max);
}
qboolean PlayerHasSentry (edict_t *ent)
{
edict_t *e=NULL;
while((e = G_Find(e, FOFS(classname), "Sentry_Gun")) != NULL)
{
if (e && e->inuse && e->creator && (e->creator == ent))
return true;
}
return false;
}
void station_dropitem (edict_t *self)
{
int index;
float health, armor, ammo;
gitem_t *item=NULL;
edict_t *item_ent;
// if there's nobody around, drop a random item
if (!self->enemy)
{
// don't cause an entity overflow
if (numNearbyEntities(self, 128, true) > 5)
return;
switch (GetRandom(1,3))
{
case 1: item_ent = SpawnHealthBox(self, HEALTHBOX_LARGE); break;
case 2: item = FindItemByClassname("item_armor_combat"); break;
case 3: item_ent = DropRandomAmmo(self); break;
}
if (item) item_ent = Drop_Item(self, item);
}
else
{
health = HealthLevel(self->enemy);
armor = ArmorLevel(self->enemy);
// get ammo level for respawn weapon
index = G_GetAmmoIndexByWeaponIndex(G_GetRespawnWeaponIndex(self->enemy));
ammo = AmmoLevel(self->enemy, index);
// if we have some ammo for respawn weapon, then get ammo level for equipped weapon
if (ammo >= 0.25)
{
index = self->enemy->client->ammo_index;
ammo = AmmoLevel(self->enemy, index);
}
// if we have full ammo AND we have a sentry built, make sure we
// have some rockets or bullets to feed the sentry
if ((ammo == 1.0) && PlayerHasSentry(self->enemy))
{
int bullet_ammo = self->enemy->client->pers.inventory[bullet_index];
int rocket_ammo = self->enemy->client->pers.inventory[rocket_index];
if (!bullet_ammo || !rocket_ammo)
{
if (!bullet_ammo)
index = bullet_index;
else if (!rocket_ammo)
index = rocket_index;
ammo = 0; // indicate that we need ammo dropped
}
}
// drop health
if ((health < 1) && (health <= armor) && (health <= ammo))
item_ent = SpawnHealthBox(self, HEALTHBOX_LARGE);
// drop armor
else if ((armor < 1) && (armor <= health) && (armor <= ammo))
item = FindItemByClassname("item_armor_combat");
// drop ammo
else if (index && (ammo < 1))
item = GetItemByIndex(index);
else
{
// drop armor shards or stimpaks
if (random() > 0.5)
item = FindItemByClassname("item_armor_shard");
else
item_ent = SpawnHealthBox(self, HEALTHBOX_SMALL);
}
// drop selected item
if (item)
item_ent = Drop_Item(self, item);
}
}
void depot_giveitems (edict_t *self)
{
}
void station_seteffects (edict_t *self)
{
vec3_t start, forward;
self->s.effects = EF_ROTATE;
if (!self->s.sound)
self->s.sound = gi.soundindex("world/amb15.wav");
if (level.time > self->delay)
{
self->s.angles[YAW] = GetRandom(0, 360);
AngleVectors(self->s.angles, forward, NULL, NULL);
VectorCopy(self->s.origin, start);
start[2] = self->absmax[2] + GetRandom(8, 32);
VectorMA(start, GetRandom(0, 32), forward, start);
gi.WriteByte (svc_temp_entity);
gi.WriteByte (TE_SPARKS);
gi.WritePosition (start);
gi.WriteDir (vec3_origin);
gi.multicast (start, MULTICAST_PVS);
self->delay = level.time + 0.1*GetRandom(1, 5);
}
}
void supplystation_think (edict_t *self)
{
float time, temp;
if (level.time > self->wait)
{
station_findtarget(self);
station_dropitem(self);
temp = 1 + 0.9*self->monsterinfo.level;
time = 50 / temp;
self->wait = level.time + time; // time until we drop another item
}
station_seteffects(self);
self->nextthink = level.time + FRAMETIME;
}
void depot_think (edict_t *self)
{
/*
float time, temp;
if (level.time > self->wait)
{
depot_findtarget(self);
depot_giveitems(self);
temp = 1 + 0.9*self->creator->myskills.abilities[MOBILE_DEPOT].current_level;
time = 50 / temp;
self->wait = level.time + time; // time until we drop another item
}
depot_seteffects(self);
*/
self->nextthink = level.time + FRAMETIME;
}
void supplystation_explode (edict_t *self, char *message)
{
if (self->creator && self->creator->inuse)
{
gi.cprintf(self->creator, PRINT_HIGH, message);
self->creator->supplystation = NULL;
T_RadiusDamage(self, self->creator, 150, self, 150, MOD_SUPPLYSTATION);
}
BecomeExplosion1(self);
}
void supplystation_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
{
char *s;
if (attacker->client)
s = va("Your supply station was destroyed by %s.\n", attacker->client->pers.netname);
else
s = "Your supply station was destroyed.\n";
supplystation_explode(self, s);
}
void supplystation_pain (edict_t *self, edict_t *other, float kick, int damage)
{
if (G_EntExists(other) && !OnSameTeam(self, other) && (level.time > self->random))
{
if (other->client)
gi.centerprintf(self->creator, "%s is attacking\nyour station!\n", other->client->pers.netname);
else
gi.centerprintf(self->creator, "Your station is under\nattack!", other->client->pers.netname);
self->random = level.time + 5;
}
}
void BuildSupplyStation (edict_t *ent, int cost, float skill_mult, float delay_mult)
{
vec3_t angles, forward, end;
edict_t *station;
trace_t tr;
int talentLevel;
station = G_Spawn();
station->creator = ent;
station->think = supplystation_think;
station->nextthink = level.time + STATION_BUILD_TIME * delay_mult;
station->s.modelindex = gi.modelindex ("models/objects/dmspot/tris.md2");
station->s.effects |= EF_PLASMA;
station->s.renderfx |= RF_IR_VISIBLE;
station->solid = SOLID_BBOX;
station->movetype = MOVETYPE_TOSS;
station->clipmask = MASK_MONSTERSOLID;
station->mass = 500;
station->mtype = SUPPLY_STATION;
station->classname = "supplystation";
station->takedamage = DAMAGE_YES;
station->health = 1000;
station->monsterinfo.level = ent->myskills.abilities[SUPPLY_STATION].current_level * skill_mult;
station->touch = V_Touch;
station->die = supplystation_die;
VectorSet(station->mins, -32, -32, -24);
VectorSet(station->maxs, 32, 32, -16);
station->s.skinnum = 1;
// starting position for station
AngleVectors (ent->client->v_angle, forward, NULL, NULL);
VectorMA(ent->s.origin, 128, forward, end);
tr = gi.trace(ent->s.origin, NULL, NULL, end, ent, MASK_SOLID);
VectorCopy(tr.endpos, end);
vectoangles(tr.plane.normal, angles);
ValidateAngles(angles);
// player is aiming at the ground
if ((tr.fraction != 1.0) && (tr.endpos[2] < ent->s.origin[2]) && (angles[PITCH] == 270))
end[2] += abs(station->mins[2])+1;
// make sure station doesn't spawn in a solid
tr = gi.trace(end, station->mins, station->maxs, end, NULL, MASK_SHOT);
if (tr.contents & MASK_SHOT)
{
gi.cprintf (ent, PRINT_HIGH, "Can't build supply station there.\n");
G_FreeEdict(station);
return;
}
VectorCopy(tr.endpos, station->s.origin);
gi.linkentity(station);
ent->supplystation = station;
ent->client->ability_delay = level.time + STATION_DELAY * delay_mult;
ent->client->pers.inventory[power_cube_index] -= cost;
ent->holdtime = level.time + STATION_BUILD_TIME * delay_mult;
gi.sound(station, CHAN_ITEM, gi.soundindex("weapons/repair.wav"), 1, ATTN_NORM, 0);
station->firewall_weak = false;
station->firewall_medium = false;
station->firewall_strong = false;
talentLevel = getTalentLevel(ent, TALENT_PRECISION_TUNING);
if (talentLevel == 1)
station->firewall_weak = true;
if (talentLevel == 2)
station->firewall_medium = true;
if (talentLevel == 3)
station->firewall_strong = true;
}
void supplystation_remove (edict_t *self)
{
if ((self->health > 1) && (level.time > self->delay))
{
if (self->creator && self->creator->inuse)
{
gi.cprintf(self->creator, PRINT_HIGH, "Supply station successfully removed.\n");
self->creator->client->pers.inventory[power_cube_index] += STATION_COST;
}
G_FreeEdict(self);
}
self->nextthink = level.time + FRAMETIME;
}
void Cmd_CreateSupplyStation_f (edict_t *ent)
{
int talentLevel, cost=STATION_COST;
float skill_mult=1.0, cost_mult=1.0, delay_mult=1.0;//Talent: Rapid Assembly & Precision Tuning
if (debuginfo->value)
gi.dprintf("%s just called Cmd_CreateSupplyStation_f\n", ent->client->pers.netname);
if (ent->supplystation && (level.time > ent->holdtime)
&& !Q_strcasecmp(gi.args(), "remove"))
{
gi.cprintf(ent, PRINT_HIGH, "Removing supply station...\n");
ent->holdtime = level.time + STATION_BUILD_TIME;
ent->client->ability_delay = level.time + STATION_DELAY;
ent->supplystation->think = supplystation_remove;
ent->supplystation->nextthink = level.time + FRAMETIME;
ent->supplystation->s.effects = EF_PLASMA;
ent->supplystation->s.sound = 0;
return;
}
if (ent->supplystation)
{
if (ent->holdtime > level.time) // the station isn't done building
return;
supplystation_explode(ent->supplystation, "Your supply station blew itself up.\n");
return;
}
if(ent->myskills.abilities[SUPPLY_STATION].disable)
return;
//Talent: Rapid Assembly
talentLevel = getTalentLevel(ent, TALENT_RAPID_ASSEMBLY);
if (talentLevel > 0)
delay_mult -= 0.167 * talentLevel;
cost *= cost_mult;
if (!G_CanUseAbilities(ent, ent->myskills.abilities[SUPPLY_STATION].current_level, cost))
return;
BuildSupplyStation(ent, cost, skill_mult, delay_mult);
}
<file_sep>#include "g_local.h"
game_locals_t game;
level_locals_t level;
game_import_t gi;
game_export_t globals;
spawn_temp_t st;
int sm_meat_index;
int snd_fry;
int meansOfDeath;
edict_t *g_edicts;
cvar_t *deathmatch;
cvar_t *coop;
cvar_t *dmflags;
cvar_t *skill;
cvar_t *fraglimit;
cvar_t *timelimit;
cvar_t *filterban;
//ZOID
cvar_t *capturelimit;
//ZOID
cvar_t *password;
cvar_t *spectator_password;
cvar_t *maxclients;
cvar_t *maxspectators;
cvar_t *maxentities;
cvar_t *g_select_empty;
cvar_t *dedicated;
cvar_t *sv_maxvelocity;
cvar_t *sv_gravity;
cvar_t *sv_rollspeed;
cvar_t *sv_rollangle;
cvar_t *gun_x;
cvar_t *gun_y;
cvar_t *gun_z;
cvar_t *run_pitch;
cvar_t *run_roll;
cvar_t *bob_up;
cvar_t *bob_pitch;
cvar_t *bob_roll;
cvar_t *sv_cheats;
//ponpoko
cvar_t *gamepath;
cvar_t *vwep;
cvar_t *sv_maplist;
cvar_t *autospawn;
float spawncycle;
//ponpoko
//JABot [start]
cvar_t *bot_showpath;
cvar_t *bot_showcombat;
cvar_t *bot_showsrgoal;
cvar_t *bot_showlrgoal;
cvar_t *bot_debugmonster;
//[end]
//K03 Begin
cvar_t *save_path;
cvar_t *particles;
cvar_t *sentry_lev1_model;
cvar_t *sentry_lev2_model;
cvar_t *sentry_lev3_model;
cvar_t *nextlevel_mult;
cvar_t *vrx_creditmult;
cvar_t *start_level;
cvar_t *start_nextlevel;
cvar_t *vrx_pointmult;
cvar_t *flood_msgs;
cvar_t *flood_persecond;
cvar_t *flood_waitdelay;
qboolean MonstersInUse;
int total_monsters;
edict_t *SPREE_DUDE;
edict_t *red_base; // 3.7 CTF
edict_t *blue_base; // 3.7 CTF
int red_flag_caps;
int blue_flag_caps;
int DEFENSE_TEAM;
int PREV_DEFENSE_TEAM;
long FLAG_FRAMES;
float SPREE_TIME;
int average_player_level;
qboolean SPREE_WAR;
qboolean INVASION_OTHERSPAWNS_REMOVED;
int invasion_difficulty_level;
qboolean found_flag;
//vec3_t nodes[MAX_NODES];
int total_nodes;
cvar_t *gamedir;
cvar_t *dm_monsters;
cvar_t *pvm_respawntime;
cvar_t *pvm_monstermult;
cvar_t *ffa_respawntime;
cvar_t *ffa_monstermult;
cvar_t *server_email;
cvar_t *reconnect_ip;
cvar_t *vrx_password;
cvar_t *min_level;
cvar_t *max_level;
cvar_t *check_dupeip;
cvar_t *check_dupename;
cvar_t *newbie_protection;
cvar_t *pvm;
cvar_t *ptr;
cvar_t *ffa;
cvar_t *domination;
cvar_t *ctf;
cvar_t *invasion;
cvar_t *nolag;
cvar_t *debuginfo;
cvar_t *adminpass;
cvar_t *team1_skin;
cvar_t *team2_skin;
cvar_t *voting;
cvar_t *gds;
cvar_t *gds_path;
cvar_t *gds_exe;
cvar_t *game_path;
cvar_t *allies;
cvar_t *pregame_time;
// class skins
cvar_t *enforce_class_skins;
cvar_t *class1_skin;
cvar_t *class2_skin;
cvar_t *class3_skin;
cvar_t *class4_skin;
cvar_t *class5_skin;
cvar_t *class6_skin;
cvar_t *class7_skin;
cvar_t *class8_skin;
cvar_t *class9_skin;
cvar_t *class10_skin;
cvar_t *class11_skin;
// world spawn ammo
cvar_t *world_min_bullets;
cvar_t *world_min_cells;
cvar_t *world_min_shells;
cvar_t *world_min_grenades;
cvar_t *world_min_rockets;
cvar_t *world_min_slugs;
cvar_t *ctf_enable_balanced_fc;
//K03 End
void SpawnEntities (char *mapname, char *entities, char *spawnpoint);
void ClientThink (edict_t *ent, usercmd_t *cmd);
qboolean ClientConnect (edict_t *ent, char *userinfo);
void ClientUserinfoChanged (edict_t *ent, char *userinfo);
void ClientDisconnect (edict_t *ent);
void ClientBegin (edict_t *ent, qboolean loadgame);
void ClientCommand (edict_t *ent);
void RunEntity (edict_t *ent);
void WriteGame (char *filename);
void ReadGame (char *filename);
void WriteLevel (char *filename);
void ReadLevel (char *filename);
void InitGame (void);
void G_RunFrame (void);
void dom_init (void);
void dom_awardpoints (void);
void PTRCheckJoinedQue (void);
//===================================================================
/*
=================
GetGameAPI
Returns a pointer to the structure with all entry points
and global variables
=================
*/
void ShutdownGame (void)
{
//K03 Begin
int i;
edict_t *ent;
for_each_player(ent, i)
{
//ent->myskills.inuse = 0;
SaveCharacter(ent); //WriteMyCharacter(ent);
}
//K03 End
gi.dprintf ("==== ShutdownGame ====\n");
gi.FreeTags (TAG_LEVEL);
gi.FreeTags (TAG_GAME);
}
game_export_t *GetGameAPI (game_import_t *import)
{
gi = *import;
globals.apiversion = GAME_API_VERSION;
globals.Init = InitGame;
globals.Shutdown = ShutdownGame;
globals.SpawnEntities = SpawnEntities;
globals.WriteGame = WriteGame;
globals.ReadGame = ReadGame;
globals.WriteLevel = WriteLevel;
globals.ReadLevel = ReadLevel;
globals.ClientThink = ClientThink;
globals.ClientConnect = ClientConnect;
globals.ClientUserinfoChanged = ClientUserinfoChanged;
globals.ClientDisconnect = ClientDisconnect;
globals.ClientBegin = ClientBegin;
globals.ClientCommand = ClientCommand;
globals.RunFrame = G_RunFrame;
globals.ServerCommand = ServerCommand;
globals.edict_size = sizeof(edict_t);
return &globals;
}
#ifndef GAME_HARD_LINKED
// this is only here so the functions in q_shared.c and q_shwin.c can link
void Sys_Error (char *error, ...)
{
va_list argptr;
char text[1024];
va_start (argptr, error);
vsprintf (text, error, argptr);
va_end (argptr);
gi.error (ERR_FATAL, "%s", text);
}
void Com_Printf (char *msg, ...)
{
va_list argptr;
char text[1024];
va_start (argptr, msg);
vsprintf (text, msg, argptr);
va_end (argptr);
gi.dprintf ("%s", text);
}
#endif
//======================================================================
/*
=================
ClientEndServerFrames
=================
*/
void ClientEndServerFrames (void)
{
int i;
edict_t *ent;
// calc the player views now that all pushing
// and damage has been added
for (i=0 ; i<maxclients->value ; i++)
{
ent = g_edicts + 1 + i;
if (!ent->inuse || !ent->client)
continue;
ClientEndServerFrame (ent);
}
}
//K03 Begin
/*
=================
CreateTargetChangeLevel
Returns the created target changelevel
=================
*/
edict_t *CreateTargetChangeLevel(char *map)
{
edict_t *ent;
ent = G_Spawn ();
ent->classname = "target_changelevel";
Com_sprintf(level.nextmap, sizeof(level.nextmap), "%s", map);
ent->map = level.nextmap;
gi.dprintf("Next map is %s.\n", ent->map);
return ent;
}
//K03 End
/*
=================
EndDMLevel
The timelimit or fraglimit has been exceeded
=================
*/
/*
void EndDMLevel (void)
{
edict_t *ent;
char *s, *t, *f;
static const char *seps = " ,\n\r";
// GHz START
int i;
edict_t *tempent;
clearallmenus();
InitJoinedQueue();
if (SPREE_WAR) // terminate any spree wars
{
SPREE_WAR = false;
SPREE_DUDE = NULL;
}
// save all characters and append to log
for_each_player(tempent, i)
{
VortexRemovePlayerSummonables(tempent);
tempent->myskills.streak = 0;
WriteMyCharacter(tempent);
if (G_EntExists(tempent))
WriteToLogfile(tempent, "Logged out.\n");
else
WriteToLogfile(tempent, "Disconnected from server.\n");
}
gi.dprintf("Ready to end level.\n");
//GHz END
// stay on same level flag
if ((int)dmflags->value & DF_SAME_LEVEL)
{
BeginIntermission (CreateTargetChangeLevel (level.mapname) );
return;
}
// see if it's in the map list
if (*sv_maplist->string) {
s = strdup(sv_maplist->string);
f = NULL;
t = strtok(s, seps);
while (t != NULL) {
if (Q_stricmp(t, level.mapname) == 0) {
// it's in the list, go to the next one
t = strtok(NULL, seps);
if (t == NULL) { // end of list, go to first one
if (f == NULL) // there isn't a first one, same level
BeginIntermission (CreateTargetChangeLevel (level.mapname) );
else
BeginIntermission (CreateTargetChangeLevel (f) );
} else
BeginIntermission (CreateTargetChangeLevel (t) );
free(s);
return;
}
if (!f)
f = t;
t = strtok(NULL, seps);
}
free(s);
}
if (level.nextmap[0]) // go to a specific map
BeginIntermission (CreateTargetChangeLevel (level.nextmap) );
else { // search for a changelevel
ent = G_Find (NULL, FOFS(classname), "target_changelevel");
if (!ent)
{ // the map designer didn't include a changelevel,
// so create a fake ent that goes back to the same level
BeginIntermission (CreateTargetChangeLevel (level.mapname) );
return;
}
BeginIntermission (ent);
}
}
*/
/*
* This function replaces _strdate for a cross-platform implementation.
* Returns the simple date string in mm/dd/yy format.
*/
char *mystrdate(char *buf)
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
strftime (buf,80,"%m/%d/%y.",timeinfo);
return buf;
}
/*
* This function replaces _strtime for a cross-platform implementation.
* Returns the simple time string in hh:mm:ss format.
*/
char *mystrtime(char *buf)
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
strftime (buf,80,"%I:%M:%S",timeinfo);
return buf;
}
void VortexEndLevel (void)
{
int i;
edict_t *tempent;
INV_AwardPlayers();
gi.dprintf("Vortex is shutting down...");
CTF_ShutDown(); // 3.7 shut down CTF, remove flags and bases
clearallmenus();
InitJoinedQueue();
InitializeTeamNumbers(); // for allies
for_each_player(tempent, i)
{
PM_RemoveMonster(tempent);
VortexRemovePlayerSummonables(tempent);
tempent->myskills.streak = 0;
SaveCharacter(tempent);
if (G_EntExists(tempent))
WriteToLogfile(tempent, "Logged out.\n");
else
WriteToLogfile(tempent, "Disconnected from server.\n");
}
SPREE_WAR = false;
SPREE_DUDE = NULL;
INVASION_OTHERSPAWNS_REMOVED = false;
gi.dprintf("OK!\n");
}
void EndDMLevel (void)
{
edict_t *ent;
int found_map=0;
static const char *seps = " ,\n\r";
//GHz START
int modenum=0;
VortexEndLevel();
//GHz END
// stay on same level flag
if ((int)dmflags->value & DF_SAME_LEVEL)
{
//BeginIntermission (CreateTargetChangeLevel(level.mapname));
VortexBeginIntermission(level.mapname);
return;
}
//3.0 Begin new voting/mapchange code
if (voting->value)
{
int mode = V_AttemptModeChange(true);
v_maplist_t *maplist;
int mapnum;
//Is the game mode changing?
if(mode)
{
//Alert everyone
switch(mode)
{
case MAPMODE_PVP:
if (pvm->value || domination->value)
gi.bprintf(PRINT_HIGH, "Switching to Player Vs. Player (PvP) mode!\n");
break;
case MAPMODE_PVM:
if (!pvm->value)
gi.bprintf(PRINT_HIGH, "Switching to Player Vs. Monster (PvM) mode!\n");
break;
case MAPMODE_DOM:
if (!domination->value)
gi.bprintf(PRINT_HIGH, "Switching to Domination (DOM) mode!\n");
break;
case MAPMODE_CTF:
if (!ctf->value)
gi.bprintf(PRINT_HIGH, "Switching to Capture The Flag (CTF) mode!\n");
break;
case MAPMODE_FFA:
if (!ffa->value)
gi.bprintf(PRINT_HIGH, "Switching to Free For All (FFA) mode!\n");
break;
case MAPMODE_INV:
if (!invasion->value)
gi.bprintf(PRINT_HIGH, "Switching to Invasion (INV) mode!\n");
break;
}
//gi.dprintf("changing to mode %d\n", mode);
//Select the map with the most votes
mapnum = FindBestMap(mode);
//gi.dprintf("mapnum=%d\n",mapnum);
//Point to the correct map list
maplist = GetMapList(mode);
if (mapnum == -1)
{
//Select a random map for this game mode
mapnum = GetRandom(0, maplist->nummaps-1);
}
//Change the map/mode
V_ChangeMap(maplist, mapnum, mode);
}
else
{
//gi.dprintf("mode not changing\n");
//Find out what current game mode is
if (pvm->value)
{
if (invasion->value)
mode = MAPMODE_INV;
else
mode = MAPMODE_PVM;
}
else if (domination->value)
mode = MAPMODE_DOM;
else if (ctf->value)
mode = MAPMODE_CTF;
else if (ffa->value)
mode = MAPMODE_FFA;
else mode = MAPMODE_PVP;
//Point to the correct map list
maplist = GetMapList(mode);
//Try to find a map that was voted for
mapnum = FindBestMap(mode);
if (mapnum == -1)
{
//Select a random map for this game mode
mapnum = GetRandom(0, maplist->nummaps-1);
}
//Change the map/mode
V_ChangeMap(maplist, mapnum, mode);
}
}
//3.0 end voting (doomie)
//This should always be true now
if (level.nextmap)
{ // go to a specific map
//BeginIntermission (CreateTargetChangeLevel (level.nextmap) );
VortexBeginIntermission(level.nextmap);
}
else
{
// search for a changelevel
ent = G_Find (NULL, FOFS(classname), "target_changelevel");
if (!ent)
{ // the map designer didn't include a changelevel,
// so create a fake ent that goes back to the same level
//BeginIntermission (CreateTargetChangeLevel (level.mapname) );
VortexBeginIntermission(level.nextmap);
return;
}
BeginIntermission (ent);
}
}
/*
=================
CheckNeedPass
=================
*/
void CheckNeedPass (void)
{
int need;
// if password or spectator_password has changed, update needpass
// as needed
if (password->modified || spectator_password->modified)
{
password->modified = spectator_password->modified = false;
need = 0;
if (*password->string && Q_strcasecmp(password->string, "none"))
need |= 1;
if (*spectator_password->string && Q_strcasecmp(spectator_password->string, "none"))
need |= 2;
gi.cvar_set("needpass", va("%d", need));
}
}
/*
=================
CheckDMRules
=================
*/
char *HiPrint(char *text);//K03
void CheckDMRules (void)
{
int i, check;//K03
float totaltime=((timelimit->value*60) - level.time);//K03 added totaltime
gclient_t *cl;
if (level.intermissiontime)
return;
if (!deathmatch->value)
return;
//K03 Begin
//GetScorePosition();//Gets each persons rank and total players in game
//K03 End
if (timelimit->value)
{
//K03 Begin
//Spawn monsters every 120 seconds
check= (int)(totaltime)%120;
if (voting->value && (level.time >= (timelimit->value - 3)*60) &&
(maplist.warning_given == false))
{
gi.bprintf (PRINT_HIGH,(va("%s\n", HiPrint("***** 3 Minute Warning: Type 'vote' to place your vote for the next map and game type *****"))) );
maplist.warning_given = true;
}
//K03 End
if (level.time >= timelimit->value*60)
{
gi.bprintf (PRINT_HIGH, "Timelimit hit.\n");
EndDMLevel ();
return;
}
}
if (fraglimit->value)
{
for (i=0 ; i<maxclients->value ; i++)
{
cl = game.clients + i;
if (!g_edicts[i+1].inuse)
continue;
//K03 Begin
if (voting->value && (cl->resp.frags >= (fraglimit->value-5)) &&
(maplist.warning_given == false))
{
gi.bprintf (PRINT_HIGH,(va("%s\n", HiPrint("***** 5 Frags Remaining: Type 'vote' to place your vote for the next map and game type *****"))) );
maplist.warning_given = true;
}
//K03 End
if (cl->resp.frags >= fraglimit->value)
{
gi.bprintf (PRINT_HIGH, "Fraglimit hit.\n");
EndDMLevel ();
return;
}
}
}
if (INVASION_OTHERSPAWNS_REMOVED && (INV_GetNumPlayerSpawns() < 1))
{
gi.bprintf(PRINT_HIGH, "Humans were unable to stop the invasion. Game over.\n");
EndDMLevel();
return;
}
}
/*
=============
ExitLevel
=============
*/
void ExitLevel (void)
{
int i;
edict_t *ent;
char command [256];
//JABot[start] (Disconnect all bots before changing map)
BOT_RemoveBot("all");
//[end]
//GHz START
VortexEndLevel();
//GHz END
if(level.changemap)
Com_sprintf (command, sizeof(command), "gamemap \"%s\"\n", level.changemap);
else if (level.nextmap)
Com_sprintf (command, sizeof(command), "gamemap \"%s\"\n", level.nextmap);
else
{
//default to q2dm1 and give an error
gi.dprintf("ERROR in ExitLevel()!!\nlevel.changemap = %s\nlevel.nextmap = %s\n", level.changemap, level.nextmap);
Com_sprintf (command, sizeof(command), "gamemap \"%s\"\n", "q2dm1");
}
gi.AddCommandString (command);
level.changemap = NULL;
level.exitintermission = 0;
level.intermissiontime = 0;
ClientEndServerFrames ();
// clear some things before going to next level
for (i=0 ; i<maxclients->value ; i++)
{
ent = g_edicts + 1 + i;
if (!ent->inuse)
continue;
if (ent->health > ent->client->pers.max_health)
ent->health = ent->client->pers.max_health;
}
}
/*
================
G_RunFrame
Advances the world by 0.1 seconds
================
*/
void tech_spawnall (void);
void thinkDisconnect(edict_t *ent);
void G_InitEdict (edict_t *e);
void check_for_levelup(edict_t *ent);//K03
void RunVotes ();
void RunBotVotes ();
void G_RunFrame (void)
{
int i;//j;
static int ofs;
static float next_fragadd = 0;
edict_t *ent;
//vec3_t v,vv;
qboolean haveflag;
// gitem_t *item;
level.framenum++;
level.time = level.framenum*FRAMETIME;
// choose a client for monsters to target this frame
// AI_SetSightClient ();
// exit intermissions
if (level.exitintermission)
{
ExitLevel();
return;
}
if(spawncycle < level.time)
spawncycle = level.time + FRAMETIME * 10;
if(spawncycle < 130)
spawncycle = 130;
#ifndef OLD_VOTE_SYSTEM // Paril
RunVotes();
RunBotVotes();
#endif
//
// treat each object in turn
// even the world gets a chance to think
//
haveflag = false;
ent = &g_edicts[0];
for (i=0 ; i<globals.num_edicts ; i++, ent++)
{
if (!ent->inuse)
continue;
//4.0 reset chainlightning flag
ent->flags &= ~FL_CLIGHTNING;
level.current_entity = ent;
VectorCopy (ent->s.origin, ent->s.old_origin);
// if the ground entity moved, make sure we are still on it
if ((ent->groundentity) && (ent->groundentity->linkcount != ent->groundentity_linkcount))
{
ent->groundentity = NULL;
if ( !(ent->flags & (FL_SWIM|FL_FLY)) && (ent->svflags & SVF_MONSTER) )
{
M_CheckGround (ent);
}
}
if (i > 0 && i <= maxclients->value && !(ent->svflags & SVF_MONSTER))
{
ClientBeginServerFrame (ent);
//JABot[start]
if ( ent->ai.is_bot )
G_RunEntity (ent);
//[end]
continue;
}
G_RunEntity (ent);
}
// see if it is time to end a deathmatch
CheckDMRules ();
// see if needpass needs updated
CheckNeedPass ();
// build the playerstate_t structures for all players
ClientEndServerFrames ();
//JABot[start]
AITools_Frame(); //give think time to AI debug tools
//[end]
//GHz START
// auto-save files every 3 minutes
if (!(level.framenum % 1800))
{
for (i = 0; i < maxclients->value; i++) {
ent = &g_edicts[i];
if (!G_EntExists(ent))
continue;
SaveCharacter(ent);
}
gi.dprintf("INFO: All players saved.\n");
}
//GHz END
//decino: save nodes every 1 minute (for the bots)
// if (!(level.framenum % 600))
// {
// AITools_SaveNodes();
// gi.dprintf("INFO: Updated bot nodes.\n");
// }
//3.0 Remove votes by players who left the server
//Every 5 minutes
#ifdef OLD_VOTE_SYSTEM // Paril
if (!(level.framenum % 3000))
CheckPlayerVotes();
#endif
//3.0 END
if (level.time < pregame_time->value)
if (level.time == pregame_time->value-45)
gi.bprintf(PRINT_HIGH, "15 seconds have passed, voting has been enabled.\n");
if (level.time == pregame_time->value-30) {
gi.bprintf(PRINT_HIGH, "30 seconds left of pre-game\n");
for (i = 0; i < maxclients->value; i++) {
ent = &g_edicts[i];
if (!ent->inuse)
continue;
if (!ent->client)
continue;
// if (ent->client->disconnect_time > 0)
//continue;
gi.cprintf(ent, PRINT_HIGH, "You will not be able to access the Armory in the game\n");
}
}
if (level.time == pregame_time->value-10)
gi.bprintf(PRINT_HIGH, "10 seconds left of pre-game\n");
if (level.time == pregame_time->value-5)
gi.bprintf(PRINT_HIGH, "5 seconds\n");
if (level.time == pregame_time->value-4)
gi.bprintf(PRINT_HIGH, "4\n");
if (level.time == pregame_time->value-3)
gi.bprintf(PRINT_HIGH, "3\n");
if (level.time == pregame_time->value-2)
gi.bprintf(PRINT_HIGH, "2\n");
if (level.time == pregame_time->value-1)
gi.bprintf(PRINT_HIGH, "1\n");
if (level.time == pregame_time->value) {
gi.bprintf(PRINT_HIGH, "Game commences!\n");
gi.sound(ent, CHAN_VOICE, gi.soundindex("misc/fight.wav"), 1, ATTN_NONE, 0);
tech_spawnall();
for (i = 0; i < maxclients->value; i++) {
ent = &g_edicts[i];
if (!ent->inuse)
continue;
if (!ent->client)
continue;
//r1: fixed illegal effects being set
ent->s.effects &= ~EF_COLOR_SHELL;
ent->s.renderfx &= ~RF_SHELL_RED;
//RemoveAllCurses(ent);
//RemoveAllAuras(ent);
AuraRemove(ent, 0);
CurseRemove(ent, 0);
if (ent->client)
ent->client->is_poisoned = false;
ent->Slower = level.time - 1;
}
}
if (domination->value && (level.time == pregame_time->value))
dom_init();
if (ctf->value && (level.time == pregame_time->value))
CTF_Init();
if (domination->value && (level.time > pregame_time->value))
dom_awardpoints();
PTRCheckJoinedQue();
INV_SpawnPlayers();
//decino: randomly morph a player into a boss with alot of players
if (V_IsPVP() && !(level.framenum%100) && total_players() >= 8 && random() >= 0.99 && !SPREE_WAR)
CreateRandomPlayerBoss(true);
//decino: double check
if (level.num_bots < 0)
level.num_bots = 0;
//decino: keeping trying to spawn bots depending on the vote settings and amount of players in-game, make sure they don't spawn during votes
if (V_IsPVP() && !(level.framenum%(20+GetRandom(1,20))) && level.num_bots < level.bots_max && level.spawnbots)
{
BOT_SpawnBot ( NULL, "", "", NULL );
}
//4.4 occasionally spawn a boss in PvP mode
if (V_IsPVP() && !(level.framenum%100) && total_players() >= 8 && random() >= 0.99 && !SPREE_WAR)
{
edict_t *e=NULL;
qboolean bossExists=false;
// search for an existing monster boss
for (e=g_edicts ; e < &g_edicts[globals.num_edicts]; e++)
{
if (G_EntIsAlive(e) && e->mtype == M_COMMANDER)
{
qboolean bossExists = true;
break;
}
}
// if there aren't any, then spawn one
if (!bossExists)
SpawnDrone(world, 30, true);
}
}
<file_sep>#include "g_local.h"
int v_LoadMapList(int mode)
{
FILE *fptr;
v_maplist_t *maplist;
char filename[256];
int iterator = 0;
//determine path
#if defined(_WIN32) || defined(WIN32)
sprintf(filename, "%s\\Settings\\", game_path->string);
#else
sprintf(filename, "%s/Settings/", game_path->string);
#endif
switch(mode)
{
case MAPMODE_PVP:
strcat(filename, "maplist_PVP.txt");
maplist = &maplist_PVP;
break;
case MAPMODE_DOM:
strcat(filename, "maplist_DOM.txt");
maplist = &maplist_DOM;
break;
case MAPMODE_PVM:
strcat(filename, "maplist_PVM.txt");
maplist = &maplist_PVM;
break;
case MAPMODE_CTF:
strcat(filename, "maplist_CTF.txt");
maplist = &maplist_CTF;
break;
case MAPMODE_FFA:
strcat(filename, "maplist_FFA.txt");
maplist = &maplist_FFA;
break;
case MAPMODE_INV:
strcat(filename, "maplist_INV.txt");
maplist = &maplist_INV;
break;
default:
gi.dprintf("ERROR in v_LoadMapList(). Incorrect map mode. (%d)\n", mode);
return 0;
}
//gi.dprintf("mode = %d\n", mode);
if ((fptr = fopen(filename, "r")) != NULL)
{
char buf[128];
while (fgets(buf, 128, fptr) != NULL)
{
strcpy(maplist->mapnames[iterator], buf);
maplist->mapnames[iterator][strlen(maplist->mapnames[iterator])-1] = 0;
++iterator;
}
fclose(fptr);
maplist->nummaps = iterator;
}
else
{
gi.dprintf("Error loading map file: %s\n", filename);
maplist->nummaps = 0;
}
return maplist->nummaps;
} | 0605541247cbf0380eb26c86c64f30af0e2c910b | [
"C",
"Makefile"
] | 23 | C | QwazyWabbitWOS/newvortex | be063508379e46c37ed2d9a066de98d28db489e7 | 960898e79065e76c6c77c56df3846c8a25280b29 |
refs/heads/master | <file_sep># My Code here....
def map_to_negativize(source_array)
i = 0
array = []
while i<source_array.length do
array[i] = source_array[i]*-1
i+=1
end
return array
end
def map_to_no_change(source_array)
i = 0
array = []
while i<source_array.length do
array[i] = source_array[i]
i+=1
end
return array
end
def map_to_double(source_array)
i = 0
array = []
while i<source_array.length do
array[i] = source_array[i]*2
i+=1
end
return array
end
def map_to_square(source_array)
i = 0
array = []
while i<source_array.length do
array[i] = source_array[i]**2
i+=1
end
return array
end
def reduce_to_total(source_array, starting_point=0)
i = 0
total = starting_point
while i<source_array.length do
total += source_array[i]
i+=1
end
return total
end
def reduce_to_all_true(source_array)
i = 0
while i<source_array.length do
if(source_array[i]==false)
return false
end
i+=1
end
return true
end
def reduce_to_any_true(source_array)
i = 0
while i<source_array.length do
if(source_array[i]==true)
return true
end
i+=1
end
return false
end
| 90ad9888dd5889605bf99d6ca913b731d36e4804 | [
"Ruby"
] | 1 | Ruby | phyunmin/ruby-enumerables-introduction-to-map-and-reduce-lab-seattle-web-012720 | 0cf95561027ea3c1f29837ddc75a2a439668fd2a | 6997b9bbe6cf2a577d72921691a076f983b791ec |
refs/heads/master | <file_sep>#pragma once
#include "Shape.h"
#include <glm/glm.hpp>
#include <iostream>
#include <fstream>
using namespace std;
class Triangle : public Shape
{
public:
vec3 pOne, pTwo, pThree; // Vector containers for each of the 3 vertices of the triangle
vec3 normOne, normTwo, normThree; // Vectors containing position of normals
vec3 shapeColour; // Triangle Colour
float u, v, w, t;
Triangle(vec3 p1, vec3 p2, vec3 p3, vec3 n1, vec3 n2, vec3 n3, vec3 col);
Triangle();
bool detect(vec3 ray, vec3 dir, vec3 collide[], float& dist);
vec3 colour(vec3 lighting[], vec3 collide[], vec3 dir, Shape *shapes[], vec3 camSpace, float& dist, int k);
~Triangle();
};
<file_sep>#include "stdafx.h"
#include "Sphere.h"
#include "Shape.h"
#include "Plane.h"
#include "Triangle.h"
#include <glm/glm.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#define PI 3.14159265359
using namespace std;
float width = 640;
float height = 480;
// Pointer array
vec3 **image = new vec3*[(int)width];
// Top class pointer using virtual function
Shape* shapes[6];
void setup()
{
//////////////////////////////////////////////////////////////////////
// //
// Spheres as (vec3 position, vec3 colour, float radius) //
// Triangles as (vec3 vert1, vec3 vert2, vec3 vert3, vec3 colour) //
// Plane as (vec3 position, vec3 normal, vec3 colour) //
// //
//////////////////////////////////////////////////////////////////////
shapes[0] = new Triangle(vec3(-10, 5, -10), vec3(-3, 5, -10), vec3(-10, 1, -10), vec3(0.0, 0.6, 1.0), vec3(-0.4, -0.4, -1.0), vec3(0.4, -0.4, 1.0), vec3(0.1, 0.1, 0.6));
shapes[1] = new Plane(vec3(0, -20, -10), vec3(0, -1, 0), vec3(0.4, 0.4, 0.4));
shapes[2] = new Sphere(vec3(-5, 1, -10), vec3 (1.00, 0.32, 0.36), 4); // Red Sphere
shapes[3] = new Sphere(vec3(4, 1, -15), vec3(0.90, 0.76, 0.46), 2); // Yellow Sphere
shapes[4] = new Sphere(vec3(5, 1, -5), vec3(0.65, 0.77, 0.97), 3); // Blue Sphere
shapes[5] = new Sphere(vec3(-8, 4, -10), vec3(0.80, 0.80, 0.80), 3); // Light Grey Sphere
shapes[6] = new Triangle(vec3(4, 6, -8), vec3(-4, 6, -8), vec3(4, -3, -8), vec3(0.0, 0.6, 1.0), vec3(-0.4, -0.4, -1.0), vec3(0.4, -0.4, 1.0), vec3(0.4, 0.4, 0.1));
// Lighting Constraints
vec3 lighting[4];
lighting[0] = vec3(0.0, 100.0, 0); // Position of the light source in the scene
lighting[1] = vec3(0.5, 0.5, 0.5); // Diffuse vector value
lighting[2] = vec3(0.7, 0.7, 0.7); // Specular vector value
lighting[3] = vec3(0.5, 0.5, 0.5); // Ambient light vector container - reference p504 in book
double angle;
angle = 90 * (PI / 180.0);
//////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// Sets up vector array with 2 dimensions using pointers //
// As image iterates through x values, iterate through y values before moving to next x value //
// //
//////////////////////////////////////////////////////////////////////////////////////////////////////
for (int i(0); i < width; i++) {
image[i] = new vec3[(int)height];
}
// Initialise loop to run through each pixel of the image, ready for Ray Casting
for (int j(0); j < height; j++) {
for (int i(0); i < width; i++) {
// Ray Casting Loop
double pixNormX = (i + 0.5) / width;
double pixNormY = (j + 0.5) / height;
// Aspect Ratio Calc
float aspRatio = width / height;
// Pixel Remap
double pixRemapX = ((2 * pixNormX) - 1) * aspRatio;
double pixRemapY = 1 - 2 * pixNormY;
// FOV calc
double pixCamX = (pixRemapX * tan(angle / 2.0));
double pixCamY = (pixRemapY * tan(angle / 2.0));
// Ray Calc
vec3 pCamspace(pixCamX, pixCamY, -1); // Take Camera space and distance away from cam for new Vector
vec3 rayOrigin(0, 0, 0); // Ray starts at camera's world position
vec3 rayDirection = pCamspace - rayOrigin; // Define direction of ray through normal calculation
rayDirection = normalize(rayDirection); // Normalize ray into unit vector
float minT = FLT_MAX;
// Shape Creation and Ray Collision Detection Loop
// k used for clarity in reading
for (int k(0); k < 7; k++) {
vec3 collisions[2];
float shapeDistance;
bool hitShape = shapes[k]->detect(rayOrigin, rayDirection, collisions, shapeDistance); // Iterates through ray collisions per shape in the scene
if (hitShape == true && shapeDistance < minT) {
minT = shapeDistance;
image[i][j] = shapes[k]->colour(lighting, collisions, rayDirection, shapes, pCamspace, shapeDistance, k);
}
}
}
}
//////////////////////////////////////////////////////////////
// //
// Save to a PPM image //
// //
// Loop to create the image that the file will take in //
// Top line titles the file name and extension //
// //
//////////////////////////////////////////////////////////////
string filedir = "./";
filedir.append("image");
filedir.append(".ppm");
ofstream ofs(filedir, ios::out | ios::binary);
ofs << "P6\n" << width << " " << height << "\n255\n"; // Formatting, do not change
for (unsigned y = 0; y < height; ++y) {
for (unsigned x = 0; x < width; ++x) {
ofs << (unsigned char)(fmin((float)1, (float)image[x][y].x) * 255) <<
(unsigned char)(fmin((float)1, (float)image[x][y].y) * 255) <<
(unsigned char)(fmin((float)1, (float)image[x][y].z) * 255);
}
}
ofs.close();
};
int main() {
setup();
return 0;
}
<file_sep>#include "stdafx.h"
#include "Triangle.h"
Triangle::Triangle(vec3 p1, vec3 p2, vec3 p3, vec3 n1, vec3 n2, vec3 n3, vec3 col) {
pOne = p1;
pTwo = p2;
pThree = p3;
normOne = n1;
normTwo = n2;
normThree = n3;
shapeColour.x = col.x;
shapeColour.y = col.y;
shapeColour.z = col.z;
}
Triangle::Triangle(){}
bool Triangle::detect(vec3 ray, vec3 dir, vec3 collide[], float& dist) {
vec3 edgeOne, edgeTwo; // Used to calculate e1 and e2 in barycentric equation
// Co-Ordinate Calculation
edgeOne = pTwo - pOne; // e1 = b - a
edgeTwo = pThree - pOne; // e2 = c - a
float denominator = dot(edgeOne, cross(dir, edgeTwo));
u = dot((ray - pOne), cross(dir, edgeTwo)) / denominator; // u = ((o - a) dot (d x e2)) / e1 dot (d x e2)
v = dot(dir, (cross(ray - pOne, edgeOne))) / denominator; // v = d dot ((o - a) x e1) / e1 dot (d x e2)
w = 1 - u - v; // 3rd Barycentric Co-Ordinate
t = dot(edgeTwo, (cross(ray - pOne, edgeOne))) / denominator;
// Check if point is in triangle
if (u < 0 || u > 1) {
// u = False
return false;
}
else if (v < 0 || u + v > 1) {
// u + v & False
return false;
}
else
// u + v < 1 & True
collide[0] = (u * pOne) + (v * pTwo) + (w * pThree);
return true;
}
//////////////////////////
// //
// Colour calculation //
// //
//////////////////////////
vec3 Triangle::colour(vec3 lighting[], vec3 collide[], vec3 dir, Shape *shapes[], vec3 camSpace, float& dist, int k) {
vec3 pixelColour;
vec3 ambientColour, diffuseColour, specularColour;
vec3 lightRay;
lightRay = lighting[0] - collide[0];
float shadowT = FLT_MAX;
vec3 rayNorm = normalize(lighting[0] - collide[0]);
vec3 triNorm = normalize((w * normOne) + (u * normTwo) + (v * normThree));
double diffuseNormalise = dot(rayNorm, triNorm);
ambientColour = shapeColour * lighting[3];
diffuseColour.x = lighting[1].x * 1.0 * max(0.0, diffuseNormalise);
diffuseColour.y = lighting[1].y * 1.0 * max(0.0, diffuseNormalise);
diffuseColour.z = lighting[1].z * 1.0 * max(0.0, diffuseNormalise);
vec3 reflection = 2 * (dot(lightRay, triNorm)) * triNorm - lightRay;
vec3 reflectNorm = normalize(reflection);
vec3 dirNorm = normalize(dir);
double specularNormalise = dot(reflectNorm, dirNorm);
specularColour.x = lighting[2].x * 0.5 * pow(max(0.0, specularNormalise), 128);
specularColour.y = lighting[2].y * 0.5 * pow(max(0.0, specularNormalise), 128);
specularColour.z = lighting[2].z * 0.5 * pow(max(0.0, specularNormalise), 128);
pixelColour = ambientColour + diffuseColour + specularColour;
float shadowDistance;
vec3 shadowCollisions[2];
// For all Shapes
for (int a(0); a < 5; a++) {
if (a != k && t <= 0) {
bool shadowRay = shapes[a]->detect(collide[0], lightRay, shadowCollisions, shadowDistance);
if (shadowRay == true && shadowDistance < shadowT) {
pixelColour = ambientColour + diffuseColour + specularColour;
}
else
pixelColour = ambientColour;
}
}
return pixelColour;
}
Triangle::~Triangle() {}
<file_sep>#include "stdafx.h"
#include "Sphere.h"
#define MAX_DEPTH 5
//////////////////////////////////////////////////////////////////////////
// //
// Take pre-defined positions and colour vectors to construct spheres //
// //
//////////////////////////////////////////////////////////////////////////
Sphere::Sphere(vec3 pos, vec3 colour, float rad) {
position.x = pos.x;
position.y = pos.y;
position.z = pos.z;
shapeColour.x = colour.x; // Red
shapeColour.y = colour.y; // Green
shapeColour.z = colour.z; // Blue
radius = rad;
}
//////////////////////////////////////////////////////////////////////////////////
// //
// Make operation return true if there is a collision between ray and a sphere //
// Return false for any iteration where there is no collision with a sphere //
// Pass through each sphere to determine if collision occurs with any sphere //
// //
//////////////////////////////////////////////////////////////////////////////////
bool Sphere::detect(vec3 ray, vec3 dir, vec3 collide[], float& dist) {
vec3 firstCol, secondCol; // First collision point, second collision point
vec3 collisionVecs[2] { firstCol, secondCol }; // Container array for looping
float colOne = 0;
float colTwo = 0;
float collisions[2] { colOne, colTwo }; // Container array for looping, faster calculations
// Vector storing scalar values of distance between ray and sphere origin
// Equivalent to: l = c - o
vec3 length;
float lengthDist;
length = position - ray;
lengthDist = -(length.x + length.y + length.z);
dist = lengthDist;
// Equivalent to: t(ca) = l dot d
float traj;
traj = (length.x * dir.x) + (length.y * dir.y) + (length.z * dir.z); // If positive, a collision is possible
if (traj < 0) {
return false; // If collision is not possible
}
else {
float sphereCentreRay;
float lenSqu = (length.x * length.x) + (length.y * length.y) + (length.z * length.z);
//////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// Calculate scalar value that states distance of ray and it's direction away from sphere centre //
// If value is larger than radius, ray never intersects sphere //
// Equivalent to: s^2 = l^2 - t(ca)^2 --> s = sqrt(l^2 - t(ca)^2) //
// //
//////////////////////////////////////////////////////////////////////////////////////////////////////
sphereCentreRay = sqrt(lenSqu - (traj * traj));
if (sphereCentreRay > radius) {
return false;
}
else {
float sphereCollision;
// Equivalent to: t(hc) = sqrt(r^2 - s^2)
sphereCollision = sqrt((radius * radius) - (sphereCentreRay * sphereCentreRay));
colOne = traj - sphereCollision; // t(0) = t(ca) - t(hc)
colTwo = traj + sphereCollision; // t(1) = t(ca) + t(hc)
float collisionLength;
if (colOne < colTwo)
collisionLength = colOne;
else
collisionLength = colTwo;
collisions[0] = colOne;
collisions[1] = colTwo;
// Returns all values
for (int i(0); i < 2; i++) {
// Returns vectors for collision points with scalar form:
// p = o + t(n)d
collisionVecs[i] = ray + (collisions[i] * dir);
collide[i] = collisionVecs[i];
//////////////////////////////
// //
// Shadow Calculation //
// n = (p - c) / ||p - c|| //
// //
//////////////////////////////
vec3 dirNorm, normal, normAlter;
normAlter.x = collisionVecs[i].x + (collisionVecs[i].x - position.x) * 1e-4;
normAlter.y = collisionVecs[i].y + (collisionVecs[i].y - position.y) * 1e-4;
normAlter.z = collisionVecs[i].z + (collisionVecs[i].z - position.z) * 1e-4;
dirNorm = normalize(dir); // V Ray Normalised
normal = normalize(collisionVecs[0] - position); // N Vector Normalised
// Recurse call for reflections
for (int r(0); r < 6; r++) {
reflections(dir, normal);
}
}
}
}
return true && dist;
}
//////////////////////////////////////////////////////////////////
// //
// Calculates direction of the ray once reflected off of shape //
// Takes ray direction and collision position normal vector //
// Returns new ray vector direction //
// //
//////////////////////////////////////////////////////////////////
vec3 Sphere::reflections(vec3 dir, vec3 norm) {
vec3 refRay;
refRay = dir - (((dot(dir, norm)) * norm) * ((dot(dir, norm)) * norm));
return refRay;
}
// Lighting array = position, diffuse, specular, ambient
// Collide takes in collision points of ray with object
vec3 Sphere::colour(vec3 lighting[], vec3 collide[], vec3 dir, Shape *shapes[], vec3 camSpace, float& dist, int k) {
vec3 pixelColour;
// Ambient Calculation
vec3 ambientColour, diffuseColour, specularColour;
ambientColour = shapeColour * lighting[3];
// Diffuse Calculation
vec3 lightRay, pixelNormal; // l = s - p, n = p - c
for (int i(0); i < 2; i++) {
// l = s - p
lightRay = lighting[0] - collide[i]; // Create light ray from point of intersection to light source
pixelNormal = collide[i] - position;
float shadowT = FLT_MAX;
vec3 rayNorm = normalize(lightRay); // Used in shadow creation
vec3 pixelNorm = normalize(pixelNormal);
double diffuseNormalise = dot(rayNorm, pixelNorm);
diffuseColour.x = lighting[1].x * 0.3 * max(0.0, diffuseNormalise);
diffuseColour.y = lighting[1].y * 0.3 * max(0.0, diffuseNormalise);
diffuseColour.z = lighting[1].z * 0.3 * max(0.0, diffuseNormalise);
vec3 reflection; // r = 2 (l dot n) n - l
reflection = 2 * (dot(lightRay, pixelNormal)) * pixelNormal - lightRay;
vec3 reflectNorm = normalize(reflection);
double specularNormalise = dot(reflectNorm, pixelNorm);
specularColour.x = lighting[2].x * 1.0 * pow(max(0.0, specularNormalise), 128);
specularColour.y = lighting[2].y * 1.0 * pow(max(0.0, specularNormalise), 128);
specularColour.z = lighting[2].z * 1.0 * pow(max(0.0, specularNormalise), 128);
pixelColour = ambientColour + diffuseColour + specularColour;
float shadowDistance;
vec3 shadowCollisions[2];
vec3 intersection;
intersection.x = collide[i].x + (collide[i].x - position.x) * 1e-4;
intersection.y = collide[i].y + (collide[i].y - position.y) * 1e-4;
intersection.z = collide[i].z + (collide[i].z - position.z) * 1e-4;
// For all Shapes
for (int a(0); a < 5; a++) {
if (a != k) {
bool shadowRay = shapes[a]->detect(intersection, lightRay, shadowCollisions, shadowDistance);
if (shadowRay == true && shadowDistance < shadowT) {
pixelColour = ambientColour;
}
else
pixelColour = ambientColour + diffuseColour + specularColour;
}
}
}
return pixelColour;
}
Sphere::Sphere(){}
Sphere::~Sphere(){}
<file_sep>#include "stdafx.h"
#include "Plane.h"
Plane::Plane(vec3 pos, vec3 norm, vec3 colour) {
position = pos;
normal = norm;
shapeColour = colour;
}
Plane::Plane() {
}
bool Plane::detect(vec3 ray, vec3 dir, vec3 collide[], float& dist) {
double test = dot(dir, normal);
if (test <= 0.01) {
return false;
}
else {
t = dot((position - ray), normal) / test;
collide[0] = ray + (t * dir);
}
return true;
}
vec3 Plane::colour(vec3 lighting[], vec3 collide[], vec3 dir, Shape *shapes[], vec3 camSpace, float& dist, int k) {
vec3 pixelColour;
vec3 ambientColour, diffuseColour, specularColour;
vec3 lightRay, pixelNormal;
lightRay = lighting[0] - collide[0];
pixelNormal = collide[0] - position;
float shadowT = FLT_MAX;
vec3 rayNorm = normalize(lightRay); // Used in shadow creation
vec3 pixelNorm = normalize(pixelNormal);
double diffuseNormalise = dot(rayNorm, pixelNorm);
if (diffuseNormalise < 0) {
diffuseNormalise = -diffuseNormalise;
}
diffuseColour.x = lighting[1].x * 1.0 * max(0.0, diffuseNormalise);
diffuseColour.y = lighting[1].y * 1.0 * max(0.0, diffuseNormalise);
diffuseColour.z = lighting[1].z * 1.0 * max(0.0, diffuseNormalise);
vec3 reflection; // r = 2 (l dot n) n - l
reflection = 2 * (dot(lightRay, pixelNormal)) * pixelNormal - lightRay;
vec3 reflectNorm = normalize(reflection);
vec3 dirNorm = normalize(dir);
double specularNormalise = dot(reflectNorm, dirNorm);
specularColour.x = lighting[2].x * 0.5 * pow(max(0.0, specularNormalise), 128);
specularColour.y = lighting[2].y * 0.5 * pow(max(0.0, specularNormalise), 128);
specularColour.z = lighting[2].z * 0.5 * pow(max(0.0, specularNormalise), 128);
ambientColour = shapeColour * lighting[3];
float shadowDistance;
vec3 shadowCollisions[2];
// For all Shapes
for (int a(0); a < 5; a++) {
if (a != k && t <= 0) {
bool shadowRay = shapes[a]->detect(collide[0], lightRay, shadowCollisions, shadowDistance);
if (shadowRay == true && shadowDistance < shadowT) {
pixelColour = ambientColour;
}
else
pixelColour = ambientColour + diffuseColour + specularColour;
}
}
return pixelColour;
}
Plane::~Plane(){
}
<file_sep>#pragma once
#include <glm/glm.hpp>
#include <iostream>
#include <fstream>
using namespace glm;
using namespace std;
class Shape
{
public:
//////////////////////////////////////////////////////
// //
// Virtuals enable all instances of shape classes //
// Default instances are below //
// //
//////////////////////////////////////////////////////
virtual bool detect(vec3 ray, vec3 dir, vec3 collide[], float& dist)
{
std::cout << "Passed" << std::endl;
return true;
}
virtual vec3 reflections(vec3 dir, vec3 norm)
{
return vec3(0, 0, 0);
}
virtual vec3 colour(vec3 lighting[], vec3 collide[], vec3 dir, Shape *shapes[], vec3 camSpace, float& dist, int k)
{
return vec3(0, 0, 0);
}
Shape();
~Shape();
};
<file_sep>#pragma once
#include "Shape.h"
#include <glm/glm.hpp>
#include <iostream>
#include <fstream>
using namespace std;
class Sphere : public Shape
{
public:
float radius;
vec3 position, shapeColour;
float colDist;
Sphere(vec3 pos, vec3 colour, float rad);
Sphere();
bool detect(vec3 ray, vec3 dir, vec3 collide[], float& dist);
vec3 reflections(vec3 dir, vec3 norm);
vec3 colour(vec3 lighting[], vec3 collide[], vec3 dir, Shape *shapes[], vec3 camSpace, float& dist, int k);
~Sphere();
};
<file_sep>#pragma once
#include "Shape.h"
#include <glm/glm.hpp>
#include <iostream>
#include <fstream>
using namespace std;
class Plane : public Shape
{
public:
vec3 position, normal, shapeColour;
float planeSize, t;
Plane(vec3 position, vec3 normal, vec3 colour);
Plane();
bool detect(vec3 ray, vec3 dir, vec3 collide[], float& dist);
vec3 colour(vec3 lighting[], vec3 collide[], vec3 dir, Shape *shapes[], vec3 camSpace, float& dist, int k);
~Plane();
};
| 8a472c09be0bbb847c26d2beaede4b884258ae96 | [
"C++"
] | 8 | C++ | sttot/Phong_Shading | 7d1fd2b16700d961205dda74b7823882380c77e9 | c12fa9086ab09d6c69f67bcbde73627a8bd37c56 |
refs/heads/master | <file_sep>coinbasedemo
============
CoinBase API demo, let's you:
1.Get the balance of an acount
2.Generate a payment button example
https://www.coinbase.com allows you to sell/buy bitcoins, also provides a VERY customizable environment.
How to run (from shell):
$ coinBaseDemo.sh <action> <apiKey> <apiSecret>
How to run (inside GGTS):
Add to the classpath every JAR file in /lib
Example to run from GGTS:
--classpath "${workspace_loc:/coinbasedemo}:./lib/commons-codec-1.6.jar:./lib/commons-logging-1.1.3.jar:./lib/fluent-hc-4.3.5.jar:./lib/httpclient-4.3.5.jar:./lib/httpclient-cache-4.3.5.jar:./lib/httpcore-4.3.2.jar:./lib/httpmime-4.3.5.jar:${workspace_loc:/coinbasedemo}" --main groovy.ui.GroovyMain "${resource_loc:/coinbasedemo/org/foa/coinbase/CoinBaseDemo.groovy}" get_checkout <apiKey> <apiSecret>
How it works:
coinBaseDemo <action> <apiKey> <apiSecret>
<action> : get_balance | get_checkout
<apiKey> : your CoinBase api_key
<apiSecret> : your CoinBase api_secret
<file_sep>#!/bin/sh
groovy -cp lib/*:. src/org/foa/coinbase/CoinBaseDemo.groovy $1 $2 $3
| 294ea5e43a47af37d0c15c77b3953b7b2a324c46 | [
"Markdown",
"Shell"
] | 2 | Markdown | aguilerafabian/coinbasedemo | ac8d1002454abe65862a2877ab4f4d5e4e8d0ca0 | 2feaa92359b70b63532cbca3f4db5d8afce8ede3 |
refs/heads/master | <file_sep>// api urls
var API_PROXY = 'https://sc-api-proxy.herokuapp.com';
var SECRET_TRACK = API_PROXY + '/tracks/12345/stream?secret_token=s-ZUFsV';
var STREAM_WITH_TIME = API_PROXY + '/tracks/242594586/stream#t=13:10';
// web app urls
var PLAYLIST = 'http://soundcloud.com/jxnblk/sets/yello';
var TRACKS = 'http://soundcloud.com/shura/tracks';
var TRACK_WITH_TIME =
'https://soundcloud.com/balamii/dj-sotofett-b2b-brian-not-brian-jayda-g-jan-2016#t=13:10';
describe('soundcloud-audio', function() {
var player;
before(function() {
player = new SoundCloudAudio(null, API_PROXY);
});
it('should create new player instance', function() {
expect(player).to.be.ok;
});
describe('when resolving playlist', function() {
var playlist;
var firstTrack;
var secondTrack;
before(function(done) {
player.resolve(PLAYLIST, function(_playlist) {
playlist = _playlist;
firstTrack = playlist.tracks[0].stream_url;
secondTrack = playlist.tracks[1].stream_url;
done();
});
});
it('should have an array of tracks', function() {
expect(playlist.tracks).to.be.an('array');
});
it('should have playing defined as false', function() {
expect(player.playing).to.be.false;
});
it('should have playlist duration in seconds', function() {
expect(player.duration).to.be.a('number');
});
describe('when playing playlist', function() {
before(function() {
player.play();
});
it('should have playing defined as true', function() {
expect(player.playing).to.be.ok;
});
describe('when skipping to next track', function() {
before(function() {
player.next();
});
it('should have second track playing', function() {
expect(player.playing).to.contain(secondTrack);
});
describe('when skipping to previous track', function() {
before(function() {
player.previous();
});
it('should have first track playing', function() {
expect(player.playing).to.contain(firstTrack);
});
describe('when pausing the track', function() {
before(function() {
player.pause();
});
it('should have playing as false', function() {
expect(player.playing).to.be.false;
});
});
describe('pausing on a track other than the first', function() {
before(function() {
player.play();
player.next();
player.pause();
player.play();
});
it('should resume at the current track', function() {
expect(player.playing).to.contain(secondTrack);
});
});
describe('next() at the end of a playlist', function() {
before(function() {
player.play({ playlistIndex: playlist.tracks.length - 1 });
player.next({ loop: true });
});
it('should loop to the beginning if loop is set', function() {
expect(player.playing).to.contain(firstTrack);
});
});
});
});
});
});
// SoundCloud is not supporting resolving track urls
xdescribe('when resolving artist tracks', function() {
var fakePlaylist;
var firstTrack;
var secondTrack;
before(function(done) {
player.resolve(TRACKS, function(_fakePlaylist) {
fakePlaylist = _fakePlaylist;
firstTrack = fakePlaylist.tracks[0].stream_url;
secondTrack = fakePlaylist.tracks[1].stream_url;
done();
});
});
it('should have an array of tracks', function() {
expect(fakePlaylist.tracks).to.be.an('array');
});
it('should have playing defined as false', function() {
expect(player.playing).to.be.false;
});
it('should have playlist duration in seconds', function() {
expect(player.duration)
.to.be.a('number')
.and.equal(0);
});
describe('when playing playlist', function() {
before(function() {
player.play();
});
it('should have playing defined as true', function() {
expect(player.playing).to.be.ok;
});
describe('when skipping to next track', function() {
before(function() {
player.next();
});
it('should have second track playing', function() {
expect(player.playing).to.contain(secondTrack);
});
describe('when skipping to previous track', function() {
before(function() {
player.previous();
});
it('should have first track playing', function() {
expect(player.playing).to.contain(firstTrack);
});
describe('when pausing the track', function() {
before(function() {
player.pause();
});
it('should have first track playing', function() {
expect(player.playing).to.be.false;
});
});
});
});
});
});
describe('when streaming secret tracks', function() {
before(function() {
player.play({ streamUrl: SECRET_TRACK });
});
it('should have playing defined as the correct url', function() {
expect(player.playing).to.equal(SECRET_TRACK);
});
});
describe('when streaming track with time hash', function() {
before(function() {
player.play({ streamUrl: STREAM_WITH_TIME });
});
it('should have playing defined as the correct url', function() {
expect(player.playing).to.equal(STREAM_WITH_TIME);
});
});
describe('when resolving track with time hash', function() {
before(function(done) {
player.resolve(TRACK_WITH_TIME, function() {
player.play();
done();
});
});
it('should have playing defined as the correct url', function() {
expect(player.playing).to.equal(STREAM_WITH_TIME);
});
});
});
| 465e66c1b09832fd701249190d7151b72e609d57 | [
"JavaScript"
] | 1 | JavaScript | olliekav/soundcloud-audio.js | 3d4945fbfc645d90de2ba0ff00429dd1df0a53c3 | 94facaad571805db7ecb0f1c0a678ebb1d8702c2 |
refs/heads/master | <file_sep>"""
Writen by <NAME>.
29.8.2016
run: python eukref_gbretrieve.py -h for usage.
This pipeline requires USEARCH (32bit version is OK) and NCBI Blast to be installed. If you are using linux and cannot
install programs as administrator, you can install both under your account and add them to your PATH or put executables
into the folder you are using this script from.
You will also need localy placed NCBI NT database, which can be downloaded from NCBI ftp server.
"""
import os
import pickle
import argparse
import re
print "Genbank SSU rRNA gene parser."
print "Contributors: <NAME>, <NAME>, <NAME> and <NAME>"
print "29 August 2016"
print "\n\nrun: python eukref_gbretrieve.py -h for help.\n\nThis pipeline requires USEARCH (32bit version is OK) and NCBI Blast to be installed. If you are using linux and cannot\ninstall programs as administrator, you can install both under your account and add them to your PATH. \n\nYou will also need localy placed NCBI NT database, which can be downloaded from NCBI ftp server."
print "\n\n"
parser = argparse.ArgumentParser(
description='Iterative Taxon Level Specific Blast')
parser.add_argument(
'-i',
'--db',
help='Dataset of sarting sequences in fasta format. MUST be in standard GenBank format (>gi|ginumber|gb|accession| ), or have the accession number followed by a space (>accession ), input filename',
required=True)
parser.add_argument(
'-dbnt',
'--path_to_nt',
help='Path to NCBI nt database, string',
required=True)
parser.add_argument(
'-dbsi',
'--path_to_ReferenceDB',
help='Path to Reference database, formated as DNA, string',
required=True)
parser.add_argument(
'-n',
'--num_seqs_per_round',
help='Number of sequences recovered per blast, integer',
required=True)
parser.add_argument(
'-p',
'--cpu',
help='Number of cpu cores used for blast, integer',
required=True)
parser.add_argument(
'-g',
'--group_name',
help='Name of taxon group to be sampled',
required=True)
parser.add_argument(
'-m',
'--nt_blast_method',
help='"megablast" or "blastn"',
required=True)
parser.add_argument(
'-idnt',
'--percent_identity_nt',
help='percent identity for blast hits against NT, float',
required=True)
parser.add_argument(
'-idsi',
'--percent_identity_ReferenceDB',
help='percent identity for blast hits against Reference DB, float',
required=True)
parser.add_argument(
'-td',
'--taxonomy_dict',
help='path to taxonomy dictionary - file tax_d.bin',
required=True)
args = parser.parse_args()
db = args.db
path_to_nt = args.path_to_nt
path_to_silva = args.path_to_ReferenceDB
num_seq_per_round = args.num_seqs_per_round
cpu = args.cpu
group_name = args.group_name
percent_id_nt = float(args.percent_identity_nt)
percent_id_silva = float(args.percent_identity_ReferenceDB)
blast_method = args.nt_blast_method
taxonomy_dict_file = args.taxonomy_dict
print db
print path_to_nt
print path_to_silva
print num_seq_per_round
print cpu
print group_name
# loads in the tax dictionary
tax_d = pickle.load(open('tax_d.bin', 'rb'))
Renaming_d = {}
os.system("usearch -makeudb_usearch Reference_DB.fas -output Reference_DB.udb")
os.system("usearch -makeudb_usearch gb203_pr2_all_10_28_97p_noorg.fasta -output gb203_pr2_all_10_28_97p_noorg.udb")
# runs blast against NT database
def nt_blast(query_file, num_seqs, outf):
OUTFORMAT = "6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore sscinames scomnames sblastnames sskingdoms"
os.system(
"blastn -task %s -query %s -db %s -num_threads %s -max_target_seqs %s -outfmt '%s' -out %s" %
(blast_method,
query_file,
path_to_nt,
str(cpu),
str(num_seqs),
OUTFORMAT,
outf))
infile = open(outf)
lines = infile.readlines()
infile.close()
acc = []
# this is the part that renames the seq.
for line in lines:
if float(line.split()[2]) >= float(percent_id_nt):
hit_column = line.split()[1]
acc.append(hit_column.split('|')[3])
Renaming_d[hit_column.split('|')[3]] = [line.split(
'\t')[-4], line.split('\t')[-2], line.split('\t')[-1]]
accset = set(acc)
return accset
def silva_blast(query_file, outf):
coord_dict = {}
os.system(
'usearch -usearch_local %s -db %s -strand both -maxhits 1 -id 0.8 -threads %s -blast6out %s' %
(query_file, path_to_silva, cpu, outf))
infile = open(outf)
lines = infile.readlines()
infile.close()
done = []
acc = []
for line in lines:
p_id = line.split()[2]
ac_hit = line.split()[1]
ac_hit = ac_hit.split('.')[0]
jaba = 0
if ac_hit not in done:
done.append(line.split('|')[3])
jaba = jaba + 1
if tax_d[ac_hit].count('Bacteria') > 0 or tax_d[
ac_hit].count('Archaea') > 0:
bad_hits[line.split('|')[0]] = 'This is bad hit'
# print ac_hit, 'bacteria'
elif float(p_id) > 95.0 and tax_d[ac_hit].count(group_name) == 0 and tax_d[ac_hit] not in allowed:
# print 'bad hit'
bad_hits[line.split('|')[3]] = 'This is bad hit'
# print tax_d[ac_hit]
# print ac_hit
elif float(p_id) < float(percent_id_silva):
bad_hits[line.split('|')[3]] = 'This is bad hit'
# print ac_hit
# print float(p_id)
else:
coord_dict[line.split('|')[3]] = (
line.split()[6], line.split()[7])
acc.append(line.split('|')[3])
# print acc
# print len(acc)
return (acc, coord_dict)
# print confusing_sequences
# print len(bad_hits)
# load fasta file into dictionary
def load_fasta_file(fname):
infile = open(fname)
line = infile.read()
infile.close()
seqs = line[1:].split('\n>')
d = {}
for seq in seqs:
d[seq.split('\n')[0]] = ''.join(seq.split('\n')[1:])
return d
# removes sequences shorter than 500 bp in length. At end of run prints accessions of short seqs to short_seqs_acc.txt
def trim_short_seqs(fnamein, fnameout, length):
d = load_fasta_file(fnamein)
out = open(fnameout, 'w')
#print d
for i in d:
if i != '':
if len(d[i]) > int(length) and len(d[i]) < 5000:
out.write('>%s\n%s\n' % (i, d[i]))
else:
shortout.write('%s\n' % (i.split('|')[3]))
# makes_empt_dict of accession numbers in fasta file
def make_ac_dict(fname):
d = {}
infile = open(fname)
line = infile.read()
infile.close()
seqs = line[1:].split('\n>')
for seq in seqs:
d[seq.split('|')[3]] = ''
#print d
return d
# run uchime to search for chimeric seqs.
def run_uchime(fnamein, fnameout):
whynot = open(fnamein, 'r')
line = whynot.read()
whynot.close()
d = {}
seqs = line[1:].split('\n>')
#print seqs
out = open('temp_chime_in.fas', 'w')
for seq in seqs:
d[seq.split('|')[3]] = seq
out.write(
'>%s;size=1;\n%s\n' %
(seq.split('|')[3],
''.join(
seq.split('\n')[
1:])))
out.close()
os.system('usearch -uchime_ref temp_chime_in.fas -db %s -nonchimeras temp_no_chimeras.fas -chimeras temp_chimeras.fas -strand plus' % (path_to_silva))
infile = open('temp_no_chimeras.fas')
line = infile.read()
infile.close()
seqs = line[1:].split('\n>')
out = open(fnameout, 'w')
#print seqs
if line.count('>') != 0:
for seq in seqs:
out.write('>%s\n' % (d[seq.split(';')[0]]))
else:
pass
try:
infile = open('temp_chimera.fas')
line = infile.read()
infile.close()
seqs = line[1:].split('\n>')
for seq in seqs:
chimeraout.write('%s\n' % (seq.split('|')[3]))
os.system('rm temp_chime_in.fas temp_chimeras.fas temp_no_chimeras.fas')
except IOError:
pass
out.close()
# function for outputting a list of all accessions to be used further.
def out_accessions(infile, out_fasta_file, out_accessions_file):
out_acc = open(out_accessions_file, 'w')
out_fasta = open(out_fasta_file, 'w')
current_DB = open(infile, "U").read()
seqs = current_DB[1:].split('\n>')
seq_d = {}
for seq in seqs:
if seq.count('|') != 0:
acc = seq.split('|')[3]
clean_acc = re.sub(r'\.[1-9]', '', acc)
seq_d[clean_acc] = ''.join(seq.split('\n')[1:])
else:
acc = seq.split()[0]
clean_acc = re.sub(r'\.[1-9]', '', acc)
seq_d[clean_acc] = ''.join(seq.split('\n')[1:])
for i in seq_d:
out_fasta.write(">%s\n%s\n" % (i, seq_d[i]))
out_acc.write("%s\n" % (i))
# lines = seq.split('\n')
# rest_of_seq = '\n'.join(lines[1:])
# for line in lines:
# if line.startswith(">"):
# line = line.split(">")[1]
# try:
# # find the accession from GenBank format
# acc = line.split('|')[3]
# clean_acc = re.sub(r'\.[1-9]', '', acc)
# if clean_acc in accessions:
# next
# else:
# accessions.append(clean_acc)
# out_acc.write("%s\n" % (clean_acc))
#
# out_fasta.write(">%s\n%s" % (clean_acc, rest_of_seq))
# except IndexError:
# # if not in old genbank format assume in form of >accession.1 other info, with a space delimiter
# acc = seq.split()[0]
# clean_acc = re.sub(r'\.[1-9]', '', acc)
# if clean_acc in accessions:
# next
# else:
# accessions.append(clean_acc)
# out_acc.write("%s\n" % (clean_acc))
# out_fasta.write(">%s\n%s" % (clean_acc, rest_of_seq))
# ###################################################################
# ######################### SCRIPT ITSELF ###########################
# ###################################################################
shortout = open('short_seqs_acc.txt', 'w')
chimeraout = open('chimera_seqs_acc.txt', 'w')
bad_hits = {}
allowed = []
confusing_sequences = []
# ###################### Analyze initial DB #########################
# Format New Sequences
infile = open(db)
line = infile.read()
infile.close()
acc_count = 0
out = open('%s_reformated' % (db), 'w')
seqs = line[1:].split('\n>')
for seq in seqs:
try:
ac = seq.split('|')[3]
out.write('>%s\n' % (seq))
except IndexError:
# if not in old genbank format assume in form of >accession.1 other info, with a space delimiter
accession = seq.split()[0]
print '>gi|nogi|gb|%s\n' % (accession)
sequence = ''.join(seq.split('\n')[1:])
out.write('>gi|noginumber|gb|%s|\n%s\n' % (accession, sequence))
acc_count = acc_count + 1
out.close()
os.system('cp %s %s_old_version' % (db, db))
#os.system('cp %s_reformated %s' % (db, db))
os.system('cp %s_reformated current_DB.fas' % (db))
print 'Runing uchime on initial fasta file'
run_uchime('current_DB.fas', 'temp_initial_db.fas')
print 'Removing short sequences from initial fasta file'
trim_short_seqs('temp_initial_db.fas', 'new_round.fas', 500)
# counter of cycles
c = 0
db_dict = load_fasta_file(db)
# ###################### Start Cycling DB #########################
while True:
c = c + 1
print 'starting cycle %s' % (int(c))
# run usearch
print 'running usearch'
os.system('usearch -sortbylength new_round.fas -fastaout DB.sorted.fas -minseqlength 64')
os.system('usearch -cluster_smallmem DB.sorted.fas -id 0.97 -centroids temp_DB_clust.fas -uc temp_DB_clust.uc')
# remove seqs shorter 500
# trim_short_seqs('temp_DB_clust.fas', 'temp_DB_clust_500.fas', 500)
# print 'removing short sequences'
# remove species that are already in the database
print 'running blast'
hits_acs = nt_blast(
'temp_DB_clust.fas',
num_seq_per_round,
'temp_DB_clust_500.blastntab')
# remove_repeats when compared to current_DB.fas
dict_existing = make_ac_dict('current_DB.fas')
hits_acs2 = list(hits_acs)
for i in hits_acs2:
try:
yup = dict_existing[i]
hits_acs.remove(i)
except KeyError:
pass
#print len(hits_acs)
# remove repeated BAD hits
for i in hits_acs2:
try:
yup = bad_hits[i]
hits_acs.remove(i)
except KeyError:
pass
#print len(hits_acs)
# Kill cycle if no new sequences
if len(hits_acs) == 0:
print 'NO NEW SEQUENCES'
break
# Keep running next cycle
else:
# write accessions into text file
out = open('temp_to_get_acs.txt', 'w')
for i in hits_acs:
out.write('%s\n' % (i))
out.close()
# recover fasta file for accessions
os.system(
'blastdbcmd -entry_batch temp_to_get_acs.txt -db %s -out temp_results.fas' %
(path_to_nt))
trim_short_seqs('temp_results.fas', 'temp_results_500.fas', 500)
# blast against Silva remove <70%ID and >95%ID other groups, This returns
# accession numbers
print 'blasting against SILVA'
silva_blast_results = silva_blast(
'temp_results_500.fas', 'temp_results.silvatab')
silva_parsed_acs = silva_blast_results[0]
silva_coord_dict = silva_blast_results[1]
#print silva_coord_dict
# Write the accession numbers into text file
if silva_parsed_acs != []:
out = open('temp_to_get_acs.txt', 'w')
for i in silva_parsed_acs:
out.write('%s\n' % (i))
out.close()
# pull passed sequences from the NCBI db
os.system(
'blastdbcmd -entry_batch temp_to_get_acs.txt -db %s -out temp_results_silva_untrimmed.fas' %
(path_to_nt))
# run uchime
# Trim sequences based on best hit
infile = open('temp_results_silva_untrimmed.fas')
line = infile.read()
infile.close()
out = open('temp_results_silva.fas', 'w')
seqs = line[1:].split('\n>')
for i in seqs:
new_seq = ''.join(i.split('\n')[1:])
hit_len = int(silva_coord_dict[i.split('|')[3]][
0]) - int(silva_coord_dict[i.split('|')[3]][1])
#print hit_len
if hit_len > 0:
if float(hit_len) / float(len(new_seq)) < 0.8:
new_seq = new_seq[int(silva_coord_dict[i.split('|')[3]][0]):int(
silva_coord_dict[i.split('|')[3]][1])]
else:
new_seq = new_seq
elif hit_len < 0:
#print -float(hit_len) / float(len(new_seq))
if -float(hit_len) / float(len(new_seq)) < 0.8:
#print new_seq
new_seq = new_seq[int(silva_coord_dict[i.split('|')[3]][0]):int(
silva_coord_dict[i.split('|')[3]][1])]
#print new_seq
else:
new_seq = new_seq
out.write('>%s\n%s\n' % (i.split('\n')[0], new_seq))
out.close()
prdel = open('temp_results_silva.fas')
run_uchime(
'temp_results_silva.fas',
'temp_results_silva_uchime.fas')
prdel = open('temp_results_silva.fas')
# remove short sequences
trim_short_seqs(
'temp_results_silva_uchime.fas',
'temp_results_silva_uchime_500.fas',
500)
# merge new sequences with old database
os.system(
'cat current_DB.fas temp_results_silva_uchime_500.fas > new_DB.fas')
os.system('mv new_DB.fas current_DB.fas')
# restart cycle with new sequences
os.system('mv temp_results_silva_uchime_500.fas new_round.fas')
# remove temporary files - move to ne folder
os.system('mkdir cycle_%s' % (c))
os.system('mv temp* cycle_%s' % (c))
os.system('cp current_DB.fas cycle_%s' % (c))
# check there are new sequences left
infile = open('new_round.fas')
line = infile.read()
infile.close()
if line == '':
break
else:
break
# run function to rename sequences in output fasta file
#rename_sequences('current_DB.fas', 'current_DB_tree_names.fas')
# run function to output a list of accessions in the final DB
out_accessions('current_DB.fas', 'current_DB_final.fas', 'accessions_current_DB.txt')
# ####### TO ADD #########
# re-recover short seqs
# re-recover chimera seqs
# deal with Genome sequences
# add gi restricted blast to remove the already removed seqs - not it is
# little clumsy
<file_sep>#!/usr/bin/env python
print "\nScript for parsing GenBank metadata and renaming fasta file for annotation."
#print "Contributors: <NAME> and <NAME>"
#print "22 November 2016"
print "\nrun: python eukref_gbmetadata.py -h for help.\n"
import os
import argparse
import re
from Bio import SeqIO
from Bio.Blast import NCBIXML
parser = argparse.ArgumentParser(
description='Rename fasta sequences and create metadata text file for FigTree annotation')
parser.add_argument(
'-gb',
'--input_gb_file_fp',
help='Path to GenBank formatted file with accessions to be renamed. Get this file from the NCBI nucleotide database online (see pipeline overview)',
required=False)
parser.add_argument(
'-t',
'--ref_tax',
help='Path to reference database taxonomy file formatted accession \t taxonomy. E.g. SIVLA 128 full taxa map file. Reference database taxonomy will be added to the metadata file',
required=False)
parser.add_argument(
'-i',
'--input_fasta_file_fp',
help='Path to Fasta file to be renamed. May be current_DB.fas, current_DB.clustered.fas, or other. Header MUST either be 1) in standard GenBank format (e.g. >gi|ginumber|gb|accession| ) or 2) begin with the accession number. Get this file from the NCBI nucleotide database online (see pipeline overview)',
required=False)
parser.add_argument(
'--outgroup',
help='Path to Fasta file with outgroups.',
required=False)
parser.add_argument(
'-o',
'--output_fasta_file_fp',
help='Path to output fasta file',
required=False)
parser.add_argument(
'-m',
'--output_metadata_fp',
help='Output metadata file in tab delimited format',
required=False)
args = parser.parse_args()
ref_tax = args.ref_tax
input_gb_file_fp = args.input_gb_file_fp
input_fasta_file_fp = args.input_fasta_file_fp
outgroup = args.outgroup
output_fasta_file_fp = args.output_fasta_file_fp
output_metadata_fp = args.output_metadata_fp
outfasta = open(output_fasta_file_fp, "w")
outmeta = open(output_metadata_fp, "w")
##############################
#### function definitions ####
##############################
# function just loops through outgroup fasta file and adds OUTGROUP to line. writes to outfile.
def rename_outgroup(infile, outfile):
for line in open(infile, "U"):
if line.startswith(">"):
line = line.replace(">" , ">OUTGROUP__")
outfile.write(line)
else:
outfile.write(line)
# function to print metadata in tab delimited format based on gb formatted input file.
# version if SILVA or PR2 reference taxonomy file passed
def metadata_retrieve_ref(infile, outfile, ref_accessions):
# original script from here
OUT = outmeta
OUT.write("Accession\tTaxonomy\tReference_taxonomy\tOrganism\tclone\tSource\tEnvironment\tHost\tCountry\tPublication\tAuthors\tJournal\n")
result_handle = open(infile, "U")
# array to make sure each accession is uniq.
uniq_acc = []
gbfiles = SeqIO.parse(result_handle, 'gb')
for rec in gbfiles:
acc = rec.id
# strip off .1 from accessions
clean_acc = re.sub(r'\.[1-9]', '', acc)
#if already have seen accession move onto next record. Else append accession to uniq_acc list and
if clean_acc in uniq_acc:
next
else:
uniq_acc.append(clean_acc)
#default = 'NA'
#reference_taxonomy = ref_accessions.get('clean_acc', default)
if clean_acc in ref_accessions:
reference_taxonomy = ref_accessions[clean_acc]
else:
reference_taxonomy = 'NA'
source = rec.features[0]
if 'taxonomy' in rec.annotations:
taxonomy = ";".join(rec.annotations['taxonomy'])
else:
taxonomy = "NA"
if 'organism' in rec.annotations:
organism = rec.annotations['organism']
else:
organism = "NA"
if 'clone' in source.qualifiers:
clone = source.qualifiers['clone'][0]
else:
clone = "NA"
if 'environmental_sample' in source.qualifiers:
environmental_sample = "Environmental"
else:
environmental_sample = "Isolate"
if 'isolation_source' in source.qualifiers:
isolation_source = source.qualifiers['isolation_source'][0]
else:
isolation_source = "NA"
if 'host' in source.qualifiers:
host = source.qualifiers['host'][0]
else:
host = "NA"
if 'country' in source.qualifiers:
country = source.qualifiers['country'][0]
else:
country = "NA"
if 'references' in rec.annotations:
pubref = rec.annotations['references'][0]
authors = pubref.authors
title = pubref.title
journal = pubref.journal
else:
title = "NA"
authors = "NA"
journal = "NA"
fields = [clean_acc, taxonomy, reference_taxonomy, organism, clone, environmental_sample, isolation_source, host, country, title, authors, journal]
OUT.write("\t".join(fields)+ "\n")
OUT.close()
# function to print metadata in tab delimited format based on gb formatted input file.
def metadata_retrieve(infile, outfile):
accessions = {}
# original script from here
OUT = outmeta
OUT.write("Accession\tTaxonomy\tOrganism\tclone\tSource\tEnvironment\tHost\tCountry\tPublication\tAuthors\tJournal\n")
result_handle = open(infile, "U")
uniq_acc = []
gbfiles = SeqIO.parse(result_handle, 'gb')
for rec in gbfiles:
acc = rec.id
# need to make sure each accession is unique.
# strip off .1 from accessions
clean_acc = re.sub(r'\.[1-9]', '', acc)
#if already have seen accession move onto next record. Else append accession to uniq_acc list and
if clean_acc in uniq_acc:
next
else:
uniq_acc.append(clean_acc)
source = rec.features[0]
if 'taxonomy' in rec.annotations:
taxonomy = ";".join(rec.annotations['taxonomy'])
else:
taxonomy = "NA"
if 'organism' in rec.annotations:
organism = rec.annotations['organism']
else:
organism = "NA"
if 'clone' in source.qualifiers:
clone = source.qualifiers['clone'][0]
else:
clone = "NA"
if 'environmental_sample' in source.qualifiers:
environmental_sample = "Environmental"
else:
environmental_sample = "Isolate"
if 'isolation_source' in source.qualifiers:
isolation_source = source.qualifiers['isolation_source'][0]
else:
isolation_source = "NA"
if 'host' in source.qualifiers:
host = source.qualifiers['host'][0]
else:
host = "NA"
if 'country' in source.qualifiers:
country = source.qualifiers['country'][0]
else:
country = "NA"
if 'references' in rec.annotations:
pubref = rec.annotations['references'][0]
authors = pubref.authors
title = pubref.title
journal = pubref.journal
else:
title = "NA"
authors = "NA"
journal = "NA"
fields = [clean_acc, taxonomy, organism, clone, environmental_sample, isolation_source, host, country, title, authors, journal]
OUT.write("\t".join(fields)+ "\n")
OUT.close()
def rename_sequences_ref(in_gb, infile, ref_acc, outfile):
# initialize gb_tax dict to store accession, last taxonomy level, and organism name
gb_tax = {}
#result_handle = open(in_gb, "U")
# parse gb file; block to go through gb file for acc not in ref
gbfiles = SeqIO.parse(in_gb, 'gb')
# make dict of acc, last level, organism
for rec in gbfiles:
acc = rec.id
clean_acc = re.sub(r'\.[1-9]', '', acc)
#print clean_acc
if clean_acc in ref_acc:
next
else:
if 'organism' in rec.annotations:
organism = rec.annotations['organism']
#if the taxonomy string exists but is empty
if not rec.annotations['taxonomy']:
name = organism
name = name.replace(" ", "_")
#print name
#print organism
gb_tax[clean_acc] = name
elif 'taxonomy' in rec.annotations:
# get last level of taxonomy
taxonomy = rec.annotations['taxonomy']
# add accession plus last taxonomy level and organism name to tax dict
name = taxonomy[-1]+"_"+ organism
#if the taxonomy is just absent entirely
elif 'taxonomy' not in rec.annotations:
name = organism
name = name.replace(" ", "_")
gb_tax[clean_acc] = name
# go through fasta file. Match accessions first to reference taxonomy (ref_acc) then to gb_tax
for line in open(infile, "U"):
if line.startswith(">"):
#seq_acc = None
if "_" in line:
seq_acc = line.split("_")[0]
seq_acc = seq_acc.replace(">", "")
# case of old gb format with >gi|noginumber|gb|KT210044
elif "|" in line:
acc = seq.split('|')[3]
seq_acc = re.sub(r'\.[1-9]', '', acc)
seq_acc = seq_acc.replace(">", "")
# case of just accession # in header, or accession followed by white space
else:
seq_acc = line.split()[0]
seq_acc = seq_acc.replace(">", "")
if seq_acc in ref_acc:
taxonomy = ref_acc[seq_acc]
#name = None
if "; __" in taxonomy:
last_level = taxonomy.split("; __")
name = '_'.join(last_level[-2:])
#tax[seq_acc] = '_'.join(last_level[-2:-1])
else:
last_level = taxonomy.split(";")
name = '_'.join(last_level[-2:])
outfile.write(">%s_%s\n" % (seq_acc,name))
elif seq_acc in gb_tax:
outfile.write(">%s_%s\n" % (seq_acc, gb_tax[seq_acc]))
# incase accession is missing.
else:
outfile.write("%s\n" % (line.strip()))
else:
outfile.write("%s\n" % (line.strip()))
# ###################################################################
# ######################### SCRIPT ITSELF ###########################
# ###################################################################
# Make dict of silva taxonomy (or PR2) if provided.
# how to handle SILVA? read whole taxonomy file into dictionary with key, value as accession, taxonomy?
# Maybe here only want to make a dict of accession and whole taxonomy. do not split unless necessary.
ref_accessions = {}
if args.ref_tax is not None:
for line in open(ref_tax, "U"):
# split by \t
acc = line.strip().split('\t')
ref_accessions[acc[0]] = acc[1]
#print ref_accessions[acc[0]]
# run eukref_gbmetadata.py version that also reports reference taxonomy if given gb file AND given reference taxonomy file (e.g. Silva taxonomy file)
if args.input_gb_file_fp is not None and args.ref_tax is not None:
# accessions is a dictionary of accessions in file (with name?)
metadata_retrieve_ref(input_gb_file_fp, outmeta, ref_accessions)
#run eukref_gbmetadata.py if gb file given.
if args.input_gb_file_fp is not None and args.ref_tax is None:
metadata_retrieve(input_gb_file_fp, outmeta)
print "metadata file is %s" % (outmeta)
if args.outgroup is not None:
# run outgroup renaming and write outgroup seqs to outfile
rename_outgroup(outgroup, outfasta)
# doesn't really make sense to only use ref info - should also use gb record.
if args.input_fasta_file_fp is not None and args.ref_tax is not None and args.input_gb_file_fp is not None:
# need to make this function
rename_sequences_ref(input_gb_file_fp, input_fasta_file_fp, ref_accessions, outfasta)
print "fasta file for tree is %s" % (outfasta)
outfasta.close()
outmeta.close()
| 646bf6b8c76bcf74b2b5cb53893ba6c43e5365e0 | [
"Python"
] | 2 | Python | tarunaaggarwal/eukref | bd898be44e04c558dfce7d62e666c3553dbdd900 | 401dc4597fdb40888fed4d7a8a690ddff3a6df37 |
refs/heads/master | <repo_name>Malyarc/csgo-skin-market-script<file_sep>/test.js
const rifles = require('./rifles.js')
const csgomarket = require('steam-market-pricing');
var awp_skins = Object.keys(rifles.awp);
// console.log(awp_skins.length);
// console.log(awp_skins);
const factory_new_names = [];
const minimal_wear_names = [];
const field_tested_names = [];
const well_worn_names = [];
const battle_scarred_names = [];
const stattrack_factory_new_names = [];
const stattrack_minimal_wear_names = [];
const stattrack_field_tested_names = [];
const stattrack_well_worn_names = [];
const stattrack_battle_scarred_names = [];
// csgomarket.getItemPrice(730, 'StatTrak™ Desert Eagle | Crimson Web (Minimal Wear)').then(item => console.log(item));
for (var i = 0; i < awp_skins.length; i ++) {
factory_new_names.push(`AWP | ${awp_skins[i]} (Factory New)`);
stattrack_factory_new_names.push(`StatTrak™ AWP | ${awp_skins[i]} (Factory New)`);
minimal_wear_names.push(`AWP | ${awp_skins[i]} (Minimal Wear)`);
stattrack_minimal_wear_names.push(`StatTrak™ AWP | ${awp_skins[i]} (Minimal Wear)`);
field_tested_names.push(`AWP | ${awp_skins[i]} (Field-Tested)`);
stattrack_field_tested_names.push(`StatTrak™ AWP | ${awp_skins[i]} (Field-Tested)`);
well_worn_names.push(`AWP | ${awp_skins[i]} (Well-Worn)`);
stattrack_well_worn_names.push(`StatTrak™ AWP | ${awp_skins[i]} (Well-Worn)`);
battle_scarred_names.push(`AWP | ${awp_skins[i]} (Battle-Scarred)`);
stattrack_battle_scarred_names.push(`StatTrak™ AWP | ${awp_skins[i]} (Battle-Scarred)`);
}
csgomarket.getItemsPrices(730, factory_new_names).then(items => factory_new_names.forEach(name => console.log(`${name}: ${items[name].median_price}`)));
csgomarket.getItemsPrices(730, stattrack_factory_new_names).then(items => stattrack_factory_new_names.forEach(name => console.log(`${name}: ${items[name].median_price}`)));
csgomarket.getItemsPrices(730, minimal_wear_names).then(items => minimal_wear_names.forEach(name => console.log(`${name}: ${items[name].median_price}`)));
csgomarket.getItemsPrices(730, stattrack_minimal_wear_names).then(items => stattrack_minimal_wear_names.forEach(name => console.log(`${name}: ${items[name].median_price}`)));
csgomarket.getItemsPrices(730, field_tested_names).then(items => field_tested_names.forEach(name => console.log(`${name}: ${items[name].median_price}`)));
csgomarket.getItemsPrices(730, stattrack_field_tested_names).then(items => stattrack_field_tested_names.forEach(name => console.log(`${name}: ${items[name].median_price}`)));
csgomarket.getItemsPrices(730, well_worn_names).then(items => well_worn_names.forEach(name => console.log(`${name}: ${items[name].median_price}`)));
csgomarket.getItemsPrices(730, stattrack_well_worn_names).then(items => stattrack_well_worn_names.forEach(name => console.log(`${name}: ${items[name].median_price}`)));
csgomarket.getItemsPrices(730, battle_scarred_names).then(items => battle_scarred_names.forEach(name => console.log(`${name}: ${items[name].median_price}`)));
csgomarket.getItemsPrices(730, stattrack_battle_scarred_names).then(items => stattrack_battle_scarred_names.forEach(name => console.log(`${name}: ${items[name].median_price}`)));
// for (var i = 0; i < awp_skins.length; i ++) {
// csgomarket.getItemPrice(730, `AWP | ${awp_skins[i]} (Minimal Wear)`).then(item => console.log(item));
// }
<file_sep>/rifles.js
const awp = {
"Acheron" : "The 2018 Nuke Collection",
"Asiimov" : "Operation Phoenix Weapon Case",
"Atheris" : "Prisma Case",
"BOOM" : "eSports 2013 Case",
"Capillary" : "Prisma 2 Case",
"Containment Breach" : "Shattered Web Case",
"Corticera" : "eSports 2014 Summer Case",
"Dragon Lore" : "The Cobblestone Collection",
"Electric Hive" : "eSports 2013 Winter Case",
"Elite Build" : "Operation Wildfire Case",
"Fever Dream" : "Spectrum Case",
"Graphite" : "Operation Bravo Case",
"Gungnir" : "The Norse Collection",
"Hyper Beast" : "Falchion Case",
"Lightning Strike" : "CS:GO Weapon Case",
"Man-o-war" : "Chroma Case",
"Medusa" : "The Gods and Monsters Collection",
"Mortis" : "Clutch Case",
"Neo-Noir" : "Danger Zone Case",
"Oni Taiji" : "Operation Hydra Case",
"Phobos" : "Gamma Case",
"Pink DDPAT" : "The Overpass Collection",
"Pit Viper" : "The Italy Collection",
"Redline" : "Winter Offensive Weapon Case",
"Safari Mesh" : "The Lake Collection",
"Snake Camo" :"The Dust Collection",
"Sun in Leo" : "The Gods and Monsters Collection",
"The Prince" : "The Canals Collection",
"Wildfire" : "CS20 Case",
"Worm God" : "Chroma 2 Case",
}
// console.log(Object.keys(awp))
console.log(Object.keys(awp).length)
module.exports.awp = awp; | c805d045f2202bf0510a5ea3f55d819ac7381ec6 | [
"JavaScript"
] | 2 | JavaScript | Malyarc/csgo-skin-market-script | cd221b9f924debfdafface210a36d5ce04d046bf | b5667ced9df136b8be695d671734e65ebcb6453b |
refs/heads/master | <repo_name>amitamorshi/wellcare_assignment_clients-<file_sep>/src/main/resources/application-cloud.properties
eureka.instance.hostname={vcap.application.urlz[0]:localhost}
eureka.instance.nonSecurePort=80
eureka.client.region=default
eurekha.client.registryFetchIntervalSeconds= 5
eurekha.client.serviceUrl.defaulZone=http://${eureka.instance.hostname}:${server.port}/eureka/
<file_sep>/src/main/java/io/wellcare/controllers/EnrolleeController.java
package io.wellcare.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.wellcare.model.Enrollee;
import io.wellcare.service.EnrolleeService;
import java.util.List;
@RestController
@RequestMapping("/Enrollee")
public class EnrolleeController {
@Autowired
EnrolleeService enrolleeService;
@RequestMapping("/all")
public List<Enrollee> retrieveAllEnrolles() {
return enrolleeService.getEnrolless();
}
@PostMapping("/enrollee")
public void add(@RequestBody Enrollee enrollee) {
enrolleeService.addOrmodifyEnrollee(enrollee);
}
}
<file_sep>/src/main/java/io/wellcare/model/Dependent.java
package io.wellcare.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "dependent")
public class Dependent implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private Date birthdate;
@ManyToOne
@JoinColumn(name = "enrollee_id", nullable = false)
private Enrollee enrollee;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
@Override
public String toString() {
return "Dependent [id=" + id + ", name=" + name + ", birthdate=" + birthdate + "]";
}
public Enrollee getEnrollee() {
return enrollee;
}
public void setEnrollee(Enrollee e) {
this.enrollee = e;
}
}
<file_sep>/src/main/java/io/wellcare/appstarter/WellcareApp.java
package io.wellcare.appstarter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EnableDiscoveryClient
@SpringBootApplication
@ComponentScan({"io.wellcare.*"})
@EnableJpaRepositories("io.wellcare.repository")
@EntityScan("io.wellcare.model")
public class WellcareApp {
public static void main(String[] arg) {
SpringApplication.run(WellcareApp.class, arg);
}
}
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wellcare.enrollee</groupId>
<artifactId>wellcare-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Wellcare</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath />
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!--MYSQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
</dependencies>
</project> | ff7de6f283ab07c200afa0c29cda6ef4aa5b9d71 | [
"Java",
"Maven POM",
"INI"
] | 5 | INI | amitamorshi/wellcare_assignment_clients- | b24383c3ef8f252e4cc02e2afde719155019c0b0 | c7dc9fac4e700cdb083a4ba93d0350bd47e275a7 |
refs/heads/master | <file_sep>Github Jobs
===========
Screenshots




* Github Jobs android application use GitHub Jobs API to search, and view jobs.
* Application user can search jobs by job title, company name, location, and type.
* To build the project, run the command
```groovy
gradle clean build
```
* The command will generate the apk file under app/build/outputs/apk
* Third party libraries have been used, namely: Volley - HTTP library for Android, and GSON for converting JSON String to Java objects.
* AppCompat support library of android have been used for supporting ActionBar to a wide-range of Android versions and provide APIs to lower versions.
<file_sep>package com.githubjobs.android.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.githubjobs.android.R;
import com.githubjobs.android.entity.Job;
import com.githubjobs.android.network.RequestCreator;
import com.githubjobs.android.views.ViewUtil;
public class JobDetailsFgmt extends Fragment {
private static final String TAG = JobDetailsFgmt.class.getSimpleName();
private View v;
private ImageView iv;
private TextView tvTitle, tvCompany, tvType, tvLocation,
tvDesc, tvHowToApply, tvLink;
private Job job;
public void setJob(Job job) {
this.job = job;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fgmt_jobdetails, container, false);
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
iv = (ImageView) v.findViewById(R.id.fgmt_jobdetails_iv);
tvTitle = (TextView) v.findViewById(R.id.fgmt_jobdetails_tv_title);
tvCompany = (TextView) v.findViewById(R.id.fgmt_jobdetails_tv_company_name);
tvType = (TextView) v.findViewById(R.id.fgmt_jobdetails_tv_type);
tvLocation = (TextView) v.findViewById(R.id.fgmt_jobdetails_tv_location);
tvDesc = (TextView) v.findViewById(R.id.fgmt_jobdetails_tv_description);
tvHowToApply = (TextView) v.findViewById(R.id.fgmt_jobdetails_tv_how_to_apply);
tvLink = (TextView) v.findViewById(R.id.fgmt_jobdetails_tv_link);
initViews();
}
@Override
public void onResume() {
super.onResume();
AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity();
ActionBar ab = appCompatActivity.getSupportActionBar();
ab.setDisplayShowHomeEnabled(true);
ab.setDisplayHomeAsUpEnabled(true);
ab.setTitle(getActivity().getResources().getString(R.string.fgmt_jobdetails_ab_title));
}
// Initialize view values
private void initViews() {
RequestCreator.loadImage(getActivity(), job.getCompanyLogo(), iv);
tvTitle.setText(job.getTitle());
tvCompany.setText(job.getCompany());
tvType.setText(job.getType().getDescription());
tvLocation.setText(job.getLocation());
// Trim the returned Spanned returned of Html.fromHtml as it adds new line at the end
String description = job.getDescription().trim();
tvDesc.setText(ViewUtil.convertHtmlToTextFormat(description).toString().trim());
String howToApply = job.getHowToApply().trim();
tvHowToApply.setText(ViewUtil.convertHtmlToTextFormat(howToApply).toString().trim());
tvLink.setText(job.getUrl());
}
}
<file_sep>package com.githubjobs.android;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static junit.framework.Assert.assertNotNull;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(AndroidJUnit4.class)
public class GithubJobsAppTest {
/**
* The name 'test preconditions' is a convention to signal that if this
* test doesn't pass, the test case was not set up properly and it might
* explain any and all failures in other tests. This is not guaranteed
* to run before other tests, as junit uses reflection to find the tests.
*/
@SmallTest
public void testPreConditions() {
}
@Test
public void testCorrectVersion() throws Exception {
// Context of the app under test.
Context application = InstrumentationRegistry.getTargetContext();
PackageInfo info = application.getPackageManager()
.getPackageInfo(application.getPackageName(), 0);
assertNotNull(info);
assertThat("Expected result matches regular expression for app version naming",
info.versionName.matches("\\d\\.\\d\\.\\d"),
is(true));
}
}<file_sep>package com.githubjobs.android.entity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class JobTest {
private static final String JOB_JSON_FILENAME = "sample-job.json";
private static final String JOBLIST_JSON_FILENAME = "sample-job-list.json";
private static Gson gson;
@BeforeClass
public static void setUp() {
gson = new GsonBuilder().setPrettyPrinting().create();
}
@AfterClass
public static void tearDown() {
gson = null;
}
@Test
public void testJsonToJob() throws Exception {
JsonReader reader = new JsonReader(new FileReader(getJobJson()));
Job job = gson.fromJson(reader, Job.class);
assertNotNull("Job object should not be null", job);
assertEquals("Parsed JSON String not equals not Job id",
job.getId(), "da05e006-028b-11e6-98d3-5b3b448add54");
}
@Test
public void testJobToJson() throws Exception {
JsonReader reader = new JsonReader(new FileReader(getJobJson()));
Job job = gson.fromJson(reader, Job.class);
String jsonStr = gson.toJson(job);
assertNotNull("JSON String Job should not be null", jsonStr);
assertTrue("JSON String Job should not be empty", !jsonStr.isEmpty());
}
@Test
public void testJsonToJobArray() throws Exception {
JsonReader reader = new JsonReader(new FileReader(getJobListJson()));
ArrayList<Job> arr = gson.fromJson(reader, new TypeToken<List<Job>>() {}.getType());
assertTrue("Job list array should not be empty", !arr.isEmpty());
}
@Test
public void testJobArrayToJson() throws Exception {
JsonReader reader = new JsonReader(new FileReader(getJobListJson()));
ArrayList<Job> arr = gson.fromJson(reader, new TypeToken<List<Job>>() {}.getType());
String jsonArrStr = gson.toJson(arr, new TypeToken<List<Job>>() {}.getType());
assertNotNull("JSON String Job should not be null", jsonArrStr);
assertTrue("JSON String Job should not be empty", !jsonArrStr.isEmpty());
}
private File getJobJson() {
URL location = this.getClass().getResource(JOB_JSON_FILENAME);
String fullPath = location.getPath();
return new File(fullPath);
}
private File getJobListJson() {
URL location = this.getClass().getResource(JOBLIST_JSON_FILENAME);
String fullPath = location.getPath();
return new File(fullPath);
}
}
<file_sep>package com.githubjobs.android.views;
import android.app.Activity;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class ViewUtil {
/** Hide soft input keyboard */
public static void hideKeybord(View view, Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.RESULT_UNCHANGED_SHOWN);
}
/** Convert HTML value to spanned text representation */
public static Spanned convertHtmlToTextFormat(String htmlValue) {
Spanned textValue;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
textValue = Html.fromHtml(htmlValue, Html.FROM_HTML_MODE_LEGACY);
} else {
textValue = Html.fromHtml(htmlValue);
}
return textValue;
}
}
<file_sep>package com.githubjobs.android.entity;
import com.google.gson.annotations.SerializedName;
public enum JobType {
@SerializedName("Full Time")
FULL_TIME("Full Time"),
@SerializedName("Part Time")
PART_TIME("Part Time");
private final String description;
private JobType(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
<file_sep>package com.githubjobs.android.fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatCheckBox;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.githubjobs.android.MainActivity;
import com.githubjobs.android.views.ViewUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.githubjobs.android.R;
import com.githubjobs.android.entity.Job;
import com.githubjobs.android.network.HttpManager;
import com.githubjobs.android.network.RequestCreator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class JobSearchFgmt extends Fragment {
private static final String TAG = JobListFgmt.class.getName();
private View v;
private EditText etTitle, etCompany, etLocation;
private AppCompatCheckBox cbFulltime, cbParttime;
private Button btnSearch;
private ProgressDialog pgDlg;
private HttpManager httpMngr;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
httpMngr = HttpManager.getInstance(getActivity());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fgmt_jobsearch, container, false);
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
etTitle = (EditText) v.findViewById(R.id.fgmt_jobsearch_et_title);
etCompany = (EditText) v.findViewById(R.id.fgmt_jobsearch_et_company);
etLocation = (EditText) v.findViewById(R.id.fgmt_jobsearch_et_location);
cbFulltime = (AppCompatCheckBox) v.findViewById(R.id.fgmt_jobsearch_cb_fulltime);
cbParttime = (AppCompatCheckBox) v.findViewById(R.id.fgmt_jobsearch_cb_parttime);
btnSearch = (Button) v.findViewById(R.id.fgmt_joblist_btn_search);
pgDlg = new ProgressDialog(getActivity());
pgDlg.setMessage(getActivity().getResources()
.getString(R.string.progress_msg_jobsearch));
initViews();
}
@Override
public void onResume() {
super.onResume();
AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity();
ActionBar ab = appCompatActivity.getSupportActionBar();
ab.setDisplayShowHomeEnabled(true);
ab.setDisplayHomeAsUpEnabled(false);
ab.setTitle(getActivity().getResources().getString(R.string.app_name));
}
@Override
public void onDestroy() {
super.onDestroy();
if (httpMngr != null) {
httpMngr.getRequestQueue().cancelAll(TAG);
}
}
// Initialize views and listeners
private void initViews() {
View.OnClickListener btnSearchClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
ViewUtil.hideKeybord(view, getActivity());
String jobTitle = etTitle.getText().toString();
String jobCompanyName = etCompany.getText().toString();
String jobLocation = etLocation.getText().toString();
boolean isFulltime = cbFulltime.isChecked();
boolean isParttime = cbParttime.isChecked();
// Cancel any ongoing search before executing the new search filter
if (httpMngr != null) {
httpMngr.getRequestQueue().cancelAll(TAG);
}
fetchJobListData(jobTitle, jobCompanyName, jobLocation, isFulltime, isParttime);
}
};
btnSearch.setOnClickListener(btnSearchClickListener);
}
// Call API fetching job listing
private void fetchJobListData(String jobTitle, String jobCompanyName, String jobLocation,
boolean isFulltime, boolean isParttime) {
HashMap<String, String> mapQueryParams = new HashMap<>();
if (jobTitle != null && !jobTitle.isEmpty()) {
mapQueryParams.put("title", jobTitle);
}
if (jobTitle != null && !jobCompanyName.isEmpty()) {
mapQueryParams.put("company", jobCompanyName);
}
if (jobLocation != null && !jobLocation.isEmpty()) {
mapQueryParams.put("location", jobLocation);
}
if (isParttime || isFulltime) {
if (isParttime && !isFulltime)
mapQueryParams.put("full_time", "false");
else if (!isParttime && isFulltime)
mapQueryParams.put("full_time", "true");
}
StringRequest req = RequestCreator.createStringRequest(TAG,
"/positions.json",
Request.Method.GET,
mapQueryParams,
new RequestCreator.Callback() {
@Override
public void onResponse(String data) {
Log.d(TAG, data);
showJobListing(data);
showProgressDlg(false);
}
@Override
public void onError(VolleyError err) {
Log.e(TAG, err.toString());
Toast.makeText(getActivity(), getActivity().getResources()
.getString(R.string.msg_unable_to_connect),
Toast.LENGTH_SHORT).show();
showProgressDlg(false);
}
});
showProgressDlg(true);
HttpManager.getInstance(getActivity()).addToRequestQuee(req);
}
// Display fragment of JobListFgmt to show job listing
private void showJobListing(String data) {
Gson gson = new GsonBuilder().create();
ArrayList<Job> arr = gson.fromJson(data, new TypeToken<List<Job>>() {}.getType());
JobListFgmt fgmt = new JobListFgmt();
fgmt.setJobs(arr);
MainActivity activity = (MainActivity) getActivity();
activity.getSupportFragmentManager()
.beginTransaction()
.replace(R.id.activity_main_container, fgmt)
.addToBackStack(TAG)
.commit();
}
// Show progress dialog display
private void showProgressDlg(boolean isShow) {
if (pgDlg != null) {
if (isShow) {
pgDlg.show();
} else if (pgDlg.isShowing()) {
pgDlg.cancel();
}
}
}
}
| 9e55d697206416db8b42e0dc59d9dee597f840d5 | [
"Markdown",
"Java"
] | 7 | Markdown | roxxydev/android-app-githubjobs | c09ed97574b091bdcbb5a8683477ab506633e309 | 9e54e3b03c214ba028dddc55fea123dbd37d95e2 |
refs/heads/gh-pages | <file_sep>alert("That was quite brave of you.");
var a = prompt ("Please enter the first number:");
var b = prompt ("Please enter the second number:");
var x = Number(a);
var y = Number(b);
document.write('Yup, this is my "script" already.<br/><br/>');
document.write("Our first number is now " + x + ", and second one is " + y + ". Now we\'\ll see: <br/><br/>");
/*decided to separate some lines to make the code more readable for myself*/
document.write("Their sum: ");
if ((x+y) > 9000){
document.write("is over 9000!!!")
}
else{
document.write(x+y);
}
document.write("<br/><br/>Their difference: ");
if ((x-y) > 9000){
document.write("is over 9000!!!")
}
else{
document.write(x-y)
}
document.write("<br/><br/>Their multiplication: ");
if ((x*y) > 9000){
document.write("is over 9000!!!");
}
else{
document.write(x*y)
}
document.write("<br/><br/>Their division: ");
if ((x/y) > 9000){
document.write("is over 9000!!!")
}
else{
document.write(x/y)
}
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Kingdom</title>
<link rel="stylesheet" href="common.css">
</head>
<body>
<form method="get" action="index.html" style="display: inline;"><button type="submit">Main Page</button></form>
<form method="get" action="diary.html" style="display: inline;"><button type="submit">Diary</button></form>
<form method="get" action="things.html" style="display: inline;"><button type="submit">Things and Links</button></form>
<form method="get" action="jskingdom.html" style="display: inline;"><button type="submit">JavaScript Kingdom</button></form>
<form method="get" action="cssbattleground.html" style="display: inline;"><button type="submit">CSS Battleground</button></form>
<h1>Menu</h1>
<div><p>Here I am testing some JavaScripty things. If you are here, you'll most probably regret it. So here goes my first script:<br/><br/><script src="first.js"></script>
</p></div>
</body>
</html>
<file_sep># mysite
My first steps (made by myself)
Nothing interesting here, folks. Just created this thing to practice some skills
| 4417ec8aca360fa0b12bf078bd386199fb4c4075 | [
"JavaScript",
"HTML",
"Markdown"
] | 3 | JavaScript | TedKopy/mysite | 6c10541db77e5c0498a29e28410cdbf66e195647 | 7df1d29b9ab14acacaa966ce401dbd847c8e732a |
refs/heads/master | <repo_name>DPros/JS-BuyList<file_sep>/main.js
var id = 0;
function addProduct(product) {
addToStorage(product);
product = '<div class="product" index="' + id++ + '">' +
'<div class="product-title" contenteditable>' + product + '</div>' +
'<div class="quantity">' +
'<button class="decrease" disabled>-</button>' +
'<span>1</span>' +
'<button class="increase">+</button>' +
'</div>' +
'<div class="control">' +
'<button class="unbuy">Не куплено</button>' +
'<button class="buy">Куплено</button>' +
'<button class="remove">x</button>' +
'</div>' +
'</div>';
$('.add-product input').val('');
$('.add-product input').focus();
product = $('.products').append(product).children(':last');
product.find('.remove').click(function(){
remove($(this).closest('.product'));
});
product.find('.buy').click(function(){
buy($(this).closest('.product'));
});
product.find('.unbuy').click(function(){
unbuy($(this).closest('.product'));
});
product.find('.increase').click(function(){
increase($(this).closest('.product'));
});
product.find('.decrease').click(function(){
decrease($(this).closest('.product'));
});
product.find('.product-title').on('focus', function(){
var $this = $(this);
$this.data('before', $this.html());
return $this;
}).on('blur keyup paste input', function() {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$('#in-storage .n'+product.attr('index')+' .name').text($this.text());
}
return $this;
});
}
function addToStorage(product) {
$('#in-storage').append("<div class='storage-product n" + id + "'><span class='name'>" + product + "</span><span class='quantity'>1</span></div>");
}
function remove(product){
if(product.hasClass('bought')){
$('#sold').find('.n'+product.attr('index')).remove();
}else{
$('#in-storage').find('.n'+product.attr('index')).remove();
}
product.remove();
}
function buy(product){
product.find('.product-title').removeAttr('contenteditable');
product.addClass('bought');
product = $('#in-storage .n'+product.attr('index'));
product.remove();
$('#sold').append(product);
}
function unbuy(product){
product.find('.product-title').attr('contenteditable', true);
product.removeClass('bought');
product = $('#sold .n'+product.attr('index'));
product.remove();
$('#in-storage').append(product);
}
function increase(product){
if(product.find('.quantity span').text()==1){
product.find('.quantity .decrease').removeAttr('disabled');
}
var q = parseInt(product.find('.quantity span').text());
product.find('.quantity span').text(q+1);
$('#in-storage .n'+product.attr('index')).find('.quantity').text(q+1);
}
function decrease(product){
var q = parseInt(product.find('.quantity span').text());
product.find('.quantity span').text(q-1);
$('#in-storage .n'+product.attr('index')).find('.quantity').text(q-1);
if(product.find('.quantity span').text()==1){
product.find('.quantity .decrease').attr('disabled', true);
}
}
$(document).ready(function () {
addProduct("Помідори");
addProduct("Сир");
addProduct("Печиво");
$('.add-product button').click(function(){
addProduct($('.add-product').find("input").val());
});
$('.add-product input').keypress(function(event){
if(event.which==13){
addProduct($('.add-product').find("input").val());
};
});
})
| 86191f0becbfac73475dc7f8e16e3846168c313c | [
"JavaScript"
] | 1 | JavaScript | DPros/JS-BuyList | 1c3f0eb9302bf3735fd2df23f0546f65e4487640 | 4e30aae3daf16bfb94a36fd0f56d1d9798d2ffa0 |
refs/heads/master | <file_sep>/Users/Shared/App/jellyrate/Resources/alloy/controllers/feed.js<file_sep>function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
var $ = this;
var exports = {};
$.__views.id = Ti.UI.createWindow({
backgroundColor: "white",
navBarHidden: false,
barColor: "#333",
id: "id"
});
$.__views.id && $.addTopLevelView($.__views.id);
$.__views.web = Ti.UI.createWebView({
id: "web"
});
$.__views.id.add($.__views.web);
exports.destroy = function() {};
_.extend($, $.__views);
var args = arguments[0] || {};
$.web.url = args.url;
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/backbone.js<file_sep>function Controller() {
function comment() {
Alloy.CFG.navgroup.open(Alloy.createController("feedComment").getView());
}
function swipeMenu(e) {
"left" == e.direction && $.menuComment.animate({
left: -260,
duration: 500
});
"right" == e.direction && $.menuComment.animate({
left: 0,
duration: 500
});
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.feedRow = Ti.UI.createTableViewRow({
id: "feedRow"
});
$.__views.feedRow && $.addTopLevelView($.__views.feedRow);
$.__views.title = Ti.UI.createLabel({
font: {
fontSize: "16dp",
color: "#EF4144"
},
width: Ti.UI.FILL,
top: "5dp",
left: "10dp",
right: "3dp",
touchEnabled: false,
id: "title"
});
$.__views.feedRow.add($.__views.title);
$.__views.image = Ti.UI.createImageView({
height: "400dp",
left: "5dp",
right: "5dp",
top: "0dp",
touchEnabled: false,
id: "image"
});
$.__views.feedRow.add($.__views.image);
$.__views.date = Ti.UI.createLabel({
id: "date"
});
$.__views.feedRow.add($.__views.date);
$.__views.menuComment = Ti.UI.createView({
left: "-260dp",
width: "300dp",
top: "70dp",
height: "50dp",
backgroundColor: "#000",
id: "menuComment"
});
$.__views.feedRow.add($.__views.menuComment);
swipeMenu ? $.__views.menuComment.addEventListener("swipe", swipeMenu) : __defers["$.__views.menuComment!swipe!swipeMenu"] = true;
$.__views.more = Ti.UI.createButton({
left: "10dp",
width: "60dp",
height: "40dp",
top: "10dp",
font: {
fontSize: "12dp",
color: "#FFFFFF"
},
title: "...",
id: "more"
});
$.__views.menuComment.add($.__views.more);
$.__views.comment = Ti.UI.createButton({
left: "70dp",
width: "60dp",
height: "40dp",
top: "10dp",
font: {
fontSize: "12dp",
color: "#FFFFFF"
},
id: "comment"
});
$.__views.menuComment.add($.__views.comment);
$.__views.rate = Ti.UI.createButton({
id: "rate"
});
$.__views.menuComment.add($.__views.rate);
$.__views.jelly = Ti.UI.createButton({
left: "130dp",
width: "60dp",
height: "40dp",
top: "10dp",
font: {
fontSize: "12dp",
color: "#FFFFFF"
},
id: "jelly"
});
$.__views.menuComment.add($.__views.jelly);
$.__views.rating = Ti.UI.createLabel({
left: "190dp",
width: "60dp",
height: "40dp",
top: "10dp",
font: {
fontSize: "12dp",
color: "#FFFFFF"
},
id: "rating"
});
$.__views.menuComment.add($.__views.rating);
comment ? $.__views.rating.addEventListener("click", comment) : __defers["$.__views.rating!click!comment"] = true;
$.__views.__alloyId3 = Ti.UI.createView({
width: Ti.UI.FILL,
background: "#747678",
height: "70dp",
id: "__alloyId3"
});
$.__views.feedRow.add($.__views.__alloyId3);
exports.destroy = function() {};
_.extend($, $.__views);
var args = arguments[0] || {};
$.title.text = args.title;
$.image.image = "/post/moto.gif";
$.date.text = args.date;
$.rating.text = args.rating;
__defers["$.__views.menuComment!swipe!swipeMenu"] && $.__views.menuComment.addEventListener("swipe", swipeMenu);
__defers["$.__views.rating!click!comment"] && $.__views.rating.addEventListener("click", comment);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<file_sep>var moment = require('alloy/moment');
var ServicesHelper = require('Helper');
var Helper = new ServicesHelper();
var urlBase = Helper.UrlBase;
exports.definition = {
config: {
columns: {
"Id": "int",
"ParentId": "int",
"Title": "string",
"Description": "string",
"Photo": "string",
"CreatorId": "int",
"Rating": "int",
"CommentCount": "int",
"LikeCount": "int",
"Gender": "string",
"GeoLocation": "string",
"LastUpdate": "datetime"
},
adapter: {
type: "sql",
collection_name: "Post"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
sendPost: function(userId, parentId, title, description, photo, rating, comment, geolocation) {
var params = {action:'post',userId:userId, parentId:parentId, title:title, description:description, photo:photo, rating:rating, comment:comment, geolocation:geolocation};
return getRequest(urlBase, params, 1000);
},
getPosts: function(postId, userId) {
var params = {action:'getpost',id_post:postId,id_user:userId};
return getRequest(urlBase, params, 1000);
},
getFeeds: function(userId, start) {
var params = {action:'getfeed',id_user:userId, start:start, max_posts:10};
return getRequest(urlBase, params, 1000);
},
searchFeeds: function(userId, find) {
var params = {action:'searchfeed',userId:userId, find:find};
return getRequest(urlBase, params, 1000);
},
searchAutocomplete: function(userId, find) {
var params = {action:'autocomplete',userId:userId, find:find};
return getRequest(urlBase, params, 1000);
},
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
// extended functions and properties go here
});
return Collection;
}
}
<file_sep>function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
var $ = this;
var exports = {};
$.__views.profile = Ti.UI.createWindow({
backgroundImage: "/login/fondo.png",
navBarHidden: false,
barColor: "#ff9900",
top: "10dp",
left: "10dp",
textAlign: "center",
font: {
fontSize: "24dp",
fontWeight: "bold"
},
id: "profile"
});
$.__views.profile && $.addTopLevelView($.__views.profile);
$.__views.__alloyId17 = Ti.UI.createScrollView({
id: "__alloyId17"
});
$.__views.profile.add($.__views.__alloyId17);
$.__views.__alloyId18 = Ti.UI.createView({
top: 0,
border: "1px",
height: "91dp",
width: Ti.UI.FILL,
textAlign: "center",
backgroundImage: "/post/background_header2.png",
color: "#fff",
font: {
fontSize: "24dp",
fontWeight: "bold"
},
id: "__alloyId18"
});
$.__views.profile.add($.__views.__alloyId18);
$.__views.back = Ti.UI.createImageView({
top: "10dp",
left: "10dp",
image: "/general/back.gif",
width: "50dp",
id: "back"
});
$.__views.__alloyId18.add($.__views.back);
$.__views.profile = Ti.UI.createLabel({
top: "10dp",
left: "10dp",
textAlign: "center",
font: {
fontSize: "24dp",
fontWeight: "bold"
},
text: "PROFILE",
id: "profile"
});
$.__views.__alloyId18.add($.__views.profile);
$.__views.configuraciones = Ti.UI.createImageView({
top: "10dp",
right: "20dp",
image: "/general/configuraciones.gif",
width: "50dp",
id: "configuraciones"
});
$.__views.__alloyId18.add($.__views.configuraciones);
$.__views.__alloyId19 = Ti.UI.createView({
id: "__alloyId19"
});
$.__views.profile.add($.__views.__alloyId19);
$.__views.__alloyId20 = Ti.UI.createView({
id: "__alloyId20"
});
$.__views.profile.add($.__views.__alloyId20);
$.__views.__alloyId21 = Ti.UI.createView({
top: "80dp",
border: "1px",
height: "91dp",
width: Ti.UI.FILL,
textAlign: "center",
backgroundImage: "/general/footer.gif",
color: "#fff",
font: {
fontSize: "24dp",
fontWeight: "bold"
},
id: "__alloyId21"
});
$.__views.profile.add($.__views.__alloyId21);
$.__views.ALGO = Ti.UI.createImageView({
id: "ALGO"
});
$.__views.__alloyId21.add($.__views.ALGO);
$.__views.JR = Ti.UI.createImageView({
id: "JR"
});
$.__views.__alloyId21.add($.__views.JR);
$.__views.search = Ti.UI.createImageView({
id: "search"
});
$.__views.__alloyId21.add($.__views.search);
$.__views.__alloyId22 = Ti.UI.createScrollView({
id: "__alloyId22"
});
$.__views.profile.add($.__views.__alloyId22);
exports.destroy = function() {};
_.extend($, $.__views);
alert("inicio controler profile");
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<file_sep>module.exports = {
dependencies: {
"me.educore.feed": "1.0"
}
};<file_sep>exports.definition = {
config: {
columns: {
"Id": "int",
"PostId": "int",
"UserId": "int",
"Date": "date"
},
adapter: {
type: "sql",
collection_name: "Favorite"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
favorite: function(userId, postId) {
var params = {action:'favorite',userId:userId,postId:postId};
return getRequest(urlBase, params, 1000);
},
unfavorite: function(userId, postId) {
var params = {action:'unfavorite',userId:userId,postId:postId};
return getRequest(urlBase, params, 1000);
},
getlist: function(userId, init, max) {
var params = {action:'getfavorites',start:init,max_post:max};
return getRequest(urlBase, params, 1000);
},
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
// extended functions and properties go here
});
return Collection;
}
}
<file_sep>var moment = require("alloy/moment");
var ServicesHelper = require("Helper");
var Helper = new ServicesHelper();
var urlBase = Helper.UrlBase;
var USERNAME = "user", PASSWORD = "<PASSWORD>", AUTHKEY = "somelongauthkeyforvalidation";
exports.definition = {
config: {
columns: {
Id: "integer primary key",
Login: "text",
Name: "text",
Password: "<PASSWORD>",
Birthday: "date",
Gender: "text",
Photo: "text",
PhotoType: "text",
PostCount: "integer",
FollowerCount: "integer",
FollowingCount: "integer",
OauthProvider: "string",
TwitterToken: "string",
OauthUid: "string",
Email: "text",
AuthKey: "text",
LoggedIn: "integer",
LoggedInSince: "date",
Theme: "integer"
},
adapter: {
type: "sql",
collection_name: "User",
idAttribute: "Id"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
login: function(username, password) {
var params = {
action: "auth",
login: username,
passwd: <PASSWORD>
};
return getRequest(urlBase, params, 1e3);
},
setPassword: function(userId, password, newpassword) {
var params = {
action: "setpasswd",
userId: userId,
passwd: <PASSWORD>,
newpassword: <PASSWORD>
};
return getRequest(urlBase, params, 1e3);
},
follow: function(userId, followId) {
var params = {
action: "follow",
userId: userId,
followId: followId
};
return getRequest(urlBase, params, 1e3);
},
register: function(login, name, lastName, password, bio, birthday, photo, phototype) {
var params = {
action: "createuser",
login: login,
name: name,
lastName: lastname,
password: <PASSWORD>,
bio: bio,
birthday: brthday,
photo: photo,
phototype: phototype
};
return getRequest(urlBase, params, 1e3);
},
logout: function() {
this.set({
LoggedIn: 0,
LoggedInSince: "",
AuthKey: ""
});
this.save();
},
validateAuth: function() {
return 1 === this.get("LoggedIn") && this.get("AuthKey") === AUTHKEY ? true : false;
}
});
return Model;
}
};
var Alloy = require("alloy"), _ = require("alloy/underscore")._, model, collection;
model = Alloy.M("User", exports.definition, []);
collection = Alloy.C("User", exports.definition, model);
exports.Model = model;
exports.Collection = collection;<file_sep>function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
var $ = this;
var exports = {};
$.__views.signin = Ti.UI.createWindow({
id: "signin",
title: "Basic Window"
});
$.__views.signin && $.addTopLevelView($.__views.signin);
$.__views.__alloyId23 = Ti.UI.createScrollView({
id: "__alloyId23"
});
$.__views.signin.add($.__views.__alloyId23);
$.__views.__alloyId24 = Ti.UI.createLabel({
font: {
fontSize: 46,
font: "Arial Black"
},
top: 10,
color: "#ED4243",
width: 200,
text: "SIGN UP",
id: "__alloyId24"
});
$.__views.__alloyId23.add($.__views.__alloyId24);
$.__views.__alloyId25 = Ti.UI.createButton({
backgroundImage: "/login/choose-photo.png",
top: 60,
width: 90,
height: 90,
id: "__alloyId25"
});
$.__views.__alloyId23.add($.__views.__alloyId25);
$.__views.lblFullname = Ti.UI.createLabel({
font: {
fontSize: 10,
font: "Arial Black"
},
top: 170,
left: 20,
color: "#fff",
backgroundImage: "/login/label.png",
width: 90,
height: 38,
text: "FULLNAME",
id: "lblFullname"
});
$.__views.__alloyId23.add($.__views.lblFullname);
$.__views.fullname = Ti.UI.createTextField({
width: "180dp",
height: 38,
font: {
fontSize: 14,
font: "Arial Black"
},
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_LINE,
borderColor: "#BEBEBE",
top: "170dp",
right: 20,
hintText: "username",
returnKeyType: Ti.UI.RETURNKEY_NEXT,
id: "fullname"
});
$.__views.__alloyId23.add($.__views.fullname);
$.__views.lblEmail = Ti.UI.createLabel({
font: {
fontSize: 10,
font: "Arial Black"
},
top: 210,
left: 20,
color: "#fff",
backgroundImage: "/login/label.png",
width: 90,
height: 38,
text: "EMAIL",
id: "lblEmail"
});
$.__views.__alloyId23.add($.__views.lblEmail);
$.__views.email = Ti.UI.createTextField({
width: "180dp",
height: 38,
font: {
fontSize: 14,
font: "Arial Black"
},
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_LINE,
borderColor: "#BEBEBE",
top: "210dp",
right: 20,
hintText: "email",
passwordMask: <PASSWORD>,
returnKeyType: Ti.UI.RETURNKEY_DONE,
id: "email"
});
$.__views.__alloyId23.add($.__views.email);
$.__views.lblUsername = Ti.UI.createLabel({
font: {
fontSize: 10,
font: "Arial Black"
},
top: 250,
left: 20,
color: "#fff",
backgroundImage: "/login/label.png",
width: 90,
height: 38,
text: "USERNAME",
id: "lblUsername"
});
$.__views.__alloyId23.add($.__views.lblUsername);
$.__views.username = Ti.UI.createTextField({
width: "180dp",
height: 38,
font: {
fontSize: 14,
font: "Arial Black"
},
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_LINE,
borderColor: "#BEBEBE",
top: "250dp",
right: 20,
hintText: "username",
passwordMask: true,
returnKeyType: Ti.UI.RETURNKEY_DONE,
id: "username"
});
$.__views.__alloyId23.add($.__views.username);
$.__views.lblPassword = Ti.UI.createLabel({
font: {
fontSize: 10,
font: "Arial Black"
},
top: 290,
left: 20,
color: "#fff",
backgroundImage: "/login/label.png",
width: 90,
height: 38,
text: "PASSWORD",
id: "lblPassword"
});
$.__views.__alloyId23.add($.__views.lblPassword);
$.__views.password = Ti.UI.createTextField({
width: "180dp",
height: 38,
font: {
fontSize: 14,
font: "Arial Black"
},
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_LINE,
borderColor: "#BEBEBE",
top: "290dp",
right: 20,
hintText: "<PASSWORD>",
passwordMask: true,
returnKeyType: Ti.UI.RETURNKEY_DONE,
id: "password"
});
$.__views.__alloyId23.add($.__views.password);
$.__views.lblBirthday = Ti.UI.createLabel({
font: {
fontSize: 10,
font: "Arial Black"
},
top: 330,
left: 20,
color: "#fff",
backgroundImage: "/login/label.png",
width: 90,
height: 38,
text: "BIRTHDAY",
id: "lblBirthday"
});
$.__views.__alloyId23.add($.__views.lblBirthday);
$.__views.birthday = Ti.UI.createTextField({
width: "60dp",
height: 38,
font: {
fontSize: 14,
font: "Arial Black"
},
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_LINE,
borderColor: "#BEBEBE",
top: "330dp",
right: 20,
hintText: "00/00/0000",
returnKeyType: Ti.UI.RETURNKEY_DONE,
id: "birthday"
});
$.__views.__alloyId23.add($.__views.birthday);
$.__views.lblGender = Ti.UI.createLabel({
font: {
fontSize: 10,
font: "Arial Black"
},
top: 330,
left: 160,
color: "#fff",
backgroundImage: "/login/label.png",
width: 90,
height: 38,
text: "GENDER",
id: "lblGender"
});
$.__views.__alloyId23.add($.__views.lblGender);
$.__views.genderM = Ti.UI.createButton({
top: "330dp",
left: 210,
backgroundImage: "/login/man-off.gif",
width: 12,
height: 35,
id: "genderM"
});
$.__views.__alloyId23.add($.__views.genderM);
$.__views.genderF = Ti.UI.createButton({
top: "330dp",
left: 240,
backgroundImage: "/login/woman-off.gif",
width: 15,
height: 35,
id: "genderF"
});
$.__views.__alloyId23.add($.__views.genderF);
exports.destroy = function() {};
_.extend($, $.__views);
var leftButton = Ti.UI.createButton({
background: "#fff",
color: "#ff9900",
width: 41,
height: 30,
title: "Cancel"
});
leftButton.addEventListener("click", function() {
Alloy.CFG.navgroup.close($.signin, {
animated: true
});
});
$.signin.leftNavButton = leftButton;
var rightButton = Ti.UI.createButton({
background: "#fff",
color: "#ff9900",
width: 41,
height: 30,
title: "Done"
});
rightButton.addEventListener("click", function() {
Alloy.CFG.navgroup.open(Alloy.createController("home").getView());
});
$.signin.rightNavButton = rightButton;
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<file_sep>/Users/Shared/App/jellyrate/Resources/alloy.js<file_sep>var moment = require("alloy/moment");
var DBHelper = require("DBHelper");
var Helper = new DBHelper();
exports.definition = {
config: {
columns: {
Id: "text",
Name: "text",
Connected: "bool"
},
adapter: {
type: "sql",
collection_name: "SocialNetwork"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
getSocialNetwork: function() {
var model = null;
var db = Helper.openDbConnection();
var rs = db.execute("SELECT Id, Name, Connected FROM SocialNetwork");
rs.isValidRow() && (model = Alloy.createModel("SocialNetworks", {
Id: rs.fieldByName("Id"),
Name: rs.fieldByName("Name"),
Connected: rs.fieldByName("Connected")
}));
db.close();
return model;
},
updateConnectSocialNetwork: function(name, connected, id) {
var db = Helper.openDbConnection();
var rs = db.execute("SELECT Id, Name, Connected FROM SocialNetwork");
rs.isValidRow() ? db.execute("Update SocialNetwork SET Name=?, Connected=? WHERE Id=?", name, connected, id) : db.execute("INSERT into SocialNetwork (Id, Name, Connected) Values (?,?,?)", id, name, connected);
db.close();
}
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {});
return Collection;
}
};
var Alloy = require("alloy"), _ = require("alloy/underscore")._, model, collection;
model = Alloy.M("SocialNetwork", exports.definition, []);
collection = Alloy.C("SocialNetwork", exports.definition, model);
exports.Model = model;
exports.Collection = collection;<file_sep>function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
var $ = this;
var exports = {};
$.__views.commentRow = Ti.UI.createTableViewRow({
id: "commentRow"
});
$.__views.commentRow && $.addTopLevelView($.__views.commentRow);
$.__views.comment = Ti.UI.createLabel({
font: {
fontSize: "16dp",
color: "#EF4144"
},
width: Ti.UI.FILL,
top: "45dp",
left: "20dp",
right: "3dp",
touchEnabled: false,
id: "comment"
});
$.__views.commentRow.add($.__views.comment);
$.__views.image = Ti.UI.createImageView({
height: "70dp",
left: "5dp",
top: "10dp",
touchEnabled: false,
id: "image"
});
$.__views.commentRow.add($.__views.image);
$.__views.date = Ti.UI.createLabel({
id: "date"
});
$.__views.commentRow.add($.__views.date);
$.__views.rating = Ti.UI.createLabel({
font: {
fontSize: "12dp",
color: "#FFFFFF"
},
top: "70dp",
left: "10dp",
id: "rating"
});
$.__views.commentRow.add($.__views.rating);
exports.destroy = function() {};
_.extend($, $.__views);
var args = arguments[0] || {};
$.comment.text = args.comment;
$.image.image = "/post/bruno.png";
$.date.text = args.date;
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<file_sep>var posts = Alloy.Models.posts;
function refreshFeeds(start) {
var respuesta = posts.getFeeds(1, start);
if(respuesta==='"false"') {
alert("Credenciales erradas");
} else {
var rows = [];
_.each(respuesta, function(item) {
var detail = posts.getPosts(item.id_post, 1);
if(detail==='"false"' || detail==="false") {
alert("erradas");
} else {
//alert(detail);
var row = Alloy.createController('feedRow', {
articleUrl: detail.like_count,
image: detail.photo,
title: detail.title,
rating: detail.rating,
date: detail.last_update
}).getView();
rows.push(row);
$.table.appendRow(row,{animationStyle:Titanium.UI.iPhone.RowAnimationStyle.NONE});
}
});
return rows;
}
}
refreshFeeds(1);
var lastRow = 10;
var navActInd = Titanium.UI.createActivityIndicator();
$.feed.rightNavButton = navActInd;
var updating = false;
var loadingRow = Ti.UI.createTableViewRow({title:"Loading..."});
function beginUpdate()
{
updating = true;
navActInd.show();
$.table.appendRow(loadingRow);
// just mock out the reload
setTimeout(endUpdate,2000);
}
function endUpdate()
{
updating = false;
$.table.deleteRow(lastRow,{animationStyle:Titanium.UI.iPhone.RowAnimationStyle.NONE});
refreshFeeds(lastRow);
lastRow += 10;
// just scroll down a bit to the new rows to bring them into view
//$.table.scrollToIndex(lastRow-9,{animated:true,position:Ti.UI.iPhone.TableViewScrollPosition.BOTTOM});
navActInd.hide();
}
var lastDistance = 0; // calculate location to determine direction
$.table.addEventListener('scroll',function(e)
{
var offset = e.contentOffset.y;
var height = e.size.height;
var total = offset + height;
var theEnd = e.contentSize.height;
var distance = theEnd - total;
// going down is the only time we dynamically load,
// going up we can safely ignore -- note here that
// the values will be negative so we do the opposite
if (distance < lastDistance)
{
// adjust the % of rows scrolled before we decide to start fetching
var nearEnd = theEnd * .75;
if (!updating && (total >= nearEnd))
{
beginUpdate();
}
}
lastDistance = distance;
});
function cargaProfile(e){
alert("antes de cargar profile");
Alloy.CFG.navgroup.open(Alloy.createController('profile').getView());
alert("despues de cargar profile");
}
<file_sep>var moment = require("alloy/moment");
var ServicesHelper = require("Helper");
var Helper = new ServicesHelper();
var urlBase = Helper.UrlBase;
exports.definition = {
config: {
columns: {
Id: "integer primary key",
PostId: "integer",
UserId: "integer",
Date: "date",
Comment: "text"
},
adapter: {
type: "sql",
collection_name: "Comment"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
getComments: function(postId) {
var params = {
action: "getcomments",
id_post: postId,
start: 0,
max_posts: 10
};
return getRequest(urlBase, params, 1e3);
},
getComment: function(commentId) {
var params = {
action: "getcomment",
id_post_comment: commentId
};
return getRequest(urlBase, params, 1e3);
},
postComment: function(userId, postId, comment) {
var params = {
action: "comment",
userId: userId,
postId: postId,
comment: comment
};
return getRequest(urlBase, params, 1e3);
}
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {});
return Collection;
}
};
var Alloy = require("alloy"), _ = require("alloy/underscore")._, model, collection;
model = Alloy.M("Comment", exports.definition, []);
collection = Alloy.C("Comment", exports.definition, model);
exports.Model = model;
exports.Collection = collection;<file_sep>/Users/Shared/App/jellyrate/Resources/Helper.js<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/models/User.js<file_sep>function Controller() {
function refreshComments() {
var respuesta = comments.getComments(3);
if ('"false"' === respuesta) alert("Sin comentarios"); else {
var rows = [];
_.each(respuesta, function(item) {
var detail = comments.getComment(item.id_post_comment);
'"false"' === detail || "false" === detail ? alert("erradas") : rows.push(Alloy.createController("commentRow", {
articleUrl: detail.id_post_comment,
comment: "Comentario en duro. El servicio no lo retorna",
date: detail.date
}).getView());
});
$.table.setData(rows);
}
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
var $ = this;
var exports = {};
$.__views.comment = Ti.UI.createWindow({
backgroundColor: "white",
id: "comment"
});
$.__views.comment && $.addTopLevelView($.__views.comment);
$.__views.table = Ti.UI.createTableView({
top: 0,
bottom: "42dp",
id: "table"
});
$.__views.comment.add($.__views.table);
$.__views.__alloyId2 = Ti.UI.createView({
bottom: "40dp",
border: "1px",
height: "39dp",
width: Ti.UI.FILL,
textAlign: "center",
color: "#fff",
font: {
fontSize: "24dp",
fontWeight: "bold"
},
id: "__alloyId2"
});
$.__views.comment.add($.__views.__alloyId2);
$.__views.commentText = Ti.UI.createTextField({
top: 0,
left: 5,
right: 90,
id: "commentText"
});
$.__views.__alloyId2.add($.__views.commentText);
$.__views.sendButton = Ti.UI.createButton({
top: 0,
width: 80,
right: 10,
title: "Send",
id: "sendButton"
});
$.__views.__alloyId2.add($.__views.sendButton);
exports.destroy = function() {};
_.extend($, $.__views);
var comments = Alloy.Models.comments;
refreshComments();
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/CFG.js<file_sep>function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.index = Ti.UI.createWindow({
backgroundColor: "white",
navBarHidden: false,
barColor: "#333",
id: "index",
title: "Basic Window"
});
$.__views.index && $.addTopLevelView($.__views.index);
$.__views.__alloyId0 = Ti.UI.createLabel({
color: "red",
text: "I'm a Basic Window",
id: "__alloyId0"
});
$.__views.index.add($.__views.__alloyId0);
clickWin ? $.__views.__alloyId0.addEventListener("click", clickWin) : __defers["$.__views.__alloyId0!click!clickWin"] = true;
exports.destroy = function() {};
_.extend($, $.__views);
var leftButton = Ti.UI.createButton({
backgroundImage: "images/6dots.png",
width: 41,
height: 30
});
leftButton.addEventListener("click", function() {
Alloy.CFG.navgroup.close($.index, {
animated: true
});
});
$.index.leftNavButton = leftButton;
var clickWin = function() {
alert("eso");
};
__defers["$.__views.__alloyId0!click!clickWin"] && $.__views.__alloyId0.addEventListener("click", clickWin);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/underscore.js<file_sep>var comments = Alloy.Models.comments;
function refreshComments() {
var respuesta = comments.getComments(3);
if(respuesta==='"false"') {
alert("Sin comentarios");
} else {
var rows = [];
_.each(respuesta, function(item) {
var detail = comments.getComment(item.id_post_comment);
if(detail==='"false"' || detail==="false") {
alert("erradas");
} else {
rows.push(Alloy.createController('commentRow', {
articleUrl: detail.id_post_comment,
comment: 'Comentario en duro. El servicio no lo retorna',
date: detail.date
}).getView());
}
});
$.table.setData(rows);
}
}
refreshComments();<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/controllers/profile.js<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/sync/localStorage.js<file_sep>var moment = require('alloy/moment');
var ServicesHelper = require('Helper');
var Helper = new ServicesHelper();
var urlBase = Helper.UrlBase;
var USERNAME = 'user',
PASSWORD = '<PASSWORD>',
AUTHKEY = 'somelongauthkeyforvalidation';
exports.definition = {
config: {
"columns": {
"Id": "integer primary key",
"Login":"text",
"Name":"text",
"Password":"<PASSWORD>",
"Birthday":"date",
"Gender":"text",
"Photo":"text",
"PhotoType":"text",
"PostCount":"integer",
"FollowerCount":"integer",
"FollowingCount":"integer",
"OauthProvider":"string",
"TwitterToken":"string",
"OauthUid":"string",
"Email":"text",
"AuthKey":"text",
"LoggedIn":"integer",
"LoggedInSince":"date",
"Theme":"integer"
},
"adapter": {
"type": "sql",
"collection_name": "User",
"idAttribute": "Id"
}
},
extendModel : function(Model) {
_.extend(Model.prototype, {
login: function(username, password) {
var params = {action:'auth',login:username,passwd:<PASSWORD>};
return getRequest(urlBase, params, 1000);
},
setPassword: function(userId, password, newpassword) {
var params = {action:'setpasswd',userId:userId,passwd:<PASSWORD>,newpassword:<PASSWORD>};
return getRequest(urlBase, params, 1000);
},
follow: function(userId, followId) {
var params = {action:'follow',userId:userId,followId:followId};
return getRequest(urlBase, params, 1000);
},
register: function(login, name, lastName, password, bio, birthday, photo, phototype) {
var params = {action:'createuser',login:login, name:name, lastName:lastname, password:<PASSWORD>, bio:bio, birthday:brthday, photo:photo, phototype:phototype};
return getRequest(urlBase, params, 1000);
},
logout: function() {
this.set({
LoggedIn: 0,
LoggedInSince: '',
AuthKey: ''
});
this.save();
},
validateAuth: function() {
// Again, this would be done against an auth server in a real world
// scenario. We're just keeping it simple here.
if (this.get('LoggedIn') === 1 && this.get('AuthKey') === AUTHKEY) {
return true;
} else {
return false;
}
},
/*saveDataLogin: function(){
var DBHelper = require('DBHelper');
var HelperDB = new DBHelper();
var db = HelperDB.openDbConnection();
var rs = db.execute('SELECT id,email,hash FROM usuario WHERE email=?', "Partly Cloudy");
},*/
});
return Model;
}
}<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/models/RelationType.js<file_sep>var HANDLERS = ['success','error'];
var MAX_ROWS = 20; // can be overridden by args
var FEED_URL = '';
var handlers = {};
// ---------------------------
// Public Functions
// ---------------------------
exports.setHandlers = function(args) {
_.each(HANDLERS, function(h) {
if (args[h]) {
handlers[h] = args[h];
}
});
};
exports.loadFeed = function(args) {
//expecting args.url and optional args.max_rows
if (args.url) {
FEED_URL = args.url;
if(args.max_rows) {
MAX_ROWS = args.max_rows;
}
getFeed();
} else {
alert('You forgot to pass the FEED URI!');
Ti.API.error('[ERROR] URI not passed to function');
}
};
// ---------------------------
// Private Functions
// ---------------------------
function processFeedData(data) {
var entrys = [];
try {
var items = data.getElementsByTagName("item");
for(var c = 0; c < Math.min(items.length,MAX_ROWS); c++) {
entrys.push({
title: items.item(c).getElementsByTagName("title").item(0).text,
url: items.item(c).getElementsByTagName("link").item(0).text
});
}
//fire success handler
handlers.success(entrys);
} catch (e) {
Ti.API.error('[ERROR] ' + (e.error || JSON.stringify(e)));
alert('Invalid response from server. Try again.');
return;
}
}
// ---------------------------
// event handlers
// ---------------------------
function getFeed(e) {
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
if(handlers.success) {
var response = this.responseXML.documentElement;
processFeedData(response);
}
},
onerror: function(e) {
if(handlers.error) {
handlers.error(e);
} else {
alert('There was an error processing the request. Make sure you have a network connection and try again.');
Ti.API.error('[ERROR] ' + (e.error || JSON.stringify(e)));
}
},
timeout: 5000
});
xhr.open('GET', FEED_URL);
xhr.send();
}<file_sep>var socialNetwork = Alloy.Models.socialNetworks;
var loginJelly = function(e){
Alloy.CFG.navgroup.open(Alloy.createController("login").getView());
}
var signupJelly = function (e){
Alloy.CFG.navgroup.open(Alloy.createController("signup").getView());
}
function isLoggedInFacebook(){
var fb = require('facebook');
fb.appid = Ti.App.Properties.getString("ti.facebook.appid","127424943970451");
fb.permissions = ['read_stream'];
fb.forceDialogAuth = false;
return fb.loggedIn;
}
function loginFacebook(evt){
var fb = require('facebook');
fb.appid = Ti.App.Properties.getString("ti.facebook.appid","127424943970451");
fb.permissions = ['read_stream'];
fb.forceDialogAuth = false;
fb.addEventListener('login', function(e) {
if (e.success) {
//socialNetwork.updateConnectSocialNetwork();
alert('Logged In');
} else if (e.error) {
alert(e.error);
} else if (e.cancelled) {
alert("Canceled");
}
});
fb.authorize();
}
function loginTwitter(evt){
var social = require('social');
var twitter = social.create({
site: 'Twitter', // <-- this example is for Twitter. I'll expand this to other sites in the future.
consumerKey: '8i5ubq6QBRDIus8hIP8ISg', // <--- you'll want to replace this
consumerSecret: '<KEY>' // <--- and this with your own keys!
});
twitter.authorize(function() {
alert('Authorized!');
});
}
function loginInstagram(evt){
var social = require('social');
var twitter = social.create({
site: 'Instagram', // <-- this example is for Twitter. I'll expand this to other sites in the future.
consumerKey: '8i5ubq6QBRDIus8hIP8ISg', // <--- you'll want to replace this
consumerSecret: '<KEY>' // <--- and this with your own keys!
});
twitter.authorize(function() {
alert('Authorized!');
});
}
function initialize(){
if(isLoggedInFacebook()) {
//Alloy.CFG.navgroup.open(Alloy.createController('feed').getView());
}
}
initialize();
<file_sep>function Controller() {
function isLoggedInFacebook() {
var fb = require("facebook");
fb.appid = Ti.App.Properties.getString("ti.facebook.appid", "127424943970451");
fb.permissions = [ "read_stream" ];
fb.forceDialogAuth = false;
return fb.loggedIn;
}
function loginFacebook() {
var fb = require("facebook");
fb.appid = Ti.App.Properties.getString("ti.facebook.appid", "127424943970451");
fb.permissions = [ "read_stream" ];
fb.forceDialogAuth = false;
fb.addEventListener("login", function(e) {
e.success ? alert("Logged In") : e.error ? alert(e.error) : e.cancelled && alert("Canceled");
});
fb.authorize();
}
function loginTwitter() {
var social = require("social");
var twitter = social.create({
site: "Twitter",
consumerKey: "<KEY>",
consumerSecret: "<KEY>"
});
twitter.authorize(function() {
alert("Authorized!");
});
}
function loginInstagram() {
var social = require("social");
var twitter = social.create({
site: "Instagram",
consumerKey: "<KEY>",
consumerSecret: "<KEY>"
});
twitter.authorize(function() {
alert("Authorized!");
});
}
function initialize() {
isLoggedInFacebook();
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.home = Ti.UI.createWindow({
backgroundImage: "/login/fondo.png",
id: "home",
title: "Basic Window"
});
$.__views.home && $.addTopLevelView($.__views.home);
$.__views.__alloyId6 = Ti.UI.createImageView({
image: "/login/logo.png",
top: 50,
width: 250,
id: "__alloyId6"
});
$.__views.home.add($.__views.__alloyId6);
$.__views.__alloyId7 = Ti.UI.createButton({
image: "/login/login-facebook.png",
left: 20,
top: 150,
width: 130,
height: 130,
id: "__alloyId7"
});
$.__views.home.add($.__views.__alloyId7);
loginFacebook ? $.__views.__alloyId7.addEventListener("click", loginFacebook) : __defers["$.__views.__alloyId7!click!loginFacebook"] = true;
$.__views.__alloyId8 = Ti.UI.createButton({
image: "/login/login-twitter.png",
right: 20,
top: 150,
width: 130,
height: 130,
id: "__alloyId8"
});
$.__views.home.add($.__views.__alloyId8);
loginTwitter ? $.__views.__alloyId8.addEventListener("click", loginTwitter) : __defers["$.__views.__alloyId8!click!loginTwitter"] = true;
$.__views.__alloyId9 = Ti.UI.createButton({
image: "/login/login-instagram.png",
left: 20,
top: 300,
width: 130,
height: 130,
id: "__alloyId9"
});
$.__views.home.add($.__views.__alloyId9);
loginInstagram ? $.__views.__alloyId9.addEventListener("click", loginInstagram) : __defers["$.__views.__alloyId9!click!loginInstagram"] = true;
$.__views.__alloyId10 = Ti.UI.createButton({
image: "/login/login.png",
right: 20,
top: 370,
width: 130,
height: 60,
id: "__alloyId10"
});
$.__views.home.add($.__views.__alloyId10);
loginJelly ? $.__views.__alloyId10.addEventListener("click", loginJelly) : __defers["$.__views.__alloyId10!click!loginJelly"] = true;
$.__views.__alloyId11 = Ti.UI.createButton({
image: "/login/signup-with-username.png",
right: 20,
top: 300,
width: 130,
height: 60,
id: "__alloyId11"
});
$.__views.home.add($.__views.__alloyId11);
signupJelly ? $.__views.__alloyId11.addEventListener("click", signupJelly) : __defers["$.__views.__alloyId11!click!signupJelly"] = true;
exports.destroy = function() {};
_.extend($, $.__views);
Alloy.Models.socialNetworks;
var loginJelly = function() {
Alloy.CFG.navgroup.open(Alloy.createController("login").getView());
};
var signupJelly = function() {
Alloy.CFG.navgroup.open(Alloy.createController("signup").getView());
};
initialize();
__defers["$.__views.__alloyId7!click!loginFacebook"] && $.__views.__alloyId7.addEventListener("click", loginFacebook);
__defers["$.__views.__alloyId8!click!loginTwitter"] && $.__views.__alloyId8.addEventListener("click", loginTwitter);
__defers["$.__views.__alloyId9!click!loginInstagram"] && $.__views.__alloyId9.addEventListener("click", loginInstagram);
__defers["$.__views.__alloyId10!click!loginJelly"] && $.__views.__alloyId10.addEventListener("click", loginJelly);
__defers["$.__views.__alloyId11!click!signupJelly"] && $.__views.__alloyId11.addEventListener("click", signupJelly);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<file_sep>function Controller() {
function cancel() {
Alloy.CFG.navgroup.close($.login, {
animated: true
});
}
function send() {
alert("function send()");
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.login = Ti.UI.createWindow({
backgroundImage: "/login/fondo.png",
navBarHidden: true,
barColor: "#D33B3C",
id: "login",
title: "Login"
});
$.__views.login && $.addTopLevelView($.__views.login);
$.__views.navBar = Ti.UI.createView({
top: 0,
height: 50,
width: Ti.UI.FILL,
backgroundImage: "/login/top-login.png",
id: "navBar"
});
$.__views.login.add($.__views.navBar);
$.__views.leftButton = Ti.UI.createButton({
font: {
fontSize: 10,
fontWeight: "normal",
font: "BebasNeue"
},
image: "/cancel.png",
borderRadius: 0,
width: 63,
height: 25,
left: 10,
title: "",
id: "leftButton"
});
$.__views.navBar.add($.__views.leftButton);
cancel ? $.__views.leftButton.addEventListener("click", cancel) : __defers["$.__views.leftButton!click!cancel"] = true;
$.__views.rightButton = Ti.UI.createButton({
font: {
fontSize: 10,
fontWeight: "normal",
font: "BebasNeue"
},
image: "/done.png",
borderRadius: 0,
width: 63,
height: 25,
right: 10,
title: "",
id: "rightButton"
});
$.__views.navBar.add($.__views.rightButton);
send ? $.__views.rightButton.addEventListener("click", send) : __defers["$.__views.rightButton!click!send"] = true;
$.__views.__alloyId4 = Ti.UI.createScrollView({
top: 50,
id: "__alloyId4"
});
$.__views.login.add($.__views.__alloyId4);
$.__views.lblForgotTitle = Ti.UI.createLabel({
top: 40,
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
font: {
fontSize: 50,
fontWeight: "bold",
fontFamily: "BebasNeue"
},
color: "#ed4243",
text: "Forgot My Password",
id: "lblForgotTitle"
});
$.__views.__alloyId4.add($.__views.lblForgotTitle);
$.__views.lblUserEmail = Ti.UI.createView({
left: 20,
font: {
fontSize: 10,
fontWeight: "bold",
font: "Bebas Neue"
},
color: "#fff",
width: "80dp",
height: "32dp",
backgroundImage: "/login/label.png",
top: 160,
id: "lblUserEmail"
});
$.__views.__alloyId4.add($.__views.lblUserEmail);
$.__views.__alloyId5 = Ti.UI.createLabel({
left: 10,
font: {
fontSize: 10,
fontWeight: "bold",
font: "Arial"
},
color: "#fff",
width: "80dp",
height: "32dp",
text: "USERNAME",
id: "__alloyId5"
});
$.__views.lblUserEmail.add($.__views.__alloyId5);
$.__views.userEmail = Ti.UI.createTextField({
width: "180dp",
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_LINE,
borderColor: "#BEBEBE",
height: "35dp",
top: "160dp",
left: 120,
hintText: "userEmail",
returnKeyType: Ti.UI.RETURNKEY_NEXT,
id: "userEmail"
});
$.__views.__alloyId4.add($.__views.userEmail);
send ? $.__views.userEmail.addEventListener("return", send) : __defers["$.__views.userEmail!return!send"] = true;
exports.destroy = function() {};
_.extend($, $.__views);
Alloy.Models.user;
__defers["$.__views.leftButton!click!cancel"] && $.__views.leftButton.addEventListener("click", cancel);
__defers["$.__views.rightButton!click!send"] && $.__views.rightButton.addEventListener("click", send);
__defers["$.__views.userEmail!return!send"] && $.__views.userEmail.addEventListener("return", send);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/controllers/feedRow.js<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/controllers/basic.js<file_sep>alert("inicio controler profile")
<file_sep>/Users/Shared/App/jellyrate/Resources/social.js<file_sep>var args = arguments[0] || {};
//Por cada feed, obtenemos el detalle.
//$.row.articleUrl = args.title;
$.title.text = args.title;
$.image.image = '/post/moto.gif';//args.image;
$.date.text = args.date;
$.rating.text = args.rating;
function comment(){
Alloy.CFG.navgroup.open(Alloy.createController('feedComment').getView());
}
function swipeMenu(e) {
if (e.direction == 'left'){
$.menuComment.animate({left: (-260), duration: 500});
}
if (e.direction == 'right'){
$.menuComment.animate({left: (0), duration: 500});
}
}
<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/sync/properties.js<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/controllers/web.js<file_sep>/Users/Shared/App/jellyrate/Resources/app.js<file_sep>function DBHelper(){
var dbConnect;
function openDbConnection() {
this.dbConnect = Ti.Database.open('jellyDB');
return this.dbConnect;
}
function closeDbConnection(){
this.dbConnect.close();
}
};
module.exports = DBHelper;<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/widget.js<file_sep>/Users/Shared/App/jellyrate/Resources/alloy/controllers/index.js<file_sep>if(OS_IOS) {
// add navgroup to the global scope
Alloy.CFG.navgroup = $.navgroup;
}
var di = Alloy.createController('home').getView();
$.dashboard.add(di);
/*di.addEventListener("click",function(e){
$.navgroup.open(Alloy.createController(e.source.con, e.source.params).getView());
});*/
$.index.open();<file_sep>function DBHelper() {}
module.exports = DBHelper;<file_sep>//alert("en controller forgot");
//var args = arguments[0] || {};
var user = Alloy.Models.user;
//$.icon.backgroundImage = args.image;
function cancel(evt) {
//alert('000');
Alloy.CFG.navgroup.close($.login, {animated: true});
}
function done(evt) {
Alloy.CFG.navgroup.close($.login, {animated: true});
}
function send(evt){
alert("function send()");
}
<file_sep>//var args = arguments[0] || {};
var user = Alloy.Models.user;
//$.icon.backgroundImage = args.image;
function cancel(evt) {
//alert('000');
Alloy.CFG.navgroup.close($.login, {animated: true});
}
function done(evt) {
Alloy.CFG.navgroup.close($.login, {animated: true});
}
function login(e) {
if (e && e.source && _.isFunction(e.source.blur)) {
e.source.blur();
}
//alert("usuario[" + $.username.value + "] password [" + $.password.value + "] largo user-->" + $.username.value.length + "<--");
if(($.username.value.length==0) || ($.password.value.length==0)){
alert("Usuario y/o Password no puede ser vacio");
}else{
var respuesta = user.login($.username.value, $.password.value);
//alert("respuesta [" + respuesta + "]");
if(respuesta==="false") {
alert("Credenciales erradas" + respuesta);
} else {
alert("Respuesta OK" + respuesta)
Alloy.CFG.navgroup.open(Alloy.createController('feed').getView());
}
// Alloy.CFG.navgroup.open(Alloy.createController('profile').getView());
//$.login.close();
//Alloy.createController('profile').getView().open({
//transition : Ti.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT
}
}
function focusPassword() {
$.password.focus();
}
function forgotPassword(evt){
Alloy.CFG.navgroup.open(Alloy.createController('forgot').getView());
}
<file_sep>educore
=======
EduCore is a mobile application structure for iOS And Android. EduCore is built off of Appcelerator Titanium Mobile SDK and the Alloy MVC Framework. Our goal is to lower the cost of entry for education instutitions to create multi-platform native mobile applications.
----------------------------------
Appcelerator, Appcelerator Titanium and associated marks and logos are
trademarks of Appcelerator, Inc.
Titanium is Copyright (c) 2008-2012 by Appcelerator, Inc. All Rights Reserved.
Titanium is licensed under the Apache Public License (Version 2). Please
see the LICENSE file for the full license.<file_sep>function Controller() {
function cancel() {
Alloy.CFG.navgroup.close($.login, {
animated: true
});
}
function login(e) {
e && e.source && _.isFunction(e.source.blur) && e.source.blur();
if (0 == $.username.value.length || 0 == $.password.value.length) alert("Usuario y/o Password no puede ser vacio"); else {
var respuesta = user.login($.username.value, $.password.value);
if ("false" === respuesta) alert("Credenciales erradas" + respuesta); else {
alert("Respuesta OK" + respuesta);
Alloy.CFG.navgroup.open(Alloy.createController("feed").getView());
}
}
}
function focusPassword() {
$.password.focus();
}
function forgotPassword() {
Alloy.CFG.navgroup.open(Alloy.createController("forgot").getView());
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.login = Ti.UI.createWindow({
backgroundImage: "/login/fondo.png",
navBarHidden: true,
barColor: "#D33B3C",
id: "login",
title: "Login"
});
$.__views.login && $.addTopLevelView($.__views.login);
$.__views.navBar = Ti.UI.createView({
top: 0,
height: 50,
width: Ti.UI.FILL,
backgroundImage: "/login/top-login.png",
id: "navBar"
});
$.__views.login.add($.__views.navBar);
$.__views.leftButton = Ti.UI.createButton({
font: {
fontSize: 10,
fontWeight: "normal",
font: "BebasNeue"
},
image: "/cancel.png",
borderRadius: 0,
width: 63,
height: 25,
left: 10,
title: "",
id: "leftButton"
});
$.__views.navBar.add($.__views.leftButton);
cancel ? $.__views.leftButton.addEventListener("click", cancel) : __defers["$.__views.leftButton!click!cancel"] = true;
$.__views.rightButton = Ti.UI.createButton({
font: {
fontSize: 10,
fontWeight: "normal",
font: "BebasNeue"
},
image: "/done.png",
borderRadius: 0,
width: 63,
height: 25,
right: 10,
title: "",
id: "rightButton"
});
$.__views.navBar.add($.__views.rightButton);
login ? $.__views.rightButton.addEventListener("click", login) : __defers["$.__views.rightButton!click!login"] = true;
$.__views.__alloyId13 = Ti.UI.createScrollView({
top: 50,
id: "__alloyId13"
});
$.__views.login.add($.__views.__alloyId13);
$.__views.lblTitulologin = Ti.UI.createLabel({
top: 40,
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
font: {
fontSize: 50,
fontWeight: "bold",
fontFamily: "BebasNeue"
},
color: "#ed4243",
text: "LOGIN",
id: "lblTitulologin"
});
$.__views.__alloyId13.add($.__views.lblTitulologin);
$.__views.lblUsername = Ti.UI.createView({
left: 20,
font: {
fontSize: 10,
fontWeight: "bold",
font: "BebasNeue"
},
color: "#fff",
width: "80dp",
height: "32dp",
backgroundImage: "/login/label.png",
top: 160,
id: "lblUsername"
});
$.__views.__alloyId13.add($.__views.lblUsername);
$.__views.__alloyId14 = Ti.UI.createLabel({
left: 10,
font: {
fontSize: 10,
fontWeight: "bold",
fontFamily: "BebasNeue"
},
color: "#fff",
width: "80dp",
height: "32dp",
text: "USERNAME",
id: "__alloyId14"
});
$.__views.lblUsername.add($.__views.__alloyId14);
$.__views.username = Ti.UI.createTextField({
width: "180dp",
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_LINE,
borderColor: "#BEBEBE",
height: "35dp",
top: "160dp",
left: 120,
hintText: "username",
returnKeyType: Ti.UI.RETURNKEY_NEXT,
id: "username"
});
$.__views.__alloyId13.add($.__views.username);
focusPassword ? $.__views.username.addEventListener("return", focusPassword) : __defers["$.__views.username!return!focusPassword"] = true;
$.__views.lblPassword = Ti.UI.createView({
left: 20,
font: {
fontSize: 10,
fontWeight: "bold",
font: "BebasNeue"
},
color: "#fff",
width: "80dp",
height: "32dp",
backgroundImage: "/login/label.png",
top: 210,
id: "lblPassword"
});
$.__views.__alloyId13.add($.__views.lblPassword);
$.__views.__alloyId15 = Ti.UI.createLabel({
left: 10,
font: {
fontSize: 10,
fontWeight: "bold",
fontFamily: "BebasNeue"
},
color: "#fff",
width: "80dp",
height: "32dp",
text: "PASSWORD",
id: "__alloyId15"
});
$.__views.lblPassword.add($.__views.__alloyId15);
$.__views.password = Ti.UI.createTextField({
width: "180dp",
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle: Ti.UI.INPUT_BORDERSTYLE_LINE,
borderColor: "#BEBEBE",
height: "35dp",
top: "210dp",
left: 120,
hintText: "<PASSWORD>",
passwordMask: true,
returnKeyType: Ti.UI.RETURNKEY_DONE,
id: "password"
});
$.__views.__alloyId13.add($.__views.password);
login ? $.__views.password.addEventListener("return", login) : __defers["$.__views.password!return!login"] = true;
$.__views.__alloyId16 = Ti.UI.createButton({
font: {
fontSize: 10,
fontWeight: "normal",
font: "BebasNeue"
},
top: 250,
height: 12,
width: 111,
borderWidth: 0,
borderRadius: 0,
title: "I forgot my password",
id: "__alloyId16"
});
$.__views.__alloyId13.add($.__views.__alloyId16);
forgotPassword ? $.__views.__alloyId16.addEventListener("click", forgotPassword) : __defers["$.__views.__alloyId16!click!forgotPassword"] = true;
exports.destroy = function() {};
_.extend($, $.__views);
var user = Alloy.Models.user;
__defers["$.__views.leftButton!click!cancel"] && $.__views.leftButton.addEventListener("click", cancel);
__defers["$.__views.rightButton!click!login"] && $.__views.rightButton.addEventListener("click", login);
__defers["$.__views.username!return!focusPassword"] && $.__views.username.addEventListener("return", focusPassword);
__defers["$.__views.password!return!login"] && $.__views.password.addEventListener("return", login);
__defers["$.__views.__alloyId16!click!forgotPassword"] && $.__views.__alloyId16.addEventListener("click", forgotPassword);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller; | eb4456205d8f514822bd6d5fa3e830ba386673c0 | [
"JavaScript",
"Markdown"
] | 47 | JavaScript | abada/Jelly | 9531e58aba39cf5793d428977c57b41a7b913faf | 3af808a581c552ef98b726b2272bc5c78315f85f |
refs/heads/master | <repo_name>isosphere/cross-correlate-sets<file_sep>/README.md
# cross-correlate-sets
Cross-correlate two equally-sized sets of data. Supports "unbaised" correlation and normalization.
<file_sep>/cross-correlate.py
#!/usr/bin/env python
from math import sqrt
from csv import reader
def normalization_divisor(set_a, set_b):
""" Given two sets, returns the divisor that should be used to
normalize the cross-correlation value """
a_squared_sum = 0
b_squared_sum = 0
for i in range(0, len(set_a)):
a_squared_sum += set_a[i]**2
b_squared_sum += set_b[i]**2
return sqrt(a_squared_sum*b_squared_sum)
def cross_correlate(set_a, set_b, normalize=False, unbaised=False):
""" Given two equally-sized sets, returns the correlation set computed
by taking a sliding "lag" window that is used to offset the second set.
Takes an optional "normalize" flag that will normalize each item in the
correlation set (off by default). Also takes an "unbaised" flag that will
weigh each computation of the correlation of the two sets for a given lag,
giving greater lags greater weight. Since the sets have the same length,
lag can bias the correlation to lower values because there are fewer data
to iterate over, and this technique can help avoid that. It's off by default.
"""
correlation_set = {}
if normalize:
n_divisor = normalization_divisor(set_a, set_b)
if len(set_a) == len(set_b):
for lag in range(-1*(len(set_a)-1), len(set_a)):
print lag,
c_sum = 0
for i in range(0, len(set_a)):
if i - lag < 0 or i - lag >= len(set_a):
print ".", # "miss" - the lag prevents a hit for i in both sets a and b
else:
print "!", # "hit" - there's a corresponding set_b[i] for this set_a[i]
c_sum += set_a[i]*set_b[i-lag]
print ", = %.2f" % c_sum
if unbaised:
c_sum /= len(set_a) - abs(lag) # greater lag, greater c_sum
if normalize:
correlation_set[lag] = c_sum/n_divisor # FIXME unbaised flag probably makes this normalization invalid
else:
correlation_set[lag] = c_sum
return correlation_set
else:
print "Sets must have the same length"
return -1
def best_correlation(set_a, set_b, normalize=True, unbaised=False):
""" Returns the best correlation found by cross_correlate(), and the lag required to find it. """
correlation_set = cross_correlate(set_a, set_b, normalize=normalize, unbaised=unbaised)
maximum_correlation_position = max(correlation_set.iterkeys(), key=(lambda key: correlation_set[key]))
print "Best correlation when set_b lags by %d positions, with a correlation of %f" % (maximum_correlation_position, correlation_set[maximum_correlation_position])
if __name__ == "__main__":
indexes = []
set_a = []
set_b = []
with open('input.csv', 'rb') as csvfile:
inputreader = reader(csvfile) # header\nindex,set_a,set_b\nindex,set_a,set_b\n...
# skip header
next(inputreader)
for row in inputreader:
if row[0] == '':
continue
indexes.append(row[0])
set_a.append(float(row[1]))
set_b.append(float(row[2]))
best_correlation(set_a, set_b, normalize=True, unbaised=True)
| 2b127af005ee967a5e020c1a664d6610ee91d92a | [
"Markdown",
"Python"
] | 2 | Markdown | isosphere/cross-correlate-sets | 25839df00f38646c9499ed41e0db85a53b75621a | 1d7a14c62794e4a429b83ef797157f45b0b46f21 |
refs/heads/master | <repo_name>ifiokjr/whelmo<file_sep>/@whelmo/ui/.storybook/webpack.config.js
/* eslint-disable no-param-reassign */
const path = require('path')
module.exports = (baseConfig, env, config) => {
config.module.rules.push({
test: /\.ttf$/,
use: [{ loader: 'url-loader', options: { limit: 10000 } }], // or directly file-loader
include: [path.resolve(__dirname, '../src')],
})
config.module.rules.push({
test: /\.tsx?$/,
include: [path.resolve(__dirname, '../src')],
use: [
require.resolve('ts-loader'),
// require.resolve('react-docgen-typescript-loader'),
],
})
config.module.rules[0].exclude = []
config.module.rules[0].query.presets.unshift('react-native')
// console.log(config.module.rules[0])
config.module.rules[0].include.push(
/node_modules\/react-native-/,
// path.resolve(__dirname, '../node_modules/react-native-linear-gradient'),
// path.resolve(__dirname, '../node_modules/react-native-web-linear-gradient'),
path.resolve(
__dirname,
'../../../node_modules/react-native-web-linear-gradient',
),
path.resolve(__dirname, '../../../node_modules/react-native-vector-icons'),
// path.resolve(__dirname, '../../../node_modules/react-native-responsive'),
// path.resolve(__dirname, '../node_modules/react-native-responsive'),
)
config.resolve.extensions.push('.ts', '.tsx')
config.resolve.alias['react-native'] = 'react-native-web'
config.resolve.alias['react-native-linear-gradient'] =
'react-native-web-linear-gradient'
// Object.assign(config.output, {
// publicPath: 'http://localhost:6006/',
// })
return config
}
<file_sep>/@whelmo/ui/src/constants.ts
/**
* Designs are based on this width.
*/
export const BASE_DESIGN_WIDTH = 375;
/**
* Height from base designs.
*/
export const BASE_DESIGN_HEIGHT = 667;
<file_sep>/@whelmo/ui/src/utils/stories.ts
import { withInfo, WrapStoryProps } from '@storybook/addon-info';
import * as React from 'react';
import colors from '../theme/colors';
const wInfoStyle = {
header: {
h1: {
marginRight: '20px',
fontSize: '25px',
display: 'inline',
},
body: {
paddingTop: 0,
paddingBottom: 0,
// color: colors.fontDark,
fontFamily: 'Roboto',
},
h2: {
display: 'inline',
color: colors.fontDark,
},
},
infoBody: {
fontFamily: 'Roboto',
backgroundColor: colors.backgroundLight,
padding: '0px 5px',
lineHeight: '2',
},
};
export const wInfo: WithInfo = (text: string) =>
withInfo({ inline: true, styles: wInfoStyle, text });
export type WithInfo = (
text: string,
) => (
storyFn: () =>
| React.ComponentClass<{}>
| React.StatelessComponent<{}>
| JSX.Element
| Array<
React.ComponentClass<{}> | React.StatelessComponent<{}> | JSX.Element
>,
) => () => React.ReactElement<WrapStoryProps>;
<file_sep>/@whelmo/ui/src/theme/fonts.ts
import { isAndroid } from '../utils/checks';
import colors from './colors';
export const fontFamily = 'Roboto';
const color = colors.fontDark;
export enum FontWeights {
thin = '100',
extraLight = '200',
light = '300',
regular = '400',
medium = '500',
semiBold = '600',
bold = '700',
extraBold = '800',
black = '900',
}
export type FontWeightType = keyof typeof FontWeights;
export const fontConfig = {
thin: {
weight: FontWeights.thin,
name: isAndroid ? `${fontFamily}-Thin` : fontFamily,
},
extraLight: {
weight: FontWeights.extraLight,
name: isAndroid ? `${fontFamily}-ExtraLight` : fontFamily,
},
light: {
weight: FontWeights.light,
name: isAndroid ? `${fontFamily}-Light` : fontFamily,
},
regular: {
weight: FontWeights.regular,
name: isAndroid ? `${fontFamily}-Regular` : fontFamily,
},
medium: {
weight: FontWeights.medium,
name: isAndroid ? `${fontFamily}-Medium` : fontFamily,
},
semiBold: {
weight: FontWeights.semiBold,
name: isAndroid ? `${fontFamily}-SemiBold` : fontFamily,
},
bold: {
weight: FontWeights.bold,
name: isAndroid ? `${fontFamily}-Bold` : fontFamily,
},
extraBold: {
weight: FontWeights.extraBold,
name: isAndroid ? `${fontFamily}-ExtraBold` : fontFamily,
},
black: {
weight: FontWeights.black,
name: isAndroid ? `${fontFamily}-Black` : fontFamily,
},
};
export const fonts = {
thin: {
color,
fontFamily: fontConfig.thin.name,
fontWeight: fontConfig.thin.weight,
},
extraLight: {
color,
fontFamily: fontConfig.extraLight.name,
fontWeight: fontConfig.extraLight.weight,
},
light: {
color,
fontFamily: fontConfig.light.name,
fontWeight: fontConfig.light.weight,
},
regular: {
color,
fontFamily: fontConfig.regular.name,
fontWeight: fontConfig.regular.weight,
},
medium: {
color,
fontFamily: fontConfig.medium.name,
fontWeight: fontConfig.medium.weight,
},
semiBold: {
color,
fontFamily: fontConfig.semiBold.name,
fontWeight: fontConfig.semiBold.weight,
},
bold: {
color,
fontFamily: fontConfig.bold.name,
fontWeight: fontConfig.bold.weight,
},
extraBold: {
color,
fontFamily: fontConfig.extraBold.name,
fontWeight: fontConfig.extraBold.weight,
},
black: {
color,
fontFamily: fontConfig.black.name,
fontWeight: fontConfig.black.weight,
},
};
<file_sep>/scripts/postinstall
#!/usr/bin/env node
const insights = require('./helpers/insights')
const debug = require('debug')('script:postinstall')
insights.askPermission().then(() => {
insights.trackInstallAgent()
debug(process.env)
})
<file_sep>/@whelmo/ui/src/theme/colors.ts
const colors = {
primary: '#448AFF',
primaryLight: '#79BEFF',
fontDark: '#546E7A',
fontSoft: '#78909C',
backgroundLight: '#EBEFF0',
backgroundDark: '#B0BEC6',
backgroundAccent: '#ECF3FE',
backgroundStories: '#DCE2EF',
error: '#FA8A80',
success: '#64DD17',
warning: '#FCC400',
white: '#FFF',
like: '#FA80AB',
borderCard: 'rgba(207,216,220,.2)',
borderDivider: '#E7EBED',
};
export default colors;
<file_sep>/@whelmo/ui/src/utils/checks.ts
import { Dimensions, Platform, PlatformIOSStatic } from 'react-native';
export const isReactNative =
typeof navigator === 'object' && navigator.product === 'ReactNative';
export const isElectron =
typeof navigator === 'object' &&
typeof navigator.userAgent === 'string' &&
navigator.userAgent.indexOf('Electron') >= 0;
export const isWeb = !isElectron && !isReactNative;
const { width, height } = Dimensions.get('window');
export const isAndroid = Platform.OS === 'android';
export const isIOS = Platform.OS === 'ios';
export const isIPhoneX =
Platform.OS === 'ios' &&
!(Platform as PlatformIOSStatic).isPad &&
!(Platform as PlatformIOSStatic).isTVOS &&
(height === 812 || width === 812);
<file_sep>/@whelmo/ui/src/index.ts
export function testerFunction() {
// tslint:disable-next-line:no-console
console.log('this is a tester function');
}
<file_sep>/@whelmo/ui/src/utils/dimensions.ts
import { Dimensions } from 'react-native';
import { BASE_DESIGN_HEIGHT, BASE_DESIGN_WIDTH } from '../constants';
const { height, width } = Dimensions.get('screen');
/**
* Generates a responsive height in pixels from provided percentage.
*
* @param {Number} percent - percentage of device height
* @return {Number}
*/
export const responsiveHeight = (percent?: number) => {
if (percent === 100 || !isFinite(percent || NaN) || !percent) {
return height;
}
return Math.round(height * (percent / 100));
};
/**
* Generates a responsive width in pixels from provided percentage.
*
* @param {Number} w - percentage of device width
* @return {Number}
*/
export const responsiveWidth = (percent?: number) => {
if (percent === 100 || !Number.isFinite(percent || NaN) || !percent) {
return width;
}
return Math.round(width * (percent / 100));
};
/**
* @param y - the distance from top
*/
export const distanceFromBottomOfScreenToY = (y: number) => height - y;
/**
* Converts the pixel unit (e.g. value from design file) to a screen
* width relative unit.
*
* @param unit value passed to be used as base value
*/
export function relativeWidth(unit: number, rounding: boolean = true) {
const value = unit / BASE_DESIGN_WIDTH * width;
return rounding ? Math.round(value) : value;
}
/**
* For greater control of sizing, scales the base design implementation to a desired factor.
*
* Very useful in creating consistent fontSizes.
*
* @param unit value passed to be used as base value
*/
export function scaleWidth(size: number, factor: number = 0.5) {
if (!isFinite(factor)) {
return relativeWidth(size);
}
return Math.round(size + (relativeWidth(size, false) - size) * factor);
}
/**
* Converts the pixel unit (e.g. value from design file) to a screen
* height relative unit.
*
* @param unit value passed to be used as base value
*/
export function relativeHeight(unit: number) {
const value = unit / BASE_DESIGN_HEIGHT * height;
return Math.round(value);
}
/**
* Converts the pixel unit (e.g. value from design file) to a screen
* diagonal relative unit.
*
* @param unit value passed to be used as base value
*/
export function relativeDiagonal(unit: number, rounding: boolean = true) {
const defaultHypotenuse = Math.sqrt(
BASE_DESIGN_HEIGHT ** 2 + BASE_DESIGN_WIDTH ** 2,
);
const deviceHypotenuse = Math.sqrt(height ** 2 + width ** 2);
const ratio = deviceHypotenuse / defaultHypotenuse;
const value = ratio * unit;
return rounding ? Math.round(value) : value;
}
/**
* For greater control of sizing, scales the base design implementation to a desired factor.
*
* Very useful in creating consistent fontSizes.
*
* @param unit value passed to be used as base value
*/
export function scale(unit: number, factor: number = 0.7) {
if (!isFinite(factor)) {
return relativeDiagonal(unit);
}
return Math.round(unit + (relativeDiagonal(unit, false) - unit) * factor);
}
<file_sep>/@types/react-native-vector-icons/index.d.ts
declare module 'react-native-vector-icons/dist/Ionicons' {
import { Icon } from 'react-native-vector-icons/Icon';
declare const Icon: Icon;
export = Icon;
}
<file_sep>/jest.config.js
module.exports = {
collectCoverageFrom: ['**/*.{ts,tsx}', '!**/*.d.ts'],
}
<file_sep>/@types/react-native-responsive/index.d.ts
declare module 'react-native-responsive';
| efe2559100b32ca08fe4e422f07bf1b4b7a8937a | [
"JavaScript",
"TypeScript"
] | 12 | JavaScript | ifiokjr/whelmo | c426cfcb222bcfea70b6f5c01afc23a7e5c6c159 | f1cfad6a23f3cdcae8e4be1c1173a208d2e10f22 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
namespace KokoroBot
{
//comment
partial class Program
{
static string getTillerinoText(long userID)
{
switch (userID)
{
case 95568509345472512: //Kard
return "Tsunamaru - Daidai Genome [Insane] HDDT future you: 329pp 95%: 262pp | 98%: 309pp | 99%: 335pp | 100%: 370pp | 2:00 ★ 6.01 ♫ 202.5 AR9.67";
break;
case 95543627391959040: //Part
return "Panda Eyes & Teminite - Highscore [_part's madness] FLDT future you: Kardshark's praiser pp 95%: 344pp | 98%: 405pp | 99%: 489pp | 100%: 522pp | 2:00 ★ 7.25 ♫ 110 AR10.33";
break;
case 95568415057522688: //Tironas
return "Reol - Asymmetry [cRyo[Skystar]'s Farewell] future you: 50pp 95%: 304pp | 98%: 340pp | 99%: 363pp | 100%: 395pp | 4:11 ★ 6.43 ♫ 184 AR9.5";
break;
default:
int _index = Program.rng.Next(randomTillerinoTexts.Length);
return randomTillerinoTexts[_index];
break;
}
}
static string[] randomTillerinoTexts = new string[]
{
"DragonForce - Cry Thunder [Legend] HDHR future you: -10pp 95%: 817pp | 98%: 887pp | 99%: 929pp | 100%: 984pp | 5:11 ★ 8.5 ♫ 130 AR10",
"Panda Eyes & Teminite - Highscore [Tironas[Fixing]] future you: 210pp 95%: 180pp | 98%: 207pp | 99%: 230pp | 100%: 270pp | 2:00 ★ 5.84 ♫ 110 AR10"
};
internal async static Task handleTiroCommands(MessageEventArgs e, DiscordClient client, Channel currentChannel)
{
switch(e.Message.Text)
{
case "-touhou":
await client.SendMessage(currentChannel, "is THAT another TOUHOU map???");
break;
case "!r":
await client.SendMessage(currentChannel, getTillerinoText(e.Message.User.Id));
break;
default:
break;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Discord;
using NAudio;
namespace KokoroBot
{
partial class Program
{
static Discord.Audio.IDiscordVoiceClient voiceclient = null;
static Server voiceserver = null;
public static Random rng = new Random();
static bool mute = false;
static bool restart = false;
static bool quit = false;
static bool running = true;
static KokoroBotRPG rpg;
static void Main(string[] args)
{
if (!restart)
{
rpg = new KokoroBotRPG();
loadFiles();
}
else
{
restart = false;
}
{
DiscordClientConfig config = new DiscordClientConfig();
config.VoiceMode = DiscordVoiceMode.Outgoing;
config.VoiceBufferLength = 40;
var client = new DiscordClient(config);
//Display all log messages in the console
client.LogMessage += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");
client.MessageReceived += async (s, e) =>
{
Console.WriteLine(e.Message.User.Name + ": " + e.Message.Text);
if (!e.Message.IsAuthor)
{
var currentChannel = e.Channel;
if (e.User.Id == 95543627391959040)
{
if (e.Message.Text == "-mute")
{
mute = !mute;
await client.SendMessage(currentChannel, "KokoroBot is now mute: " + mute.ToString());
}
else if (e.Message.Text == "-clear")
{
if (voiceclient != null)
voiceclient.ClearVoicePCM();
}
else if (e.Message.Text == "-save")
{
saveFiles();
await client.SendMessage(currentChannel, "I have saved everything :3");
}
else if (e.Message.Text == "-dc")
{
quit = true;
running = false;
}
else if (e.Message.Text == "-restart")
{
await client.SendMessage(currentChannel, "Cya on the other side :3");
restart = true;
running = false;
await client.Disconnect();
}
else if (e.Message.Text.StartsWith("-join"))
{
var channels = e.Server.Channels.Where((Channel chan) => {
return e.Message.Text.Substring(5).TrimStart(' ') == chan.Name && chan.Type == ChannelType.Voice; });
if (channels.Any())
{
var channel = channels.First();
Console.WriteLine("KokoroBot tries to join Channel: " + channel.Name);
voiceclient = await client.JoinVoiceServer(channel);
voiceserver = e.Message.Server;
}
}
else if (e.Message.Text == "-leave")
{
if (voiceclient != null)
{
voiceclient.ClearVoicePCM();
await client.LeaveVoiceServer(voiceserver);
voiceclient = null;
voiceserver = null;
}
}
}
else if (e.User.Name == "part")
{
await client.SendMessage(currentChannel, "I don't like you. B-b-baka. >.<");
return;
}
if (!mute) {
if (e.Message.Text.Length > 0)
{
string[] splitmessage = e.Message.Text.Split(' ');
if (splitmessage[0] == "-kardfacts")
{
if (splitmessage.Length > 2)
{
if (splitmessage[1] == "add")
{
try
{
string finalstr = "";
for (int i = 2; i < splitmessage.Length; i++)
{
if (i != 2)
finalstr += ' ' + splitmessage[i];
else
finalstr = splitmessage[i];
}
if (finalstr.Length > 5)
{
kardFactsStrings.Add(finalstr);
await client.SendMessage(currentChannel, "A new fact about Kard has been added. (Yay ^-^):");
currentChannel = e.Channel;
await client.SendMessage(currentChannel, finalstr);
}
else
{
throw new IOException("Hue.");
}
}
catch (Exception)
{
await client.SendMessage(currentChannel, "That hurt <.< Don't do this again, ok? :3");
}
}
}
else
{
await client.SendMessage(currentChannel, kardFacts());
}
}
else if (e.Message.Text.StartsWith("-play"))
{
Task.Run(() => { PlaySoundWav(e); });
}
else if(e.Message.Text.StartsWith("-getclientid"))
{
if (e.Message.Text.Length > "-getclientid ".Length)
{
try {
await client.SendMessage(currentChannel, e.Server.Members.Where((User u) =>
{
return u.Name.StartsWith(e.Message.Text.Substring("-getclientid ".Length));
}).First().Id.ToString());
}
catch(Exception)
{
await client.SendMessage(currentChannel, "User does not exist. B-baka.");
}
}
else
{
await client.SendMessage(currentChannel, e.Message.User.Id.ToString());
}
}
else if(e.Message.Text.StartsWith(":"))
{
await rpg.HandleCommands(e, client, currentChannel);
}
else if (await handleSimpleCommands(e, client, currentChannel) == false)
{
await handleTiroCommands(e, client, currentChannel);
}
}
}
}
};
//Convert our sync method to an async one and block the Main function until the bot disconnects
client.Run(async () =>
{
//Connect to the Discord server using our email and password
await client.Connect(Sensitive.email, Sensitive.passwd);
while (running)
{
var inputTask = Task.Run<string>((Func<string>)Console.ReadLine);
await inputTask;
string dbgCommand = inputTask.Result;
if( dbgCommand == "exit" || restart || quit)
{
running = false;
await client.Disconnect();
} else if ( dbgCommand == "listservers")
{
foreach(Server s in client.AllServers)
{
Console.WriteLine("#######################################");
Console.WriteLine("Servername: " + s.Name);
Console.WriteLine("Voicechannels: ");
foreach(Channel c in s.VoiceChannels)
{
Console.WriteLine(" "+c.Name);
}
Console.WriteLine("Channels: ");
foreach (Channel c in s.Channels)
{
Console.WriteLine(" "+c.Name);
}
}
}
}
//If we are not a member of any server, use our invite code (made beforehand in the official Discord Client)
});
}
if (!restart)
{
saveFiles();
}
else
{
Main(new string[] { });
}
}
private static async Task<bool> handleSimpleCommands(MessageEventArgs e, DiscordClient client, Channel currentChannel)
{
switch (e.Message.Text)
{
case "-waifu":
await client.SendMessage(currentChannel, "KokoroBot is your waifu now.");
break;
case "-brainpower":
await client.SendMessage(currentChannel, "Huehuehue.");
await client.SendMessage(currentChannel, "You know...");
await client.SendMessage(currentChannel, @">youtube https://www.youtube.com/watch?v=0bOV4ExHPZY");
break;
case "-praise":
await client.SendMessage(currentChannel, "ALL PRAISE KARD (/O.o)/");
break;
case "-part":
await client.SendMessage(currentChannel, "part is the baka who created this bot.");
break;
case "-amazing":
await client.SendMessage(currentChannel, "Amazing \nAmazing \nAmazing \nAmazing \nAmazing");
break;
case "-??":
await client.SendMessage(currentChannel, "??\n??\n??\n??\n??\n??\n??\n??\n??");
break;
case "-sayo":
await client.SendMessage(currentChannel, sayoFacts());
break;
default:
return false;
}
return true;
}
private async static void PlaySoundWav(MessageEventArgs e)
{
if (e.Message.Text.Length > "-play ".Length && voiceclient != null)
{
string file = e.Message.Text.Substring("-play ".Length);
Console.WriteLine("Trying to play: " + file);
try {
var ws = new NAudio.Wave.WaveFileReader(file);
byte[] buf;
if (ws.WaveFormat.Channels > 1)
{
var tomono = new NAudio.Wave.StereoToMonoProvider16(ws);
tomono.RightVolume = 0.5f;
tomono.LeftVolume = 0.5f;
buf = new byte[ws.Length];
while (ws.HasData(ws.WaveFormat.AverageBytesPerSecond))
{
tomono.Read(buf, 0, ws.WaveFormat.AverageBytesPerSecond);
voiceclient.SendVoicePCM(buf, buf.Length);
}
}
else
{
buf = new byte[ws.Length];
ws.Read(buf, 0, buf.Length);
voiceclient.SendVoicePCM(buf, buf.Length);
}
ws.Close();
}
catch(Exception)
{
Console.WriteLine("File not found or incompatible.");
}
}
}
static string kardFacts()
{
return kardFactsStrings[rng.Next(0, kardFactsStrings.Count)];
}
static string sayoFacts()
{
var rngresult = rng.Next(0, sayoQuestStrings.Length);
return "Question:" + sayoQuestStrings[rngresult] + "\nAnswer:" + sayoAnswStrings[rngresult];
}
static List<string> kardFactsStrings;
static string[] sayoQuestStrings;
static string[] sayoAnswStrings;
static void saveFiles()
{
File.WriteAllLines("kardfacts.txt", kardFactsStrings.ToArray());
rpg.Save();
}
static void loadFiles()
{
rpg.Load();
kardFactsStrings = new List<string>(File.ReadAllLines("kardfacts.txt"));
var saystrings = new List<string>(File.ReadAllLines("sayo.txt"));
sayoQuestStrings = new string[19];
sayoAnswStrings = new string[19];
sayoAnswStrings.Initialize();
sayoQuestStrings.Initialize();
int currentnum = 0;
bool answer = true;
foreach(string s in saystrings)
{
if (s.Length > 0)
{
if (char.IsDigit(s[0]))
{
currentnum = Int32.Parse(s);
answer = !answer;
}
else if (answer)
{
if (sayoAnswStrings[currentnum] != "")
{
sayoAnswStrings[currentnum] += '\n'+" " + s;
}
else
{
sayoAnswStrings[currentnum] += " "+s;
}
}
else
{
if (sayoQuestStrings[currentnum] != "")
{
sayoQuestStrings[currentnum] += '\n' + s;
}
else
{
sayoQuestStrings[currentnum] += s;
}
}
}
}
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
using Discord;
namespace KokoroBot
{
class KokoroBotRPG
{
Dictionary<long, KRPG_player> players;
Random rng;
const int CURRENT_VERSION=1;
HashAlgorithm hshfnc = HashAlgorithm.Create("SHA");
public KokoroBotRPG()
{
players = new Dictionary<long, KRPG_player>();
rng = new Random((int)(DateTime.Now.ToFileTimeUtc() % int.MaxValue));
}
public void Load()
{
try {
if (File.Exists("kokororpg"))
{
BinaryReader br = new BinaryReader(File.OpenRead("kokororpg"));
int count = br.ReadInt32();
int vers = br.ReadInt32();
if (vers == 1)
{
for (int i = 0; i < count; i++)
{
long id = br.ReadInt64();
float xp = br.ReadSingle();
int level = br.ReadInt32();
float hp = br.ReadSingle();
var plr = new KRPG_player(id);
plr.xp = xp;
plr.level = level;
plr.hp = hp;
players.Add(id, plr);
}
}
br.Close();
}
}
catch(IOException)
{
Console.WriteLine("Did someone say IOException?");
}
}
public void Save()
{
try {
BinaryWriter bw = new BinaryWriter(File.Open("kokororpg", FileMode.OpenOrCreate));
bw.Write(players.Count);
bw.Write(CURRENT_VERSION);
var player_col = players.ToArray();
for (int i = 0; i < player_col.Length; i++)
{
bw.Write(player_col[i].Value.ID);
bw.Write(player_col[i].Value.xp);
bw.Write(player_col[i].Value.level);
bw.Write(player_col[i].Value.hp);
}
}
catch (Exception)
{
Console.WriteLine("Did someone say IOException?");
}
}
public async Task HandleCommands(MessageEventArgs e, DiscordClient client, Channel currentChannel)
{
try {
string log = "";
string clean_message = e.Message.Text.Substring(1);
if (!players.ContainsKey(e.User.Id))
{
players.Add(e.User.Id, new KRPG_player(e.User.Id));
}
KRPG_player player = players[e.User.Id];
if (clean_message.Contains("@"))
{
string command = clean_message.Split('@')[0];
command = command.Trim(' ');
string target = clean_message.Split('@')[1];
target = target.Trim(' ');
var validUsers = e.Server.Members.Where((User u) =>
{
return u.Name == target;
});
var target_usr = validUsers.First();
if (target_usr != null)
{
if (target_usr.Status == UserStatus.Offline)
{
await client.SendMessage(currentChannel, "But nobody came..");
return;
}
if (!players.ContainsKey(target_usr.Id))
{
players.Add(target_usr.Id, new KRPG_player(target_usr.Id));
}
KRPG_player target_plr;
if (target_usr.Id == player.ID)
{
target_plr = player;
}
else
{
target_plr = players[target_usr.Id];
}
if (command == "level")
{
log += target + " is level " + target_plr.level + " | " + target_plr.xp + '/' + (target_plr.level * target_plr.level * player.level) + '\n';
await client.SendMessage(currentChannel, log);
return;
}
var bytes = Encoding.UTF8.GetBytes(target_usr + command);
byte hash_b = hshfnc.ComputeHash(bytes)[0];
float variation = 0.4f + Math.Min(0.4f, player.level * 0.01f) + 0.01f * rng.Next(Math.Max(20, 60 - player.level));
float hash = (float)hash_b / 1.28f;
float scale = 0.01f * (hash - 100f);
float damagescale = Math.Max(player.level * 10, 8f * (float)Math.Pow(1.2, player.level));
float nd_absolutedamage = ((damagescale * variation) * scale);
float absolutedamage = nd_absolutedamage + calculatedLevelDamage(player, target_plr, nd_absolutedamage);
float possibledamage = damagescale + calculatedLevelDamage(player,target_plr, damagescale);
//await client.SendMessage(currentChannel, e.User.Name + ' ' + command + "s " + target + '.');
if (absolutedamage > 0)
{
log += "It deals " + absolutedamage.ToString() + '/' + possibledamage.ToString() + " damage." + '\n';
}
else
{
log += "It heals for " + absolutedamage.ToString() + '/' + possibledamage.ToString() + " damage." + '\n';
}
target_plr.hp -= absolutedamage;
if (target_plr.hp <= 0)
{
target_plr.hp = float.MaxValue;
if (target_plr != player)
{
float unadjustedxp = Math.Max((target_plr.level * target_plr.level), (target_plr.level * target_plr.level * target_plr.level)/10f);
float xpgain = unadjustedxp * (float)Math.Pow(1.25, target_plr.level - player.level);
if (xpgain <= 0.5f)
{
log += target + " has been killed for fun. You're going down a dark path, " + e.User.Name + ".\n";
}
else
{
log += target + " has been killed and resurrected. +" + xpgain + "XP" + '\n';
player.xp += xpgain;
}
}
else
{
log += target + " has killed themselves and resurrected. +1 suicide attempt" + '\n';
}
}
else
{
log += target + " has " + target_plr.hp + " left." + '\n';
}
}
}
else
{
// TODO: Item logic etc.
}
if (player.xp > player.level * player.level * player.level)
{
player.xp = player.xp - (player.level * player.level * player.level);
player.level++;
log += e.User.Name + " has leveled up to Level " + player.level + '.' + '\n';
}
if (log != "")
{
await client.SendMessage(currentChannel, log);
}
}
catch(Exception)
{
Console.WriteLine("welp.");
}
}
private static float calculatedLevelDamage(KRPG_player player, KRPG_player target_plr, float nd_absolutedamage)
{
return Math.Max(0f, (nd_absolutedamage * (((float)player.level - (float)target_plr.level) / 4f)));
}
}
class KRPG_player
{
public long ID;
public float xp;
public int level;
public float hp
{
get
{
return _hp;
}
set
{
if(value > 10.0 * Math.Pow(1.4, level))
{
_hp = (float)(10.0 * Math.Pow(1.4, level));
}
else
{
_hp = value;
}
}
}
float _hp = 0;
public KRPG_player(long ID)
{
this.ID = ID;
xp = 0;
level = 1;
hp = level * 10;
}
}
}
| 431761fb34601a8a0e09dd582ff67ad7dc695138 | [
"C#"
] | 3 | C# | part174/KokoroBot | ea8946fbb151f11ddda6a1cd43bf677ef7a40843 | 9d46ec8f2e377db95efd4044f865d0f3ddd46b60 |
refs/heads/master | <repo_name>greysky-io/validating-data-with-joi<file_sep>/server.js
const express = require('express');
const bodyParser = require('body-parser');
const Joi = require('joi');
const validationMiddleware = require('./middleware');
const app = express();
const port = 3000;
app.use(bodyParser.json());
//these should go into a database...
const books = [
{
title: "The Hitchhiker's Guide to the Galaxy",
author: '<NAME>',
pages: 42,
publishDate: new Date('10/12/1979'),
},
{
title: 'The Restaurant at the End of the Universe',
author: '<NAME>',
pages: 84,
publishDate: new Date('10/01/1980'),
},
{
title: 'Life, the Universe and Everything',
author: '<NAME>',
pages: 126,
publishDate: new Date('08/01/1982'),
},
];
const bookSchema = Joi.object().keys({
title: Joi.string().required(),
author: Joi.string().required(),
pages: Joi.number()
.integer()
.min(1)
.required(),
publishDate: Joi.date().max('now'),
});
app.get('/books', (req, res) => {
res.send(JSON.stringify(books));
});
//Add our middleware to the post route
app.post('/books', validationMiddleware(bookSchema), (req, res) => {
books.push(req.body);
res.send(JSON.stringify(res.body));
});
//Define a custom error handler
app.use((err, req, res, next) => {
if (err && err.isJoi) {
//this error was generated from Joi
return res.status(400).send(JSON.stringify({ error: err.details[0].message }));
}
//some other error, let Express handle it.
return next(err);
});
app.listen(port, () => console.log(`App is running on ${port}`));
<file_sep>/middleware.js
/**
* This module exposes a configurable Express middleware
* that can be used to validate the request body against
* the supplied object schema.
*
* If the validation fails, it will return the error
* and end the request.
*/
const Joi = require('joi');
const validationMiddleware = schema => (req, res, next) => {
const { error } = Joi.validate(req.body, schema);
if (error) {
return next(error);
}
return next();
};
module.exports = validationMiddleware;
<file_sep>/README.md
# Validating Data with Joi
This is a very simple Express app that uses Hapi's [Joi](https://github.com/hapijs/joi) validation system to validate incoming data.
Read more at this Medium post: [[LINK TO COME]]
| 0dc4e1cc21d15b1e746bf0005fbfd7425bae899b | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | greysky-io/validating-data-with-joi | 7f1d294c13ce89d71f955b2ce79e445a6c3fc586 | c2f6c460e39ec9ed79f6f7ef1c3d54a7ec70a8c1 |
refs/heads/master | <repo_name>ch000618/node_web_server<file_sep>/web/test_3.njs
const https = require('https');
const fs = require("fs");
const url = require("url");
const cheerio = require("cheerio");
const iconv = require("iconv-lite");
const BufferHelper = require('bufferhelper');
const zlib = require("zlib");
const request = require("request");
init();
function init(){
var timestamp = new Date().getTime();
var _regUrl='https://www.1399p.com/gdkl10/KaiJiang?date=2017-09-06&_='+timestamp;
var options = url.parse(_regUrl);
var buffer = new BufferHelper();
var opt={
url:_regUrl,
followRedirect: true,
method: "GET",
encoding: null,
headers: {
Accept:'text/plain, */*; q=0.01'
,'Accept-Encoding':'gzip, deflate, br'
,'Accept-Language':'zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4'
,'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36'
,'Connection':'keep-alive'
,'Host':'www.1399p.com'
,Cookie :'ccsalt=d82a4991ba9dbdad8b2f23d2db2b2119;'
//,Referer:_regUrl
,'X-Requested-With':'XMLHttpRequest'
}
};
/*
options.method='GET'
options.encoding=null;
options.headers ={
/*Accept:'text/plain, *///*; q=0.01'
//,'Accept-Encoding':'gzip, deflate, br'
//,'Accept-Language':'zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4'
//,'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36'
//,'Connection':'keep-alive'
//,'Host':'www.1399p.com'
//,Cookie :'ccsalt=<PASSWORD>;'
//,Referer:_regUrl
//,'X-Requested-With':'XMLHttpRequest'
//};
/*
var get_request_data = function(res) {
res.on('data',function(body){
buffer.concat(body);
console.log('幹');
var html = iconv.decode(buffer.toBuffer(),'utf8');
$ = cheerio.load(html,
{
ignoreWhitespace: false,
xmlMode: true
});
});
}
*/
/*
var req = https.request(options,get_request_data);
req.end();
req.on('error', function(e) {
console.error(e);
});
*/
var get_request_data = function(error,res,body){
var result=[];
zlib.gunzip(body,function(err,dezipped){
buffer.concat(dezipped);
var html = iconv.decode(buffer.toBuffer(),'utf8');
//console.log(html);
$ = cheerio.load(html,
{
ignoreWhitespace: false,
xmlMode: true
});
titles = $("tr");
for(var i=1;i<titles.length;i++) {
str = $(titles[i]).text();
text = str.replace(/\r\n|\n/g," ");
result.push(text);
}
console.log('<head><meta charset="utf-8"/></head>');
console.log(result);
});
}
request(opt,get_request_data)
}
<file_sep>/web/get_1399p_result_klc.njs
const https = require('https');
const fs = require("fs");
const url = require("url");
const cheerio = require("cheerio");
const iconv = require("iconv-lite");
const BufferHelper = require('bufferhelper');
const request = require("request");
init();
function init(){
var timestamp = new Date().getTime();
var today = Date();
var _regUrl='https://www.1399p.com/gdkl10/KaiJiang?date='+today+'&_='+timestamp;
var Referer='https://www.1399p.com/gdkl10/KaiJiang';
var Host='https://www.1399p.com/';
var options = url.parse(_regUrl);
var buffer = new BufferHelper();
//啟用cookie true / false
var jar = request.jar();
var get_request_data = function(error,res,body){
var aResult=[];
var oTitles = {};
var $={};
//buffer 轉html 並且轉換編碼
var html_parse =function(){
buffer.concat(body);
var html = iconv.decode(buffer.toBuffer(),'utf8');
$ = cheerio.load(html,
{
ignoreWhitespace: false,
xmlMode: true
});
}
var get_aResult=function(){
oTitles = $("tr");
var reg=/\r\n|\n/g;
var ch_reg=/[\u4E00-\u9FA5]+/g;
var nbsp=/ /ig;
var s=/\s+/ig;
for(var i=1;i<oTitles.length;i++) {
str = $(oTitles[i]).text();
str = str.replace(ch_reg,"");
str = str.replace(nbsp,",");
text = str.replace(reg,"");
text =text.trim();
text =text.replace(s,',');
aResult.push(text);
}
}
function exec(){
if(error || !body) { return ; }
html_parse()
get_aResult();
var JSON_result=JSON.stringify(aResult);
console.log(JSON_result);
}
exec();
}
//爬蟲 設定
/*
url:網址
followRedirect: true, 啟動自動轉跳
jar: jar, //啟用cookie 如果要自己塞 setCookies("key=val");
method: 參數傳遞方式 POST GET
encoding:編碼 預設UTF8
//請求頭 User-Agent之類的
headers:{
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36'
}
*/
var opt={
url:_regUrl,
followRedirect: true,
jar: jar,
method: "GET",
gzip: true,
encoding: null,
headers: {
Accept:'text/plain, */*; q=0.01'
,'Accept-Encoding':'gzip, deflate, br'
,'Accept-Language':'zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4'
,'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36'
,'Connection':'keep-alive'
,'Host':'www.1399p.com'
,Referer:Referer
,'X-Requested-With':'XMLHttpRequest'
}
};
request(opt,get_request_data);
}
<file_sep>/njs_exec.js
var http = require('http'); // http
var fs = require('fs'); // file system
var url = require('url'); // url
var util = require('util'); // utility
var path = require("path"); // 路徑功能
var process = require('child_process'); // 子程序
//---
var bDebug=true;
var sHost='1.aj.me'; //網頁的 Host
var sPath_root='web';
//真正的網頁資料夾
setInterval (init_test_2,10000);
//網頁請求物件
function init_test_2 (){
var sFileName='test_2.njs';
var _RET_STATUS=400;//回傳的狀態
var _RET_HEAD={}; //回傳的Header
var _RET_HTML=''; //回傳的HTML
var sPathFile=sPath_root + '/' + sFileName;
exec(sPathFile,sFileName);
}
//執行nodeJS程式
/*
sFileName=檔名
*/
function exec (sPathFile,sFileName){
var sCMD='node '+sPathFile+' --url '+ '/' + sFileName;
process.exec( sCMD ,fexec);
console.log(sCMD);
//抓取執行結果
/*
*執行程式的結果寫到內部變數
*執行輸出
*/
var fexec = function (error, stdout, stderr){
_RET_STATUS=200;
_RET_HEAD={'Content-Type': 'text/html'};
if (error) {
errstr ='<head>';
errstr+='<title>Script error</title>';
errstr+='</head>';
errstr+='<body>';
errstr+='<pre>';
errstr+=error.stack+"\n";
errstr+=error.stack+"\n";
errstr+='Error code: ' + error.code;
errstr+='</pre>';
errstr+='</body>';
_RET_HTML=errstr;
}else{
_RET_HTML=stdout;
if(_DEBUG == true){
_RET_HTML+='<pre>';
_RET_HTML+=util.inspect(_URL);
_RET_HTML+='</pre>';
}
}
}
}<file_sep>/web/2/index2.php
<?php
echo start();
//主程式
function start(){
//獲得年月
//如果有獲得年份就作獲得的年份否則為當前年份
$year = $_GET['y']?$_GET['y']:date("Y");
//如果有獲得年份就作獲得的月份否則為當前月份
$mon = $_GET['m']?$_GET['m']:date("n");
$str ="";
$str.="<html>\n";
$str.="<head>\n";
$str.="<title>月曆</title>\n";
$str.="<meta charset=\"utf-8\">\n";
$str.="<link href=\" css/5.css\" rel=\"stylesheet\" type=\"text/css\">\n";
$str.="</head>\n";
$str.="<body>\n";
$str.="<table class=\"tb1\">\n";
$str.=print_title($year,$mon);
$str.=print_week();
$str.=print_mday($year,$mon);
$str.="</table>\n";
$str.="</body>\n";
$str.="</html>\n";
return $str;
}
//存放節日陣列
/*
*/
function festival($mon,$dd){
$festival[1][1] = array("元旦");
$festival[2][28] = array("和平紀念日");
$festival[3][8] = array("婦女節");
$festival[3][21] = array("世界森林日");
$festival[4][1] = array("愚人節");
$festival[4][3] = array("兒童節");
$festival[4][5] = array("清明節");
$festival[5][1] = array("勞動節");
$festival[6][1] = array("國際兒童節");
$festival[7][15] = array("中元節");
$festival[8][8] = array("父親節");
$festival[9][3] = array("軍人節");
$festival[10][1] = array("[中]國慶日");
$festival[10][10] = array("國慶日");
$festival[10][31] = array("萬聖節");
$festival[11][11] = array("世界青年節");
$festival[12][1] = array("世界愛滋病日");
$festival[12][10] = array("世界人權日");
$festival[12][25] =array("聖誕節","行憲紀念日",);
$festival[12][31] =array("放假前一天","跨年夜",);
$str.=$festival[$mon][$dd];
//回傳陣列裡的值
return $str;
}
//非固定節日日期
function festa($mon,$toweek){
$festa[1][2]="[日]成人節";
$festa[5][2]="母親節";
$festa[5][3]="助殘節";
$festa[11][4]="[美]感恩節";
$festa[10][2]="[加]感恩節";
return $festa[$mon][$toweek];
}
/*空白字串
$a=數字,$b=字串
當a-b字串的數量剩餘的數為空白數量
如果b為空白則只補a數的空白
*/
function C_SPACE($a,$b) {
//取出$b位數,算出要補幾個空格
$c = $a - strlen($b);
//產出要補得空格 $d
$d = str_repeat(' ',$c);
//把值後面加上空格
$e=$d.$b;
return $e;
}
/*標題文字與上下月和回到當月
$year 年 $mon月
1.定義按鈕變數與限制條件超過12月進入下一年小於1月回到上一年
2.製作上個月下個月的按鈕
3.印出月曆最上方的年月跟切換月份的按鈕
*/
function print_title($year,$mon){
$td_cen="<td align=center>";
$th5="<th colspan=5>";
//定義按鈕變數與限制條件
$prey=$year;//上一年
$prem=$mon;//上一月
$nexty=$year;//下一年
$nextm=$mon;//下一月
//上個月
if($prem<=1){ //判斷月份小於1月
$prem = 12; //條件成立月份為12月
$prey--; //年分返回上個年度
}else{
$prem--;
}
//下個月
if($nextm>=12){ //判斷月份大於12月
$nextm = 1; //條件成立月份為1月
$nexty++; //年份進入下個年度y
}else{
$nextm++;
}
//上個月下個月的按鈕
$pre_m="<td><a href=index.php?y=".$prey."&m=".$prem.">上個月</a></td>";
$next_m="<td><a href=index2.php?y=".$nexty."&m=".$nextm.">下個月</a></td>";
$to_m="<a href=index2.php><span>回到當月</span></a>";
//印出月曆最上放的年月跟切換月份的按鈕
$str='';
$str.= C_SPACE(9,'<tr>')."\n";
$str.= C_SPACE(8,'').$pre_m.C_SPACE(8,'')."\n";
$str.= C_SPACE(8,'').$th5;
$str.= "<h1>".$year."年".$mon."月"."<br>"."</h1>"."\n";
$str.= C_SPACE(8,'').$to_m."\n";
$str.= C_SPACE(13,'</th>');
$str.= "\n".C_SPACE(8,'').$next_m;
$str.= "\n".C_SPACE(10,'</tr>')."\n";
return $str;
}
/*周日到周六欄位填滿
1.宣告一個陣列從放禮拜日到禮拜六的字串
2.用for迴圈從日排到六
*/
function print_week() {
$str.=C_SPACE(5,'');
$str.="<tr class=\"tr01\">";
//禮拜日到禮拜六欄位陣列
$week=array(
1=>"日",2=>"一",3=>"二",
4=>"三",5=>"四",6=>"五",
7=>"六"
);
//星期欄位從第一格到第七格依序將日到六產生字串跟表格
for($a=1; $a<=7;$a++){
$str.="\n".C_SPACE(12,'<td>');
$str.=$week[$a]."</td>";
}
$str.= "\n".C_SPACE(10,'</tr>')."\n";
return $str;
}
/* 一個月的每一天的日期
$dd是循環天數
$i為星期,$d今天
$year 年 $mon月
1.印出每個月的日期
2.判斷第一天從第幾格開始第幾天結束
3.判斷哪些天是禮拜六禮拜天
4.判斷那些天是節日
*/
function print_mday($year,$mon,$day){
$n=" ";//產生空白
//css class
$td67="<td class=\"td67\">";
$td123="<td class=\"td123\">";
$today="<td class=\"today\">";
$d=date("j");//每個月的今天
$maxday=date("t",mktime(0,0,0,$mon,1,$year));//計算當月有多少天
$w=date("w",mktime(0,0,0,$mon,1,$year));//當前月份的1號是星期幾
$dd=1;//循環天數存放日期
while($dd<=$maxday){//循環天數小於最大天數
$str.=C_SPACE(5,'')."<tr class=\"tr02\">";
//i為星期
//從星期一增加到日為止
for($i=0; $i<7;$i++){
//如果這個月1號的星期大於
//星期 且 循環天數為1 或是循環天數
//大於 最大天數 則輸出空白表格
if(($w>$i && $dd==1)||$dd>$maxday){
$str.="\n".C_SPACE(12,'<td>').$n."</td>";
continue;
}
//每個月的今天會標記
if($dd==$d){
$str.="\n".C_SPACE(8,'').$today.$dd.
"<div><p>".
"</p><div></td>";
$dd++;
continue;
}
//否則每個禮拜六禮拜日則以紅色文字輸出
if(($i%7==0)||($i%7==6)){
$str.="\n".C_SPACE(8,'').$td67.$dd.
"<div><p>".
showfesta($mon,$dd,$i,5,7,15,2,0).
showfesta($mon,$dd,$i,5,14,22,3,0).
"</p></div></td>";
$dd++;
continue;
}
//不是星期六或日使用一般格式
else{
$str.="\n".C_SPACE(12,'<td>').$dd.
"<div><p>".
showfesta($mon,$dd,$i,1,7,15,2,1).
showfesta($mon,$dd,$i,11,21,29,4,4).
showfesta($mon,$dd,$i,10,7,15,2,1).
"</p></div></td>";
$dd++;
}
}
$str.="\n".C_SPACE(10,'</tr>')." \n";
}
return $str;
}
//判斷特定月特定周節日
/*
由於有閏年閏月的問題採取以日期範圍取特定日的方式較為準確
i是存放禮拜天到禮拜六的日期的格子
dd是日期
m對照的月份
daymin則是指定日期的最小值
daymax則是最大值
weekday為禮拜幾
toweek則是該月份第幾個周幾
*/
function showfesta($mon,$dd,$i,$m,$daymin,$daymax,$toweek,$weekday){
if(($mon==$m)&&($dd>$daymin)&&($dd<$daymax)&&($i%7==$weekday)){
$str.=festa($mon,$toweek);
$dd++;
return $str;
continue;
}
}
//判斷月日是否有節日
/*
$mon月 $dd 日
如果月跟日有節日則顯示節日
如果月跟日沒有節日則空白
*/
function showfestival($mon,$dd,$num){
}
?><file_sep>/web/test_1.njs
//測試 另外執行 nodeJS 程式
const url = require('url'); // url
// const util = require('util'); // utility
// const path = require("path"); // 路徑功能
const query = require("querystring"); // GET 與 POST
const minimist = require('minimist');
console.log('<head><meta charset="utf-8"/></head>');
console.log('<pre>');
console.log('你執行了另外一支 node.JS程式');
var argv=minimist(process.argv.slice(2));
_URL=url.parse((argv.url), true);
console.log(_URL);
console.log('</pre>'); | f30e41c547197dcecda5fbe081e5018499cc6dc8 | [
"JavaScript",
"PHP"
] | 5 | JavaScript | ch000618/node_web_server | 8d0a747e43ca24b13f29da9403fc5af641c10774 | c0cbd8c5f550377e58bd064b0041e24dc24bc178 |
refs/heads/master | <repo_name>CKochanski/JAVApoz21-design-patterns<file_sep>/src/pl/sda/chainOfResponsibility/DebugLogger.java
package pl.sda.chainOfResponsibility;
public class DebugLogger implements Logger {
@Override
public void log(LoggingType loggingType, String message) {
if (this.supportedType() == loggingType) {
System.out.println("DEBUG: " + message);
} else {
System.out.println(message);
}
}
@Override
public LoggingType supportedType() {
return LoggingType.DEBUG;
}
}
<file_sep>/src/pl/sda/chainOfResponsibility/InfoLogger.java
package pl.sda.chainOfResponsibility;
public class InfoLogger implements Logger {
private final Logger nextLogger;
public InfoLogger() {
this.nextLogger = new WarnLogger();
}
@Override
public void log(LoggingType loggingType, String message) {
if (this.supportedType() == loggingType) {
System.out.println("INFO: " + message);
} else {
this.nextLogger.log(loggingType, message);
}
}
@Override
public LoggingType supportedType() {
return LoggingType.INFO;
}
}
<file_sep>/src/pl/sda/facade/Job.java
package pl.sda.facade;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;
public class Job {
private final long id;
private final ScheduledFuture<?> task;
public Job(long id, ScheduledFuture<?> task) {
this.id = id;
this.task = task;
}
public long getId() {
return id;
}
public ScheduledFuture<?> getTask() {
return task;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Job job = (Job) o;
return id == job.id && Objects.equals(task, job.task);
}
@Override
public int hashCode() {
return Objects.hash(id, task);
}
@Override
public String toString() {
return "Job{" +
"id=" + id +
", task=" + task +
'}';
}
}
<file_sep>/src/pl/sda/chainOfResponsibility/ErrorLogger.java
package pl.sda.chainOfResponsibility;
public class ErrorLogger implements Logger {
private final Logger nextLogger;
public ErrorLogger() {
this.nextLogger = new DebugLogger();
}
@Override
public void log(LoggingType loggingType, String message) {
if (this.supportedType() == loggingType) {
System.out.println("ERROR: " + message);
} else {
this.nextLogger.log(loggingType, message);
}
}
@Override
public LoggingType supportedType() {
return LoggingType.ERROR;
}
}
<file_sep>/src/pl/sda/strategy/OperationType.java
package pl.sda.strategy;
public enum OperationType {
ADDITION, SUBTRACTION, MULTIPLICATION
}
<file_sep>/src/pl/sda/strategy/Operation.java
package pl.sda.strategy;
public interface Operation {
int calculate(int arg1, int arg2);
}
<file_sep>/pom.xml
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>pl.sda</groupId>
<artifactId>DesignPatterns</artifactId>
<version>0.0.1</version>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/src/pl/sda/facade/JobsFacade.java
package pl.sda.facade;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class JobsFacade {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final JobsRepository jobsRepository = new JobsRepository();
public long schedule(long period) {
ScheduledFuture<?> scheduledTask = scheduler.scheduleAtFixedRate(someTask(), 1L, period, TimeUnit.SECONDS);
return jobsRepository.add(scheduledTask);
}
public void unschedule(long id) {
ScheduledFuture<?> future = jobsRepository.remove(id);
future.cancel(true);
}
public Set<Job> getScheduledJobs() {
return jobsRepository.getAll();
}
private Runnable someTask() {
return () -> System.out.println("Task");
}
}
<file_sep>/src/pl/sda/observer/FirstObserver.java
package pl.sda.observer;
public class FirstObserver implements Observer {
@Override
public void update(String message) {
System.out.println("Operation done by first observer " + message);
}
}
| 6580c1fd26b50c4395246e004ac1677031bcd2a1 | [
"Java",
"Maven POM"
] | 9 | Java | CKochanski/JAVApoz21-design-patterns | 3cdc8f838a9b87a2d807e7acacb32f8b15485946 | b0369b585a349f66a171a9df00f4379bb8483a45 |
refs/heads/master | <repo_name>jDTAUS/ISO-13616<file_sep>/src/main/java/org/jdtaus/iso13616/IbanSyntaxException.java
// SECTION-START[License Header]
// <editor-fold defaultstate="collapsed" desc=" Generated License ">
/*
* jDTAUS ⁑ ISO-13616
* Copyright (C) <NAME>, 2013-222
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* $JDTAUS$
*
*/
// </editor-fold>
// SECTION-END
package org.jdtaus.iso13616;
import java.util.Locale;
// SECTION-START[Documentation]
// <editor-fold defaultstate="collapsed" desc=" Generated Documentation ">
/**
* Gets thrown whenever parsing text to produce an international bank account number fails.
*
* <dl>
* <dt><b>Identifier:</b></dt><dd>jDTAUS ⁑ ISO-13616 ⁑ IBAN Syntax Exception</dd>
* <dt><b>Name:</b></dt><dd>jDTAUS ⁑ ISO-13616 ⁑ IBAN Syntax Exception</dd>
* <dt><b>Abstract:</b></dt><dd>No</dd>
* <dt><b>Final:</b></dt><dd>Yes</dd>
* <dt><b>Stateless:</b></dt><dd>No</dd>
* </dl>
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version 1.1
*/
// </editor-fold>
// SECTION-END
// SECTION-START[Annotations]
// <editor-fold defaultstate="collapsed" desc=" Generated Annotations ">
@javax.annotation.Generated( value = "org.jomc.tools.SourceFileProcessor 1.9", comments = "See http://www.jomc.org/jomc/1.9/jomc-tools-1.9" )
// </editor-fold>
// SECTION-END
public class IbanSyntaxException extends Exception
{
// SECTION-START[IbanSyntaxException]
/** Serial version UID for backwards compatibility with 2007.45.x classes. */
private static final long serialVersionUID = -475265309170567430L;
/**
* The malformed text.
* @serial
*/
private String malformedText;
/**
* The position at which parsing failed.
* @serial
*/
private int errorIndex;
/**
* Creates a new {@code IbanSyntaxException} instance taking malformed text and a position at which parsing failed.
*
* @param malformedText The malformed text.
* @param errorIndex The position at which parsing failed.
*/
public IbanSyntaxException( final String malformedText, final int errorIndex )
{
super();
this.malformedText = malformedText;
this.errorIndex = errorIndex;
}
/**
* Gets a message describing the exception.
*
* @return A message describing the exception.
*/
@Override
public String getMessage()
{
return getIbanSyntaxExceptionMessage( Locale.getDefault(), this.getMalformedText(), this.getErrorIndex() );
}
/**
* Gets a localized message describing the exception for a given locale.
*
* @param locale The locale of the localized message to get.
*
* @return A localized message describing the exception.
*
* @throws NullPointerException if {@code locale} is {@code null}.
*/
public String getLocalizedMessage( final Locale locale )
{
if ( locale == null )
{
throw new NullPointerException( "locale" );
}
return getIbanSyntaxExceptionMessage( locale, this.getMalformedText(), this.getErrorIndex() );
}
/**
* Gets the malformed text causing the exception.
*
* @return The malformed text causing the exception.
*/
public String getMalformedText()
{
return this.malformedText;
}
/**
* Gets the position at which parsing failed.
*
* @return The position at which parsing failed.
*/
public int getErrorIndex()
{
return this.errorIndex;
}
// SECTION-END
// SECTION-START[Dependencies]
// SECTION-END
// SECTION-START[Properties]
// SECTION-END
// SECTION-START[Messages]
// <editor-fold defaultstate="collapsed" desc=" Generated Messages ">
/**
* Gets the text of the {@code <IBAN Syntax Exception Message>} message.
* <p><dl>
* <dt><b>Languages:</b></dt>
* <dd>English (default)</dd>
* <dd>Deutsch</dd>
* <dt><b>Final:</b></dt><dd>No</dd>
* </dl></p>
* @param locale The locale of the message to return.
* @param malformedText Format argument.
* @param errorIndex Format argument.
* @return The text of the {@code <IBAN Syntax Exception Message>} message for {@code locale}.
*/
@SuppressWarnings({"unchecked", "unused", "PMD.UnnecessaryFullyQualifiedName"})
@javax.annotation.Generated( value = "org.jomc.tools.SourceFileProcessor 1.9", comments = "See http://www.jomc.org/jomc/1.9/jomc-tools-1.9" )
private static String getIbanSyntaxExceptionMessage( final java.util.Locale locale, final java.lang.String malformedText, final java.lang.Number errorIndex )
{
java.io.BufferedReader reader = null;
try
{
final String message = java.text.MessageFormat.format( java.util.ResourceBundle.getBundle( "org.jdtaus.iso13616.IbanSyntaxException", locale ).getString( "IBAN Syntax Exception Message" ), malformedText, errorIndex, (Object) null );
final java.lang.StringBuilder builder = new java.lang.StringBuilder( message.length() );
reader = new java.io.BufferedReader( new java.io.StringReader( message ) );
final String lineSeparator = System.getProperty( "line.separator", "\n" );
String line;
while ( ( line = reader.readLine() ) != null )
{
builder.append( lineSeparator ).append( line );
}
reader.close();
reader = null;
return builder.length() > 0 ? builder.substring( lineSeparator.length() ) : "";
}
catch( final java.io.IOException e )
{
throw new java.lang.AssertionError( e );
}
finally
{
try
{
if( reader != null )
{
reader.close();
}
}
catch( final java.io.IOException e )
{
throw new java.lang.AssertionError( e );
}
}
}
// </editor-fold>
// SECTION-END
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) <NAME>, 2013-222
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
$JDTAUS$
-->
<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">
<parent>
<groupId>org.jdtaus</groupId>
<artifactId>jdtaus-isc-parent</artifactId>
<version>1.21</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.jdtaus</groupId>
<artifactId>ISO-13616</artifactId>
<packaging>jar</packaging>
<version>2007.79-SNAPSHOT</version>
<name>jDTAUS ⁑ ISO-13616</name>
<description>ISO 13616-1:2007 specifies the elements of an international bank account number (IBAN) used to facilitate the processing of data internationally in data interchange, in financial environments as well as within and between other industries. The IBAN is designed for automated processing, but can also be used conveniently in other media interchange when appropriate (e.g. paper document exchange, etc.). ISO 13616-1:2007 does not specify internal procedures, file organization techniques, storage media, languages, etc. to be used in its implementation, nor is it designed to facilitate the routing of messages within a network. It is applicable to the textual data which might be conveyed through a system (network). This project provides a general purpose ISO 13616-1:2007 compatible IBAN Java class.</description>
<url>${jdtaus.artifacts.url}/ISO-13616/${project.version}</url>
<inceptionYear>2013</inceptionYear>
<scm>
<connection>scm:svn:http://svn.jdtaus.org/svnroot/jdtaus/ISO-13616/trunk</connection>
<developerConnection>scm:svn:http://svn.jdtaus.org/svnroot/jdtaus/ISO-13616/trunk</developerConnection>
<url>http://svn.jdtaus.org/ISO-13616/trunk</url>
</scm>
<build>
<extensions>
<extension>
<groupId>org.jdtaus</groupId>
<artifactId>jdtaus-build-resources</artifactId>
<version>${jdtaus-build.version}</version>
</extension>
</extensions>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
</resource>
<resource>
<filtering>true</filtering>
<directory>src/main/meta</directory>
<targetPath>META-INF</targetPath>
</resource>
</resources>
<testResources>
<testResource>
<filtering>true</filtering>
<directory>src/test/meta</directory>
<targetPath>META-INF</targetPath>
</testResource>
<testResource>
<filtering>false</filtering>
<directory>src/test/resources</directory>
</testResource>
<testResource>
<filtering>false</filtering>
<directory>src/test/objects</directory>
</testResource>
</testResources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.jomc</groupId>
<artifactId>maven-jomc-plugin</artifactId>
<executions>
<execution>
<id>main-default</id>
<goals>
<goal>write-main-resources</goal>
<goal>validate-main-model</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-remote-resources-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jomc</groupId>
<artifactId>maven-jomc-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<!-- Model values. -->
<implementation.level>1.1</implementation.level>
<!-- Plugin parameters. -->
<maven.compiler.source>1.5</maven.compiler.source>
<maven.compiler.target>1.5</maven.compiler.target>
<checkstyle.skip>false</checkstyle.skip>
<assembly.appendAssemblyId>false</assembly.appendAssemblyId>
<mojo.animalsniffer.signature.artifactId>java15</mojo.animalsniffer.signature.artifactId>
<mojo.animalsniffer.signature.artifactVersion>1.0</mojo.animalsniffer.signature.artifactVersion>
<jomc.with-project-name>${project.name}</jomc.with-project-name>
<jomc.templateProfile>jdtaus-java-bundles-isc</jomc.templateProfile>
<jdtaus.trac.query>order=id&version=${project.version}&component=${project.name}</jdtaus.trac.query>
<jdtaus.base.version />
</properties>
<distributionManagement>
<site>
<id>${jdtaus.artifacts.distribution.id}</id>
<name>${jdtaus.artifacts.distribution.name}</name>
<url>${jdtaus.artifacts.distribution.url}/ISO-13616/${project.version}</url>
</site>
</distributionManagement>
<profiles>
<profile>
<id>jdtaus-release</id>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<updateReleaseInfo>true</updateReleaseInfo>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>default-jar-no-fork</id>
<phase>prepare-package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
<execution>
<id>default-test-jar-no-fork</id>
<phase>prepare-package</phase>
<goals>
<goal>test-jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>default-jar</id>
<phase>prepare-package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
<execution>
<id>default-test-jar</id>
<phase>prepare-package</phase>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<id>default-test-jar</id>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
<execution>
<id>default-project-jar</id>
<phase>prepare-package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classesDirectory>${project.basedir}</classesDirectory>
<classifier>project</classifier>
<includes>
<include>LICENSE.txt</include>
<include>BUILDING.txt</include>
<include>pom.xml</include>
<include>src/**</include>
</includes>
<excludes>
<exclude>**/.*/**</exclude>
<exclude>**/target/**</exclude>
</excludes>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<executions>
<execution>
<id>default-jar</id>
<phase>prepare-package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<relativizeDecorationLinks>false</relativizeDecorationLinks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>release-copy</id>
<phase>pre-integration-test</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<type>jar</type>
<outputDirectory>${project.build.directory}/assembly/tests</outputDirectory>
</artifactItem>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<classifier>javadoc</classifier>
<type>jar</type>
<outputDirectory>${project.build.directory}/assembly/doc</outputDirectory>
</artifactItem>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<classifier>test-javadoc</classifier>
<type>jar</type>
<outputDirectory>${project.build.directory}/assembly/tests</outputDirectory>
</artifactItem>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<classifier>sources</classifier>
<type>jar</type>
<outputDirectory>${project.build.directory}/assembly/doc</outputDirectory>
</artifactItem>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<classifier>test-sources</classifier>
<type>jar</type>
<outputDirectory>${project.build.directory}/assembly/tests</outputDirectory>
</artifactItem>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<classifier>site</classifier>
<type>jar</type>
<outputDirectory>${project.build.directory}/assembly/doc</outputDirectory>
</artifactItem>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<classifier>project</classifier>
<type>jar</type>
<outputDirectory>${project.build.directory}/assembly/src</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jarsigner-plugin</artifactId>
<executions>
<execution>
<id>default-sign</id>
<phase>package</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
<execution>
<id>default-verify</id>
<phase>verify</phase>
<goals>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>default-bin-single</id>
<phase>pre-integration-test</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptors>
<descriptor>src/main/assembly/java-release.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>default-sign</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>wagon-maven-plugin</artifactId>
<executions>
<execution>
<id>default-upload</id>
<phase>deploy</phase>
<goals>
<goal>upload</goal>
</goals>
<configuration>
<fromDir>${project.build.directory}</fromDir>
<includes>*.zip*, *.tar*</includes>
<serverId>${jdtaus.frs.distribution.id}</serverId>
<toDir>ISO-13616</toDir>
<url>${jdtaus.frs.distribution.url}</url>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jarsigner-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>wagon-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<jomc.verbose>true</jomc.verbose>
<jomc.sourceProcessing>false</jomc.sourceProcessing>
<checkstyle.enable.rss>false</checkstyle.enable.rss>
<maven.site.relativizeDecorationLinks>false</maven.site.relativizeDecorationLinks>
</properties>
</profile>
</profiles>
</project>
<file_sep>/src/test/java/org/jdtaus/iso13616/test/IbanSyntaxExceptionTest.java
// SECTION-START[License Header]
// <editor-fold defaultstate="collapsed" desc=" Generated License ">
/*
* jDTAUS ⁑ ISO-13616
* Copyright (C) <NAME>, 2013-222
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* $JDTAUS$
*
*/
// </editor-fold>
// SECTION-END
package org.jdtaus.iso13616.test;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Locale;
import org.jdtaus.iso13616.IbanSyntaxException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
// SECTION-START[Documentation]
// <editor-fold defaultstate="collapsed" desc=" Generated Documentation ">
/**
* Testcases for class {@code org.jdtaus.iban.IbanSyntaxException}.
*
* <dl>
* <dt><b>Identifier:</b></dt><dd>jDTAUS ⁑ ISO-13616 ⁑ Tests ⁑ IBAN Syntax Exception Test</dd>
* <dt><b>Name:</b></dt><dd>jDTAUS ⁑ ISO-13616 ⁑ Tests ⁑ IBAN Syntax Exception Test</dd>
* <dt><b>Abstract:</b></dt><dd>No</dd>
* <dt><b>Final:</b></dt><dd>Yes</dd>
* <dt><b>Stateless:</b></dt><dd>Yes</dd>
* </dl>
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version 1.1
*/
// </editor-fold>
// SECTION-END
// SECTION-START[Annotations]
// <editor-fold defaultstate="collapsed" desc=" Generated Annotations ">
@javax.annotation.Generated( value = "org.jomc.tools.SourceFileProcessor 1.9", comments = "See http://www.jomc.org/jomc/1.9/jomc-tools-1.9" )
// </editor-fold>
// SECTION-END
public class IbanSyntaxExceptionTest
{
// SECTION-START[IbanSyntaxExceptionTest]
@Test public void LocalizedMessage() throws Exception
{
final IbanSyntaxException ibanSyntaxException = new IbanSyntaxException( "TEST", Integer.MAX_VALUE );
try
{
ibanSyntaxException.getLocalizedMessage( null );
fail( "Expected 'NullPointerException' not thrown." );
}
catch ( final NullPointerException e )
{
System.out.println( e.toString() );
assertNotNull( e.getMessage() );
}
assertNotNull( ibanSyntaxException.getLocalizedMessage( Locale.GERMAN ) );
assertNotNull( ibanSyntaxException.getLocalizedMessage( Locale.ENGLISH ) );
}
@Test public void Serializable() throws Exception
{
final ObjectOutputStream out = new ObjectOutputStream( new ByteArrayOutputStream() );
out.writeObject( new IbanSyntaxException( "TEST", Integer.MAX_VALUE ) );
out.close();
final ObjectInputStream in =
new ObjectInputStream( this.getClass().getResourceAsStream( "IbanSyntaxException.ser" ) );
final IbanSyntaxException e = (IbanSyntaxException) in.readObject();
in.close();
System.out.println( e.toString() );
assertEquals( "TEST", e.getMalformedText() );
assertEquals( Integer.MAX_VALUE, e.getErrorIndex() );
}
//
// public static void main( final String... arguments ) throws Exception
// {
// final ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( "IbanSyntaxException.ser" ) );
// out.writeObject( new IbanSyntaxException( "TEST", Integer.MAX_VALUE ) );
// out.close();
// }
//
// SECTION-END
// SECTION-START[Constructors]
// <editor-fold defaultstate="collapsed" desc=" Generated Constructors ">
/** Creates a new {@code IbanSyntaxExceptionTest} instance. */
@javax.annotation.Generated( value = "org.jomc.tools.SourceFileProcessor 1.9", comments = "See http://www.jomc.org/jomc/1.9/jomc-tools-1.9" )
public IbanSyntaxExceptionTest()
{
// SECTION-START[Default Constructor]
super();
// SECTION-END
}
// </editor-fold>
// SECTION-END
// SECTION-START[Dependencies]
// SECTION-END
// SECTION-START[Properties]
// SECTION-END
// SECTION-START[Messages]
// SECTION-END
}
<file_sep>/src/main/java/org/jdtaus/iso13616/package-info.java
// SECTION-START[License Header]
// <editor-fold defaultstate="collapsed" desc=" Generated License ">
/*
* jDTAUS ⁑ ISO-13616
* Copyright (C) <NAME>, 2013-222
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* $JDTAUS$
*
*/
// </editor-fold>
// SECTION-END
// SECTION-START[Documentation]
// <editor-fold defaultstate="collapsed" desc=" Generated Documentation ">
/**
*
* International Bank Account Number.
* <p>The IBAN structure is defined in ISO 13616-1 and consists of a two-letter ISO 3166-1 country code, followed by two
* check digits and up to thirty alphanumeric characters for a BBAN (Basic Bank Account Number) which has a fixed length
* per country and, included within it, a bank identifier with a fixed position and a fixed length per country. The
* check digits are calculated based on the scheme defined in ISO/IEC 7064 (MOD97-10). The Society for Worldwide
* Interbank Financial Telecommunication SCRL, SWIFT, has been designated by the ISO Technical Management Board to act
* as the Registration Authority for ISO 13616. Nationally-agreed, ISO 13616-compliant IBAN formats are submitted to the
* registration authority exclusively by the National Standards Body or the National Central Bank of the country. For
* further information see the <a href="../../../doc-files/IBAN-Registry_Release-78-August-2017.pdf">IBAN REGISTRY</a>.
* An updated version of the document may be found at <a href="http://www.swift.com">SWIFT</a>.</p>
*
* <dl>
* <dt><b>Identifier:</b></dt><dd>jDTAUS ⁑ ISO-13616 ⁑ IBAN</dd>
* <dt><b>Name:</b></dt><dd>jDTAUS ⁑ ISO-13616 ⁑ IBAN</dd>
* <dt><b>Abstract:</b></dt><dd>No</dd>
* <dt><b>Final:</b></dt><dd>Yes</dd>
* <dt><b>Stateless:</b></dt><dd>No</dd>
* </dl>
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version 1.1
*/
// </editor-fold>
// SECTION-END
package org.jdtaus.iso13616;
<file_sep>/src/test/java/org/jdtaus/iso13616/test/package-info.java
// SECTION-START[License Header]
// <editor-fold defaultstate="collapsed" desc=" Generated License ">
/*
* jDTAUS ⁑ ISO-13616
* Copyright (C) <NAME>, 2013-222
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* $JDTAUS$
*
*/
// </editor-fold>
// SECTION-END
// SECTION-START[Documentation]
// <editor-fold defaultstate="collapsed" desc=" Generated Documentation ">
/**
* Testcases for classes {@code org.jdtaus.iban.IBAN}, {@code org.jdtaus.iban.IbanSyntaxException} and {@code org.jdtaus.iban.IbanCheckDigitsException}.
*
* <dl>
* <dt><b>Identifier:</b></dt><dd>jDTAUS ⁑ ISO-13616 ⁑ Tests ⁑ IBAN Test</dd>
* <dt><b>Name:</b></dt><dd>jDTAUS ⁑ ISO-13616 ⁑ Tests ⁑ IBAN Test</dd>
* <dt><b>Abstract:</b></dt><dd>No</dd>
* <dt><b>Final:</b></dt><dd>Yes</dd>
* <dt><b>Stateless:</b></dt><dd>Yes</dd>
* </dl>
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version 1.1
*/
// </editor-fold>
// SECTION-END
package org.jdtaus.iso13616.test;
| 20b887649868e24058a1a3734cf20ebd99080b25 | [
"Java",
"Maven POM"
] | 5 | Java | jDTAUS/ISO-13616 | 9d40b84b6c72c81dc77829f3ff7d7b97d62843b4 | 459a27315186ec648cb0d12e9953df0f2b84698a |
refs/heads/master | <file_sep>package pl.mb.mongo;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class UserService {
private UserRepository userRepository;
public UserDto addUser(UserDto userDto) {
UserEntity userToSave = new UserEntity();
userToSave.setName(userDto.getName());
userToSave.setLastName(userDto.getLastName());
userToSave = userRepository.save(userToSave);
return entityToDto(userToSave);
}
private UserDto entityToDto(UserEntity userEntity) {
return new UserDto(userEntity.getId(),
userEntity.getName(),
userEntity.getLastName());
}
}
<file_sep>package pl.mb.mongo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDto {
String id;
String name;
String lastName;
}
<file_sep>package pl.mb.mongo;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@AllArgsConstructor
public class UserController {
private UserService userService;
@PostMapping("/users")
public ResponseEntity addUser(@RequestBody UserDto user) {
UserDto userDto = userService.addUser(user);
return new ResponseEntity(userDto, HttpStatus.OK);
}
}
<file_sep>package pl.mb.mongo;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserRepository extends MongoRepository<UserEntity, String> {
}
| ba9ba0c80205e0b67a7bbe566ca10b70c3864aac | [
"Java"
] | 4 | Java | michalbasinski/SDA_J9_SpringMongo | 4b996d6b95a0bc6fcf356bc5311ac5814c3ece79 | b92307093a24bc82efe77421009c473d7b377868 |
refs/heads/master | <file_sep>(function (angular) {
angular.module('ngToolbarApp', []);
}(angular))<file_sep># ngToolbar
toolbar create from bootstrap and angular1.x
| 97b2a0d3c70703388fccecbd9449f84122641b99 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | supperbowen/ngToolbar | 2f18d389ac855598c8bf13096590010945d914df | 1a1c58709867ada2de2c4564ce5e9aeb07fe707d |
refs/heads/master | <repo_name>cran/allanvar<file_sep>/man/gyroz.Rd
\name{gyroz}
\alias{gyroz}
\docType{data}
\title{Gyro sensor output for one-axis simulated gyroscope}
\description{
This dataset is an object of class "ts" (time series) with sensor output at a specifid
frequency.
}
\usage{data(gyroz)}
\source{
Simulated gyro using R software. It is not from a real sensor but it has a clear Random Walk and
Rate Random Walk with a small dataset.
}
\examples{
data(gyroz)
frequency(gyroz)
plot(gyroz)
}
\keyword{datasets}
<file_sep>/man/plotav.Rd
\name{plotav}
\alias{plotav}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
Allan Variance plot
}
\description{
This function plot the Allan variance graph. That is the Allan deviation \eqn{\sigma(\tau)} against the cluster time \eqn{\tau}
}
\usage{
plotav(avdf)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{avdf}{
\code{data.frame} with the results after calculating the Allan variance using \code{\link{avar}}, \code{\link{avarn}} or \code{\link{avari}}
}
}
\details{
\code{plotav} has been developed in order to plot the Allan variance estimation in an easy way but for sure other plot functions and stronger R graphics capabilities could also be used in order to visualize the slopes.
}
\value{
%% ~Describe the value returned
%% If it is a LIST, use
%% \item{comp1 }{Description of 'comp1'}
%% \item{comp2 }{Description of 'comp2'}
%% ...
Allan variance plot: Log-Log plot of the standard deviation \eqn{\sigma(\tau)} against the cluster times.
}
\references{
IEEE Std 952-1997 \emph{IEEE Standard Specification Format Guide and Test Procedure for
Single Axis Interferometric Fiber Optic Gyros}.
}
\author{
<NAME> <<EMAIL>>
}
%\note{
%A&R Group, DFKI, CAR-CSIC
%}
%% ~Make other sections like Warning with \section{Warning }{....} ~
%\seealso{
%% ~~objects to See Also as \code{\link{help}}, ~~~
%}
\examples{
#Load data
data(gyroz)
#Allan variance computation using avar
avgyroz <- avar(gyroz@.Data, frequency(gyroz))
plotav(avgyroz)
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
<file_sep>/R/avarn.R
################################################################################
# Automation and Robotic Section
# European Space Research and Technology Center (ESTEC)
# European Space Agency (ESA)
##
# Centre for Automation and Robotics (CAR)
# CSIC- Universidad Politecnica de Madrid
#
# Header: avarn(param1, param2)
#
# Author: <NAME>
#
# Date: 10-05-2010
#
# Input Parameters:
# values -> array with the data (angular velocity or acceleration)
# freq -> sampling frecuency in Herz
#
# Output Parameters:
# data frame structure with tree fields
# $av -> Allan Variance
# $time -> cluster time of the computation
# $error -> error of the estimation (quality of the variance)
#
# Description: avarn function computes the Allan variance estimation describe
# in the equation in the documentation attached to this package.
# Therefore the input has to be the output rate/acceleration from the sensors
# In this version of the Allan variance computation the number and size of
# cluster n has been computed as the maximum number of cluster into N
# values recorded, which is ceil [(N-1)/2].
#
# License: GPL-2
#
#' @export
#
################################################################################
avarn <- function (values, freq)
{
N = length(values) # Number of data availables
tau = 1/freq # sampling time
n = ceiling((N-1)/2) #Number of clusters
#Allan variance array
av <- rep (0,n)
#Time array
time <- rep(0,n)
#Percentage error array of the AV estimation
error <- rep(0,n)#1...n
print ("Calculating...")
# Minimal cluster size is 1 and max is n
# in time would be 1*tau and max time would be n*tau
for (i in 1:(n))
{
omega = rep(0,floor(N/i))
T = i*tau
l <- 1
k <- 1
while (k <= floor(N/i))
{
omega[k] = sum (values[l:(l+(i-1))])/i
l <- l + i
k <- k + 1
}
sumvalue <- 0
for (k in 1: (length(omega)-1))
{
sumvalue = sumvalue + (omega[k+1]-omega[k])^2
}
av[i] = sumvalue/(2*(length(omega)-1))
time[i] = T
#Equation for error AV estimation
#See Papoulis (1991) for further information
error[i] = 1/sqrt(2*((N/i)-1))
}
return (data.frame(time, av, error))
}
<file_sep>/R/avari.R
################################################################################
# Automation and Robotic Section
# European Space Research and Technology Center (ESTEC)
# European Space Agency (ESA)
##
# Centre for Automation and Robotics (CAR)
# CSIC- Universidad Politecnica de Madrid
#
# Header: avarn(param1, param2)
#
# Author: <NAME>
#
# Date: 10-05-2010
#
# Input Parameters:
# values -> array with the data recorded (angle or velocity)
# freq -> sampling frecuency
#
# Output Parameters:
# data frame structure with tree fields
# $av -> Allan Variance
# $time -> cluster time of the computation
# $error -> error of the estimation (quality of the variance)
#
# Description: avari function computes the Allan variance estimation describe
# in the equation in the documentation attached to this package
# Therefore the input has to be the integral value of output rate/acceleration
# from the sensors, that means angle from gyros and velocity from accelerometers
# In this version of the Allan variance computation the number and size of
# cluster n has been computed as in the avar function.
# n=2^l, l=1,2,3,...(Allan 1987)
#
# License: GPL-2
#
#' @export
#
################################################################################
avari <- function (values, freq)
{
N = length(values) # Number of data availables
tau = 1/freq # sampling time
n = ceiling((N-1)/2)
p = floor (log10(n)/log10(2)) #Number of clusters
#Allan variance array
av <- rep (0,p)#0...p-1
#Time array
time <- rep(0,p)#0...p-1
#Percentage error array of the AV estimation
error <- rep(0,p)#0...p-1
print ("Calculating...")
# Minimal cluster size is 1 and max is 2^p
# in time would be 1*tau and max time would be (2^p)*tau
for (i in 0:(p-1))
{
omega = rep(0,N-2*(2^i)) #N-2*(2^i) is the number of that cluster
T = (2^i)*tau
sumvalue <- 0
for (k in 1: (length(omega)))
{
sumvalue = sumvalue + (values[k+2*(2^i)]-(2*values[k+(2^i)])+values[k])^2
}
av[i+1] = sumvalue/(2*((T)^2)*(N-(2*(2^i)))) #i+1 because i starts at 0 (2^0 = 1)
time[i+1] = T #i+1 because i starts at 0 (2^0 = 1)
#Equation for error AV estimation
#See Papoulis (1991) for further information
error[i+1] = 1/sqrt(2*((N/(2^i))-1))
}
return (data.frame(time, av, error))
}
<file_sep>/man/avarn.Rd
\name{avarn}
\alias{avarn}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
Allan Variance (incremental cluster size by unit).
}
\description{
The function \code{avarn} computes the Allan Variance of a set of values with a given constant sampling frequency. The input has to be the output rate/acceleration from the sensors. In this version of the Allan variance computation the number and size of cluster n has been computed as the maximum number of cluster into N recorded values, which is ceil [(N-1)/2].
}
\usage{
avarn(values, freq)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{values}{
Calibrated sensor output (i.e: angular velocity or acceleration)
}
\item{freq}{
Sampling frequency rate in Hertz
}
}
\details{
It computes the Allan variance in the same way that \code{avar} function. The difference is that the number of cluster time and size are selected as the maximum number of cluster into N recorded values. However, Papoulis et.al recommend to estimate the amplitude of different noise components defined as in \code{avar} function. Therefore is recommended to use the \code{\link{avar}} in most of the cases, considering also computational cost.
}
\value{
%% ~Describe the value returned
%% If it is a LIST, use
%% \item{comp1 }{Description of 'comp1'}
%% \item{comp2 }{Description of 'comp2'}
%% ...
Return an object of class \code{\link{data.frame}} containing the Allan Variance computation with the following fields:
\item{time}{Value of the cluster time.}
\item{av}{The Allan variance value: variance among clusters of same size.}
\item{error}{Error on the estimation: Uncertainty of the value.}
}
\references{
<NAME>. (1966)
\emph{Statistics of Atomic Frequency Standards} Proceedings of IEEE, vol. 54, no. 2, pp. 221-230, Feb, 1966.
IEEE Std 952-1997 \emph{IEEE Standard Specification Format Guide and Test Procedure for
Single Axis Interferometric Fiber Optic Gyros}.
Papoulis, A and Unnikrisha,S (2002)
\emph{Probability, Random Variables and Stochastic Processes} Fourth Edition. McGraw Hill Series in electrical and Computer Engineering.
}
\author{
<NAME> <<EMAIL>>
}
%\note{
%A&R Group, DFKI, CAR-CSIC
%}
%% ~Make other sections like Warning with \section{Warning }{....} ~
%\seealso{
%% ~~objects to See Also as \code{\link{help}}, ~~~
%}
\examples{
#Load data
data(gyroz)
#Allan variance computation using avarn
avngyroz <- avarn(gyroz@.Data, frequency(gyroz))
plotav(avngyroz)
abline(1.0+log(avngyroz$time[1]), -1/2, col="green", lwd=4, lty=10)
abline(1.0+log(avngyroz$time[1]), 1/2, col="green", lwd=4, lty=10)
legend(0.11, 1e-03, c("Random Walk"))
legend(25, 1e-03, c("Rate Random Walk"))
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
<file_sep>/man/avari.Rd
\name{avari}
\alias{avari}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
Allan Variance (from integrated values).
}
\description{
The function \code{avari} computes the Allan Variance of a set of values with a given constant sampling frequency. The diferent with \code{avar} function is that the input values are the integral value of sensor output (i.e: rate/acceleration). That means angle from gyros and velocity from accelerometers. In this version of the Allan variance computation the number and size of cluster n has been computed as in \code{\link{avar}} function \eqn{n=2^l, l=1,2,\ldots}(Allan 1987).
}
\usage{
avari(values, freq)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{values}{
Integration of the calibrated sensor output (i.e: angel or velocity)
}
\item{freq}{
Sampling frequency rate in Hertz
}
}
\details{
The Allan variance can also be defined either in terms of the output rate as defined in \code{\link{avar}} by \eqn{\Omega(t)} or using the output angle/velocity as this function does. Defining:
\deqn{\theta(t) = \int^t \Omega(t^{'})dt^{'}}
The lower integration limit is not specified as only angle differences are employed in the definition. Angle measurement are made at discrete times given by \eqn{t = nt_0, n = 1,2,\ldots, N}. The notation is simplify by writing \eqn{\theta_k = \theta (k t_0)}. The cluster average is now defined as:
\eqn{\bar{\Omega}_k(\tau)= (\theta_{k+n} - \theta_k)/\tau} and \eqn{\bar{\Omega}_{k+1}(\tau)= (\theta_{k+2n} - \theta_{k+n})/(\tau)}
The equivalent Allan Variance estimation is defined as:
\deqn{\theta^2(\tau) = 1/(2\tau^2 (N - 2n)) \sum_{k=1}^{N-2n} [\theta_{k+2n} - 2\theta_{k+n} + \theta_k ]^2}
}
\value{
%% ~Describe the value returned
%% If it is a LIST, use
%% \item{comp1 }{Description of 'comp1'}
%% \item{comp2 }{Description of 'comp2'}
%% ...
Return an object of class \code{\link{data.frame}} containing the Allan Variance computation with the following fields:
\item{time}{Value of the cluster time.}
\item{av}{The Allan variance value: variance among clusters of same size.}
\item{error}{Error on the estimation: Uncertainty of the value.}
}
\references{
<NAME>. (1966)
\emph{Statistics of Atomic Frequency Standards} Proceedings of IEEE, vol. 54, no. 2, pp. 221-230, Feb, 1966.
IEEE Std 952-1997 \emph{IEEE Standard Specification Format Guide and Test Procedure for
Single Axis Interferometric Fiber Optic Gyros}.
<NAME>.; <NAME>.; <NAME> (2008)
\emph{Analysis and Modeling of Inertial Sensors Using Allan Variance} IEEE Transaction on Instrumentation and Measurement.
}
\author{
<NAME> <<EMAIL>>
}
%\note{
%A&R Group, DFKI, CAR-CSIC
%}
%% ~Make other sections like Warning with \section{Warning }{....} ~
%\seealso{
%% ~~objects to See Also as \code{\link{help}}, ~~~
%}
\examples{
#Load data
data(gyroz)
#Allan variance computation using avari
#Simple integration of the angular velocity
igyroz <- cumsum(gyroz@.Data * (1/frequency(gyroz)))
igyroz <- ts (igyroz, start=c(igyroz[1]), delta=(1/frequency(gyroz)))
avigyroz <- avari(igyroz@.Data, frequency(igyroz))
plotav(avigyroz)
abline(1.0+log(avigyroz$time[1]), -1/2, col="green", lwd=4, lty=10)
abline(1.0+log(avigyroz$time[1]), 1/2, col="green", lwd=4, lty=10)
legend(0.11, 1e-03, c("Random Walk"))
legend(25, 1e-03, c("Rate Random Walk"))
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
<file_sep>/R/plotav.R
################################################################################
# Automation and Robotic Section
# European Space Research and Technology Center (ESTEC)
# European Space Agency (ESA)
##
# Centre for Automation and Robotics (CAR)
# CSIC- Universidad Politecnica de Madrid
#
# Header: plotAV(param)
#
# Author: <NAME>
#
# Date: 10-05-2010
#
# Input Parameters:
# one data frame structure with tree fields
# $av -> Allan Variance
# $time -> cluster time of the computation
# $error -> error of the estimation (quality of the variance)
#
# Output Parameters:
# visual plotting
#
# Description:
# The R packages required for the execution of this script are:
# gplots, install.packages("gplots", dependencies = TRUE), for installing
#
# plotAV function computes the plot of the values for a Allan variance
# estimation.
#
# License: GPL-2
#
#' @export
#' @importFrom graphics plot lines axis grid title
#' @importFrom gplots plotCI
#
################################################################################
plotav <- function (avdf)
{
#Load library
#library(gplots)
#Plot Error Bars and Confidence Intervals
plotCI(x= avdf$time, y=sqrt(avdf$av), uiw = sqrt(avdf$av)*avdf$error, gap=0, lty = 1, xaxt="n", yaxt="n", col="blue", log="xy", lwd=1, xlab="", ylab="")
#Plot the line
lines (avdf$time,sqrt(avdf$av), col="blue")
#Axis numbers scale
axis(1, c(0.001,0.01, 0.1, 0, 1, 10, 100, 1000, 10000))
axis(2, c(0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 0, 1, 10, 100, 1000))
#Grid log-log
grid(equilogs=TRUE, lwd=1, col="orange")
#Information (title and axis labels)
title(main = "Allan variance Analysis", xlab = "Cluster Times (Sec)", ylab = "Allan Standard Deviation")
#legend(10, 5e-03, c("Allan Variance"), fill = c("blue"))
}
<file_sep>/man/avar.Rd
\name{avar}
\alias{avar}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
Allan Variance (cluster size as a power of 2).
}
\description{
The function \code{avar} computes the Allan Variance of a set of values with a given constant sampling frequency. The input has to be the output rate/acceleration from the sensors. In this version of the Allan variance computation the number and size of cluster has been computed as a power of 2 n=2^l, l=1,2,3,...(Allan 1987) which is convenient to estimate the amplitude of different noise components.
}
\usage{
avar(values, freq)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{values}{
Calibrated sensor output (i.e: angular velocity or acceleration)
}
\item{freq}{
Sampling frequency rate in Hertz
}
}
\details{
Considering a number \eqn{N} of outputs from the sensor at a constant time interval of \eqn{t_0}. \eqn{n} groups of consecutive data points could be formed \eqn{(n<N/2)}, each member of the groups is a cluster. Associated with each cluster is a time \eqn{\tau}, which is equal \eqn{t_0, 2t_0, 3t_0 \ldots nt_0}. Taking the instantaneous output of the inertial sensors (i.e. angular velocity) here denoted by \eqn{\Omega(t)}, the cluster average is:
\deqn{\bar{\Omega}_k(\tau)= 1/\tau \int_{t_k}^{t_{k+1}} \Omega(t)dt}
Where \eqn{\bar{\Omega}(t)} represents the cluster average value of the output rate for a cluster which starts from the \eqn{kth} data point and contains \eqn{n} data points depending on the length of \eqn{\tau}. The definition of the subsequent cluster average is as following, where \eqn{t_{k+1}= t_k + \tau}
\deqn{\bar{\Omega}_{k+1}(\tau)= 1/\tau \int_{t_{k+1}}^{t_{k+1}+\tau} \Omega(t)dt}
The interesting value for the Allan variance analysis is the difference for each of two adjacent clusters.
\deqn{\varepsilon_{k+1,k} = \bar{\Omega}_{k+1}(\tau) - \bar{\Omega}_k(\tau)}
For each cluster of time \eqn{\tau}, the ensemble of defined of the previous formula forms a set of random variables. The important information is the variance of \eqn{\varepsilon_s} over all the clusters of the same size that can be formed from the entire data. Then the Alla Variance of the length \eqn{\tau}, is defined as
\deqn{ \theta^2(\tau)= 1/(2(N-2n)) \sum_{k=1}^{N-2n} [ \bar{\Omega}_{k+1}(t) - \bar{\Omega}_k(t)]^2}
Obviously, for any finite number of data points (\eqn{N}), a finite numbers of cluster of a fixed length (\eqn{\tau}) can be formed. Hence \eqn{\theta^2(\tau)} represents an estimation of the real variance. The quality of estimate depends on the number of independent clusters of a fixed length that can be formed. Defining the parameters as the percentage error in estimating the Allan standard deviation of the cluster due to the finiteness of the number of clusters gives
\deqn{\zeta_{AV} = (\sigma(\tau,M) - \sigma(\tau))/(\sigma(\tau))}
where \eqn{\sigma(\tau,M)} denotes the estimate of the Allan standard deviation obtained from \eqn{M} independent clusters, \eqn{\sigma(\tau,M)} approaches its theoretical value \eqn{\sigma(\tau)} in the limit of \eqn{M} approaching infinity. A lengthy and straightforward calculation shows the percentage error, the formula has been used in the error of the estimation of the Allan Variance and it is equal to :
\deqn{\sigma(\zeta_{AV}) = 1/(\sqrt{2(N/n-1)})}
Where \eqn{N} is the total number of data points in the entire data set and \eqn{n} is the number of data points contained in the cluster. The equation shows that the error of the estimation is short when the length of the cluster is small as the number of independent cluster performed is large.
Characterization of stochastic errors requires identifying its PSD function. There is a unique relationship between the Allan variance (time-domain) and the PSD (frequency-domain) of the random process defined by
\deqn{\sigma^2(\tau) = 4 \int_{0}^{\infty}S_\Omega(f)(\sin^4(\pi f \tau))/((\pi f \tau)^2)df}
Where \eqn{S_\Omega(f)} is the two-side PSD of the random process.
}
\value{
%% ~Describe the value returned
%% If it is a LIST, use
%% \item{comp1 }{Description of 'comp1'}
%% \item{comp2 }{Description of 'comp2'}
%% ...
Return an object of class \code{\link{data.frame}} containing the Allan Variance computation with the following fields:
\item{time}{Value of the cluster time.}
\item{av}{The Allan variance value: variance among clusters of same size.}
\item{error}{Error on the estimation: Uncertainty of the value.}
}
\references{
<NAME>. (1966)
\emph{Statistics of Atomic Frequency Standards} Proceedings of IEEE, vol. 54, no. 2, pp. 221-230, Feb, 1966.
IEEE Std 952-1997 \emph{IEEE Standard Specification Format Guide and Test Procedure for
Single Axis Interferometric Fiber Optic Gyros}.
Papoulis, A and Unnikrisha,S (2002)
\emph{Probability, Random Variables and Stochastic Processes} Fourth Edition. McGraw Hill Series in electrical and Computer Engineering.
}
\author{
<NAME> <<EMAIL>>
}
%\note{
%A&R Group, DFKI, CAR-CSIC
%}
%\seealso{
%% ~~objects to See Also as \code{\link{help}}, ~~~
%}
\examples{
#Load data
data(gyroz)
#Allan variance computation using avar
avgyroz <- avar(gyroz@.Data, frequency(gyroz))
plotav(avgyroz)
abline(1.0+log(avgyroz$time[1]), -1/2, col="green", lwd=4, lty=10)
abline(1.0+log(avgyroz$time[1]), 1/2, col="green", lwd=4, lty=10)
legend(0.11, 1e-03, c("Random Walk"))
legend(25, 1e-03, c("Rate Random Walk"))
}
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{ ~kwd1 }
\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
<file_sep>/demo/allanvar.R
#Loading values
data(gyroz)
#Allan variance computation using avar
avgyroz <- avar(gyroz@.Data[1:1000], frequency(gyroz))
plotav(avgyroz)
abline(1.0+log(avgyroz$time[1]), -1/2, col="green", lwd=4, lty=10)
abline(1.0+log(avgyroz$time[1]), 1/2, col="green", lwd=4, lty=10)
legend(0.11, 1e-03, c("Random Walk"))
legend(2, 1e-03, c("Rate Random Walk"))
#Allan variance computation using avarn
avngyroz <- avarn(gyroz@.Data[1:1000], frequency(gyroz))
plotav(avngyroz)
abline(1.0+log(avngyroz$time[1]), -1/2, col="green", lwd=4, lty=10)
abline(1.0+log(avngyroz$time[1]), 1/2, col="green", lwd=4, lty=10)
legend(0.11, 1e-03, c("Random Walk"))
legend(2, 1e-03, c("Rate Random Walk"))
##Allan variance computation using avari
##Simple integration of the angular velocity
igyroz <- cumsum(gyroz@.Data[1:1000] * (1/frequency(gyroz)))
igyroz <- ts (igyroz, start=c(igyroz[1]), delta=(1/frequency(gyroz)))
avigyroz <- avari(igyroz@.Data, frequency(igyroz))
plotav(avigyroz)
abline(1.0+log(avigyroz$time[1]), -1/2, col="green", lwd=4, lty=10)
abline(1.0+log(avigyroz$time[1]), 1/2, col="green", lwd=4, lty=10)
legend(0.11, 1e-03, c("Random Walk"))
legend(2, 1e-03, c("Rate Random Walk"))
#Ploting all
plot (avgyroz$time,sqrt(avgyroz$av),log= "xy", xaxt="n" , yaxt="n", type="l", col="blue", xlab="", ylab="")
lines (avngyroz$time,sqrt(avngyroz$av), col="green", lwd=1)
lines (avigyroz$time,sqrt(avigyroz$av), col="red")
axis(1, c(0.001, 0.01, 0.1, 0, 1, 10, 100, 1000, 10000, 100000))
axis(2, c(0.00001, 0.0001, 0.001, 0.01, 0.1, 0, 1, 10, 100, 1000, 10000))
grid(equilogs=TRUE, lwd=1, col="orange")
title(main = "Allan variance Analysis Comparison", xlab = "Cluster Times (Sec)", ylab = "Allan Standard Deviation (rad/s)")
legend(1, 1e-03, c("GyroZ (avar)", "GyroZ(avarn)", "GyroZ(avari)"), fill = c("blue", "green", "red"))
<file_sep>/man/allanvar-package.Rd
\name{allanvar}
\alias{allanvar}
\alias{allanvar}
\docType{package}
\title{
Allan Variance Package
}
\description{
Set of function to compute the Allan Variance of sensor output in order to
perform sensor characterization of the most dominant stochastic errors
underlying the signal.
}
\details{
\tabular{ll}{
Package: \tab allanvar\cr
Type: \tab Package\cr
Version: \tab 1.1\cr
Date: \tab 2015-07-07\cr
License: \tab GPL-2\cr
LazyLoad: \tab yes\cr
}
The Allan Variance method was developed by <NAME> in 1966. Allan proposed
a simple variance analysis method for the study of oscillator stability (Allan
1966). After that this method has been adopted by the inertial sensor
community for the simplicity of the technique in comparatively to others
techniques like the power spectral density in the frequency domain or the
autocorrelation function. The Allan variance can provide directly information
on the types and magnitude of various noise terms. Since the analogies to
inertial sensors, this method has been adapted to random drift characterization
of inertial sensors.In the 80's was publishes the first paper related to the
use if the Allan variance with inertial sensors (Kochakian 1980). In 1983
Tehrani gave out the detailed deviation about the Allan variance noise terms
expression from their rate noise power spectral density for the ring laser gyro
(Tehrani 1983). In 2003, the Allan variance method was first applied in Micro
Electrical Mechanical Sensor (MEMS) noise identification (Haiying and El-Sheimy
2003) (El-Sheimy et. al. 2008) and is presented as a standard
recommendation for IEEE (Institute of Electrical and Electronics Engineers,
Inc.) since 1997 (IEEE Std 952-1997).
Following the Annex C in the IEEE recommendation (IEEE Std 952-1997), a number
of specific noise terms can be identified using the Allan variance. Those noise
terms are known to exist in inertial sensors. In this package the Allan
Variance technique is developed in R in order to easilly identified the
dominant stochastic noise processes. Since the Allan variance technique is a
graphic method based on ploting the Allan standard deviation against the
cluster time a plot utility is also available in this package.
To summarize, \code{Alla Variance Packages} provides with a set of functions to
compute the Allan variance. The identification of the noise terms in the Allan
variance is performed in a \eqn{log-log} graph of the Allan deviation against
the cluster time \eqn{\tau}. Then, the package provides with a function
\code{\link{plotav}} to visualize the results in a \eqn{log-log} graph.
Afterwards, simple analyses are needed to calculate the noise coefficients. The
reader can find abundant information in the literature concerning noise
characterization using the Allan variance technique.
}
\author{
<NAME>
\email{<EMAIL>}
}
\references{
All<NAME>. (1966)
\emph{Statistics of Atomic Frequency Standards} Proceedings of IEEE, vol. 54,
no. 2, pp. 221-230, Feb, 1966.
<NAME>. (1987)
\emph{Time and Frequency (Time-Domain) Characterization, Estimation,
and Prediction of Precision Clocks and Oscillators} IEEE Transportations on
Ultrasonics, Ferroelectrics, and Frequency Control, Vol. UFFC -34, no.6, pp.647-
654.
<NAME>. and <NAME>. (2003)
\emph{Inertial Sensors Errors Modelling Using Allan
Variance} Best Presentation Winning Paper, The US Institute of Navigation, ION
GPS/GNSS 2003 Proceedings, pp. 2860-2867, Sep 9-12, Portland.
<NAME>. (2010)
\emph{Characterization and Modeling of Inertial
Sensors for Rover Attitude Estimation} Escuela Tecnica Superior de
Ingenieros Industriales, <NAME>, 2. 28006, Madrid (Spain),
Nov/2010. Publisher: Automation and Robotics Section of the European Space
Research and Technology Center (ESTEC) and Universidad Politecnica de
Madrid.
<NAME>.; <NAME>.; <NAME> (2008)
\emph{Analysis and Modeling of Inertial Sensors Using Allan Variance} IEEE
Transaction on Instrumentation and Measurement.
IEEE Std 952-1997
\emph{IEEE Standard Specification Format Guide and Test
Procedure for Single Axis Interferometric Fiber Optic Gyros}.
<NAME>. (1980)
\emph{Time-Domain Uncertainty Charts (Green Charts): A
Tool for Validating the Design of IMU/Instrument Interfaces} Proceedings of
the AIAA Guidance and Control Conference, Aug. 11-13, 1980.
<NAME> and Unnikrisha,S (2002)
\emph{Probability, Random Variables and
Stochastic Processes} Fourth Edition. McGraw-Hill Series in Electrical and
Computer Engineering.
<NAME>. (1983)
\emph{Ring Laser Gyro Data Analysis with Cluster Sampling
Technique} Proceedings of SPIE, vol. 412}
%~~ Optionally other standard keywords, one per line, from file KEYWORDS in the
%R documentation directory ~~
\keyword{ package }
\examples{
#This example is also available under
#the command: demo(allanvar)
#Loading values
data(gyroz)
#Allan variance computation using avar
avgyroz <- avar(gyroz@.Data, frequency(gyroz))
#Allan variance computation using avarn
avngyroz <- avarn(gyroz@.Data, frequency(gyroz))
#Allan variance computation using avari
#Simple integration of the angular velocity
igyroz <- cumsum(gyroz@.Data * (1/frequency(gyroz)))
igyroz <- ts (igyroz, start=c(igyroz[1]), delta=(1/frequency(gyroz)))
avigyroz <- avari(igyroz@.Data, frequency(igyroz))
#Ploting all
plot (avgyroz$time,sqrt(avgyroz$av),log= "xy", xaxt="n" , yaxt="n", type="l",
col="blue", xlab="", ylab="")
lines (avngyroz$time,sqrt(avngyroz$av), col="green", lwd=1)
lines (avigyroz$time,sqrt(avigyroz$av), col="red")
axis(1, c(0.001, 0.01, 0.1, 0, 1, 10, 100, 1000, 10000, 100000))
axis(2, c(0.00001, 0.0001, 0.001, 0.01, 0.1, 0, 1, 10, 100, 1000, 10000))
grid(equilogs=TRUE, lwd=1, col="orange")
title(main = "Allan variance Analysis Comparison", xlab = "Cluster Times
(Sec)", ylab = "Allan Standard Deviation (rad/s)")
legend(10, 4e-03, c("GyroZ (avar)", "GyroZ(avarn)", "GyroZ(avari)"), fill =
c("blue", "green", "red"))
}
<file_sep>/R/avar.R
################################################################################
# Automation and Robotic Section
# European Space Research and Technology Center (ESTEC)
# European Space Agency (ESA)
##
# Centre for Automation and Robotics (CAR)
# CSIC- Universidad Politecnica de Madrid
#
# Header: avar(param1, param2)
#
# Author: <NAME>
#
# Date: 10-05-2010
#
# Input Parameters:
# values -> array with the data (angular velocity or acceleration)
# freq -> sampling frecuency in Herz
#
# Output Parameters:
# data frame structure with tree fields
# $av -> Allan Variance
# $time -> cluster time of the computation
# $error -> error of the estimation (quality of the variance)
#
# Description: avar function computes the Allan variance estimation describe
# in the equation in the documentation attached to this packages.
# Therefore the input has to be the output rate/acceleration from the sensors
# In this version of the Allan variance computation the number and size of
# cluster has been computed as a power of 2 n=2^l, l=1,2,3,...(Allan 1987)
# which is convenient to estimate the amplitude of different noise components.
#
# License: GPL-2
#
#' @export
#
################################################################################
avar <- function (values, freq)
{
N = length(values) # Number of data availables
tau = 1/freq # sampling time
n = ceiling((N-1)/2)
p = floor (log10(n)/log10(2)) #Number of clusters
#Allan variance array
av <- rep (0,p+1)#0 and 1...p
#Time array
time <- rep(0,p+1)#0 and 1...p
#Percentage error array of the AV estimation
error <- rep(0,p+1)#0 and 1...p
print ("Calculating...")
# Minimal cluster size is 1 and max is 2^p
# in time would be 1*tau and max time would be (2^p)*tau
for (i in 0:(p))
{
omega = rep(0,floor(N/(2^i))) #floor(N/(2^i)) is the number of the cluster
T = (2^i)*tau
l <- 1
k <- 1
#Perfome the average values
while (k <= floor(N/(2^i)))
{
omega[k] = sum (values[l:(l+((2^i)-1))])/(2^i)
l <- l + (2^i)
k <- k + 1
}
sumvalue <- 0
#Perfome the difference of the average values
for (k in 1: (length(omega)-1))
{
sumvalue = sumvalue + (omega[k+1]-omega[k])^2
}
#Compute the final step for Allan Variance estimation
av[i+1] = sumvalue/(2*(length(omega)-1)) #i+1 because i starts at 0 (2^0 = 1)
time[i+1] = T #i+1 because i starts at 0 (2^0 = 1)
#Equation for error AV estimation
#See Papoulis (1991) for further information
error[i+1] = 1/sqrt(2*((N/(2^i))-1))
}
return (data.frame(time, av, error))
}
| 7c7e7efe51cad6211ee03dbf10b0a0789fe0246c | [
"R"
] | 11 | R | cran/allanvar | e277b8b6e0af6fea7881184da924bae18defe869 | eb8c52e1afedcaee5f6a8b439b8b4f1d3c1454ff |
refs/heads/main | <file_sep>/* avoid putting Back and Forward buttons into Customize view, they become buggy
and can even break firefox to the point you gotta use about:support -> troubleshooting restart */
(function() {
let movable = [
"back-button",
"forward-button",
];
for(let id of movable) {
try {
document.getElementById(id).setAttribute("removable", "true");
} catch(e) {}
}
})();
| dbe6926195caf47d3e35f85a04c1b228212a1c32 | [
"JavaScript"
] | 1 | JavaScript | MacDos/Oneliner-Deluxe | 435d75b4827da530f8f2a6331d04221d2ddfeb90 | aa6634c7740fcbc5075a4248ae776ba51c296fe1 |
refs/heads/master | <file_sep>// 加载模块函数
console.info(require);
// 模块对象
console.info(module);
// 导出对象别名
console.info(exports);
// 当前文件的绝对路径
console.info(__filename);
// 当前文件所在目录
console.info(__dirname);<file_sep>export default {
hi: 'hey guys, I am mhe'
}<file_sep>// // 加载模块函数
// console.info(require);
// // 模块对象
// console.info(module);
// // 导出对象别名
// console.info(exports);
// // 当前文件的绝对路径
// console.info(__filename);
// // 当前文件所在目录
// console.info(__dirname);
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.info(__filename);
console.info(__dirname);<file_sep>import conSomething from './testExport.js';
import './heading.css';
const y = conSomething();
const testHas0 = () => {
console.info("123");
return 10;
}
const x = testHas0()
export default () => {
const element = document.createElement("h2");
element.textContent = "hello world";
element.classList.add('heading');
element.addEventListener('click', () => {
alert("hello webpack");
});
return element;
}
const x111 = () => {
console.info(123)
}<file_sep>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 载入HtmlWebpackPlugin, 他不需要解构, 默认导出就是
const webpack = require('webpack');
class myPlugin {
// 定义一个类, 然后定义一个apply方法
apply(compiler) {
// apply方法会在webpack启用时, 自动被调用
// 接收一个compiler对象参数, 这个对象就是webpack工作过程中的核心对象, 包含了此次构建的所有配置信息, 也是通过这个对象去注册钩子函数
// 这里编写一个插件用于去除打包过程后bundle.js下所有的注释, 因此, 这个过程应该是在bundle.js出现后实施
// emit在 输出 asset 到 output 目录之前执行(就是即将往输出目录输出文件)
// ! 通过compiler.hooks.emit去访问到这个钩子, 通过tap方法去注册函数
// ! tap方法接收两个参数, 第一个是插件名称, 第二个就是挂载到这个钩子上的函数了
compiler.hooks.emit.tap("myPlugin", compilation => {
// * compilation这个对象可以理解成此次打包过程中的上下文, 打包结果都会放到这个对象中
// assets是即将写入目录中的资源文件信息, 是一个对象, 键名是文件的名称
for (const name in compilation.assets) {
// 通过source方法可以拿到对应地内容
// 需求是做一个去除bundle.js注释的插件, 因此要判断文件名
if (name.match(/.js$/)) {
// console.info(compilation.assets[name].source())
// 然后进行处理
const contents = compilation.assets[name].source();
const withoutComments = contents.replace(/\/\*\*+\*\//g, "");
// 处理完成后, 需要去替换compilation.assets下的对应地内容
compilation.assets[name] = {
source: () => withoutComments, // 依然使用一个source方法去暴露
size: () => withoutComments.length, // 还需要一个size方法, 去返回一个内容的大小, 这个是webpack要求的所必须的方法
}
}
}
})
}
}
module.exports = {
// 开发模式变量
entry: './src/main.js', // 入口文件, 如果是一个相对路径, 前面的./是不能省略的
output: { // output设置输出文件的配置, 该属性是一个对象
filename: 'bundle.js', // 设置输出文件名称
path: path.join(__dirname, 'dist'), // path执行文件输出所在的目录, 他必须使用绝对路径, 默认就是dist
// publicPath: '/'
},
mode: 'none',
devtool: 'eval',
module: {
rules: [
{
test: /.js$/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env']
},
},
exclude: path.join(__dirname, 'node_modules')
},
{
test: /.css$/,
use: [
'style-loader', 'css-loader'
]
},
{
test: /.(jpg|png|gif|bmp|jpeg)$/,
use: {
loader: 'url-loader',
options: {
limit: 10 * 1024,
}
}
},
{
test: /.html$/,
use: {
loader: 'html-loader',
options: {
// attributes: ["img:src", "a:href"], // 目前已弃用这种方式
sources: {
list: [
{
tag: 'img', // 标签名
attribute: 'src', // 挂载标签上的属性名
type: 'src', // 属性名对应地原类型
},
]
},
minimize: process.env === 'production' ? true : false,
esModule: true
}
},
exclude: path.join(__dirname, 'index.html')
}
]
},
plugins: [ // 配置插件的数组
new HtmlWebpackPlugin({
title: 'webpack学习',
filename: 'index.html',
template: 'index.html',
inject: 'body',
}),
new myPlugin(),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
http2: true,
hot: true,
// open: true,
// https: true,
contentBase: [
path.join(__dirname, 'src/favicons')
], // 可以是字符串, 也可以是数组
proxy: {
'/api': {
// 也就是说请求 localhost:3000/api/users -> https://api.github.com/api/users
target: 'https://api.github.com',
// 但是在https://api.github.com的接口中并没有/api, 因此需要添加一层代理路径的重写
pathRewrite: {
'^/api': "", // 这个属性最终会生成一个正则去匹配上面的路径
},
// ws: true,
// timeout: 9999999999,
// 不能使用localhost:3000作为请求 github 的主机名
// 主机名由于服务端判断请求应该走哪一个网站, 设置changeOrigin为true, 就会将代理请求作为实际的主机名去请求
changeOrigin: true,
}
}
}
}<file_sep>import createHeading from './heading';
const heading = createHeading();
document.body.append(heading);
console.info("main.js running");
console.info111("main.js running");<file_sep># 关于我自己
我是Lisher, 一个前端开发老油条
<file_sep>const path = require('path');
const { CleanWebpackPlugin } = require("clean-webpack-plugin"); // 这个模块解构出来一个CleanWebpackPlugin, 就是用于清除dist目录的插件
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 载入HtmlWebpackPlugin, 他不需要解构, 默认导出就是
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin'); // 用于压缩css文件
const TerserWebpackPlugin = require('terser-webpack-plugin'); // 压缩JS
class myPlugin {
// 定义一个类, 然后定义一个apply方法
apply(compiler) {
// apply方法会在webpack启用时, 自动被调用
// 接收一个compiler对象参数, 这个对象就是webpack工作过程中的核心对象, 包含了此次构建的所有配置信息, 也是通过这个对象去注册钩子函数
// 这里编写一个插件用于去除打包过程后bundle.js下所有的注释, 因此, 这个过程应该是在bundle.js出现后实施
// emit在 输出 asset 到 output 目录之前执行(就是即将往输出目录输出文件)
// ! 通过compiler.hooks.emit去访问到这个钩子, 通过tap方法去注册函数
// ! tap方法接收两个参数, 第一个是插件名称, 第二个就是挂载到这个钩子上的函数了
compiler.hooks.emit.tap("myPlugin", compilation => {
// * compilation这个对象可以理解成此次打包过程中的上下文, 打包结果都会放到这个对象中
// assets是即将写入目录中的资源文件信息, 是一个对象, 键名是文件的名称
for (const name in compilation.assets) {
// 通过source方法可以拿到对应地内容
// 需求是做一个去除bundle.js注释的插件, 因此要判断文件名
if (name.match(/.js$/)) {
// console.info(compilation.assets[name].source())
// 然后进行处理
const contents = compilation.assets[name].source();
const withoutComments = contents.replace(/\/\*\*+\*\//g, "");
// 处理完成后, 需要去替换compilation.assets下的对应地内容
compilation.assets[name] = {
source: () => withoutComments, // 依然使用一个source方法去暴露
size: () => withoutComments.length, // 还需要一个size方法, 去返回一个内容的大小, 这个是webpack要求的所必须的方法
}
}
}
})
}
}
/* module.exports = {
entry: './src/main.js', // 入口文件, 如果是一个相对路径, 前面的./是不能省略的
output: { // output设置输出文件的配置, 该属性是一个对象
filename: 'bundle.js', // 设置输出文件名称
path: path.join(__dirname, 'dist'), // path执行文件输出所在的目录, 他必须使用绝对路径, 默认就是dist
// publicPath: '/'
},
mode: 'none',
devtool: 'eval',
module: { // 使用loader需要添加具体的配置, 就是在webpack.config.js中添加一个module, 下面配置rules数组
// rules就是针对其他资源的加载规则配置, 每一个规则对象都有两个属性:
// 一个test属性, 是正则表达式, 用于匹配打包过程中所遇到的文件路径
// 一个use属性, 用于表示使用的loader
rules: [
{
test: /.js$/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env']
},
},
exclude: path.join(__dirname, 'node_modules')
},
{
test: /.css$/,// 表示匹配所有的.css结尾的文件, 也就是匹配所有的css文件
use: [
// 改成数组后, 配置多个loader, 执行是从后往前执行, 就像一个栈一样, 先进后出, 最先进去的最后执行
'style-loader', 'css-loader'
] // cssloader的作用就是将css文件转换成一个js模块, 具体实现就是将css代码转换成字符串push到了一个数组中
// 但是单纯向上面这样只使用一个css-loader就会发现没有任何代码引用这一串字符串
// 因此这里还需要一个style-loader, 就是将css的字符串通过style标签放到页面上
// 通过设置两个loader就会发现 __webpack_modules__下面多了两个模块, 主要代表的就是css-loader和style-loader模块
// css-loader生成的css字符串, 就通过 insertStyleElement函数 创建一个style标签, 挂载到页面中
},
{
test: /.(jpg|png|gif|bmp|jpeg)$/,
use: {
loader: 'url-loader',
// 其实所有的loader都可以通过这种方式去配置
options: {
limit: 10 * 1024, // 10kb大小限制, 这样之后大于10kb的依然会使用file-loader
// 这种方式是默认使用file-loader, 因此一定不要忘了安装file-loader
}
}
},
{
test: /.html$/,
use: {
loader: 'html-loader',
options: {
// attributes: ["img:src", "a:href"], // 目前已弃用这种方式
sources: {
list: [
{
tag: 'img', // 标签名
attribute: 'src', // 挂载标签上的属性名
type: 'src', // 属性名对应地原类型
},
]
},
minimize: process.env === 'production' ? true : false,
esModule: true
}
},
exclude: path.join(__dirname, 'index.html')
}
]
},
plugins: [ // 配置插件的数组
// * 大部分webpack插件模块导出的都是一个类, 所以使用它, 是通过这个类去创建一个实例, 将实例放入plugins数组中
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'webpack学习',
filename: 'index.html',
template: 'index.html',
inject: 'body',
// meta: {
// viewport: 'width=device-width'
// }
}),
// new CopyWebpackPlugin({
// patterns: [
// { from: "src/favicons", to: "dest" },
// ],
// }),
new myPlugin(),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
http2: true,
hot: true,
// open: true,
// https: true,
contentBase: [
path.join(__dirname, 'src/favicons')
], // 可以是字符串, 也可以是数组
proxy: {
'/api': {
// 也就是说请求 localhost:3000/api/users -> https://api.github.com/api/users
target: 'https://api.github.com',
// 但是在https://api.github.com的接口中并没有/api, 因此需要添加一层代理路径的重写
pathRewrite: {
'^/api': "", // 这个属性最终会生成一个正则去匹配上面的路径
},
// ws: true,
// timeout: 9999999999,
// 不能使用localhost:3000作为请求 github 的主机名
// 主机名由于服务端判断请求应该走哪一个网站, 设置changeOrigin为true, 就会将代理请求作为实际的主机名去请求
changeOrigin: true,
}
}
}
} */
module.exports = (env, argv) => {
console.info(env)
const config = {
// 开发模式变量
entry: './src/main.js', // 入口文件, 如果是一个相对路径, 前面的./是不能省略的
output: { // output设置输出文件的配置, 该属性是一个对象
filename: 'bundle.js', // 设置输出文件名称
path: path.join(__dirname, 'dist'), // path执行文件输出所在的目录, 他必须使用绝对路径, 默认就是dist
// publicPath: '/'
},
mode: 'none',
devtool: false,
module: { // 使用loader需要添加具体的配置, 就是在webpack.config.js中添加一个module, 下面配置rules数组
// rules就是针对其他资源的加载规则配置, 每一个规则对象都有两个属性:
// 一个test属性, 是正则表达式, 用于匹配打包过程中所遇到的文件路径
// 一个use属性, 用于表示使用的loader
rules: [
{
test: /.js$/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env']
},
},
exclude: path.join(__dirname, 'node_modules')
},
{
test: /.css$/,// 表示匹配所有的.css结尾的文件, 也就是匹配所有的css文件
use: [
// 改成数组后, 配置多个loader, 执行是从后往前执行, 就像一个栈一样, 先进后出, 最先进去的最后执行
// 'style-loader', // 使用MiniCssExtractPlugin就用不上他了, 不需要注入style标签的方式, 而是直接link
MiniCssExtractPlugin.loader,
'css-loader'
] // cssloader的作用就是将css文件转换成一个js模块, 具体实现就是将css代码转换成字符串push到了一个数组中
// 但是单纯向上面这样只使用一个css-loader就会发现没有任何代码引用这一串字符串
// 因此这里还需要一个style-loader, 就是将css的字符串通过style标签放到页面上
// 通过设置两个loader就会发现 __webpack_modules__下面多了两个模块, 主要代表的就是css-loader和style-loader模块
// css-loader生成的css字符串, 就通过 insertStyleElement函数 创建一个style标签, 挂载到页面中
},
{
test: /.(jpg|png|gif|bmp|jpeg)$/,
use: {
loader: 'url-loader',
// 其实所有的loader都可以通过这种方式去配置
options: {
limit: 10 * 1024, // 10kb大小限制, 这样之后大于10kb的依然会使用file-loader
// 这种方式是默认使用file-loader, 因此一定不要忘了安装file-loader
}
}
},
{
test: /.html$/,
use: {
loader: 'html-loader',
options: {
// attributes: ["img:src", "a:href"], // 目前已弃用这种方式
sources: {
list: [
{
tag: 'img', // 标签名
attribute: 'src', // 挂载标签上的属性名
type: 'src', // 属性名对应地原类型
},
]
},
minimize: process.env === 'production' ? true : false,
esModule: true
}
},
exclude: path.join(__dirname, 'index.html')
}
]
},
plugins: [ // 配置插件的数组
new HtmlWebpackPlugin({
title: 'webpack学习',
filename: 'index.html',
template: 'index.html',
inject: 'body',
// meta: {
// viewport: 'width=device-width'
// }
}),
// new CopyWebpackPlugin({
// patterns: [
// { from: "src/favicons", to: "dest" },
// ],
// }),
new myPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
// 这个插件的构造函数接收一个对象, 对象的每一个键值, 都是往process.env中注入的东西
API_BASE_URL: '"https://api.example.com"'
}),
new MiniCssExtractPlugin(),
],
devServer: {
http2: true,
hot: true,
// open: true,
// https: true,
contentBase: [
path.join(__dirname, 'src/favicons')
], // 可以是字符串, 也可以是数组
proxy: {
'/api': {
// 也就是说请求 localhost:3000/api/users -> https://api.github.com/api/users
target: 'https://api.github.com',
// 但是在https://api.github.com的接口中并没有/api, 因此需要添加一层代理路径的重写
pathRewrite: {
'^/api': "", // 这个属性最终会生成一个正则去匹配上面的路径
},
// ws: true,
// timeout: 9999999999,
// 不能使用localhost:3000作为请求 github 的主机名
// 主机名由于服务端判断请求应该走哪一个网站, 设置changeOrigin为true, 就会将代理请求作为实际的主机名去请求
changeOrigin: true,
}
}
},
optimization: {
// usedExports: true,
// minimize: true,
// concatenateModules: true
sideEffects: true, // production模式下自动开始
minimizer: [
new OptimizeCssAssetsWebpackPlugin(),
new TerserWebpackPlugin()
]
}
}
if (env.production) {
// env.production 已经不再是以前那种直接就是值了, 而是确定下面的production是否为true
console.info("123")
config.mode = 'production';
config.devtool = false;
config.plugins = [
...config.plugins,
// 这里添加clean-webpack-plugin和copy-webpack-plugin, 这两个就是之前说的开发阶段可以省略的插件
new CleanWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [
{ from: "src/favicons", to: "dest" },
],
})
]
}
return config;
}<file_sep>import about from './about.md';
console.info(about);<file_sep>export const log = msg => {
console.info('----------INFO----------');
console.info(msg);
console.info('------------------------');
}
export const error = msg => {
console.error('----------ERROR----------');
console.error(msg);
console.error('-------------------------');
}<file_sep>// 这个文件同样运行在node环境中
// 不过rollup会自己处理这个配置文件, 因此可以直接使用es module
// 需要导出一个配置对象
// 同时必须使用--config 去使用配置文件, 因为默认他不会 使用配置文件
import json from 'rollup-plugin-json';// 默认导出的就是一个函数
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
export default {
input: 'src/index.js',
output: {
// file: 'dist/bundle.js',
// format: 'iife'
dir: 'dist',
format: 'amd'
},
plugins: [
json(), // 将调用结果放过来, 而不是函数
resolve(), // 这样即可在js文件中通过文件名导入第三方模块了
commonjs()
]
}<file_sep>export const light = "liang";
export default () => {
console.info("123");
return 10n;
}
<file_sep>export default {
bar: () => {
console.info("accept")
}
}<file_sep>// import { log } from './logger';
// import messages from './messages';
// import {name, version} from '../package.json';
// import _ from 'lodash-es';
// console.info(name)
// console.info(version)
// // 使用模块成员
// const msg = messages.hi;
// log(msg);
// log(_.camelCase('hello world'))
import('./logger').then(({log}) => {
log("code splitting");
})<file_sep>let name = 'zs';
let age = "18";
export {name, age};
setTimeout(() => {
name = "wangwu"
}, 1000)<file_sep>const common = require('./webpack.common');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require("clean-webpack-plugin"); // 这个模块解构出来一个CleanWebpackPlugin, 就是用于清除dist目录的插件
const { merge } = require('webpack-merge');
// 使用Object.assign会后项完全覆盖前项相同键名的属性, 但是对于引用类型, 我们只希望做添加, 而不是完全覆盖
// 所以Object.assign并不合适, 可以使用lodash.merge, 不过社区中提供了专用的webpackMerge这个库
module.exports = () => {
return merge(common, {
mode: "production",
plugins: [
new CleanWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [
{ from: "src/favicons", to: "dest" },
],
}),
],
devtool: false
})
}<file_sep>// 每个webpack的loader都需要导出一个函数, 这个函数就是对所加载到的资源的一个处理过程
const marked = require("marked"); // 解析markdown用的库
module.exports = source => {
// * 该函数的输入就是加载到的资源文件的内容
// * 输出就是此次加工过后的结果
// * 通过 source 来接收输入, 通过返回值来输出
const html = marked(source); // 获取的结果是一段html字符串
// 如果直接返回, 就会和刚刚一样, 返回值不是一段js代码
// 这里我们其实就是希望导出这段html字符串
// 但是又不能只做一段简单的拼接, 这样换行符, 内部的引号等会出问题
// 因此使用JSON.stringify()做转换
// return `export default${JSON.stringify(html)}`;
return html;
}
<file_sep>import createHeading from './heading.js';
// import conSomething from './testExport.js';
// import './main.css';
import url from './favicons/github.png';
const heading = createHeading();
document.body.append(heading);
const img = new Image();
img.src = url;
document.body.append(img);
// ! 部分loader加载的资源中一些方法也会触发资源模块加载
import './main.css';
console.info(API_BASE_URL)
// import footerHtml from './footer.html';
// console.info(footerHtml)
// const testHt = document.createElement(footerHtml)
// document.body.append(testHt);
module.hot.accept('./heading', () => {
console.info("heading模块更新了, 需要手动处理热更新逻辑")
})
<file_sep>export const foo = "hello";
export const bar = "es mdoule"; | 004de4d9c3bc1fdea6f158c1d03c851f405ae902 | [
"JavaScript",
"Markdown"
] | 19 | JavaScript | Lisheri/studyFiles | d307e90a565108cb1cc0b3fea4a7d2c78ae9e1b5 | 28d2dce33a44c11ba1fb1553cb84f4b1d708a226 |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router' ;
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-tbk2',
templateUrl: './tbk2.component.html',
styleUrls: ['./tbk2.component.css']
})
export class Tbk2Component implements OnInit {
constructor(private router:ActivatedRoute,private http:HttpClient) { }
tbk2;
ngOnInit() {
this.http.get('/api/tbk2').subscribe((data)=>{
this.tbk2 = data;
});
}
}
<file_sep>import { Component, OnInit,Output,EventEmitter } from '@angular/core';
import { CommonService} from '../../seriveces/common.service';
@Component({
selector: 'app-child1',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
constructor(private local:CommonService) { }
ngOnInit() {
}
txt;
@Output() text1 = new EventEmitter();
add(e){
if(e.keyCode==13){
this.text1.emit(this.txt);
this.txt="";
}
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-qieshuo1',
templateUrl: './qieshuo1.component.html',
styleUrls: ['./qieshuo1.component.css']
})
export class Qieshuo1Component implements OnInit {
constructor(private http:HttpClient) { }
qieshuo1;
ngOnInit() {
this.http.get('/api/qieshuo').subscribe((data)=>{
this.qieshuo1 = data;
});
}
}
<file_sep>import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ModalController } from 'ionic-angular';
import { FaxianPage } from '../faxian/faxian';
/**
* Generated class for the PageonePage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@Component({
selector: 'page-pageone',
templateUrl: 'pageone.html',
})
export class PageonePage {
constructor(public navCtrl: NavController, public navParams: NavParams,public modalCtrl: ModalController) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad PageonePage');
let profileModal = this.modalCtrl.create(FaxianPage);
profileModal.present();
}
}
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { FaxianPage } from './faxian';
@NgModule({
declarations: [
FaxianPage,
],
imports: [
IonicPageModule.forChild(FaxianPage),
],
})
export class FaxianPageModule {}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Tbk3Component } from './tbk3.component';
describe('Tbk3Component', () => {
let component: Tbk3Component;
let fixture: ComponentFixture<Tbk3Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ Tbk3Component ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Tbk3Component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component } from '@angular/core';
/**
* Generated class for the AbcComponent component.
*
* See https://angular.io/api/core/Component for more info on Angular
* Components.
*/
@Component({
selector: 'abc',
templateUrl: 'abc.html'
})
export class AbcComponent {
text: string;
constructor() {
console.log('Hello AbcComponent Component');
this.text = 'this is abc component';
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router' ;
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-tongzhi',
templateUrl: './tongzhi.component.html',
styleUrls: ['./tongzhi.component.css']
})
export class TongzhiComponent implements OnInit {
constructor(private router:ActivatedRoute,private http:HttpClient) { }
tongzhi;
ngOnInit() {
this.http.get('/api/tongzhi').subscribe((data)=>{
this.tongzhi = data;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-qieshuo3',
templateUrl: './qieshuo3.component.html',
styleUrls: ['./qieshuo3.component.css']
})
export class Qieshuo3Component implements OnInit {
constructor() { }
ngOnInit() {
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Qieshuo1Component } from './qieshuo1.component';
describe('Qieshuo1Component', () => {
let component: Qieshuo1Component;
let fixture: ComponentFixture<Qieshuo1Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ Qieshuo1Component ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Qieshuo1Component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router' ;
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-tbk3',
templateUrl: './tbk3.component.html',
styleUrls: ['./tbk3.component.css']
})
export class Tbk3Component implements OnInit {
constructor(private router:ActivatedRoute,private http:HttpClient) { }
tbk3;
ngOnInit() {
this.http.get('/api/tbk3').subscribe((data)=>{
this.tbk3 = data;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-tongbu',
templateUrl: './tongbu.component.html',
styleUrls: ['./tongbu.component.css']
})
export class TongbuComponent implements OnInit {
constructor(private http:HttpClient) { }
arr=['<<',1,2,3,4,5,6,7,8,9,'>>'];
courseId:number;
tongbuke;
ngOnInit() {
// this.courseId = this.router.snapshot.params['courseId'];
// this.router.params.subscribe((params)=>{
// this.courseId = params['courseId'];
// });
this.http.get('/api/tongbuke').subscribe((data)=>{
this.tongbuke = data;
});
}
}
class Course{
constructor(
public id:number,
public courseName:string,
public images:string,
public task:number,
public person:number){
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-qieshuo',
templateUrl: './qieshuo.component.html',
styleUrls: ['./qieshuo.component.css']
})
export class QieshuoComponent implements OnInit {
constructor(private router:ActivatedRoute,private http:HttpClient) { }
qieshuo;
ngOnInit() {
this.http.get('/api/qieshuo').subscribe((data)=>{
this.qieshuo = data;
});
}
}
<file_sep>import { NgModule } from '@angular/core';
import { AComponent } from './a/a';
import { BComponent } from './b/b';
import { AbcComponent } from './abc/abc';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
@NgModule({
declarations: [AComponent,
AComponent,
AComponent,
BComponent,
AbcComponent],
imports: [
BrowserModule,
IonicModule.forRoot(ComponentsModule,{
backButtonText: '首页',
iconMode: 'ios',
modalEnter: 'modal-slide-in',
modalLeave: 'modal-slide-out',
tabsPlacement: 'bottom',
pageTransition: 'ios-transition',
tabsHideOnSubPages:true
})
],
exports: [AComponent,
AComponent,
AComponent,
BComponent,
AbcComponent,]
})
export class ComponentsModule {}
<file_sep>import { Component, OnInit,Input ,EventEmitter} from '@angular/core';
import { CommonService} from '../../seriveces/common.service';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
constructor(private local:CommonService) { }
data=[];
data1=[];
ngOnInit() {
if(this.local.get('data:')===undefined||localStorage.getItem('data:').length==0){
localStorage.setItem('data:','');
console.log(this.data);
}
else{
this.data=localStorage.getItem('data:').split(',');
}
console.log(this.data.length);
}
add(event){
this.data.push(event);
this.local.set('data:',this.data);
}
del(i){
this.data1.push(this.data[i]);
this.data.splice(i,1);
}
del1(i){
this.data.push(this.data1[i]);
this.data1.splice(i,1);
}
del2(i){
this.data.splice(i,1);
this.local.set('data:',this.data);
}
}
<file_sep>import { Component} from '@angular/core';
import { NavController } from 'ionic-angular';
import { BPage } from '../b/b';
import { Action } from 'rxjs/scheduler/Action';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
icons:string = "tuijian";
constructor(public navCtrl: NavController) {}
goSub(inp){
this.navCtrl.push(BPage,{id:1});
console.log(inp);
}
ionViewDidLoad(){
}
isActive = 0;
isClick(i){
this.isActive = i;
}
change(){
console.log('a');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router' ;
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-tbk1',
templateUrl: './tbk1.component.html',
styleUrls: ['./tbk1.component.css']
})
export class Tbk1Component implements OnInit {
constructor(private router:ActivatedRoute,private http:HttpClient) { }
tbk1;
ngOnInit() {
this.http.get('/api/tbk1').subscribe((data)=>{
this.tbk1 = data;
});
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Component } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { TongbuComponent } from './components/tongbu/tongbu.component';
import { CourseComponent } from './components/course/course.component';
import { ShequComponent } from './components/shequ/shequ.component';
import { HomeComponent } from './components/home/home.component';
import { HttpClientModule } from '@angular/common/http';
import { RenwuComponent } from './components/renwu/renwu.component';
import { TbkComponent } from './components/tbk/tbk.component';
import { KechengComponent } from './components/kecheng/kecheng.component';
import { QieshuoComponent } from './components/qieshuo/qieshuo.component';
import { TongzhiComponent } from './components/tongzhi/tongzhi.component';
import { Tbk1Component } from './components/tbk1/tbk1.component';
import { Tbk2Component } from './components/tbk2/tbk2.component';
import { Tbk3Component } from './components/tbk3/tbk3.component';
import { Qieshuo1Component } from './components/qieshuo1/qieshuo1.component';
import { Qieshuo2Component } from './components/qieshuo2/qieshuo2.component';
import { Qieshuo3Component } from './components/qieshuo3/qieshuo3.component'
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
TongbuComponent,
CourseComponent,
ShequComponent,
HomeComponent,
RenwuComponent,
TbkComponent,
KechengComponent,
QieshuoComponent,
TongzhiComponent,
Tbk1Component,
Tbk2Component,
Tbk3Component,
Qieshuo1Component,
Qieshuo2Component,
Qieshuo3Component
],
imports: [
BrowserModule,
RouterModule.forRoot([
{
path:'home',
component:HomeComponent,
children:[
{path:'renwu',component:RenwuComponent},
{path:'tbk',component:TbkComponent,children:[
{path:'tbk1',component:Tbk1Component},
{path:'tbk2',component:Tbk2Component},
{path:'tbk3',component:Tbk3Component},
{path:'**',component:Tbk1Component},
]},
{path:'kecheng',component:KechengComponent},
{path:'qieshuo',component:QieshuoComponent,children:[
{path:'qieshuo1',component:Qieshuo1Component},
{path:'qieshuo2',component:Qieshuo2Component},
{path:'qieshuo3',component:Qieshuo3Component},
{path:'**',component:Qieshuo1Component},
]},
{path:'tongzhi',component:TongzhiComponent},
{path:'**',component:RenwuComponent},
]},
{path:'tongbu',component:TongbuComponent},
{path:'shequ',component:ShequComponent},
{path:'course',component:CourseComponent},
{path:'',redirectTo:'home',pathMatch:'full'},
{path:'**',component:TongbuComponent},
]),
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
export class Course{
constructor(
public id:number,
public courseName:string,
public images:string,
public task:number,
public person:number
){}
}
export class Course1{
constructor(
public id:number,
public courseName:string,
public images:string,
public task:number,
public person:number,
public information:string,
){}
}
const renwu = [
new Course(1,
'2016级混合应用开发',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
3,91,),
new Course(2,
'2016级HTML5与CSS3前端',
"http://usercontent.edu2act.cn/media/team/18-09-11/B32yP44hiothFxyegigXe7.jpg?imageView2/1/w/230/h/130",
5,91),
new Course(3,
'JavaScript进阶(2016级H5方向基础课)',
"http://usercontent.edu2act.cn/media/team/18-03-05/6niXYjHC5hvoAbWKUQCdPa.jpg?imageView2/1/w/230/h/130",
2,91),
new Course(4,
'2016级操作系统',
"http://usercontent.edu2act.cn/media/team/18-02-26/T6JLRm2Y9noLzWNjwAhF8X.png?imageView2/1/w/230/h/130",
7,398),
new Course(5,
'2016级数据库原理',
"http://usercontent.edu2act.cn/media/team/18-02-26/QMXWNRHDsraTaVofSiRCbF.png?imageView2/1/w/230/h/130",
6,400),
new Course(6,
'2016级数据结构',
"http://usercontent.edu2act.cn/media/team/17-09-15/ywftcr7DiN6JwRPEgUxPwB.jpg?imageView2/1/w/230/h/130",
29,428),
]
const course = [
new Course1(1,
'Github 开源之旅视频课程第...',
"http://usercontent.edu2act.cn/media/cs/17-02-20/BRmabjXmc6M87Hx678jgkk.png?imageView2/1/w/320/h/190",
14,3738,
'完成本课程之后,能够达到以下目标:- 实名注册 Github 账户- 能够在 Github 上搜索资料- 能够...'),
new Course1(2,
'CSS3基础',
"http://usercontent.edu2act.cn/media/cs/16-11-14/XgKaLUTcWTUsPaqF2hXSHK.png?imageView2/1/w/320/h/190",
12,2320,
'CSS3在以前的基础上添加了诸多新的选择器以及新的样式。本课程将讲解CSS3新样式以及新特性...'),
new Course1(3,
'HTML5基础',
"http://usercontent.edu2act.cn/media/cs/16-11-11/JjHN2Za86UhpyK8u6MEtsC.png?imageView2/1/w/320/h/190",
12,1312,
'HTML5是最新的一项Web标准,在原有HTML4的基础上定义了一些新的标签和新的JavaScript...'),
new Course1(4,
'Selenium IDE WEB自动化测...',
"http://usercontent.edu2act.cn/media/cs/16-11-08/8ZkV8KMVi6mMQBwJ4bB7i6.png?imageView2/1/w/320/h/190",
12,3794,
'上篇对自动化测试的基础知识做一些交代,为真正做自动化测试做好铺垫,然后讲解IDE工具的基本...'),
new Course1(5,
'扩展的ICONIX软件过程实践',
"http://usercontent.edu2act.cn/media/cs/16-11-03/TeZqcmxukYntmh8UigEeqU.png?imageView2/1/w/320/h/190",
12,2269,
'ICONIX软件过程的主体设计思想是尽早进入编码阶段,缩短分析设计周期的软件开发方法合理的简...'),
new Course1(6,
'Selenium IDE WEB自动化测...',
"http://usercontent.edu2act.cn/media/cs/16-10-28/93BLumGUzRct9BRxKQgWnn.png?imageView2/1/w/320/h/190",
11,3131,
'上篇对自动化测试的基础知识做一些交代,为真正做自动化测试做好铺垫,然后讲解IDE工具的基...'),
new Course1(7,
'网页制作与开发',
"http://usercontent.edu2act.cn/media/cs/16-09-22/Qrnx7yH2tp7mGGLSdbhWHc.png?imageView2/1/w/320/h/190",
42,1572,
'本课程利用线上与线下相结合的授课方式,以网页开发主流软件Dreamweaver为工具,教给学...'),
new Course1(8,
'产品&交互设计那些事儿',
"http://usercontent.edu2act.cn/media/cs/16-09-08/DTAweqRQeVWst8N8RmH3pe.png?imageView2/1/w/320/h/190",
5,1084,
'本课程是和学员一起探讨交流关于产品设计和交互设计的一些经验教训,结合具体案例讲解体案例讲...'),
new Course1(9,
'VR AR产品设计的思考视频...',
"http://usercontent.edu2act.cn/media/cs/16-09-08/2sLJNqumrjAEQjwGMCGRN5.png?imageView2/1/w/320/h/190",
3,4335,
'“2016是VR元年”,这一观点早已在计算机互联网行业中流行开来,与VR相关的各种分析各种分...'),
new Course1(10,
'ProcessOn界面原型绘制',
"http://usercontent.edu2act.cn/media/cs/16-09-02/QV7FBJ72fUkL3sv6Te2FEP.png?imageView2/1/w/320/h/190",
2,4324,
'ProcessOn是国内比较有名的图形设计分享社区,有着强大的在线制图功能ProcessOn界面原型绘...'),
new Course1(11,
'ProcessOn绘制流程图',
"http://usercontent.edu2act.cn/media/cs/16-09-02/SKFDejikkVQYmQJePPMCPk.png?imageView2/1/w/320/h/190",
4,3053,
'绘制流程图是在产品设计过程中需求调研阶段非常重要的手段。流程图可以让流程图可以提供一种...'),
new Course1(12,
'项目管理平台Redmine',
"http://usercontent.edu2act.cn/media/cs/16-09-02/zv88bojNGWP9zZcThYAhS.png?imageView2/1/w/320/h/190",
8,4423,
'本课程讲解了项目管理平台redmine的安装部署、管理员维护、普通用户使用,和其他...'),
];
const shequ = [
new Course1(1,
'链栈的表示及基本操作的实现',
"http://usercontent.edu2act.cn/media/userheader/18-04-28/MHsG2fvR989uTfkLRZxDCY.jpeg?imageView2/1/w/256/h/256",
14,3738,
'写了一点链栈的基本操作,第一次发文,如发现错误之处请大家及时指正。// 补充:链栈的基本操作 #include <stdio.h> #include <stdlib.h> typedef int ElemTyp'),
new Course1(2,
'js数组',
"http://usercontent.edu2act.cn/media/userheader/18-03-11/H2v8Qhkq4DnS33dBbBYKMo.jpg?imageView2/1/w/256/h/256",
12,2320,
'声明:数组声明的三种方式:1. var arr = new Array();(声明一个空数组对象) arr[0]="abc";2. var arr = new Array(5);(声明数组并初始化长度,注意数组'),
new Course1(3,
'WEB开发(二)———函数',
"http://www.edu2act.net/static/img/m.png",
12,1312,
'(一)函数三要素函数的三要素为函数名、参数(形参,实参),返回值。(二)函数定义与调用函数定义的关键字为function,不能省略,也不要能简写。'),
new Course1(4,
'类定义关键字详解',
"http://usercontent.edu2act.cn/media/userheader/18-06-11/hcnaQiW74323X9xzQNu8pR.jpg?imageView2/1/w/256/h/256",
12,3794,
'JAVA类与对象(三)----类定义关键字详解 static 表示静态,它可以修饰属性,方法和代码块。1.static修饰属性(类变量),那么这个属性就可以用类名.属性名来'),
new Course1(5,
'一个java文件中可以包含多个main方法',
"http://usercontent.edu2act.cn/media/userheader/18-06-11/hcnaQiW74323X9xzQNu8pR.jpg?imageView2/1/w/256/h/256",
12,2269,
'一个java文件中可包含多个main方法java中的main方法是java应用程序的入口,java程序在运行时,首先调用执行main方法。但并不是说java中只能有一个main方法'),
new Course1(6,
'数据结构———线性表的经典应用',
"http://usercontent.edu2act.cn/media/userheader/17-07-18/KbeV987Y2GWmTnUD76Jzan.jpg?imageView2/1/w/256/h/256",
11,3131,
'1. 一元多项式的表示和相加 在数学上,一个一元多项式\(P_{n}(x)\)可升序写成:\(P_{n}(x) = p_{0}+p_{1}x^1+p_{2}x^2+...++p_{n}x^n\)它由n+1个系数唯一确定。'),
new Course1(7,
'栈和队列之间的相互转化',
"http://usercontent.edu2act.cn/media/userheader/18-03-11/H2v8Qhkq4DnS33dBbBYKMo.jpg?imageView2/1/w/256/h/256",
42,1572,
'队列实现栈需要两个队列data,help,因为队列是先进先出,想要模拟栈的结构,每次取栈顶的元素也就相当于取队列中队尾的元素,要取data队列的队尾元'),
new Course1(8,
'WEB开发(er)———字符串类型',
"http://www.edu2act.net/static/img/m.png",
5,1084,
'在C语言中的数据类型中没有字符串类型,字符串是字符数组,那么字符串可以遍历。在前端JavaScript中数组和字符串是两种数据类型,也就是字符串类型是存在'),
new Course1(9,
'数据结构———栈和队列的逻辑特征',
"http://usercontent.edu2act.cn/media/userheader/18-06-27/qaxwRNWziva8oHjepZHiga.jpg?imageView2/1/w/256/h/256",
3,4335,
'线性表是最常用且最简单的一种线性结构。 线性结构的特点: (1) 存在唯一的一个被称作“第一个”的数据元素。 (2) 存在唯一的一个被称作“最后一个&rd'),
new Course1(10,
'初探JVM',
"http://usercontent.edu2act.cn/media/userheader/18-03-11/H2v8Qhkq4DnS33dBbBYKMo.jpg?imageView2/1/w/256/h/256",
2,4324,
'今天晚上翻了翻别人的博客了解了jvm的一些基础,因为每个人的侧重点不同,我也联系自己的看法整理一份。 首先要了解jvm基本架构,总的分为三个主要的子'),
new Course1(11,
'Javascript中时间的绑定',
"http://usercontent.edu2act.cn/media/userheader/16-11-10/jut8pNbf66NgrWMdGPWejD.jpg?imageView2/1/w/256/h/256",
4,3053,
'一、 事件 事件是您在编程时系统内的发生的动作或者发生的事情,系统通过它来告诉您在您愿意的情况下您可以以某种方式对它做出回应。在Web中,事件在浏览'),
new Course1(12,
'Java中编写自己的类之重写equals()方法',
"http://www.edu2act.net/static/img/m.png",
8,4423,
'1.Object类中的equals()方法equals()方法用于检测某个对象是否同另一个对象相等。它最初是在Object类中定义的,Object类中equals()方法的实现是判断两个对'),
];
const tongbuke = [
new Course(1,
'2016级混合应用开发',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91),
new Course(2,
'2017-12-软件测试基础',
"http://www.edu2act.net/static/img/course.png",
4,399),
new Course(3,
'2017级Web开发(二)',
"http://usercontent.edu2act.cn/media/team/18-09-11/Ypf253J7ydMQ2CckxWf6zJ.jpg?imageView2/1/w/230/h/130",
10,90),
new Course(4,
'2016级测试方向Web系...',
"http://usercontent.edu2act.cn/media/team/18-09-11/AbbCZfnQVQHxyU2GBbQ5SB.jpg?imageView2/1/w/230/h/130",
3,52),
new Course(5,
'2016级HTML与CSS前...',
"http://usercontent.edu2act.cn/media/team/18-09-11/B32yP44hiothFxyegigXe7.jpg?imageView2/1/w/230/h/130",
5,91),
new Course(6,
'2017级3、4班软件测试...',
"http://usercontent.edu2act.cn/media/team/18-09-09/jHw7UZ9hmNxJtTgCDuf9c3.jpg?imageView2/1/w/230/h/130",
3,120),
new Course(7,
'2018级信息素养实践',
"http://usercontent.edu2act.cn/media/team/18-09-06/UTjLGPA9oHaKeHMLi9Ko4c.jpg?imageView2/1/w/230/h/130",
0,12),
new Course(8,
'2018级计算机导论',
"http://usercontent.edu2act.cn/media/team/18-09-06/HUcdGNR48SfNpHPRjGQqXb.jpg?imageView2/1/w/230/h/130",
1,396),
new Course(9,
'2018-2019第一学期面向...',
"http://www.edu2act.net/static/img/course.png",
5,400),
new Course(10,
'2017级3、4班软件测试...',
"http://usercontent.edu2act.cn/media/team/18-09-06/bE6jL98kCfWg3Hij6gyokN.jpg?imageView2/1/w/230/h/130",
4,401),
new Course(11,
'2017级3、4班软件测试...',
"http://usercontent.edu2act.cn/media/team/18-07-09/3ydhisn3DM8PR9hNY9vCjA.jpg?imageView2/1/w/230/h/130",
0,78),
new Course(12,
'2017级3、4班软件测试...',
"http://usercontent.edu2act.cn/media/team/18-07-09/J3LxZ5cMMP9JFjGuDbSsh8.png?imageView2/1/w/230/h/130",
13,92),
];
const tbk1 = [
new Course1(1,
'任务三--雪梨平台开发',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'2016级混合应用开发'),
]
const tbk2 = [
new Course1(1,
'任务五--canvas',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'2016级HTML5与CSS前端开发'),
new Course1(2,
'任务二 -- js基础练习与应用',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'2016级混合应用开发'),
new Course1(3,
'任务四--文件与拖放',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'2016级HTML5与CSS前端开发'),
new Course1(4,
'任务以--组件交互与服务',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'2016级混合应用开发'),
new Course1(5,
'任务二--表单',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'2016级HTML5与CSS前端开发'),
new Course1(6,
'任务二十一--关于查找和排序的作业',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'2016级数据结构'),
new Course1(7,
'任务二十--查找(一)',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'2016级数据结构'),
]
const tbk3 = [
new Course1(1,
'任务一HTML标签及特性',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'2016级HTML5与CSS前端开发'),
new Course1(2,
'任务二十二',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'JavaScript进阶(2016级H5方向基础课)'),
new Course1(3,
'第六章综合练习题',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'2016级操作系统'),
new Course1(4,
'任务二十一',
"http://usercontent.edu2act.cn/media/team/18-09-18/VE66xjRaii5X8Y9qFZQLZC.jpg?imageView2/1/w/230/h/130",
2,91,
'JavaScript进阶(2016级H5方向基础课)'),
]
const qieshuo = [
new Course1(1,
'陶卓',
"http://usercontent.edu2act.cn/media/userheader/16-11-10/jut8pNbf66NgrWMdGPWejD.jpg?imageView2/1/w/256/h/256",
2,91,
'我整理了之前做过的练习题,帮助大家及时复习。第一章练习题;第一、二章复习题;进制转换和原反补练习题。'),
new Course1(2,
'冬青',
"http://www.edu2act.net/static/img/m.png",
2,91,
'下载FTP ftp://10.7.1.53 视频和所需软件,34班第三章的rar文件,下节课看视频,搭建学习环境。'),
new Course1(3,
'1-黄鹏',
"http://usercontent.edu2act.cn/media/userheader/18-05-07/srkXwzoatk4oc4ARB5BeTc.jpg?imageView2/1/w/256/h/256",
2,91,
'1.万维网:客户端可以通过浏览器访问服务器上的网页。2.是对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址。'),
new Course1(4,
'任务十一:程序设计引导练习题 ',
"http://usercontent.edu2act.cn/media/userheader/16-11-10/jut8pNbf66NgrWMdGPWejD.jpg?imageView2/1/w/256/h/256",
2,91,
'1、一般来说,如果要想在一个链表中插入一个结点,使之成为第i个结点,则必须先在链表中找到第( )个结点。 2、若入栈序列是 a, b, c, d, e,则不可能的出栈序列是( )。 A.edcba B.decba ...'),
new Course1(5,
'任务十:请用python设计一个程序,实现如下效果 ',
"http://usercontent.edu2act.cn/media/userheader/16-11-10/jut8pNbf66NgrWMdGPWejD.jpg?imageView2/1/w/256/h/256",
2,91,
''),
new Course1(6,
'课程设计',
"http://usercontent.edu2act.cn/media/userheader/16-11-10/jut8pNbf66NgrWMdGPWejD.jpg?imageView2/1/w/256/h/256",
2,91,
'请同学们自由结组来完成课程设计,要求如下: 1. 该设计最终要能提交一份实现简单功能的程序,如猜数游戏、扑克猜牌、2048等,确保调试无误后才可提交 2. 每小组人数不得超过5人,并确定小组...'),
]
const tongzhi = [
new Course1(1,
'陶卓',
"http://usercontent.edu2act.cn/media/userheader/16-11-10/jut8pNbf66NgrWMdGPWejD.jpg?imageView2/1/w/256/h/256",
2,91,
'@全体成员 请大家注意任务的发布和截止时间啊,发到互动里面的作业是不会导出在作业统计表里面的'),
new Course1(2,
'陶卓',
"http://usercontent.edu2act.cn/media/userheader/16-11-10/jut8pNbf66NgrWMdGPWejD.jpg?imageView2/1/w/256/h/256",
2,91,
'@全体成员 任务一中练习题答案,点此打开'),
]
var touxiang = "http://usercontent.edu2act.cn/media/userheader/18-05-07/srkXwzoatk4oc4ARB5BeTc.jpg";
app.get('/api',(req,res)=>{
res.json(tongbuke);
});
app.get('/api/course',(req,res)=>{
res.json(course);
});
app.get('/api/tongbuke',(req,res)=>{
res.json(tongbuke);
});
app.get('/api/tbk1',(req,res)=>{
res.json(tbk1);
});
app.get('/api/tbk2',(req,res)=>{
res.json(tbk2);
});
app.get('/api/tbk3',(req,res)=>{
res.json(tbk3);
});
app.get('/api/qieshuo',(req,res)=>{
res.json(qieshuo);
});
app.get('/api/tongzhi',(req,res)=>{
res.json(tongzhi);
});
app.get('/api/shequ',(req,res)=>{
res.json(shequ);
});
app.get('/api/tongbuke/:id',(req,res)=>{
res.json(tongbuke.filter((ele)=>{
return ele.id == req.params.id;
}));
});
app.get('/api/renwu',(req,res)=>{
res.json(renwu);
});
app.post('/api',(req,res)=>{
res.json(touxiang);
});
app.listen(8000); | 4dc0807e67d97c3a444954dded5439ae8c2c0fef | [
"TypeScript"
] | 19 | TypeScript | haungpeng/-web- | 6d9c06e88b0614da7358e0a5cb4090221ec2e0eb | abb79eae5f83ae88cdca564e616000ae81be636f |
refs/heads/master | <file_sep>(function($){
$(function(){
$('.button-collapse').sideNav();
$('.parallax').parallax();
$('.carousel.carousel-slider').carousel({
full_width: true
});
autoplay()
function autoplay() {
$('.carousel').carousel('next');
setTimeout(autoplay, 4500);
}
$('.modal-trigger').leanModal({
dismissible: true, // Modal can be dismissed by clicking outside of the modal
opacity: .5, // Opacity of modal background
in_duration: 300, // Transition in duration
out_duration: 200, // Transition out duration
starting_top: '4%', // Starting top style attribute
ending_top: '10%', // Ending top style attribute
}
);
}); // end of document ready
})(jQuery); // end of jQuery name space
| 8da33ed20cb5898f8f307fafa80673b3fb896bd3 | [
"JavaScript"
] | 1 | JavaScript | FranCarstens/KarolWilliams | babe6b74c1d3adca065469d26522774bb6983e9f | 57952a10f1f7521fbf3927f73edcd9439670b1c1 |
refs/heads/master | <repo_name>Ahdw/menhir<file_sep>/src/strategie/StrategieForte.java
package strategie;
import java.util.ArrayList;
import partie.Partie;
import carte.Carte;
import joueur.Joueur;
/**
* @author <NAME> et <NAME>
*
* La classe StrategieForte hérite de Stratégie et implémente les méthodes relatives à la stratégie forte.
*
* @see Strategie
*/
public class StrategieForte extends Strategie {
private int valeurAJouer=0;
/**
* Constructeur de la classe.
*/
public StrategieForte(){
}
/**
* Permet de choisir un joueur à attaquer.
* return target : Joueur choisi.
*/
public Joueur choisisJoueur() {
int random = (int) (Math.random()*Partie.getPartie().getNbJoueur());
Joueur target = Partie.getPartie().getListeJoueur().get(random);
while (target.equals(Partie.getPartie().getJoueurActuel())){
target = Partie.getPartie().getListeJoueur().get((random+1)%(Partie.getPartie().getNbJoueur()));
}
return target;
}
/**
* Permet de choisir une carte à jouer.
* @return c : Carte à jouer.
*/
public Carte choisisCarte() {
ArrayList<Carte> main = Partie.getPartie().getJoueurActuel().getMain();
int a = main.size();
int index = (int) (Math.random()*a);
c = main.get(index);
return c;
}
/**
* Permet de choisir une action à effectuer.
* @return int : action choisie.
*/
public int choisisAction() {
int val = 0;
switch (valeurAJouer%4)
{
case 0:
val = 0;
valeurAJouer++;
break;
case 1:
val = 2;
valeurAJouer++;
break;
case 2:
val = 1;
valeurAJouer++;
break;
case 3:
val = 1;
valeurAJouer++;
break;
}
return val;
}
/**
* Permet de choisir au début de chaque manche dans le mode avancé si l'on veut piocher une carte allié ou deux graines.
* @return int : choix.
*/
public int choisis() {
return (int) (Math.random()+1);
}
/**
* Permet de choisir si l'on veut jouer une carte allié.
* @return int : choix.
*/
public int choisisJouerAllie() {
return (int) (Math.random()*2);
}
}
<file_sep>/src/carte/Engrais.java
package carte;
import cailloux.Cailloux;
/**
* @author <NAME> et <NAME>
*
* La classe Engrais est une classe utilisée dans la classe CarteIngredient. Elle représente la ligne engrais de la carte
* et permet de faire grandir des menhirs.
*/
public class Engrais extends Carte {
/**
* Constructeur
* @param a : tableau d'entiers donnant la force de la carte.
*/
public Engrais(int[] a){
nom = "Engrais";
force = a;
}
/**
* Méthode réalisant l'action de la carte : faire pousser des graines.
*/
public void effectuer() {
int force = confirm(this.force[partie.getSaison()]);
for(int i=0;i<force;i++){
Cailloux c = partie.getJoueurActuel().getGraine().get(0);
c.gandir();
partie.getJoueurActuel().getMenhir().add(c);
partie.getJoueurActuel().getGraine().remove(0);
}
this.annonce = nom+" "+ force;
}
/**
* Méthode retournant la force de la carte à la saison actuelle.
* @param a : int
* @return force de la carte
*/
int confirm(int a){
int force = 0;
if(a <= partie.getJoueurActuel().getGraine().size()){
force = a;
}
else{
force = partie.getJoueurActuel().getGraine().size();
}
return force;
}
}
<file_sep>/readme.md
# Menhir project
This is an immature student java project with GUI.
Menhir is a card game.
<file_sep>/src/strategie/StrategieManuele.java
package strategie;
import carte.Carte;
import exception.InputException;
import joueur.Joueur;
/**
* @author <NAME> et <NAME>
*
* La classe StrategieManuelle hérite de Stratégie et implémente les méthodes relatives à la stratégie manuelle.
*
* @see Strategie
*/
public class StrategieManuele extends Strategie {
/**
* Constructeur de la classe.
*/
public StrategieManuele(){
}
/**
* Permet de choisir manuellement le nom du jouer à attaquer.
* @return Joueur : la cible choisie.
*/
public Joueur choisisJoueur() throws InputException {
return ctrl.saisieTarget();
}
/**
* Permet de choisir la carte à jouer manuellement.
* @return c : Carte choisie à jouer.
*/
public Carte choisisCarte() throws InputException {
try {
c = ctrl.saisieCarte();
}
catch (InputException e){
throw e;
}
return c;
}
/**
* Permet de choisir manuellement l'action à effectuer de la carte.
* @return action : int choix de l'action à effectuer.
*/
public int choisisAction() throws InputException {
int action;
try {
action = ctrl.saisieAction();
}
catch (InputException e){
throw e;
}
return action;
}
/**
* Permet de choisir manuellement au début de chaque manche dans le mode avancé si on pioche une carte allié ou deux graines.
* @return int : choix.
*/
public int choisis() throws InputException {
int choix;
try {
choix = ctrl.saisieChoix();
}
catch (InputException e){
throw e;
}
return choix;
}
/**
* Permet de choisir manuellement si l'on veux jouer une carte allié.
* @return choix : int choix effectué.
*/
public int choisisJouerAllie() throws InputException {
int choix;
try {
choix = ctrl.saisieChoixAllie();
}
catch (InputException e){
throw e;
}
return choix;
}
}
<file_sep>/src/controle/Controle.java
package controle;
import carte.Carte;
import exception.InputException;
import joueur.Joueur;
public interface Controle {
public void update();
public int saisieMode() throws InputException;
public int saisieStrategie() throws InputException;
public int saisieNbJoueur() throws InputException;
public String saisieNom() throws InputException;
public Boolean saisieSexe() throws InputException;
public int saisieAge() throws InputException;
public Carte saisieCarte() throws InputException;
public int saisieAction() throws InputException;
public Joueur saisieTarget() throws InputException;
public int saisieChoix() throws InputException;
public int saisieChoixAllie() throws InputException;
//public void setAnnonce(String str);
//public void setNotification(String str);
//public void setInfo(String str);
}
<file_sep>/src/viewGraphic/ViewChamps.java
package viewGraphic;
import java.awt.Image;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import javax.imageio.ImageIO;
import javax.swing.*;
import joueur.Joueur;
import partie.Partie;
public class ViewChamps {
private ViewPrinciple v = ViewPrinciple.getView();
private JPanel pane = v.getPanel();
private int nbj = Partie.getPartie().getNbJoueur();
private ArrayList<PLabel> graines = new ArrayList<PLabel>();
private ArrayList<PLabel> menhirs = new ArrayList<PLabel>();
private ArrayList<Joueur> joueurVirtuel = Partie.getPartie().getListeJoueurVirtuel();
private static ViewChamps vch;
private ViewChamps(){
init();
}
public static ViewChamps getVch(){
if(vch == null){
vch = new ViewChamps();
}
return vch;
}
public void init(){
Joueur jr = Partie.getPartie().getJoueurReel();
PLabel champs = new PLabel(jr);
JLabel info = new JLabel(jr.getNom()+" "+jr.getAge(), SwingConstants.CENTER);
JLabel graine = new JLabel();
JLabel menhir = new JLabel();
PLabel ng = new PLabel(jr);
PLabel nm = new PLabel(jr);
champs.setBounds(10, 240, 200, 200);
info.setBounds(20, 260, 150, 20);
graine.setBounds(20, 290, 40, 60);
ng.setBounds(100, 240+80, 70, 20);
menhir.setBounds(20, 360, 40, 60);
nm.setBounds(100, 240+150, 70, 20);
Image icon;
try {
icon = ImageIO.read(this.getClass().getResource("/champs.jpg"));
champs.setIcon(new ImageIcon(icon));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
icon = ImageIO.read(this.getClass().getResource("/graine.png"));
graine.setIcon(new ImageIcon(icon));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
icon = ImageIO.read(this.getClass().getResource("/menhir.png"));
menhir.setIcon(new ImageIcon(icon));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pane.add(info);
pane.add(graine);
pane.add(menhir);
pane.add(nm);
pane.add(ng);
pane.add(champs);
graines.add(ng);
menhirs.add(nm);
// champs.setText("<html><div style='text-align: center;'><font color=black size=5>"+Partie.getPartie().getJoueurReel().getNom()+" "+Partie.getPartie().getJoueurReel().getAge()+"<br/>Graines:"+Partie.getPartie().getJoueurReel().getGraine().size()+"<br/>Menhir:"+Partie.getPartie().getJoueurReel().getMenhir().size()+"</font></html>");
// champs.setIconTextGap(-200);
for(int i=0; i<5;i++){
if(i<nbj-1){
initChamps(i,this.joueurVirtuel.get(i));
}
else{
JLabel defaut = new JLabel();
defaut.setBounds(10*(i+1)+200*i, 10, 200, 200);
Image profile;
try {
profile = ImageIO.read(this.getClass().getResource("/farfadet.jpg"));
defaut.setIcon(new ImageIcon(profile));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pane.add(defaut);
pane.repaint();
}
}
}
/**
* create champs for one virtual player
*/
void initChamps(int n, Joueur j){
PLabel champs = new PLabel(j);
JLabel info = new JLabel(j.getNom()+" "+j.getAge(), SwingConstants.CENTER);
JLabel graine = new JLabel();
JLabel menhir = new JLabel();
PLabel ng = new PLabel(j);
PLabel nm = new PLabel(j);
champs.setBounds(10*(n+1)+200*n, 10, 200, 200);
info.setBounds(10*(n+2)+200*n, 30, 150, 20);
graine.setBounds(10*(n+2)+200*n, 60, 40, 60);
menhir.setBounds(10*(n+2)+200*n, 130, 40, 60);
ng.setBounds(100+10*(n+1)+200*n, 10+80, 70, 20);
nm.setBounds(100+10*(n+1)+200*n, 10+150, 70, 20);
Image icon;
try {
icon = ImageIO.read(this.getClass().getResource("/champs.jpg"));
champs.setIcon(new ImageIcon(icon));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
icon = ImageIO.read(this.getClass().getResource("/graine.png"));
graine.setIcon(new ImageIcon(icon));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
icon = ImageIO.read(this.getClass().getResource("/menhir.png"));
menhir.setIcon(new ImageIcon(icon));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// champs.setText("<html><div style='text-align: center;'><font color=black size=5>"+j.getNom()+" "+j.getAge()+"<br/>Graines:"+j.getGraine().size()+"<br/>Menhir:"+j.getMenhir().size()+"</font></html>");
// champs.setIconTextGap(-200);
pane.add(info);
pane.add(graine);
pane.add(menhir);
pane.add(nm);
pane.add(ng);
pane.add(champs);
graines.add(ng);
menhirs.add(nm);
}
/**
* update the numbers of all the players
*/
public void update(){
LinkedList<Joueur> joueur = Partie.getPartie().getListeJoueur();
Iterator<Joueur> it = joueur.iterator();
while(it.hasNext()){
Joueur j = it.next();
Iterator<PLabel> itP = graines.iterator();
while(itP.hasNext()){
PLabel p = itP.next();
Joueur jj = p.getJ();
if(jj.getNom() == j.getNom()){
p.setText("x "+j.getGraine().size());
}
}
Iterator<PLabel> itP1 = menhirs.iterator();
while(itP1.hasNext()){
PLabel p1 = itP1.next();
Joueur jj1 = p1.getJ();
if(jj1.getNom() == j.getNom()){
p1.setText("x "+j.getMenhir().size());
}
}
}
}
public static void reset(){
vch = null;
}
}
<file_sep>/src/carte/CarteIngredient.java
package carte;
import java.util.Iterator;
import java.util.LinkedList;
import exception.InputException;
/**
* @author <NAME> et <NAME>
*
* La classe CarteIngredient est une composition des cartes @see Geant, @see Farfadet et @see Engrais.
*/
public class CarteIngredient extends Carte {
LinkedList<Carte> action = new LinkedList<Carte>();
/**
* Le constructeur de CarteIngredient.
* @param nom : String
* @param serial : String
* @param actions : Tableau de cartes
*/
public CarteIngredient(String nom, String serial, Carte[] actions){
this.nom = nom;
this.serial = serial;
for(int a=0;a<3;a++){
this.action.add(actions[a]);
}
}
/**
* methode permettant de réaliser l'action de la carte choisie.
*/
public void effectuer() {
int choix = 0;
int flag = 1;
while(flag == 1){
try {
choix = partie.getJoueurActuel().getStrategie().choisisAction();
flag = 0;
} catch (InputException e) {
System.out.println(e.getMessage());
}
}
action.get(choix).effectuer();
this.annonce = action.get(choix).getAnnonce();
}
/**
* méthode pour décrire une carte ingrédient en chaine de caractère.
* @return la chaine de caractère.
*/
public String toString(){
int k = 4;
String str = this.nom+"\n";
Iterator<Carte> it = action.iterator();
while(it.hasNext()){
Carte c = it.next();
str += c.nom; //add action name
for(int j=0;j<k;j++){ //add k spaces
str += " ";
}
for(int i=0;i<4;i++){
str += c.force[i]+" "; //add value and a space
}
str += "\n"; //add \n
k = k/2; //k changes for next time
}
return str;
}
}
<file_sep>/src/carte/TaupeGeant.java
package carte;
import exception.InputException;
import joueur.Joueur;
/**
* @author <NAME> et <NAME>
*
* La classe TaupeGeante représente la carte allié taupe géante dans le jeu du menhir.
* Elle permet de détruire des ménhirs à un autre joueur.
*/
public class TaupeGeant extends Carte {
Joueur j;
/**
* Constructeur de la classe TaupeGeante
* @param serial : String
* @param a : Tableau d'entiers
*/
public TaupeGeant(String serial, int[] a){
this.serial = serial;
nom = "Taupe Geant";
force = a;
}
/**
* Méthode permettant de lancer l'action de TaupeGeante.
*/
public void effectuer() {
int intent = confirm(this.force[partie.getSaison()]);
for(int i=0;i<intent;i++){
j.getMenhir().remove(0);
}
this.annonce = nom+" "+j.getNom()+" "+intent;
}
/**
* Permet de récupérer la force de la carte en fonction de la saison actuelle.
* @param a : int
* @return force de l'action.
*/
int confirm(int a){
int force = 0;
j = null;
int flag = 1;
while(flag == 1){
try {
j = partie.getJoueurActuel().getStrategie().choisisJoueur();
flag = 0;
} catch (InputException e) {
System.out.println(e.getMessage());
}
}
if(a < j.getMenhir().size()){
force = a;
}
else{
force = j.getMenhir().size();
}
return force;
}
/**
* Permet de réaliser l'action de la taupe en fonction de la force de la carte et de la protection du joueur.
* @param origine
*/
public void effectuer(Joueur origine){
int intent = confirm(this.force[partie.getSaison()],origine);
for(int i=0;i<intent;i++){
j.getMenhir().remove(0);
}
this.annonce = nom+" "+j.getNom()+" "+intent;
}
/**
* Permet de récupérer la force de l'action en fonction de la saison actuelle et de la protection du joueur.
* @param a
* @param origine
* @return
*/
int confirm(int a, Joueur origine){
int force = 0;
j = null;
int flag = 1;
while(flag == 1){
try {
j = origine.getStrategie().choisisJoueur();
flag = 0;
} catch (InputException e) {
System.out.println(e.getMessage());
}
}
if(a < j.getMenhir().size()){
force = a;
}
else{
force = j.getMenhir().size();
}
return force;
}
/**
* Méthode permettant de décrire la carte taupe géante sous forme de caine de caractère
* @return str : chaine de caractère
*/
public String toString(){
String str = this.nom;
for (int i=0;i<4;i++){
str += " "+force[i];
}
str += "\n";
return str;
}
}
<file_sep>/src/modeDeJeu/ModeRapide.java
package modeDeJeu;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import cailloux.Cailloux;
import carte.Carte;
import carte.CarteIngredient;
import carte.Engrais;
import carte.Farfadet;
import carte.Geant;
import controle.Graphic;
import joueur.Joueur;
import joueur.JoueurReel;
import partie.Partie;
import viewGraphic.ViewCarte;
import viewGraphic.ViewChamps;
import viewGraphic.ViewPrinciple;
/**
* @author <NAME> et <NAME>
*
* La classe ModeRapide permet de gérer le déroulement d'une partie
* rapide en gérant le tour des jours et les saisons.
*/
public class ModeRapide implements Mode {
/**
* Contructeur de la classe.
*/
public ModeRapide(){
if (Partie.getCtrl() instanceof Graphic){
this.vp = ViewPrinciple.getView();
}
}
private static final String[] nom = {"RAYON DE LUNE","CHANT DE SIRENE","LARME DE DRYADE","FONTAINE D'EAU PURE",
"POUDRE D'OR","RACINE D'ARC-EN-CIEL","ESPRIT DE DOLMEN","RIRE DE FEES"};
private static final int[][] value = { //rayon de lune
{1,1,1,1},{2,0,1,1},{2,0,2,0},//rayon de lune 1
{2,0,1,1},{1,3,0,0},{0,1,2,1},//rayon de lune 2
{0,0,4,0},{0,2,2,0},{0,0,1,3},
//chant de sirene
{1,3,1,0},{1,2,1,1},{0,1,4,0},
{2,1,1,1},{1,0,2,2},{3,0,0,2},
{1,2,2,0},{1,1,2,1},{2,0,1,2},
//<NAME>
{2,1,1,2},{1,1,1,3},{2,0,2,2},
{0,3,0,3},{2,1,3,0},{1,1,3,1},
{1,2,1,2},{1,0,1,4},{2,4,0,0},
//dontaine d'eau pure
{1,3,1,2},{2,1,2,2},{0,0,3,4},
{2,2,0,3},{1,1,4,1},{1,2,1,3},
{2,2,3,1},{2,3,0,3},{1,1,3,3},
//poudre d'or
{2,2,3,1},{2,3,0,3},{1,1,3,3},
{2,2,2,2},{0,4,4,0},{1,3,2,2},
{3,1,3,1},{1,4,2,1},{2,4,1,1},
//racine d'arc-en-ciel
{4,1,1,1},{1,2,1,3},{1,2,2,2},
{2,3,2,0},{0,4,3,0},{2,1,1,3},
{2,2,3,0},{1,1,1,4},{2,0,3,2},
//esprit de dolmen
{3,1,4,1},{2,1,3,3},{2,3,2,2},
{2,4,1,2},{2,2,2,3},{1,4,3,1},
{3,3,3,0},{1,3,3,2},{2,3,1,3},
//rire de fees
{1,2,2,1},{1,2,3,0},{0,2,2,2},
{4,0,1,1},{1,1,3,1},{0,0,3,3},
{2,0,1,3},{0,3,0,3},{1,2,2,1},
};
private LinkedList<Carte> talon = new LinkedList <Carte>();
private int valueIndex = 0, serialIndex = 1;
private ViewPrinciple vp = null;
/**
* Permet d'initialiser les cartes et de les ajouter dans la pioche.
*/
public void initCarte() {
for(int i=0;i<8;i++){
createCarte(nom[i]);
}
serialIndex = 1;
Collections.shuffle(talon);
}
/**
* Permet de démarrer la manche qui correspond à la partie pour le mode rapide.
* Cela distribue les cartes et les cailloux.
*/
public void demarrerManche() {
distribuerCarte();
distribuerCailloux();
ViewChamps.getVch().update();
}
/**
* La méthode dérouler permet de gérer l'entièreté de la partie avec les différent tours des joueurs,
* les saisons et la fin de la partie.
*/
public void derouler() {
demarrerManche();
for(int i=0;i<4;i++){//4 saisons
vp.updateS(Partie.getPartie().toString());
for(int j=0;j<Partie.getPartie().getNbJoueur();j++){
Partie.getPartie().getJoueurActuel().getStrategie().jouer();
setJoueurActuel();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(Partie.getCtrl() instanceof Graphic){
vp.update("\n*******Fin De "+Partie.getPartie().toString()+"*******");
}
changeSaison();
}
fin();
}
/**
* Permet de changer de joueur actuel.
*/
public void setJoueurActuel() {
Joueur j = Partie.getPartie().getJoueurActuel();
LinkedList<Joueur> list = Partie.getPartie().getListeJoueur();
int index = Partie.getPartie().getListeJoueur().indexOf(j);
Partie.getPartie().setJoueurActuel(list.get((index+1)%list.size()));
}
/**
* Permet de passer à la saison suivante.
*/
public void changeSaison() {
int saison = (Partie.getPartie().getSaison()+1)%4;
Partie.getPartie().setSaison(saison);
}
/**
* Permet de donner la force des cartes créées.
* @return force : tableau d'entiers.
*/
int[] forceValue(){
int[] force = new int[4];
force = value[valueIndex];
valueIndex ++;
return force;
}
/**
* Permet de créer un tableau comportant les cartes géant, engrais et farfadet.
* @return action : tableau comportant les 3 cartes.
*/
Carte[] create(){
Carte[] action = new Carte[3];
action[0] = new Geant(forceValue());
action[1] = new Engrais(forceValue());
action[2] = new Farfadet(forceValue());
return action;
}
/**
* Permet de créer les cartes ingrédient.
* @param nom : String le nom de la carte
*/
void createCarte(String nom){
for(int c=0;c<3;c++){
talon.add(new CarteIngredient(nom,"g_"+serialIndex,create()));
serialIndex ++;
}
}
/**
* Permet de distribuer les cartes venant de la pioche au début de la partie à chaque joueur.
*/
void distribuerCarte(){
Collections.shuffle(talon);
for(int i=0; i<4; i++){
Iterator <Joueur> it = Partie.getPartie().getListeJoueur().iterator();
while(it.hasNext()){
it.next().getMain().add(talon.poll());
}
}
if(Partie.getCtrl() instanceof Graphic){
ViewCarte.getVc().create();
}
}
/**
* Permet de donner des cailloux à chaque joueur.
*/
void distribuerCailloux(){
for(int i=0; i<2; i++){
Iterator <Joueur> it = Partie.getPartie().getListeJoueur().iterator();
while(it.hasNext()){
it.next().getGraine().add(new Cailloux());
}
}
}
/**
* Permet de récupérer la pioche.
*/
public LinkedList<Carte> getTalon(){
return talon;
}
/**
* Permet de terminer la partie en comptant les points et en déterminant le gagnant.
*/
public void fin(){
int menhir = 0;
Joueur gagnant = null;
String str;
Iterator<Joueur> it = Partie.getPartie().getListeJoueur().iterator();
while(it.hasNext()){
Joueur j = it.next();
if(j.getMenhir().size() >= menhir){
menhir = j.getMenhir().size();
gagnant = j;
}
}
if(gagnant instanceof JoueurReel){
str = "<html>CONGRATULATIONS !<br/>You are the winner!</html>";
ViewPrinciple.getView().update(str);
}
else{
str = "<html>WHAT A PITTY !<br/>You lose this one</html>";
ViewPrinciple.getView().update(str);
}
ViewPrinciple.getView().fin(str);
}
/**
* Il n'y a pas de carte Allié dans la partie normale donc on return null quoi qu'il arrive.
* @return null
*/
public LinkedList<Carte> getAllie() {
return null;
}
}
<file_sep>/src/modeDeJeu/Mode.java
package modeDeJeu;
import java.util.LinkedList;
import carte.Carte;
/**
* @author <NAME> et <NAME>
*
* L'interface Mode permet de définir quelles méthodes les différents modes de jeu devront implémenter.
* @see ModeAvance
* @see modeRapide
*/
public interface Mode {
/**
* Permet d'initialiser les cartes et de les distribuer.
*/
public void initCarte();
/**
* Permet de démarret une manche.
*/
public void demarrerManche();
/**
* Permet de faire dérouler la partie avec l'ordre des joueurs et la geston des saisons.
*/
public void derouler();
/**
* Permet de changer le joueur actuel.
*/
public void setJoueurActuel();
/**
* Permet de passer à la saison suivante.
*/
public void changeSaison();
/**
* Permet de récupérer la pioche.
* @return Linkedlist <Carte> : la liste des cartes de la pioche.
*/
public LinkedList<Carte> getTalon();
/**
* permet de récupérer la liste des cartes alliées.
* @return LinkedList <Carte> : la liste des cartes alliés.
*/
public LinkedList<Carte> getAllie(); //uniquement pour la mode avance
/**
* Permet de terminer la partie en comptant les points.
*/
public void fin();
}
<file_sep>/src/viewGraphic/ViewCarte.java
package viewGraphic;
import java.awt.Color;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import carte.Carte;
import carte.TaupeGeant;
import controle.Graphic;
import joueur.Joueur;
import joueur.JoueurVirtuel;
import partie.Partie;
public class ViewCarte {
private ViewPrinciple v = ViewPrinciple.getView();
private JPanel pane = v.getPanel();
private ArrayList<CButton> buttons = new ArrayList<CButton>();
private ArrayList<JLabel> labels = new ArrayList<JLabel>();//background of the cards
private CButton abutton;
private ViewChamps vch;
private static ViewCarte vc;
private ViewCarte(){
}
public static ViewCarte getVc(){
if(vc == null){
vc = new ViewCarte();
}
return vc;
}
public ViewChamps getVch(){
return this.vch;
}
/**
* create cards button separately
* @param serial
*/
public void initButton(String serial, Carte c, int n) {
//background of the cards,labels
JLabel defaut = new JLabel();
labels.add(defaut);
defaut.setBounds(10*n+200*(n-1), 450, 200, 200);
Image profile;
try {
profile = ImageIO.read(this.getClass().getResource("/geant.jpg"));
defaut.setIcon(new ImageIcon(profile));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
defaut.setVisible(false);
//buttons
CButton button = new CButton(c);
buttons.add(button);
button.addActionListener(new SubWindow(button));
try {
Image icon = ImageIO.read(this.getClass().getResource("/"+serial+".jpg"));
button.setIcon(new ImageIcon(icon));
} catch (IOException e1) {
e1.printStackTrace();
}
button.setBounds(10*n+200*(n-1), 450, 200, 200);
pane.add(defaut);
pane.add(button);
button.setEnabled(false);
}
/**
* create buttons for hand cards
* @param p
*/
public void create(){
ArrayList<Carte> temp = Partie.getPartie().getJoueurReel().getMain();
for(int i = 0; i<4; i++){
initButton(temp.get(i).getSerial(),temp.get(i),i+1);
}
vch = ViewChamps.getVch();
vch.init();
pane.repaint();
}
/**
* add new button for carte allie
*/
public void addA(Carte c){
CButton button = new CButton(c);
this.abutton = button;
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(c instanceof TaupeGeant){
/**
* sub window to choose target name
*/
JFrame subWin = new JFrame("Choose target");
JPanel p = new JPanel();
Joueur target;
LinkedList<Joueur> temp = Partie.getPartie().getListeJoueur();
for(int i = 0; i<temp.size();i++){
target = temp.get(i);
if( target instanceof JoueurVirtuel){
PButton name = new PButton(target);
name.setText(target.getNom());
name.addActionListener(new Names(name,target,subWin));
name.setBackground(Color.WHITE);
p.add(name);
}
}
p.repaint();
subWin.add(p);
subWin.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
subWin.setLocationRelativeTo(null);
subWin.pack();
subWin.setResizable(false);
subWin.setVisible(true);
}
button.setVisible(false);
Graphic.getGraphic().update();//restore parameters
if(c instanceof TaupeGeant){
TaupeGeant tg = (TaupeGeant) c;
tg.effectuer(Partie.getPartie().getJoueurReel());
}
else{
c.effectuer();
}
Graphic.getGraphic().setCarte(c);//notify the motor to continue(case chien)
}
});
try {
Image icon = ImageIO.read(this.getClass().getResource("/"+c.getSerial()+".jpg"));
button.setIcon(new ImageIcon(icon));
} catch (IOException e1) {
e1.printStackTrace();
}
button.setBounds(850, 450, 200, 200);
pane.add(button);
button.setEnabled(false);
}
/**
* set ingredient card buttons enabled to disabled (or inverse)
*/
public void update(){
Iterator<CButton> it = buttons.iterator();
while(it.hasNext()){
CButton x = it.next();
Boolean b = !x.isEnabled();
x.setEnabled(b);
}
}
/**
* set carte allie enabled to disabled (or inverse)
*/
public void updateA(){
Boolean b = !this.abutton.isEnabled();
this.abutton.setEnabled(b);
}
/**
* set backgrounds invisible
*/
public void updateL(){
Iterator<JLabel> it = this.labels.iterator();
while(it.hasNext()){
it.next().setVisible(false);
}
}
/**
* inner class for the card buttons
* @author Dawei
*
*/
class SubWindow implements ActionListener, Runnable{
private CButton button;
private Carte c;
SubWindow(CButton button){
this.button = button;
this.c = button.getC();
}
public void actionPerformed(ActionEvent e) {
this.run();
}
@Override
public void run() {
update();//disable the cards
Graphic.getGraphic().setCarte(c);
JFrame box = new JFrame("Choose Action");
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel text = new JLabel();
text.setBounds(10, 5, 120, 20);
JButton geant = new JButton("Geant");
JButton engrais = new JButton("Engrais");
JButton farfadet = new JButton("Farfadet");
JButton exit = new JButton("exit");
geant.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
update();//enable the cards
text.setText("piocher des graines");
Graphic.getGraphic().setInt(0);
button.setVisible(false);
int index = buttons.indexOf(button);
labels.get(index).setVisible(true);
box.setVisible(false);
}
});
engrais.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
update();//enable the cards
text.setText("engrais des graines");
Graphic.getGraphic().setInt(1);
button.setVisible(false);
int index = buttons.indexOf(button);
labels.get(index).setVisible(true);
box.setVisible(false);
}
});
farfadet.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
text.setText("voler des graines");
Graphic.getGraphic().setInt(2);
/**
* sub window to choose target name
*/
JFrame subWin = new JFrame("Choose target");
JPanel p = new JPanel();
Joueur target;
LinkedList<Joueur> temp = Partie.getPartie().getListeJoueur();
for(int i = 0; i<temp.size();i++){
target = temp.get(i);
if( target instanceof JoueurVirtuel){
PButton name = new PButton(target);
name.setText(target.getNom());
name.addActionListener(new Names(name,target,subWin));
name.setBackground(Color.WHITE);
p.add(name);
}
}
subWin.add(p);
subWin.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
subWin.setLocationRelativeTo(null);
subWin.pack();
subWin.setResizable(false);
subWin.setVisible(true);
/**
* end action for button farfadet
*/
button.setVisible(false);
update();//enable the cards
int index = buttons.indexOf(button);
labels.get(index).setVisible(true);
box.setVisible(false);
// box.dispose();
}
});
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//button.setVisible(false);
update();//enable the cards
box.setVisible(false);
// box.dispose();
}
});
geant.setBackground(Color.CYAN);
engrais.setBackground(Color.CYAN);
farfadet.setBackground(Color.CYAN);
exit.setBackground(Color.GRAY);
geant.setBounds(20, 30, 90, 30);
engrais.setBounds(20, 70, 90, 30);
farfadet.setBounds(20, 110, 90, 30);
exit.setBounds(20, 150, 90, 30);
panel.add(text);
panel.add(geant);
panel.add(engrais);
panel.add(farfadet);
panel.add(exit);
box.add(panel);
box.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
box.setSize(150,240);
box.setResizable(false);
box.setLocationRelativeTo(null);
box.setVisible(true);
}
}
/**
* another inner class, to show the list of names
*/
class Names implements Runnable, ActionListener{
PButton pb;
Joueur j;
JFrame f;
public Names(PButton pb, Joueur j, JFrame f){
this.pb = pb;
this.j = j;
this.f = f;
}
@Override
public void actionPerformed(ActionEvent e) {
this.run();
}
@Override
public void run() {
Graphic.getGraphic().setJ(j);
pb.setVisible(false);
f.setVisible(false);
f.dispose();
}
}
public JButton getAbutton() {
return abutton;
}
public static void reset(){
vc = null;
}
}
<file_sep>/src/joueur/JoueurVirtuel.java
package joueur;
import java.util.Collections;
import java.util.LinkedList;
import strategie.Strategie;
/**
* @author <NAME> et <NAME>
*
* La classe JoueurVirtuel permet de représenter les joueurs contrôlés par l'ordinateur.
*/
public class JoueurVirtuel extends Joueur {
private static final String[] NAMES_M = {"Mike","John","Sam","Jones","Alex"};
private static final String[] NAMES_F = {"Maria","Jane","Christine","Cherry","Pussy"};
private static LinkedList<String> names_m = new LinkedList<String>();
private static LinkedList<String> names_f = new LinkedList<String>();
/**
* Constructeur de la classe.
* @param strategie : C'est la stratégie que vont suivre les joueurs virtuels.
*/
public JoueurVirtuel(Strategie strategie){
this.strategie = strategie;
setProfile();
}
/**
* Initialise les joueurs virtuels en leur donnant des noms.
*/
public static void init(){
for(int i=0; i<NAMES_M.length;i++){
names_m.add(NAMES_M[i]);
}
for(int i=0; i<NAMES_F.length;i++){
names_f.add(NAMES_F[i]);
}
}
/**
* Permet de définir les différentes informations des joueurs virtuels.
*/
public void setProfile() {
double a = Math.random();
age = (int)((a+8)*(Math.random()*3+1));//age ~ 8-36
if(a <= .5){
sexe = true;
}
else{
sexe = false;
}
if(sexe == false){
Collections.shuffle(names_m);
nom = names_m.pop();
}
else{
Collections.shuffle(names_f);
nom = names_f.pop();
}
}
}
<file_sep>/src/cailloux/Cailloux.java
package cailloux;
/**
* @author <NAME> et <NAME>
*
* La classe cailloux permet de représenter les graines ou les menhirs dans une partie du jeu du menhir.
*
*/
public class Cailloux {
boolean estMenhir = false;
/**
* La méthode grandir permet simplement de changer une graine en menhir.
*/
public void gandir(){
estMenhir = true;
}
}
<file_sep>/src/strategie/Strategie.java
package strategie;
import carte.Carte;
import carte.Chien;
import controle.Controle;
import controle.Graphic;
import exception.InputException;
import joueur.Joueur;
import joueur.JoueurReel;
import modeDeJeu.Mode;
import modeDeJeu.ModeAvance;
import modeDeJeu.ModeRapide;
import partie.Partie;
import viewGraphic.ViewCarte;
import viewGraphic.ViewChamps;
import viewGraphic.ViewParametre;
import viewGraphic.ViewPrinciple;
/**
* @author <NAME> et <NAME>
*
* La classe Strategie est une classe abstraite qui permet de définir les méthodes des classes qui en héritent.
* Selon la stratégie, le comportement du joueur ne sera pas le même.
*
* @see StrategieFaible
* @see StrategieForte
* @see StrategieManuele
*
*/
public abstract class Strategie implements Runnable{
protected Controle ctrl = Partie.getCtrl();
protected Carte c;
protected ViewPrinciple vp = ViewPrinciple.getView();
/**
* Permet de choisir un joueur sur lequel faire une action.
* @return Joueur choisis.
* @throws InputException
*/
public abstract Joueur choisisJoueur() throws InputException;
/**
* Permet de choisir une carte à jouer.
* @return Carte choisie.
* @throws InputException
*/
public abstract Carte choisisCarte() throws InputException;
/**
* Permet de choisir une action à faire selon la carte choisie.
* @return int : action choisie
* @throws InputException
*/
public abstract int choisisAction() throws InputException;
/**
* Permet de choisir au début de chaque manche dans le mode avancé si on pioche une carte allié ou deux graines.
* @return int : choix
* @throws InputException
*/
public abstract int choisis() throws InputException;
/**
* Permet de choisir si on veut poser la carte allié ou pas.
* @return int : choix
* @throws InputException
*/
public abstract int choisisJouerAllie() throws InputException;
/**
* Permet de vérifier les choix.
* @param intent : int
* @param j : Joueur
*/
public void confirm(int intent, Joueur j){
Mode mode = Partie.getPartie().getMode();
if(mode instanceof ModeAvance){ //mode avance
if(j.getAllie().size()!=0 && j.getAllie().get(0) instanceof Chien){ //carte allie existe et elle est carte chien
Chien chien = (Chien) j.getAllie().get(0); //lui reference comme chien
Joueur joueur = Partie.getPartie().getJoueurActuel();
String str = "<html>"+joueur.getNom() + " veut voler vos graines<br/>mais vous avez un chien de garde<br/>Veuillez poser cette carte?</html>";
if(j instanceof JoueurReel){
ViewParametre.getVpr().popC(str);
}
int flag = 1;
int choix = 0;
//get choix
while(flag == 1){
try {
choix = choisisJouerAllie();
flag = 0;
} catch (InputException e) {
System.out.println(e.getMessage());
}
}
if(choix == 1){
if(j instanceof JoueurReel){
ViewCarte.getVc().getAbutton().setVisible(false);
}
chien.effectuer(intent, j);
this.vp.update(chien.getAnnonce());
j.getAllie().clear();
Partie.getPartie().getMode().getAllie().add(chien);
}
}
}
}
/**
* Permet de lancer le processus de jeu d'une carte.
*/
public void jouer() {
this.run();
ViewChamps.getVch().update();
}
/**
* Permet de choisir une carte allié ou une carte ingrédient (en fonction du mode de jeu).
*/
public void run(){
if(Partie.getPartie().getMode() instanceof ModeRapide){
jouerIngredient();
}
else {
jouerIngredient();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jouerAllie();
}
ctrl.update();
}
/**
* Permet de jouer une carte ingrédient.
*/
void jouerIngredient(){
//enable the buttons
if(Partie.getPartie().getJoueurActuel() instanceof JoueurReel){
ViewCarte.getVc().update();
}
int flag = 1;
while(flag == 1){
try {
c = choisisCarte();
c.effectuer();
flag = 0;
} catch (InputException e) {
System.out.println(e.getMessage());
}
}
Partie.getPartie().getMode().getTalon().add(c);
Partie.getPartie().getJoueurActuel().getMain().remove(c);
//System.out.println(this.toString());
vp.update(Partie.getPartie().getJoueurActuel().getNom()+" "+c.getAnnonce());
//disable the buttons
if(Partie.getPartie().getJoueurActuel() instanceof JoueurReel){
ViewCarte.getVc().update();
}
}
/**
* Permet de jouer une carte allié.
*/
void jouerAllie(){
if(Partie.getPartie().getJoueurActuel().getAllie().size()>0){
int choix = 0;
int flag = 1;
if(Partie.getPartie().getJoueurActuel() instanceof JoueurReel){
ViewParametre.getVpr().popC("Veuillez poser cette carte allié?");
}
while(flag == 1){
try {
Graphic.getGraphic().update();
choix = choisisJouerAllie();
flag = 0;
} catch (InputException e) {
System.out.println(e.getMessage());
}
}
if(choix == 1){
c = Partie.getPartie().getJoueurActuel().getAllie().get(0);
if(Partie.getPartie().getJoueurActuel() instanceof JoueurReel){
ViewCarte.getVc().updateA();//enable carte allie
ViewCarte.getVc().getAbutton().doClick();
Partie.getPartie().getMode().getAllie().add(c);
Partie.getPartie().getJoueurActuel().getAllie().clear();
this.vp.update(Partie.getPartie().getJoueurActuel().getNom()+" "+c.getAnnonce());
Graphic.getGraphic().update();//restore the attributes
}
else{
c =Partie.getPartie().getJoueurActuel().getAllie().get(0);
c.effectuer();
Partie.getPartie().getMode().getAllie().add(c);
Partie.getPartie().getJoueurActuel().getAllie().clear();
this.vp.update(Partie.getPartie().getJoueurActuel().getNom()+" "+c.getAnnonce());
}
}
}
Graphic.getGraphic().update();
}
public String toString(){
String str = "\n"+Partie.getPartie().getJoueurActuel().getNom()+":\n"+"Graine: "+Partie.getPartie().getJoueurActuel().getGraine().size()+"\nMenhir: "+Partie.getPartie().getJoueurActuel().getMenhir().size();
str += "\n"+c.getAnnonce();
return str;
}
}
<file_sep>/src/viewGraphic/ViewPrinciple.java
package viewGraphic;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import partie.Partie;
public class ViewPrinciple {
/**
* attributs
*/
public static ViewPrinciple view;
JFrame frame = new JFrame();
JPanel pane = new JPanel();
JLabel annonce = new JLabel();
JLabel manche = new JLabel();
JLabel saison = new JLabel();
/**
* constructor
*/
private ViewPrinciple(){
init("Menir Simulator");
}
/**
* get instance
* @return
*/
public static ViewPrinciple getView(){
if(view == null){
view = new ViewPrinciple();
}
return view;
}
/**
* get the label annonce
*/
public JLabel getAnnonce(){
return this.annonce;
}
/**
* main view
* @param title
*/
public void init(String title){
frame.setTitle(title);
pane.setLayout(null);
frame.add(pane);
frame.setSize(1080, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
}
/**
* start with the parameters panel
*/
public void start(){
ViewParametre.getVpr().init();
}
/**
* get the panel
*/
public JPanel getPanel(){
return this.pane;
}
/**
* update the annonce
*/
public void update(String str){
annonce.setBounds(500, 370, 300, 50);
this.pane.add(annonce);
this.annonce.setVisible(true);
this.annonce.setText(str);
}
/**
* update saison
*/
public void updateS(String str){
saison.setBounds(500, 320, 300, 20);
this.pane.add(saison);
this.saison.setText(str);
}
/**
* update the annonce of manche
*/
public void updateM(String str){
manche.setBounds(500, 270, 300, 20);
this.pane.add(manche);
this.manche.setVisible(true);
this.manche.setText(str);
}
/**
* pop a window in the end
*/
public void fin(String str){
JFrame sframe = new JFrame("The end");
JPanel spanel = new JPanel();
JLabel slabel = new JLabel(str,SwingConstants.CENTER);
JButton retry = new JButton("Retry");
JButton exit = new JButton("Exit");
retry.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
pane.removeAll();
Partie.reset();
start();
sframe.setVisible(false);
sframe.dispose();
}
});
exit.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
spanel.setLayout(null);
slabel.setBounds(0, 0, 300, 100);
retry.setBounds(40, 120, 100, 20);
exit.setBounds(160, 120, 100, 20);
retry.setBackground(Color.WHITE);
exit.setBackground(Color.GRAY);
spanel.add(slabel);
spanel.add(retry);
spanel.add(exit);
sframe.add(spanel);
sframe.setSize(300, 200);
sframe.setResizable(false);
sframe.setVisible(true);
sframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
sframe.setLocationRelativeTo(null);
}
}
| e0bddc8ec7b9b58605c727f0fe7382c75645782a | [
"Markdown",
"Java"
] | 15 | Java | Ahdw/menhir | dc0f13de8cb20b97ba894df48bc024ca687daf53 | 9405d4fa7bf609cef99dd709b124c4bde4c2b11c |
refs/heads/master | <repo_name>danielrey133/documentation<file_sep>/CHANGELOG.md
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### 1.0.4 (2021-05-26)
### Bug Fixes
* add executable flags on bin files ([14b5d67](https://github.com/themefisher/themefisher-docs/commit/14b5d6799960630e9254dc414bb6a20c4baf6016))
### Chore
* add release scripts ([101e8ad](https://github.com/themefisher/themefisher-docs/commit/101e8ad64738f3836702d847e577d08571296957))
* update bootstrap 5 module ([1af8e2b](https://github.com/themefisher/themefisher-docs/commit/1af8e2ba89d1dede40ff6cad77cdf287bcec4c5a))
<file_sep>/config/_default/module.toml
[[imports]]
path = "github.com/themefisher/core-docs"
disabled = false
[[imports]]
path = "github.com/dnb-hugo/components/netlification"
disabled = false
<file_sep>/netlify.toml
[build]
publish = "public"
command = "bin/netlify.sh"
[build.environment]
HUGO_VERSION = "0.79.1"
HUGO_BASEURL = "/"
HUGO_ENV = "production"
NODE_VERSION = "14.14.0"
NPM_VERSION = "6.14.8"
GO_VERSION = "1.15"
<file_sep>/bin/replacements.template.sh
#!/bin/bash
declare -a REPLACE=(
'/home/patrick/Projects/dnb-hugo/debugprint'
'/home/patrick/Projects/dnb-hugo/components/functions'
'/home/patrick/Projects/dnb-hugo/components/netlification'
'/home/patrick/Projects/dnb-hugo/libraries/bootstrap5'
'/home/patrick/Projects/ThemeFisher/core-docs'
)
<file_sep>/go.mod
module github.com/themefisher/documentation
go 1.15
require (
github.com/dnb-hugo/components/netlification v1.1.13 // indirect
github.com/themefisher/core-docs v1.0.38 // indirect
)
| 11e5df0542e0a21ceb23e839d70fbe10998e1b74 | [
"Markdown",
"TOML",
"Go Module",
"Shell"
] | 5 | Markdown | danielrey133/documentation | 425b461c8722f1a4a7297e6f8ac86f1f5e157f07 | 37593600c44d9152c251a5b7db7add085a4e6ec7 |
refs/heads/master | <repo_name>DmitryUrsa/film-html-markup<file_sep>/js/main.js
document.addEventListener("DOMContentLoaded", function () {
// Sidebar menu toggler
const menuItems = document.querySelectorAll(".sidebar-menu__item--has-child");
const menuToggle = (e) => {
e.classList.toggle("sidebar-menu__item--active");
};
menuItems.forEach((element) => {
element.addEventListener("click", () => {
menuToggle(element);
});
});
// Fav button toggler
const favButtons = document.querySelectorAll(".like");
const removeFavButtons = document.querySelectorAll(".remove-like");
const favToggle = (e) => {
e.parentNode.querySelector(".like").classList.toggle("like--active");
};
const favRemove = (e) => {
e.parentNode.querySelector(".like").classList.remove("like--active");
};
favButtons.forEach((element) => {
element.addEventListener("click", (e) => {
e.preventDefault();
favToggle(element);
});
});
removeFavButtons.forEach((element) => {
element.addEventListener("click", (e) => {
e.preventDefault();
favRemove(element);
});
});
tippy(".like", {
content: "В избранное",
});
tippy(".remove-like", {
content: "Удалить из избранного",
});
// Mobile menu toggle
const burger = document.querySelectorAll(".hamburger");
const sidebar = document.querySelector(".sidebar");
burger.forEach((element) => {
element.addEventListener("click", (e) => {
burger.forEach((element) => {
element.classList.toggle("is-active");
});
sidebar.classList.toggle("sidebar--open");
});
});
});
| 10395f88f40c73c0e7859431049a9b84e0d6f864 | [
"JavaScript"
] | 1 | JavaScript | DmitryUrsa/film-html-markup | b68b4bb19635a4eded79b7f8dff72f67e0e1ac2c | 2c302ff3d3748108a5644fdc7d384df82b5e4d32 |
refs/heads/master | <repo_name>smi97/Lab_2<file_sep>/Tests/print_hello_world.cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <iostream>
#include "../sources/incr.cpp"
TEST_CASE( "Increments are computed", "[increment]" ) {
REQUIRE( incr(1) == 2 );
REQUIRE( incr(2) == 3 );
REQUIRE( incr(3) == 4 );
REQUIRE( incr(10) == 11 );
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.0.2)
project(hello_world)
include_directories(include)
set(SOURCE_EXE examples/main.cpp)
set(SOURCE_LIB sources/print_hello_world.cpp)
set(SOURCE_TEST Tests/main.cpp)
add_library(hw STATIC ${SOURCE_LIB})
add_executable(main ${SOURCE_EXE})
add_executable(test ${SOURCE_TEST})
target_link_libraries(main hw)
| 78d4c0e66cf8acc5ca02db2b2949a253d4551537 | [
"CMake",
"C++"
] | 2 | C++ | smi97/Lab_2 | 0b81dcaee33f2ce37d1e6ca1fe3b798c6bc8e1e3 | bdc2a19149bb88246271fce35bd2f9bcae57fa09 |
refs/heads/master | <repo_name>liuyapu/demo<file_sep>/src/main/java/com/example/demo/service/impl/UserServiceImpl.java
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.transaction.Transactional;
@Service
@Transactional
public class UserServiceImpl implements UserService{
@Resource
private UserMapper userMapper;
@Override
public User getUserById(String userId) {
//System.out.println("111:"+userMapper.selectUserById(userId).getUserId());
System.out.println("iml层:"+userId);
return userMapper.selectUserById(userId);
}
}
<file_sep>/src/main/java/com/example/demo/entity/User.java
package com.example.demo.entity;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
@Getter
@Setter
@ToString
@Builder
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
@Repository
public class User {
private String userId;
private String userName;
private String userSex;
private Timestamp createTime;
private Timestamp updateTime;
}
<file_sep>/src/main/java/com/example/demo/controller/UserController.java
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test1")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getUserById")
public User GetUser(@RequestParam("userId") String userId){
System.out.println(userId);
User user = userService.getUserById(userId);
if(user == null){
System.out.println("没取到");
}
//System.out.println(user.toString());
return user;
}
}
<file_sep>/src/main/java/com/example/demo/service/UserService.java
package com.example.demo.service;
import com.example.demo.entity.User;
import org.springframework.stereotype.Service;
@Service
public interface UserService {
User getUserById(String userId);
}
| 4d0df239de357091d884a3a28cf885efd48be730 | [
"Java"
] | 4 | Java | liuyapu/demo | 50e2ff44036affe37c27099e77612df66a75197f | ec31a6627f44deac3db007675f22b10c72873578 |
refs/heads/master | <repo_name>edznan/csharp-hangman<file_sep>/hangman/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace hangman
{
class Program
{
static void Main(string[] args)
{
bool a = true;
Console.WriteLine("Welcome!");
string[] words = new string[25];
words[0] = "bottle";
words[1] = "game";
words[2] = "crash";
words[3] = "pineapple";
words[4] = "screen";
words[5] = "smartphone";
words[6] = "flower";
words[7] = "blackberry";
words[8] = "fire";
words[9] = "water";
words[10] = "truck";
words[11] = "paper";
words[12] = "color";
words[13] = "machine";
words[14] = "book";
words[15] = "coffee";
words[16] = "tea";
words[17] = "supermarket";
words[18] = "highway";
words[19] = "road";
words[20] = "door";
words[21] = "building";
words[22] = "spaceship";
words[23] = "programming";
words[24] = "tower";
Random rnd = new Random();
var mix = rnd.Next(0, 25);
string chosenWord = words[mix];
char[] guess = new char[chosenWord.Length];
Console.WriteLine("Please enter your guess: ");
for (int p = 0; p < chosenWord.Length; p++)
guess[p] = '*';
while (a)
{
char playerGuess = char.Parse(Console.ReadLine());
for (int j = 0; j < chosenWord.Length; j++)
{
if (playerGuess == chosenWord[j])
guess[j] = playerGuess;
}
Console.WriteLine(guess);
if (new string(guess) == chosenWord)
a = false;
}
Console.WriteLine("Write the entire word.");
Console.ReadLine();
}
}
}<file_sep>/README.md
# csharp-hangman
| c3f10f77a299cd997a8ad66c85c984a7ec82e2a3 | [
"Markdown",
"C#"
] | 2 | C# | edznan/csharp-hangman | 2e333e5189b9e0bb03f3656f8881fac3bde9d75f | 0c53abc664cdb54668de12200e4b1c4255055634 |
refs/heads/master | <file_sep>#include "stdafx.h"
#include "filetree.h"
#include <windows.h>
SYSTEMTIME sys;
using namespace std;
typedef struct time
{
int year;
int month;
int day;
int hour;
int minute;
int second;
};
typedef struct file
{
int flag;
int cf;
char name[20];
char filetype[10];
time time;
struct file *parent, *firstchild, *brother;
int n; //数量
int level; //层次
int size; //大小
};
filetree::filetree()
{
root = new file;
root->level = 0;
root->cf = 0;
root->n = 0;
root->time.year = sys.wYear;
root->time.month = sys.wMonth;
root->time.day = sys.wDay;
root->time.hour = sys.wHour;
root->time.minute = sys.wMinute;
root->time.second = sys.wSecond;
root->filetype[0] = '\0';
strcpy_s(root->name,"AAA");
root->brother = NULL;
root->firstchild = NULL;
root->brother = NULL;
}
filetree::~filetree()
{
}
void filetree::shownode(file *q)
{
if (q)
{
printf("%s", q->name);
if (q->cf)
printf(".%s", q->filetype);
}
}
void filetree::unfold(file *p)
{
shownode(p);
printf(" 包括:\n");
if (!p->firstchild)
{
printf("没有此目录或文件\n");
return;
}
p = p->firstchild;//第一个孩子节点
if (p)
{
printf("\t");
shownode(p);
printf("\n");
while (p->brother)//兄弟节点
{
p = p->brother;
printf("\t");
shownode(p);
printf("\n");
}
}
}
void filetree::addnode(file *p)
{
file *q = NULL;
file *w = NULL;
if (p->cf)
{
printf("不能添加文件!\n");
return;
}
q = new file;
printf("0.Directory\t1.File\n");//创建目录还是文件
scanf_s("%d", &q->cf);
printf("输入名字:");
scanf_s("%s", q->name, 20);
getchar();
if (q->cf)//创建文件步骤
{
printf("输入文件类型:");
scanf_s("%s", q->filetype, 10);
printf("输入数量:");
scanf_s("%d", &q->size);
getchar();
}
if (p->firstchild)
w = Compare(q->name, p->firstchild);
if (w)
{
if (!strcmp(q->filetype, w->filetype))
printf("已经存在,不能添加!\n");
return;
}
if (!q->cf)//创建目录步骤
{
q->filetype[0] = '\0';
q->size = 0;
}
GetLocalTime(&sys);
q->time.year = sys.wYear;
q->time.month = sys.wMonth;
q->time.day = sys.wDay;
q->time.hour = sys.wHour;
q->time.second = sys.wSecond;
q->flag = 0;
q->parent = p;
q->firstchild = NULL;
q->brother = NULL;
q->level = p->level + 1;
q->n = 0;
p->n++;
if (!p->firstchild)
{
p->firstchild = q;//存地址,建立目录树形结构
}
else
{
p = p->firstchild;
while (p->brother)
{
p = p->brother;
}
p->brother = q;
}
printf("添加成功!\n");
}
file * filetree::Locate(file * p)
{
int i = 0;
char d, c[10], t[10];
t[0] = '\0';
scanf_s("%c", &d);
scanf_s("%c", &d);//接收输入的目录路径
while (d != '*'&&d != '.')//目录路径不为空以及不包含.,循环查找当前目录以及其子目录是否存在所输入目录
{
if (d == '\\')
{
c[i] = '\0';
scanf_s("%c", &d);
i = 0;
p = Compare(c, p);
if (!p)
{
printf("路径有误!\n");
return NULL;
}
p = p->firstchild;//对子目录进行查找
}
c[i++] = d;
scanf_s("%c", &d);
}
if (d == '.')
{
i = 0;
scanf_s("%c", &d);
while (d != '*')
{
t[i++] = d;
scanf_s("%c", &d);
}
t[i] = '\0';
}
if (d == '*')//路径结束标记
{
c[i] = '\0';
p = Compare(c, p);
if (!p)
{
printf("目录路径有误!\n");
return NULL;
}
if (t[0] != '\0'&&p->filetype[0] != '\0')//路径名称合法
{
if (strcmp(t, p->filetype))
{
printf("文件路径有误!\n");
return NULL;
}
return p;
}
else if (t[0] == '\0'&&p->filetype[0] == '\0')
return p;
}
printf("路径有误!\n");
return NULL;
}
void filetree::del(file * p)
{
file *q,*kid;
if (p->firstchild != NULL)
{
cout << "有子文件不能删除"<<endl;
}
else
{
q = p->parent;
kid = q->firstchild;
if (strcmp(kid->name, p->name) == 0)
q->firstchild = kid->brother;
else
{
while (strcmp(kid->brother->name, p->name) == 0)
kid = kid->brother;
kid->brother = kid->brother->brother;
}
cout << "删除成功"<<endl;
}
}
void filetree::Traverser(file * p)
{
int i;
file *q = p;
if (!p) return;
for (i = 0; i<p->level; i++)
{
printf(" ");//缩进
}
shownode(q);//显示节点信息
printf("\n");
Traverser(p->firstchild);//显示第一个孩子节点
Traverser(p->brother);//显示兄弟节点
}
void filetree::information(file * p) //显示文件夹信息
{
printf("name:%s\n", p->name);
if (p->filetype[0] != '\0')
{
printf("文件类型:%s\n", p->filetype);
printf("大小:%dK\n", p->size);
}
else printf("菜单\n");
printf("创建时间:");
printf("%d%d%d\n", p->time.year, p->time.month, p->time.day);
printf("包含的文件数量:%d\n", p->n);
}
file * filetree::Compare(char * ch, file * p)
{
int i;
if (!p) return NULL;
if (!p->parent)//跟父节点比较
{
i = strcmp(ch, p->name);
if (!i) return p;
return NULL;
}
p = p->parent;
p = p->firstchild;
i = strcmp(ch, p->name);//跟第一个孩子节点比较
if (!i) return p;//在目录里面,返回目录地址
else
{
while (p->brother)//跟兄弟节点比较
{
p = p->brother;
if (!strcmp(ch, p->name)) return p;
}
return NULL;//不在目录里面,返回空
}
}
<file_sep>#pragma once
class filetree
{
public:
filetree();
~filetree();
void shownode(file *q);
void unfold(file *p);
void addnode(file *p);
file *Locate(file *p);
void del(file *p);
void Traverser(file *p);
void information(file *p);
file * Compare(char *ch, file *p);
file *root;
private:
};
<file_sep>========================================================================
控制台应用程序:目录管理 数据结构课设 项目概述
========================================================================
应用程序向导已为您创建了此 目录管理 数据结构课设 应用程序。
本文件概要介绍组成 目录管理 数据结构课设 应用程序的每个文件的内容。
目录管理 数据结构课设.vcxproj
这是使用应用程序向导生成的 VC++ 项目的主项目文件,其中包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。
目录管理 数据结构课设.vcxproj.filters
这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。
目录管理 数据结构课设.cpp
这是主应用程序源文件。
/////////////////////////////////////////////////////////////////////////////
其他标准文件:
StdAfx.h, StdAfx.cpp
这些文件用于生成名为 目录管理 数据结构课设.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。
/////////////////////////////////////////////////////////////////////////////
其他注释:
应用程序向导使用“TODO:”注释来指示应添加或自定义的源代码部分。
/////////////////////////////////////////////////////////////////////////////
<file_sep># test
test
这是一个测试文件
hello world;
| 8b093b5f5e4bd9ad0d1f6b15105c606a11bf6136 | [
"Markdown",
"Text",
"C++"
] | 4 | C++ | ExplosiveYan/test | deaa0efa04a00f359896eef9a73b6e358be0110a | 81d5c62177b0215fe3a63d2e77ba1fb015655969 |
refs/heads/master | <repo_name>devinhumphrey52/Python3_Basic_Output_with_Variables<file_sep>/Basic_Output_with_Variables.py
userNum = int(input('Enter integer: \n'))
print("You entered:", userNum)
print (userNum,"squared is", end = " ")
print(userNum * userNum)
print("And", userNum, "cubed is", userNum * userNum *userNum, '!!')
userNum2 = int(input('Enter another integer: \n'))
print('4 +', userNum2, 'is', end =" ")
print(4 + userNum2)
print('4 *', userNum2, 'is', end=" ")
print(4 * userNum2)
<file_sep>/README.md
# Python3_Basic_Output_with_Variables
A simple console based app designed to show basic output with variables
| c2eb8a4db08f3bc32506c066667eea956da230c2 | [
"Markdown",
"Python"
] | 2 | Python | devinhumphrey52/Python3_Basic_Output_with_Variables | 2da3ee3053f121d1ed319ac81ef2110a039e9589 | 03cd47fa092c5c336f5c71f7cbbea688415a8b9d |
refs/heads/master | <repo_name>ahter/djugl-talk-aug-2019<file_sep>/example/core/views.py
def some_useful_function():
essential_variable = 42
other_variable = None
assert essential_variable != other_variable
return essential_variable
<file_sep>/README.md
# djugl-talk-aug-2019
Sample files for DJUGL August 2019
| f28914fdf61697493e2cb5caff84a7c913f139b7 | [
"Markdown",
"Python"
] | 2 | Python | ahter/djugl-talk-aug-2019 | 949748f73c654ec947694828ac6930f16bd7db7a | b27f7c3f55122629242b10d739aeeb1381b83557 |
refs/heads/master | <repo_name>yshing/ghost-hash<file_sep>/apply-patch.sh
#!/usr/bin/env bash
cp ./patch/core-rss.js ./node_modules/ghost/core/server/data/xml/rss/index.js
<file_sep>/README.md
## Already-setup Ghost 1.8.0 for fast development
Owner set to ghost. login at (http://localhost:4096/ghost)[http://localhost:4096/ghost]
```
<EMAIL>
k2.digital
```
Should generate Facebook instant article ready rss feed after apply patch.
```
./apply-patch.sh
```
## Dev environment
Require NodeJS best latest LTS version [NodeJS.org](https://nodejs.org/en/)
And pm2 for process manageing of dev server. `npm i -g pm2` if not installed
Then simply run `npm start` to run the server.
Default endpoint at [http://localhost:4096](http://localhost:4096)
## Related Documentation:
[Ghost API Doc] (https://api.ghost.org/docs)
[Ghost Doc](https://docs.ghost.org/docs)
[Ghost Slack Channel](http://slack.ghost.org/)
[Ghost CN](http://www.ghostchina.com/)
[handlebarsjs](http://handlebarsjs.com/)<file_sep>/index.js
var express = require('express');
var ghost = require('ghost')
var app = express();
var server = app.listen(4096, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
ghost().then(function (ghostServer){
app.use( ghostServer.rootApp);
ghostServer.start(server);
}) | def07ec9ac6e050e06670d70fda648cdce0d1c5f | [
"Markdown",
"JavaScript",
"Shell"
] | 3 | Shell | yshing/ghost-hash | 89650f873b98a8e134697d368ac5f1d0a70d5079 | 4849311042fe5ec06cae24b9379df19ea28fd2ee |
refs/heads/master | <file_sep>#!/bin/bash
set -e
PHPINI=/usr/local/etc/php/php.ini
# php environment
PHP_ALLOW_URL_FOPEN=${PHP_ALLOW_URL_FOPEN:-On}
PHP_DISPLAY_ERRORS=${PHP_DISPLAY_ERRORS:-Off}
PHP_MAX_EXECUTION_TIME=${PHP_MAX_EXECUTION_TIME:-360}
PHP_MAX_INPUT_TIME=${PHP_MAX_INPUT_TIME:-360}
PHP_MEMORY_LIMIT=${PHP_MEMORY_LIMIT:-256}
PHP_POST_MAX_SIZE=${PHP_POST_MAX_SIZE:-256}
PHP_SHORT_OPEN_TAG=${PHP_SHORT_OPEN_TAG:-On}
PHP_TIMEZONE=${PHP_TIMEZONE:-Europe/Moscow}
PHP_UPLOAD_MAX_FILEZIZE=${PHP_UPLOAD_MAX_FILEZIZE:-256}
PHP_MAX_FILE_UPLOADS=${PHP_MAX_FILE_UPLOADS:-250}
WORKERS_NUMBER=${WORKERS_NUMBER:-4}
PHP_TZ=`echo ${PHP_TIMEZONE} |sed 's|\/|\\\/|g'`
# set timezone
ln -snf /usr/share/zoneinfo/${PHP_TIMEZONE} /etc/localtime
dpkg-reconfigure -f noninteractive tzdata
sed -i -e "s/WORKERS_NUMBER/${WORKERS_NUMBER}/g" /etc/supervisord.conf
if [ -f /var/www/html/config/php/php.ini ]; then
cp /var/www/html/config/php/php.ini ${PHPINI}
else
sed -i \
-e "s/memory_limit = 128M/memory_limit = ${PHP_MEMORY_LIMIT}M/g" \
-e "s/short_open_tag = Off/short_open_tag = ${PHP_SHORT_OPEN_TAG}/g" \
-e "s/upload_max_filesize = 2M/upload_max_filesize = ${PHP_UPLOAD_MAX_FILEZIZE}M/g" \
-e "s/max_file_uploads = 20/max_file_uploads = ${PHP_MAX_FILE_UPLOADS}/g" \
-e "s/max_execution_time = 30/max_execution_time = ${PHP_MAX_EXECUTION_TIME}/g" \
-e "s/max_input_time = 60/max_input_time = ${PHP_MAX_INPUT_TIME}/g" \
-e "s/display_errors = Off/display_errors = ${PHP_DISPLAY_ERRORS}/g" \
-e "s/post_max_size = 8M/post_max_size = ${PHP_POST_MAX_SIZE}M/g" \
-e "s/allow_url_fopen = On/allow_url_fopen = ${PHP_ALLOW_URL_FOPEN}/g" \
-e "s/;date.timezone =/date.timezone = ${PHP_TZ}/g" \
${PHPINI}
fi
usermod -s /bin/bash www-data
chown www-data:www-data /var/www -R
if [ ! -f /var/www/html/install.lock ]; then
BRANCH=${BRANCH:-master}
DB_PORT=${DB_PORT:-3306}
DB_CONNECTION=${DB_CONNECTION:-mysql}
MEMCACHED_PORT=${MEMCACHED_PORT:-11211}
REDIS_PORT=${REDIS_PORT:-6379}
REDIS_PASSWORD=${REDIS_PASSWORD:-null}
IMAGE_DRIVER=${IMAGE_DRIVER:-imagick}
DISK_DRIVER=${DISK_DRIVER:-local}
RABBITMQ_PORT=${RABBITMQ_PORT:-5672}
RABBITMQ_VHOST=${RABBITMQ_VHOST:-/}
RABBITMQ_LOGIN=${RABBITMQ_LOGIN:-guest}
RABBITMQ_PASSWORD=${RABBITMQ_PASSWORD:-guest}
QUEUE_DRIVER=${QUEUE_DRIVER:-database}
CACHE_DRIVER=${CACHE_DRIVER:-file}
SESSION_DRIVER=${SESSION_DRIVER:-file}
su -s /bin/bash - www-data -c "cd /var/www/html/ && git clone -b ${BRANCH} --single-branch https://github.com/pgallery/gallery && \
cd /var/www/html/gallery && composer install && composer update && cp .env.example .env && \
php artisan key:generate"
sed -i \
-e "s/APP_URL=http:\/\/localhost/APP_URL=http:\/\/${URL}/g" \
-e "s/APP_TIMEZONE=Europe\/Moscow/APP_TIMEZONE=${PHP_TZ}/g" \
-e "s/DB_CONNECTION=mysql/DB_CONNECTION=${DB_CONNECTION}/g" \
-e "s/DB_HOST=127.0.0.1/DB_HOST=${DB_HOST}/g" \
-e "s/DB_PORT=3306/DB_PORT=${DB_PORT}/g" \
-e "s/DB_DATABASE=homestead/DB_DATABASE=${DB_DATABASE}/g" \
-e "s/DB_USERNAME=homestead/DB_USERNAME=${DB_USERNAME}/g" \
-e "s/DB_PASSWORD=secret/DB_PASSWORD=${DB_PASSWORD}/g" \
-e "s/IMAGE_DRIVER=gd/IMAGE_DRIVER=${IMAGE_DRIVER}/g" \
-e "s/DISK_DRIVER=local/DISK_DRIVER=${DISK_DRIVER}/g" \
-e "s/CACHE_DRIVER=file/CACHE_DRIVER=${CACHE_DRIVER}/g" \
-e "s/SESSION_DRIVER=file/SESSION_DRIVER=${SESSION_DRIVER}/g" \
-e "s/QUEUE_DRIVER=sync/QUEUE_DRIVER=${QUEUE_DRIVER}/g" \
/var/www/html/gallery/.env
if [ ${DISK_DRIVER} == 'bizmrg' ]; then
sed -i \
-e "s/AWS_ENDPOINT=/AWS_ENDPOINT=${AWS_ENDPOINT}/g" \
-e "s/AWS_KEY=/AWS_KEY=${AWS_KEY}/g" \
-e "s/AWS_SECRET=/AWS_SECRET=${AWS_SECRET}/g" \
-e "s/AWS_BUCKET=/AWS_BUCKET=${AWS_BUCKET}/g" \
/var/www/html/gallery/.env
fi
if [ ${DISK_DRIVER} == 's3' ]; then
sed -i \
-e "s/AWS_KEY=/AWS_KEY=${AWS_KEY}/g" \
-e "s/AWS_SECRET=/AWS_SECRET=${AWS_SECRET}/g" \
-e "s/AWS_REGION=/AWS_REGION=${AWS_REGION}/g" \
-e "s/AWS_BUCKET=/AWS_BUCKET=${AWS_BUCKET}/g" \
/var/www/html/gallery/.env
fi
if [ -n ${MEMCACHED_HOST} ]; then
sed -i \
-e "s/MEMCACHED_HOST=/MEMCACHED_HOST=${MEMCACHED_HOST}/g" \
-e "s/MEMCACHED_PORT=/MEMCACHED_PORT=${MEMCACHED_PORT}/g" \
-e "s/MEMCACHED_USERNAME=/MEMCACHED_USERNAME=${MEMCACHED_USERNAME}/g" \
-e "s/MEMCACHED_PASSWORD=/MEMCACHED_PASSWORD=${MEMCACHED_PASSWORD}/g" \
/var/www/html/gallery/.env
fi
if [ -n ${RABBITMQ_HOST} ]; then
RABBITMQ_VHOST_TAG=`echo ${RABBITMQ_VHOST} |sed 's|\/|\\\/|g'`
sed -i \
-e "s/RABBITMQ_HOST=/RABBITMQ_HOST=${RABBITMQ_HOST}/g" \
-e "s/RABBITMQ_PORT=/RABBITMQ_PORT=${RABBITMQ_PORT}/g" \
-e "s/RABBITMQ_VHOST=/RABBITMQ_VHOST=${RABBITMQ_VHOST_TAG}/g" \
-e "s/RABBITMQ_LOGIN=/RABBITMQ_LOGIN=${RABBITMQ_LOGIN}/g" \
-e "s/RABBITMQ_PASSWORD=/RABBITMQ_PASSWORD=${RABBITMQ_PASSWORD}/g" \
/var/www/html/gallery/.env
fi
if [ -n ${REDIS_HOST} ]; then
sed -i \
-e "s/REDIS_HOST=/REDIS_HOST=${REDIS_HOST}/g" \
-e "s/REDIS_PORT=/REDIS_PORT=${REDIS_PORT}/g" \
-e "s/REDIS_PASSWORD=/REDIS_PASSWORD=${REDIS_PASSWORD}/g" \
/var/www/html/gallery/.env
fi
su -s /bin/bash - www-data -c "cd /var/www/html/gallery && php artisan migrate && \
php artisan db:seed && php artisan route:cache"
su -s /bin/bash - www-data -c "cd /var/www/html/gallery && php artisan queues enabled"
if [ -n ${GALLERY_USER} ] || [ -n ${GALLERY_PASSWORD} ]; then
su -s /bin/bash - www-data -c "cd /var/www/html/gallery && php artisan usermod <EMAIL> --email=${GALLERY_USER} --password=${<PASSWORD>}"
fi
su -s /bin/bash - www-data -c "touch /var/www/html/install.lock"
fi
/usr/bin/supervisord -n -c /etc/supervisord.conf
<file_sep>#!/bin/bash
set -e
su -s /bin/bash - www-data -c "cd /var/www/html/gallery \
&& php artisan $@"
<file_sep>## Описание
Это Dockerfile, позволяющие собрать простой образ для Docker с PHP-CLI 7.1, 7.2 или 7.3 для запуска воркеров Laravel проекта pGallery.
Собран на основе образа: [https://github.com/pgallery/php](https://github.com/pgallery/php)
## Репозиторий Git
Репозиторий исходных файлов данного проекта: [https://github.com/pgallery/workers](https://github.com/pgallery/workers)
## Репозиторий Docker Hub
Расположение образа в Docker Hub: [https://hub.docker.com/r/pgallery/workers/](https://hub.docker.com/r/pgallery/workers/)
## Использование Docker Hub
```
sudo docker pull pgallery/workers
```
## Запуск
```
docker run -d --name phpfpm \
-v /home/username/sitename/www/:/var/www/html/ \
pgallery/php-fpm
docker run -d -p 80:80 -p 443:443 \
--link phpfpm:phpfpm \
-v /home/username/sitename/www/:/var/www/html/ \
-v /home/username/sitename/logs/:/var/log/nginx/ \
pgallery/nginx
docker run -d --name workers \
-v /home/username/sitename/www/:/var/www/html/ \
-v /home/username/sitename/logs/:/var/log/workers/ \
pgallery/workers
```
## Доступные параметры конфигурации
### Параметры изменяющие настройки PHP
| Параметр | Изменяемая директива | По умолчанию |
|----------|----------------------|--------------|
|**PHP_ALLOW_URL_FOPEN**| allow_url_fopen | On |
|**PHP_DISPLAY_ERRORS**| display_errors | Off |
|**PHP_MAX_EXECUTION_TIME**| max_execution_time | 360 |
|**PHP_MAX_INPUT_TIME**| max_input_time | 360 |
|**PHP_MEMORY_LIMIT**| memory_limit | 256M |
|**PHP_POST_MAX_SIZE**| post_max_size | 256M |
|**PHP_SHORT_OPEN_TAG**| short_open_tag | On |
|**PHP_TIMEZONE**| date.timezone | Europe/Moscow |
|**PHP_UPLOAD_MAX_FILEZIZE**| upload_max_filesize | 256M |
|**PHP_MAX_FILE_UPLOADS**| max_file_uploads | 250 |
#### Пример использования
```
sudo docker run -d \
-e 'PHP_TIMEZONE=Europe/Moscow' \
-e 'PHP_MEMORY_LIMIT=512' \
-e 'PHP_SHORT_OPEN_TAG=On' \
-e 'PHP_UPLOAD_MAX_FILEZIZE=16' \
-e 'PHP_MAX_EXECUTION_TIME=120' \
-e 'PHP_MAX_INPUT_TIME=120' \
-e 'PHP_DISPLAY_ERRORS=On' \
-e 'PHP_POST_MAX_SIZE=32' \
-e 'PHP_ALLOW_URL_FOPEN=Off' \
pgallery/workers
```
## Использование собственных конфигурационных файлов
Вы можете использовать собственные конфигурационные файлы для php. Для этого Вам необходимо создать их в директории **/var/www/html/config/**. При их обнаружении, Ваши конфигурационные файлы будут скопированы и заменят существующие.
### PHP
- **/var/www/html/config/php/php.ini** - данным файлом будет заменен /usr/local/etc/php/php.ini (при этом параметры, изменяющие настройки PHP, переданные при запуске контейнера, будут игнорированы)
- **/var/www/html/config/php/pool.conf** - данным файлом будет заменен /usr/local/etc/php-fpm.d/www.conf
<file_sep>#!/bin/bash
set -e
su -s /bin/bash - www-data -c "cd /var/www/html/gallery \
&& git pull \
&& composer update \
&& php artisan migrate \
&& php artisan view:clear \
&& php artisan route:clear \
&& php artisan cache:clear \
&& php artisan route:cache"
| 68e166d783f1b8f3e5234fb52f63baab4aa431b3 | [
"Markdown",
"Shell"
] | 4 | Shell | pgallery/workers | 6b02f12605a82f3b33e80a9363785856a8685f43 | d343cb5772c84a506af8e7a2313f44744e4df1ca |
refs/heads/master | <file_sep>using System.Collections.Generic;
using System.IO;
using System.Web.Optimization;
namespace Contacts.App_Start
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
// Scripts
bundles.Add(new ScriptBundle("~/bundles/layoutscripts") {Orderer = new AsDefinedBundleOrderer()}.Include(
"~/Scripts/Common/json.js",
"~/Scripts/Common/jquery-{version}.js",
"~/Scripts/Common/jquery-ui-{version}.js",
"~/Scripts/Common/jquery.unobtrusive*",
"~/Scripts/Common/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/Common/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/contacts").Include(
"~/Scripts/Views/contacts.js"));
// Styles
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css") {Orderer = new AsDefinedBundleOrderer()}.Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
}
public class AsDefinedBundleOrderer : IBundleOrderer
{
public IEnumerable<FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files)
{
return files;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Contacts.Contracts;
using Contacts.Domain;
namespace Contacts.Services
{
public class ContactsService : IContactsService
{
#region Data
private List<ContactGroup> _contactGroups = new List<ContactGroup>
{
new ContactGroup {Id = 1, Name = "Unsorted"},
new ContactGroup {Id = 2, Name = "Best friends"},
new ContactGroup {Id = 3, Name = "Haters gonna hate"},
new ContactGroup {Id = 4, Name = "Family"}
};
private List<Contact> _contacts = new List<Contact>
{
new Contact
{
Id = 1,
Email = "<EMAIL>",
FirstName = "Dave",
MiddleName = String.Empty,
LastName = "Gahan",
Phone = "(093)2696232",
ContactGroupId = 1
},
new Contact
{
Id = 2,
Email = "<EMAIL>",
FirstName = "Megan",
MiddleName = String.Empty,
LastName = "Fox",
Phone = "(093)3456232",
ContactGroupId = 2
},
new Contact
{
Id = 3,
Email = "<EMAIL>",
FirstName = "Santa",
MiddleName = String.Empty,
LastName = "Klaus",
Phone = "(093)1111111",
ContactGroupId = 1
},
new Contact
{
Id = 4,
Email = "<EMAIL>",
FirstName = "Elvis",
MiddleName = String.Empty,
LastName = "Presley",
Phone = "2222222",
ContactGroupId = 4
},
new Contact
{
Id = 5,
Email = "<EMAIL>",
FirstName = "Hater",
MiddleName = String.Empty,
LastName = "<NAME>",
Phone = "(067)3333333",
ContactGroupId = 2
},
new Contact
{
Id = 6,
Email = "<EMAIL>",
FirstName = "Wall-e",
MiddleName = "Forever",
LastName = "Alone",
Phone = "(093)5673378",
ContactGroupId = 3
}
};
#endregion
#region IContactsService
public IList<ContactGroup> GetAllGroups()
{
try
{
var result = _contactGroups;
return result;
}
catch (Exception ex)
{
Trace.WriteLine("GetAllGroups: " + ex.Message);
throw;
}
}
public IList<Contact> GetContactsByGroup(ContactGroup contactGroup)
{
try
{
var result = _contacts.Where(c => c.ContactGroupId == contactGroup.Id).ToList();
return result;
}
catch (Exception ex)
{
Trace.WriteLine("GetAllGroups: " + ex.Message);
throw;
}
}
public Contact GetContactById(int contactId)
{
try
{
var result = _contacts.FirstOrDefault(c => c.Id == contactId);
return result;
}
catch (Exception ex)
{
Trace.WriteLine("GetContactById: " + ex.Message);
throw;
}
}
public ContactGroup GetGroupById(int contactGroupId)
{
try
{
var result = _contactGroups.FirstOrDefault(cg => cg.Id == contactGroupId);
return result;
}
catch (Exception ex)
{
Trace.WriteLine("GetGroupById: " + ex.Message);
throw;
}
}
public int AddContact(Contact contact)
{
if (contact == null)
throw new ArgumentNullException("contact");
if (_contacts.Any(c => contact.FullName.ToLower().Trim() == c.FullName))
{
throw new ArgumentException("A contact with the specified name already exists");
}
try
{
contact.Id = _contacts.Max(c => c.Id) + 1;
_contacts.Add(contact);
return contact.Id;
}
catch (Exception ex)
{
Trace.WriteLine("AddContact: " + ex.Message);
throw;
}
}
public void RemoveContact(Contact contact)
{
if (contact == null)
throw new ArgumentNullException("contact");
try
{
_contacts.Remove(contact);
}
catch (Exception ex)
{
Trace.WriteLine("RemoveContact: " + ex.Message);
throw;
}
}
public void RemoveContactFromGroup(Contact contact)
{
if (contact == null)
throw new ArgumentNullException("contact");
try
{
var foundContact = _contacts.FirstOrDefault(c => c.Id == contact.Id);
if (foundContact != null)
{
var contactGroup = _contactGroups.FirstOrDefault(cg => cg.Name == "Unsorted");
if (contactGroup != null)
foundContact.ContactGroupId = contactGroup.Id;
}
}
catch (Exception ex)
{
Trace.WriteLine("RemoveContactFromGroup: " + ex.Message);
throw;
}
}
public void AddContactToGroup(Contact contact, ContactGroup contactGroup)
{
if (contact == null)
throw new ArgumentNullException("contact");
if (contactGroup == null)
throw new ArgumentNullException("contactGroup");
try
{
var foundContact = _contacts.FirstOrDefault(c => c.Id == contact.Id);
if (foundContact != null)
foundContact.ContactGroupId = contactGroup.Id;
}
catch (Exception ex)
{
Trace.WriteLine("AddContactToGroup: " + ex.Message);
throw;
}
}
#endregion
}
}
<file_sep>using System;
namespace Contacts.Domain
{
public sealed class Contact
{
public Int32 Id { get; set; }
public String Email { get; set; }
public String FirstName { get; set; }
public String MiddleName { get; set; }
public String LastName { get; set; }
public String Phone { get; set; }
public Int32 ContactGroupId { get; set; }
public string FullName
{
get
{
return string.Format("{0} {1}{2}",
FirstName,
!string.IsNullOrEmpty(MiddleName) ? MiddleName + " " : string.Empty,
LastName);
}
}
public override string ToString()
{
return FullName;
}
}
}
<file_sep>using System;
using System.Diagnostics;
using System.Linq;
using System.Web.Mvc;
using Contacts.Domain;
using Contacts.Services;
using Contacts.Utilities;
namespace Contacts.Controllers
{
public class HomeController : Controller
{
private static ContactsService _contactService = new ContactsService();
#region Views
[Authorize]
public ActionResult Index()
{
ViewBag.Message = "Contacts ASP.NET MVC application";
return View();
}
public ActionResult About()
{
return View();
}
#endregion
#region Get methods
[Authorize]
[HttpPost]
public JsonResult GetAllGroups()
{
var result = new ServiceResponse<Object>();
try
{
result.Result = GetAllGroupsResponse();
}
catch (Exception ex)
{
Trace.WriteLine("GetAllGroups: " + ex.Message);
result.Message = ex.Message;
}
return JsonResponse(result);
}
[Authorize]
[HttpPost]
public JsonResult GetContact(int contactId)
{
var result = new ServiceResponse<Object>();
try
{
result.Result = GetContactResponse(contactId);
}
catch (Exception ex)
{
Trace.WriteLine("GetContact: " + ex.Message);
result.Message = ex.Message;
}
return JsonResponse(result);
}
#endregion
#region Add/Remove contact
[Authorize]
[HttpPost]
public JsonResult AddContact(string firstName, string middleName, string lastName, string email, string phone,
int contactGroupId)
{
var result = new ServiceResponse<Object>();
var contact = new Contact
{
FirstName = firstName,
MiddleName = middleName,
LastName = lastName,
Email = email,
Phone = phone,
ContactGroupId = contactGroupId
};
try
{
_contactService.AddContact(contact);
}
catch (Exception ex)
{
Trace.WriteLine("AddContact: " + ex.Message);
result.Message = ex.Message;
}
result.Result = GetAllGroupsResponse();
return JsonResponse(result);
}
[Authorize]
[HttpPost]
public JsonResult RemoveContact(int contactId)
{
var result = new ServiceResponse<Object>();
var contact = _contactService.GetContactById(contactId);
try
{
_contactService.RemoveContact(contact);
}
catch (Exception ex)
{
Trace.WriteLine("RemoveContact: " + ex.Message);
result.Message = ex.Message;
}
result.Result = GetAllGroupsResponse();
return JsonResponse(result);
}
#endregion
#region Add/Remove to/from group
[Authorize]
[HttpPost]
public JsonResult RemoveContactFromGroup(int contactId)
{
var result = new ServiceResponse<Object>();
Contact contact = null;
try
{
contact = _contactService.GetContactById(contactId);
}
catch (Exception ex)
{
Trace.WriteLine("RemoveContactFromGroup: " + ex.Message);
result.Message = "A contact does not exist";
}
if (contact != null)
{
try
{
_contactService.RemoveContactFromGroup(contact);
}
catch (Exception ex)
{
Trace.WriteLine("RemoveContactFromGroup: " + ex.Message);
result.Message = ex.Message;
}
}
result.Result = GetAllGroupsResponse();
return JsonResponse(result);
}
[Authorize]
[HttpPost]
public JsonResult AddContactToGroup(int contactId, int contactGroupId)
{
var result = new ServiceResponse<Object>();
Contact contact = null;
ContactGroup contactGroup = null;
try
{
contact = _contactService.GetContactById(contactId);
contactGroup = _contactService.GetGroupById(contactGroupId);
}
catch (Exception ex)
{
Trace.WriteLine("AddContactToGroup: " + ex.Message);
result.Message = "A contact or group does not exist";
}
if (contact != null && contactGroup != null)
{
try
{
_contactService.AddContactToGroup(contact, contactGroup);
}
catch (Exception ex)
{
Trace.WriteLine("AddContactToGroup: " + ex.Message);
result.Message = ex.Message;
}
}
result.Result = GetAllGroupsResponse();
return JsonResponse(result);
}
#endregion
#region Private methods
private Object GetAllGroupsResponse()
{
var groups = _contactService.GetAllGroups().OrderBy(g => g.Name).Select(g => new
{
id = g.Id,
name = g.Name,
contacts = _contactService.GetContactsByGroup(g).OrderBy(p => p.FullName).
Select(p => new {id = p.Id, name = p.FullName})
.ToList()
}).ToList();
var data = new
{
groups
};
return data;
}
private Object GetContactResponse(int contactId)
{
var contact = _contactService.GetContactById(contactId);
var data = new
{
name = contact.FullName,
email = contact.Email,
phone = contact.Phone,
group = _contactService.GetGroupById(contact.ContactGroupId).Name
};
return data;
}
private JsonResult JsonResponse(ServiceResponse<Object> serviceResponse)
{
var data = new
{
result = serviceResponse.Result,
message = serviceResponse.Message
};
return Json(data);
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using Contacts.Domain;
namespace Contacts.Contracts
{
internal interface IContactsService
{
IList<ContactGroup> GetAllGroups();
IList<Contact> GetContactsByGroup(ContactGroup contactGroup);
Contact GetContactById(int contactId);
ContactGroup GetGroupById(int contactGroupId);
Int32 AddContact(Contact contact);
void RemoveContact(Contact contact);
void RemoveContactFromGroup(Contact contact);
void AddContactToGroup(Contact contact, ContactGroup contactGroup);
}
}<file_sep>$(document).ready(function() {
contactManager = new ContactManagementControl();
});
function ContactManagementControl() {
this.contactsData = {};
this.activeGroup;
this.getAllGroupsPath = '/Home/GetAllGroups';
this.getContactPath = '/Home/GetContact';
this.addContactPath = '/Home/AddContact';
this.removeContactPath = '/Home/RemoveContact';
this.removeContactFromGroupPath = '/Home/RemoveContactFromGroup';
this.addContactToGroupPath = '/Home/AddContactToGroup';
this.addContactDialog = $("#addContactDialog");
this.removeContactDialog = $("#removeContactDialog");
this.removeContactFromGroupDialog = $("#removeContactFromGroupDialog");
this.addContactToGroupDialog = $("#addContactToGroupDialog");
this.regexName = /^[^<>`~!/@\#}$%:;,)(^?{&*=|'+\[\]\\]+$/;
this.regexEmail = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
this.regexPhone = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
this.removeContactButton = $("#removeContactButton");
this.addNewContactButton = $("#addNewContactButton");
this.removeContactFromGroupButton = $("#removeContactFromGroupButton");
this.addContactToGroupButton = $("#addContactToGroupButton");
this.currentId = $("#currentId");
this.currentFullName = $("#currentFullName");
this.currentEmail = $("#currentEmail");
this.currentPhone = $("#currentPhone");
this.currentGroup = $("#currentGroup");
this.removeContactButton.attr("disabled", "disabled");
this.requestContactsData();
}
ContactManagementControl.prototype = {
requestContactsData: function() {
var self = this;
this.showLoader();
$.ajax(
{
type: "POST",
url: self.getAllGroupsPath,
data: JSON.stringify(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(responseData) {
if (responseData.message) {
self.hideLoader();
self.errorHandler(responseData.message);
} else {
self.contactsData = responseData.result;
self.updateContactsView();
self.hideLoader();
}
}
});
$("#groupsLists .groups-list").change(function() {
self.activeGroup = $("#groupsLists .groups-list").val();
self.updateContactsView();
});
this.addContactDialog.dialog({
autoOpen: false,
width: 360,
title: "Add New Contact",
modal: true,
resizable: false,
draggable: false,
buttons: [{
id: "addContactOkButton",
text: "Ok",
click: function() {
var group = 1;
if (self.activeGroup != 0)
group = self.activeGroup;
if (self.validateContact(self.addContactDialog) === true) {
self.addContact(self.addContactDialog.find("input#firstName").val(),
self.addContactDialog.find("input#middleName").val(),
self.addContactDialog.find("input#lastName").val(),
self.addContactDialog.find("input#email").val(),
self.addContactDialog.find("input#phone").val(), group);
}
}
}, {
id: "addContactCancelButton",
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}],
open: function() {
$("#addContactOkButton").focus();
}
});
this.removeContactDialog.dialog({
autoOpen: false,
width: 300,
title: "Remove contact",
modal: true,
resizable: false,
draggable: false,
buttons: [{
id: "removeContactOkButton",
text: "Ok",
click: function() {
self.removeContact(self.currentId.val());
$(this).dialog("close");
self.removeContactButton.attr("disabled", "disabled");
}
}, {
id: "removeContactCancelButton",
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}],
open: function() {
$("#removeContactCancelButton").focus();
}
});
this.removeContactFromGroupDialog.dialog({
autoOpen: false,
width: 300,
title: "Remove Contact From Group",
modal: true,
resizable: false,
draggable: false,
buttons: [{
id: "removeContactFromGroupOkButton",
text: "Ok",
click: function() {
self.removeContactFromGroup(self.currentId.val());
$(this).dialog("close");
}
}, {
id: "removeContactFromGroupCancelButton",
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}],
open: function() {
$("#removeContactFromGroupCancelButton").focus();
}
});
this.addContactToGroupDialog.dialog({
autoOpen: false,
width: 300,
title: "Add Contact To Group",
modal: true,
resizable: false,
draggable: false,
buttons: [{
id: "addContactToGroupOkButton",
text: "Ok",
click: function() {
self.addContactToGroup(self.currentId.val(), self.activeGroup);
$(this).dialog("close");
}
}, {
id: "addContactToGroupCancelButton",
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}],
open: function() {
$("#addContactToGroupCancelButton").focus();
}
});
self.addNewContactButton.click(function() {
self.addContactDialog.find("input").val("");
self.addContactDialog.find(".error").text("");
self.addContactDialog.dialog("open");
});
self.removeContactButton.click(function() {
self.removeContactDialog.dialog("open");
});
self.removeContactFromGroupButton.click(function() {
self.removeContactFromGroupDialog.dialog("open");
});
self.addContactToGroupButton.click(function() {
self.addContactToGroupDialog.dialog("open");
});
},
updateContactsView: function() {
var self = this;
$("#groupsLists select.groups-list").empty().append('<option value="0">All Groups</option>');
$.each(this.contactsData.groups, function() {
$("#groupsLists select.groups-list").append('<option value="' + this.id + '">' + this.name + '</option>');
});
if (!this.activeGroup) {
this.activeGroup = $("#groupsLists select.groups-list").val();
} else {
$("#groupsLists select.groups-list").val(self.activeGroup);
}
$("#groupsLists .all-contacts-wrapper").empty();
$.each(this.contactsData.groups, function() {
if (self.activeGroup == 0 || this.id == self.activeGroup) {
$.each(this.contacts, function() {
self.setContactAction(this.id, this.name);
});
}
});
},
setContactAction: function(contactId, contactName) {
var self = this;
$("#groupsLists .all-contacts-wrapper").append('<div class="current-contact" id="contact_' + contactId + '"><a class="set-action"></a><span class="hover"></span>' + '<span class="name">' + contactName + '</span></div>');
$("#groupsLists .all-contacts-wrapper .current-contact").last().find("a.set-action").click(function() {
self.getContact(contactId);
});
},
getContact: function(contactId) {
var self = this;
var params = {
contactId: contactId
};
this.showLoader();
$.ajax(
{
type: "POST",
url: self.getContactPath,
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(responseData) {
if (responseData.message) {
self.hideLoader();
self.errorHandler(responseData.message);
} else {
self.currentId.val(contactId);
self.currentFullName.text(responseData.result.name);
self.currentEmail.attr("href", "mailto:" + responseData.result.email);
self.currentEmail.text(responseData.result.email);
self.currentPhone.attr("href", "callto:" + responseData.result.phone);
self.currentPhone.text(responseData.result.phone);
self.currentGroup.text(responseData.result.group);
self.hideLoader();
$("#groupsLists .contact-info-wrapper").show(500);
self.removeContactButton.removeAttr("disabled");
}
}
});
},
addContact: function(firstName, middleName, lastName, email, phone, contactGroupId) {
var self = this;
var params = {
firstName: firstName,
middleName: middleName,
lastName: lastName,
email: email,
phone: phone,
contactGroupId: contactGroupId
};
this.showLoader();
$.ajax(
{
type: "POST",
url: self.addContactPath,
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(responseData) {
if (responseData.message) {
self.hideLoader();
self.errorHandler(responseData.message);
} else {
self.contactsData = responseData.result;
self.addContactDialog.dialog("close");
self.updateContactsView();
self.hideLoader();
}
}
});
},
removeContact: function(contactId) {
var self = this;
var params = {
contactId: contactId
};
this.showLoader();
$.ajax(
{
type: "POST",
url: self.removeContactPath,
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(responseData) {
if (responseData.message) {
self.hideLoader();
self.errorHandler(responseData.message);
} else {
$("#groupsLists .contact-info-wrapper").hide(500);
self.contactsData = responseData.result;
self.updateContactsView();
self.hideLoader();
}
}
});
},
removeContactFromGroup: function(contactId) {
var self = this;
var params = {
contactId: contactId
};
this.showLoader();
$.ajax(
{
type: "POST",
url: self.removeContactFromGroupPath,
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(responseData) {
if (responseData.message) {
self.hideLoader();
self.errorHandler(responseData.message);
} else {
self.getContact(self.currentId.val());
self.contactsData = responseData.result;
self.updateContactsView();
self.hideLoader();
}
}
});
},
addContactToGroup: function(contactId, contactGroupId) {
var self = this;
var params = {
contactId: contactId,
contactGroupId: contactGroupId
};
this.showLoader();
$.ajax(
{
type: "POST",
url: self.addContactToGroupPath,
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(responseData) {
if (responseData.message) {
self.hideLoader();
self.errorHandler(responseData.message);
} else {
self.getContact(self.currentId.val());
self.contactsData = responseData.result;
self.updateContactsView();
self.hideLoader();
}
}
});
},
validateContact: function(contactDialog) {
var isValid = true;
if (!this.regexName.test(contactDialog.find("input#firstName").val())) {
contactDialog.find(".first-name .error").text("The first name is invalid");
isValid = false;
} else {
contactDialog.find(".first-name .error").text("");
}
if (contactDialog.find("input#middleName").val() != "") {
if (!this.regexName.test(contactDialog.find("input#middleName").val())) {
contactDialog.find(".middle-name .error").text("The middle name is invalid");
isValid = false;
}
} else {
contactDialog.find(".middle-name .error").text("");
}
if (!this.regexName.test(contactDialog.find("input#lastName").val())) {
contactDialog.find(".last-name .error").text("The last name is invalid");
isValid = false;
} else {
contactDialog.find(".last-name .error").text("");
}
if (!this.regexEmail.test(contactDialog.find("input#email").val())) {
contactDialog.find(".email .error").text("The e-mail is invalid");
isValid = false;
} else {
contactDialog.find(".email .error").text("");
}
if (!this.regexPhone.test(contactDialog.find("input#phone").val())) {
contactDialog.find(".phone .error").text("The phone is invalid");
isValid = false;
} else {
contactDialog.find(".phone .error").text("");
}
return isValid;
},
errorHandler: function(errorText) {
alert(errorText);
this.hideLoader();
},
showLoader: function() {
$("#groupsLists .load-hover").show();
},
hideLoader: function() {
$("#groupsLists .load-hover").hide();
}
};<file_sep>namespace Contacts.Utilities
{
public class ServiceResponse<T>
{
public string Message { get; set; }
public T Result { get; set; }
}
}<file_sep>#Contacts
Demo application for managing contacts. Try here http://programulyacontacts.azurewebsites.net
| 695e5a27a32f38b39e79adcd060194d7bf7e895b | [
"JavaScript",
"C#",
"Markdown"
] | 8 | C# | programulya/Contacts | 659d804b9a084268742508644223c54313f3880b | 06e77bd77e3c16fd0261b61d2b296c103c2d9b49 |
refs/heads/master | <repo_name>amyhre16/sequelizedBurger<file_sep>/controllers/burgers_controller.js
'use strict';
// import /models/burgers.js
var burger = require('./../models');
// export the function with routes
// app is passed in from server.js
// all routes listen to / route
module.exports = function(app) {
app.get('/', function(req, res) {
/*
SELECT * FROM burgers
results is the array containing results from the query
*/
burger.Burger.findAll({}).then(function(results) {
/*
burgers is the array that contains the rows from the query
*/
var burgers = [];
for (var i = 0; i < results.length; i++) {
// push each row to the burgers array
burgers.push(results[i].dataValues);
}
// render burgers to the index.handlebars page
res.render('index', {burgers: burgers});
});
});
app.post('/', function(req, res) {
/*
INSERT INTO burgers (burger_name) VALUES (req.body.burger_name)
*/
burger.Burger.create({
burger_name: req.body.burger_name
}).then(function(results) {
// redirect page to home route
res.redirect('/');
});
});
/*
UPDATE burgers SET devoured = 1 WHERE id = req.body.id
*/
app.put('/', function(req, res) {
burger.Burger.update({
devoured: true
}, {
where: {
id: req.body.id
}
}).then(function(results) {
// redirect page to home route
res.redirect('/');
});
});
}; | 43547cf9c59a81c0d54f9c7f89041e5bd944ddda | [
"JavaScript"
] | 1 | JavaScript | amyhre16/sequelizedBurger | 918516fc306d5d2abbeea2fff4598e2b6c82df45 | 24daf7dd47ae349d90ae21aa7a7a161ba8eb4c8f |
refs/heads/master | <repo_name>zeclo/Vue.js<file_sep>/vue-blog/src/store/index.ts
import { createStore } from 'vuex';
export default createStore({
// 変数定義(初期値設定も行う)
state: {
count: 10,
stations2: [
// 連想配列の定義
{ sakuradouri: '名古屋' },
{ sakuradouri: '国際センター' },
{ sakuradouri: '丸の内' },
],
csvData: [
['サイト名1', 'サイトURL1', false],
['サイト名2', 'サイトURL2', false],
['サイト名3', 'サイトURL3', false],
],
hoverFlag: false,
},
// gettersオプションで定義
getters: {
// stateから別の値を計算
squared(state) {
return state.count * state.count;
},
// 他のgettersの値を使うことも可能(省略技法ももちろん使える)
cubed: (state, getters) => state.count * getters.squared,
},
// mutationsオプションで定義
mutations: {
// 'increment'mutationを定義
increment(state, payload) {
state.count += payload.amount;
},
hoverFlagOn2(state, val) {
state.csvData[val][2] = true;
},
hoverFlagOff2(state, val) {
state.csvData[val][2] = false;
},
},
// actionオプションで定義
actions: {
hoverFlagOn(ctx, val) {
ctx.commit('hoverFlagOn2', val);
},
hoverFlagOff(ctx, val) {
ctx.commit('hoverFlagOff2', val);
},
},
modules: {
},
});
<file_sep>/sample/src/router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import HelloWorld2 from '@/components/HelloWorld2';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld2',
component: HelloWorld2,
},
],
});
| b025b2e45b78f378036d11519b581b663aabc159 | [
"JavaScript",
"TypeScript"
] | 2 | TypeScript | zeclo/Vue.js | 0cc3ee12177fa5bcac64a0c58d5aca63dd6e1110 | 4a04766eb6212e56897fc019e8e6b90580bd943c |
refs/heads/master | <repo_name>art4711/go_decoder_test<file_sep>/README.md
# Performance of decoding stored data in Go.
Tests to see the performance of various ways to retreive data in Go.
## Test setup:
### Choices
1. I don't care about encoding at this moment. Imagine a file
pre-generated at some point in time that we need to read efficiently
at run-time.
2. I store floats because at least encoding/binary has optimizations
for integers. So imagine this is a game that wants to store vertex
data.
### Details
What we do is to generate an array of 1 million (not at all) random
float32 numbers and store them in a file, the test tests that what we
get is at least close to what is expected, then the benchmarks test
decoding all the floating point values into an array (and make a sum
of that array, because why not).
## Encodings:
### bi - normal file I/O with encoding/binary
Reads the file through `binary.Read`, couldn't be simpler.
### js - normal file I/O with encoding/json
Reads the file through `json.Decode`.
### jd - deflated file I/O with encoding/json
Reads the file through `flate.Reader` and `json.Decode`. Added to see
if the performance of json was caused by the larger amount of data
that needs to be read (it wasn't).
### gb - normal file I/O with encoding/gob
Reader the file through `gob.Decode`. Maybe the standard wire format
performs better (spoiler: it doesn't).
### bc - ioutil.ReadALL I/O with brutal casting
Reads the whole file with `ioutil.ReadAll`, takes the byte slice,
casts it to `reflect.SliceHeader`, copies the slice header,
performs some brain surgery on it, casts it to our expected slice.
### fm - mmap of file and hand-crafting a []float32 slice
Let's see how things perfom when we can use modern (30 years old)
memory management facilities of an operating system and don't need
to copy data back and forth.
### ba - io.ReadAt I/O with brutal casting
I didn't like that bc was doing more memory allocations than expected.
So I figured I would try `io.ReadAt` to get my byte slice. Yup, even
better.
### sl - sqlite3
Just put all values into a one-column table in Sqlite3. Fetch all rows
(sorted). I'm expecting this benchmark to run on a geological time
scale.
### bx - more or less equivalent to bi
Just to study the code of encoding/binary I extracted the relevant
parts of its code. This performs more or less the same as bi which
is a good indication that I found the right code.
### by - various experiments on how to make bx faster
Here I performed experiments to see how to make encoding/binary
faster. Trying to get the reflection based code fast failed,
everything I tried gave at most 50% speed improvements (like not
trying to figure out the type of the value of every slice element over
and over and over again). So let's see how encoding/binary would
perform if floats had a fast path just like ints.
## Results.
The test is done on a relatively new MacBook Pro. The disk (SSD) is
irrelevant because we're not timing writing and since all the data is
generated on test startup it will be in the buffer cache during the
test so we shouldn't be hitting the disk at all (if we do then there's
so much load on the machine that the test results are invalid anyway).
(rounding to 2 significant digits below)
encoding | consumption speed | file size |
---------|-------------------|-----------|
bi | 120 MB/s | 4MB |
js | 8.0 MB/s | 11MB |
jd | 6.0 MB/s | 4.5MB |
fm | 3400 MB/s | 4MB |
gb | 90 MB/s | 5.9MB |
bc | 624 MB/s | 4MB |
ba | 1367 MB/s | 4MB |
sl | 2.6 MB/s | 18MB |
bx | 130 MB/s | 4MB |
by | 540 MB/s | 4MB |
Raw data from one test run:
$ go test -bench .
PASS
BenchmarkReadBinary 50 35737438 ns/op 117.36 MB/s 8388690 B/op 4 allocs/op
BenchmarkReadJSON 2 525182241 ns/op 7.99 MB/s 54173740 B/op 1026677 allocs/op
BenchmarkReadJDef 2 696049978 ns/op 6.03 MB/s 54236860 B/op 1027243 allocs/op
BenchmarkReadFmap 1000 1227830 ns/op 3416.03 MB/s 32 B/op 1 allocs/op
BenchmarkReadGob 50 51869066 ns/op 80.86 MB/s 10384991 B/op 320 allocs/op
BenchmarkReadBrutal 200 6716936 ns/op 624.44 MB/s 16775281 B/op 15 allocs/op
BenchmarkReadBrutalA 500 3066435 ns/op 1367.81 MB/s 4194304 B/op 1 allocs/op
BenchmarkReadSqlite3 1 1596527775 ns/op 2.63 MB/s 71190440 B/op 2097197 allocs/op
BenchmarkReadBinx 100 32981009 ns/op 127.17 MB/s 8388673 B/op 4 allocs/op
BenchmarkReadBiny 200 7741075 ns/op 541.82 MB/s 8388651 B/op 3 allocs/op
### Additional result.
An C program equivalent to `ba` performs only 1.5x faster (around
2GB/s), so the problem is not in the I/O subsystem in Go, it's all in
the decoding and encoding. Something equivalent to fmap performs 1.2x
faster. Except if the mmap:ed array isn't `volatile` and we don't use
the sum which allows the compiler to optimize away everything and then
it actually performs 1132712x faster.
## Conclusion
Of the idiomatic ways of decoding things raw binary is the fastest as
expected. gob isn't that far behind which is good news because that
gives us type safety without ruining performance (compared to doing it
entirely raw). JSON is slow even though I didn't expect it to be so
catastrophically slow. Compressed JSON is even slower (tested to rule
out file size that could be the reason for JSON to be slow).
What surprised me the most was how sqlite3 didn't perform that bad at
all. It's the worst possible database schema and we still a third of
the performance of JSON. Shoving multiple values into the same row did
speed it up by a factor of 2 or so, I suspect the cost is actually in
the reflections in rows.Scan, not the database itself.
Breaking the rules of course gives us better performance, but I didn't
expect it to be so much better. Even the raw encoding/binary is 6
times slower than the brutal cast that does the same amount of file
I/O and should do the same amount of memory allocations (but somehow
does twice (I figured it out, ioutil.ReadAll does something stupid,
io.ReadAt doesn't, reflected in the `ba` test)). Mmap and a brutal
cast, of course, outperforms everything by a wide margin, as it should
be.
I understand that modern systems are all about sending JSON over HTTP,
but that's no excuse for a systems programming language to be so far
away from decent performance when it comes to reading raw data.
The most hilarious thing was when I dug even deeper in `by`. We go
through all the effort to properly decode the data through
endian-independent wrappers so that we don't switch on the endianness
of the machine we're running on, all is done with type safety and how
modern, pretty, well-written code should be written without any
assumptions about how memory works and then at the end (this is from
the math package):
func Float32frombits(b uint32) float32 { return *(*float32)(unsafe.Pointer(&b)) }
So deep down, even the go programmers gave up at this level. Which
makes the whole effort completely wasted, we end up with a brutal cast
anyway. You can't abstract away data and memory. Your code is running
on a computer, not a mathematically and philosophically pure computer
science device. Sometimes you just need [to think about hex numbers
and their relationships with the operating system, the hardware, and
ancient blood
rituals](http://research.microsoft.com/en-us/people/mickens/thenightwatch.pdf).
## Code
The test code in [decode_test.go](decode_test.go) should be simple
enough to understand. I went a bit wild abstracting things, but it
should be clear what part does what. The filemap code it depends on
may or may not work on any operating system other than MacOS because
there is some type screwup going on in CGO. It should be trivial to
figure it out (and even more trivial to comment out that test).
The C code to do the same thing is in
[decode_test.c.go_test_picks_this_up](decode_test.c.go_test_picks_this_up)
named that way because `go test` wants to compile c files for some
reason. It uses [my stopwatch code](https://github.com/art4711/timing).
It's written as lazily as I could get away with and wants a file
generated by first running go test.<file_sep>/decode_test.go
/*
* Copyright (c) 2015 <NAME> <<EMAIL>>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package decode_test
import (
"testing"
"math/rand"
"math"
"encoding/binary"
"encoding/json"
"encoding/gob"
"os"
"fmt"
"io"
"io/ioutil"
"github.com/art4711/filemap"
"compress/flate"
"unsafe"
"reflect"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"errors"
)
const size = 1024*1024
const expected = float32(523902.12)
type tested interface {
Generate(string, []float32)
OpenReader(string) error
Reset()
ReadAndSum(testing.TB) float32
Close()
}
type simpleFileOC struct {
f *os.File
}
func (sf *simpleFileOC)OpenReader(fname string) error {
f, err := os.Open(fname)
sf.f = f
return err
}
func (sf *simpleFileOC)Close() {
sf.f.Close()
}
type simpleFile struct {
simpleFileOC
}
func (sf *simpleFile)Reset() {
sf.f.Seek(0, os.SEEK_SET)
}
type binFile struct {}
func (b *binFile)Generate(fname string, floatarr []float32) {
file, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
panic(err)
}
defer file.Close()
err = binary.Write(file, binary.LittleEndian, floatarr)
if err != nil {
panic(err)
}
}
/*
* File I/O with encoding/binary to read and write the data
*/
type bi struct {
simpleFile
binFile
}
func (bi *bi)ReadAndSum(tb testing.TB) float32 {
floatarr := make([]float32, size)
if err := binary.Read(bi.f, binary.LittleEndian, floatarr); err != nil {
tb.Fatal(err)
}
s := float32(0)
for _, v := range floatarr {
s += v
}
return s
}
/*
* File I/O with encoding/json to read and write the data
*/
type js struct {
simpleFile
}
func (js *js)Generate(fname string, floatarr []float32) {
file, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
panic(err)
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.Encode(floatarr)
}
func (js *js)ReadAndSum(tb testing.TB) float32 {
floatarr := make([]float32, size)
decoder := json.NewDecoder(js.f)
if err := decoder.Decode(&floatarr); err != nil {
tb.Fatal(err)
}
s := float32(0)
for _, v := range floatarr {
s += v
}
return s
}
/*
* Deflated file I/O with encoding/json to read and write the data
*/
type jd struct {
simpleFile
}
func (jd *jd)Generate(fname string, floatarr []float32) {
file, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
panic(err)
}
defer file.Close()
wr, err := flate.NewWriter(file, flate.DefaultCompression)
if err != nil {
panic(err)
}
defer wr.Close()
encoder := json.NewEncoder(wr)
encoder.Encode(floatarr)
}
func (jd *jd)ReadAndSum(tb testing.TB) float32 {
floatarr := make([]float32, size)
r := flate.NewReader(jd.f)
defer r.Close()
decoder := json.NewDecoder(r)
if err := decoder.Decode(&floatarr); err != nil {
tb.Fatal(err)
}
s := float32(0)
for _, v := range floatarr {
s += v
}
return s
}
/*
* mmap:ed file I/O with brutal casting to read the data.
*/
type fm struct {
fmap *filemap.Map
binFile
}
func (fm *fm)ReadAndSum(tb testing.TB) float32 {
sl, err := fm.fmap.Slice(4 * size, 0, size);
if err != nil {
tb.Fatal(err)
}
floatarr := *(*[]float32)(sl)
s := float32(0)
for _, v := range floatarr {
s += v
}
return s
}
func (fm *fm)OpenReader(fname string) error {
f, err := os.Open(fname)
if err != nil {
return err
}
defer f.Close()
fm.fmap, err = filemap.NewReader(f)
return err
}
func (fm *fm)Reset() {
// no need to do anything.
}
func (fm *fm)Close() {
fm.fmap.Close()
}
/*
* ioutil.ReadAll with brutal casting to read the data.
*/
type bc struct {
simpleFile
binFile
}
func (bc *bc)ReadAndSum(tb testing.TB) float32 {
b, err := ioutil.ReadAll(bc.f)
if err != nil {
tb.Fatal(err)
}
bsl := (*reflect.SliceHeader)(unsafe.Pointer(&b))
fsl := *bsl
fsl.Len /= 4
fsl.Cap /= 4
floatarr := *(*[]float32)(unsafe.Pointer(&fsl))
s := float32(0)
for _, v := range floatarr {
s += v
}
return s
}
/*
* File I/O with ReadAt and brutal casting to read the data.
*/
type ba struct {
simpleFileOC
binFile
}
func (ba *ba)ReadAndSum(tb testing.TB) float32 {
b := make([]byte, size * 4)
n, err := ba.f.ReadAt(b, 0)
if err != nil {
tb.Fatal(err)
}
if n != size * 4 {
tb.Fatalf("readat: %v", n)
}
bsl := (*reflect.SliceHeader)(unsafe.Pointer(&b))
fsl := *bsl
fsl.Len /= 4
fsl.Cap /= 4
floatarr := *(*[]float32)(unsafe.Pointer(&fsl))
s := float32(0)
for _, v := range floatarr {
s += v
}
return s
}
func (ba *ba)Reset() {
}
/*
* File I/O with encoding/gob to read and write the data
*/
type gb struct {
simpleFile
}
func (gb *gb)Generate(fname string, floatarr []float32) {
file, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
panic(err)
}
defer file.Close()
encoder := gob.NewEncoder(file)
encoder.Encode(floatarr)
}
func (gb *gb)ReadAndSum(tb testing.TB) float32 {
floatarr := make([]float32, size)
decoder := gob.NewDecoder(gb.f)
if err := decoder.Decode(&floatarr); err != nil {
tb.Fatal(err)
}
s := float32(0)
for _, v := range floatarr {
s += v
}
return s
}
/*
* File I/O with more or less the same thing that encoding/binary does to read and write the data
*/
type bx struct {
simpleFile
binFile
}
type bxcoder struct {
buf []byte
}
func (d *bxcoder) uint32() uint32 {
x := uint32(d.buf[0]) | uint32(d.buf[1]) << 8 | uint32(d.buf[2]) << 16 | uint32(d.buf[3]) << 24
d.buf = d.buf[4:]
return x
}
func (d *bxcoder)value(v reflect.Value) {
switch v.Kind() {
case reflect.Slice:
l := v.Len()
for i := 0; i < l; i++ {
d.value(v.Index(i))
}
case reflect.Float32:
v.SetFloat(float64(math.Float32frombits(d.uint32())))
default:
panic("this is not a generic implementation")
}
}
func (bx *bx)ReadAndSum(tb testing.TB) float32 {
floatarr := make([]float32, size)
v := reflect.ValueOf(floatarr)
sz := v.Len() * int(v.Type().Elem().Size())
bxc := &bxcoder{}
bxc.buf = make([]byte, sz)
if _, err := io.ReadFull(bx.f, bxc.buf); err != nil {
tb.Fatal(err)
}
bxc.value(v)
s := float32(0)
for _, v := range floatarr {
s += v
}
return s
}
/*
* Same as bx, but let's try to be smart about it.
*/
type by struct {
simpleFile
binFile
}
func intDataSize(data interface{}) int {
switch data := data.(type) {
case []float32:
return 4 * len(data)
}
return 0
}
func u32(b []byte) uint32 {
return (uint32(b[0]) | uint32(b[1]) << 8 | uint32(b[2]) << 16 | uint32(b[3]) << 24)
}
func (by *by)read(r io.Reader, data interface{}) error {
if n := intDataSize(data); n != 0 {
var b [8]byte
var bs []byte
if n > len(b) {
bs = make([]byte, n)
} else {
bs = b[:n]
}
if _, err := io.ReadFull(r, bs); err != nil {
return err
}
switch data := data.(type) {
case []float32:
for i := range data {
data[i] = math.Float32frombits(u32(bs[4*i:]))
}
}
return nil
}
return errors.New("not reached, please")
}
func (by *by)ReadAndSum(tb testing.TB) float32 {
floatarr := make([]float32, size)
err := by.read(by.f, floatarr)
if err != nil {
tb.Fatal(err)
}
s := float32(0)
for _, v := range floatarr {
s += v
}
return s
}
/*
* Sqlite3 dumb storage.
*/
type sl struct {
db *sql.DB
stmt *sql.Stmt
}
func (sl *sl)Generate(fname string, floatarr []float32) {
os.Remove(fname)
db, err := sql.Open("sqlite3", fname)
if err != nil {
panic(err)
}
defer db.Close()
cStmt := "create table foo (id integer not null primary key, value float)"
_, err = db.Exec(cStmt)
if err != nil {
panic(err)
}
tx, err := db.Begin()
if err != nil {
panic(err)
}
stmt, err := tx.Prepare("insert into foo(value) values (?)")
if err != nil {
panic(err)
}
for _, v := range floatarr {
if _, err := stmt.Exec(v); err != nil {
panic(err)
}
}
tx.Commit()
stmt.Close()
}
func (sl *sl)OpenReader(fname string) error {
db, err := sql.Open("sqlite3", fname)
if err != nil {
return err
}
sl.db = db
sl.stmt, err = sl.db.Prepare("select value from foo order by id")
if err != nil {
panic(err)
}
return err
}
func (sl *sl)ReadAndSum(tb testing.TB) float32 {
rows, err := sl.stmt.Query()
if err != nil {
tb.Fatal(err)
}
defer rows.Close()
floatarr := make([]float32, size)
i := 0
for rows.Next() {
err = rows.Scan(&floatarr[i])
if err != nil {
tb.Fatal(err)
}
i++
}
if i != size {
tb.Fatal(fmt.Errorf("rows mismatch: %d != %d", i, size));
}
s := float32(0)
for _, v := range floatarr {
s += v
}
return s
}
func (sl *sl)Reset() {
}
func (sl *sl)Close() {
sl.db.Close()
}
type mm struct {
fa []float32
}
func (mm *mm) Generate(fname string, floatarr []float32) {
mm.fa = floatarr
}
func (mm *mm) OpenReader(string) error {
return nil
}
func (mm *mm) Reset() {
}
func (mm *mm) ReadAndSum(testing.TB) float32 {
s := float32(0)
for _, v := range mm.fa {
s += v
}
return s
}
func (mm *mm) Close() {
}
const (
T_BI = iota
T_JS
T_JD
T_FM
T_GB
T_BC
T_BA
T_SL
T_BX
T_BY
T_MM
)
type tt struct{
tt tested
fname string
}
var toTest = [...]tt{
T_BI: { &bi{}, "float-file.bin" },
T_JS: { &js{}, "float-file.json" },
T_JD: { &jd{}, "float-file.json.z" },
T_FM: { &fm{}, "float-file.fm" },
T_GB: { &gb{}, "float-file.gob" },
T_BC: { &bc{}, "float-file.bc" },
T_BA: { &ba{}, "float-file.ba" },
T_SL: { &sl{}, "float-file.sl" },
T_BX: { &bx{}, "float-file.bx" },
T_BY: { &by{}, "float-file.by" },
T_MM: { &mm{}, "" },
}
/* We're not testing encoding, just decoding. */
func init() {
floatarr := [size]float32{}
rand.Seed(4711)
for i := range floatarr {
floatarr[i] = rand.Float32()
}
for _, te := range toTest {
te.tt.Generate(te.fname, floatarr[:])
}
}
func genericBenchmark(b *testing.B, which int) {
te := toTest[which]
b.ReportAllocs()
err := te.tt.OpenReader(te.fname)
if err != nil {
b.Fatal(err)
}
defer te.tt.Close()
for t := 0; t < b.N; t++ {
te.tt.Reset()
te.tt.ReadAndSum(b)
b.SetBytes(size * 4)
}
}
func BenchmarkReadBinary(b *testing.B) {
genericBenchmark(b, T_BI)
}
func BenchmarkReadJSON(b *testing.B) {
genericBenchmark(b, T_JS)
}
func BenchmarkReadJDef(b *testing.B) {
genericBenchmark(b, T_JD)
}
func BenchmarkReadFmap(b *testing.B) {
genericBenchmark(b, T_FM)
}
func BenchmarkReadGob(b *testing.B) {
genericBenchmark(b, T_GB)
}
func BenchmarkReadBrutal(b *testing.B) {
genericBenchmark(b, T_BC)
}
func BenchmarkReadBrutalA(b *testing.B) {
genericBenchmark(b, T_BA)
}
func BenchmarkReadSqlite3(b *testing.B) {
genericBenchmark(b, T_SL)
}
func BenchmarkReadBinx(b *testing.B) {
genericBenchmark(b, T_BX)
}
func BenchmarkReadBiny(b *testing.B) {
genericBenchmark(b, T_BY)
}
func BenchmarkReadMM(b *testing.B) {
genericBenchmark(b, T_MM)
}
func genericTest(t *testing.T, which int) {
te := toTest[which]
err := te.tt.OpenReader(te.fname)
if err != nil {
t.Fatal(err)
}
defer te.tt.Close()
s := te.tt.ReadAndSum(t)
if math.Abs(float64(s - expected)) > 0.005 {
t.Fatalf("%v != %v, did the pseudo-random generator change?", s, expected)
}
}
func TestSumBinary(t *testing.T) {
genericTest(t, T_BI)
}
func TestSumJSON(t *testing.T) {
genericTest(t, T_JS)
}
func TestSumJDef(t *testing.T) {
genericTest(t, T_JD)
}
func TestSumFmap(t *testing.T) {
genericTest(t, T_FM)
}
func TestSumGob(t *testing.T) {
genericTest(t, T_GB)
}
func TestSumBrutal(t *testing.T) {
genericTest(t, T_BC)
}
func TestSumBrutalA(t *testing.T) {
genericTest(t, T_BA)
}
func TestSumSqlite3(t *testing.T) {
genericTest(t, T_SL)
}
func TestSumBinx(t *testing.T) {
genericTest(t, T_BX)
}
func TestSumBiny(t *testing.T) {
genericTest(t, T_BY)
}
func TestSumMM(t *testing.T) {
genericTest(t, T_MM)
}
| 74b676a7294c0f9199728f315451dfbfe4d59924 | [
"Markdown",
"Go"
] | 2 | Markdown | art4711/go_decoder_test | 38da218a5141699ff9c7dc261a3bcd841343215f | f2634f5d601c10ec90a3b558288d8cb4e7cde9af |
refs/heads/master | <repo_name>GDGMonterrey/firemaps<file_sep>/gulpfile.js
var gulp = require('gulp'),
coffee = require('gulp-coffee'),
jade = require('gulp-jade'),
less = require('gulp-less');
gulp.task('transpile-jade', function(){
return gulp.src("app/jade/index.jade")
.pipe(jade())
.pipe(gulp.dest('build/'))
});
gulp.task('transpile-less', function(){
return gulp.src("app/less/map.less")
.pipe(less())
.pipe(gulp.dest('build/css'))
});
gulp.task('transpile-coffee', function(){
return gulp.src("app/coffee/map.coffee")
.pipe(coffee({bare: true}))
.pipe(gulp.dest('build/js'))
});
gulp.task('default', ['transpile-jade', 'transpile-less', 'transpile-coffee']);<file_sep>/README.md
# firemaps
Puedes ver nuestros avances [aquí](https://firemaps.firebaseapp.com)
#Requisitos
* Node
* Gulp
#Instalación
Instala los paquetes para transpilar los archivos fuente.
```
npm install
```
Ejecuta el comando gulp para ejecutar las task de transpilación, este construira una carpeta build con los archivos listos para agregar a un servidor.
| a0836967cc2460ef9252b9d13d8f62854f1d10d6 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | GDGMonterrey/firemaps | caf206aaf30a5733c3f8f50fe6ffbdd7885b446f | dbd47b653e6934d281a4a04c46bba2b9a6d71d44 |
refs/heads/master | <file_sep># P5
Project 5 for OpenClassrooms.
The goal of this project is to build the frontend for an eCommerce Website.
For the existing backend, clone the repository below and follow the instructions in the README.md file.
--> https://github.com/OpenClassrooms-Student-Center/JWDP5
For the frontend, clone this repository and start up the live server in VS code.
<file_sep>// Get single prod details from the API via prod ID
const urlParams = new URLSearchParams(window.location.search);
const productId = urlParams.get('id');
let img = document.getElementById('productImg');
let product = document.getElementById('productName');
let price = document.getElementById('productPrice');
let description = document.getElementById('productDescription');
let productOptions = document.getElementById('productOptions');
// Store the product object in outer scope
let productDetails = {};
// Dynamically show selected item
function getProduct() {
fetch('http://localhost:3000/api/cameras/' + productId)
.then(response => response.json())
.then(data => {
productDetails = data;
img.src = `${data.imageUrl}`;
product.textContent = `${data.name}`;
price.textContent = `${data.price / 100}.00$`;
description.textContent = `${data.description}`;
for (let i = 0; i < data.lenses.length; i++) {
let option = document.createElement('option');
option.setAttribute('id', 'option')
option.value = data.lenses[i];
option.innerHTML = data.lenses[i];
productOptions.appendChild(option);
}
})
.catch(err => console.log(err))
};
getProduct();
// Add to cart
let addBtn = document.getElementById('addToCart')
// Select lens
productOptions.addEventListener('change', (e) => {
// save value to products array
let lens = e.target.value
addBtn.disabled = false
addBtn.innerHTML = 'Add to cart';
});
// Save product to localstorage (add to cart)
addBtn.onclick = function addToLocalStorage() {
product = {
"id": productDetails._id,
"name": productDetails.name,
"price": productDetails.price,
"imageUrl": productDetails.imageUrl,
"quantity": 1,
"option": productOptions.value
};
if (localStorage.getItem("productsInCart") === null) { //checking if local storage is 'null' and adding item if 'true'
localStorage.setItem("productsInCart", JSON.stringify([]));
};
let cart = JSON.parse(localStorage.getItem("productsInCart")); //assigning local storage item to a variable
if (cart.length == 0) { //if there are no objects in the cart it will push active camera
cart.push(product);
addBtn.innerHTML = 'Added!';
addBtn.disabled = true
console.log("Item added to cart!");
console.log(product);
} else {
let index = cart.findIndex(o => o.id == product.id + product.option); //checking if camera with current id is already in local storage
if (index != -1) { //if so, alert user
console.log("Item already added to cart!");
alert("Item already added to cart!");
} else { //if not, add to cart
cart.push(product);
addBtn.innerHTML = 'Added!';
addBtn.disabled = true
console.log("Item added to cart!");
console.log(product);
};
};
localStorage.setItem("productsInCart", JSON.stringify(cart)); //saving item back to local storage
};
<file_sep>const allProducts = document.getElementById('allProducts');
// Iterate over the data, create product cards, and append them to the dom
fetch('http://localhost:3000/api/cameras')
// Turn json into js array of objects
.then(response => response.json())
.then(data => {
for(let i = 0; i < data.length; i++) {
// Create a box
let box = document.createElement('div');
box.classList.add('item');
box.classList.add('col-lg-4');
box.classList.add('col-md-6');
box.setAttribute("id", "products");
//Create box for spacing
let content = document.createElement('div')
content.classList.add('content')
// Image
let img = document.createElement('img');
img.setAttribute('src', data[i].imageUrl)
img.classList.add('img')
//Single page link for img
let linkWrapper = document.createElement('a');
linkWrapper.href = `product.html?id=${data[i]._id}`
linkWrapper.appendChild(img)
//Name
let name = document.createElement('h2');
name.innerHTML = data[i].name;
linkWrapper.appendChild(name) //Single page link for name
// Price
let price = document.createElement('p');
price.innerHTML = `${data[i].price / 100}.00$`;
price.classList.add('price')
// Description
let description = document.createElement('p');
description.innerHTML = data[i].description;
description.classList.add('description')
//Append them
content.appendChild(linkWrapper);
content.appendChild(price);
content.appendChild(description);
box.appendChild(content)
// Append it to something!
allProducts.appendChild(box);
// Create anchor element.
let a = document.createElement('a');
a.style.fontWeight = "500"
// Set the href property.
a.href = `product.html?id=${data[i]._id}`;
// Create the text node for anchor element.
let link = document.createTextNode("See lens options");
// Append the text node to anchor element.
a.appendChild(link);
// Set the title.
a.title = "This is Link";
// Append the anchor element .
content.append(a);
}
})
.catch(err => console.log(err));<file_sep>// CART CONTENT (WHEN EMPTY)
let emptyContent = document.getElementById('emptyContent');
let box = document.getElementById('cartProducts');
function removeContent() {
emptyContent.style.display = "none"
}
// DYNAMIC CART ITEMS
let cart = document.getElementById('cartProducts')
let cartItems = JSON.parse(localStorage.getItem("productsInCart"));
for (let i = 0; i < cartItems.length; i++){
product = cartItems[i];
// Create box
let box = document.createElement('div');
box.classList.add('cartProduct')
box.setAttribute('id', 'cartProduct')
cart.appendChild(box); //append box to cart
// IMG
let img = document.createElement('img');
img.classList.add('prodImage')
img.setAttribute('src', product.imageUrl);
box.appendChild(img); //append it to box
// Create container
let container = document.createElement('div');
container.classList.add('prodContainer')
container.setAttribute('id', 'prodContainer')
box.appendChild(container); //append box to cart
// Title
let title = document.createElement('h3');
title.classList.add('title');
title.innerHTML = `${product.name}`;
container.appendChild(title); //append it to box
// Option
let option = document.createElement('h3');
option.classList.add('option', 'sectionItem');
option.innerHTML = `${product.option}`;
container.appendChild(option); //append it to box
// Quantity
let quantity = document.createElement('input');
quantity.classList.add('itemQuantity', 'sectionItem');
quantity.setAttribute('id', 'itemQuantity')
quantity.setAttribute('type', 'number');
quantity.setAttribute('value', product.quantity);
quantity.setAttribute('name', 'quantity');
quantity.setAttribute('min', 1);
quantity.setAttribute('data-index', i);
container.appendChild(quantity); //append it to container
// Price
let price = document.createElement('h3');
price.classList.add('price');
price.setAttribute('id', 'productPrice');
price.innerHTML = '$' + `${product.price}`;
container.appendChild(price); //append it to box
// Remove
let remove = document.createElement('img');
remove.src = "img/bin.png";
remove.classList.add('removeBtn');
remove.setAttribute('id', 'removeBtn');
remove.setAttribute('data-index', i);
remove.addEventListener('click', function(e) {
let index = e.target.attributes['data-index'].value;
cartItems.splice(index, 1);
localStorage.setItem('productsInCart', JSON.stringify(cartItems));
location.reload();
})
container.appendChild(remove); //append it to box
removeContent()
updateTotal()
};
// QUANTITY
let quantityInput = document.getElementsByClassName('itemQuantity');
for(let i = 0; i < quantityInput.length; i++) {
let input = quantityInput[i];
input.addEventListener('change', quantityChanged);
};
function quantityChanged(e) {
let input = e.target;
let value = input.value;
let index = e.target.attributes['data-index'].value;
if(value <= 0) { //Check if value is invalid (number < or = to 1)
value = 1 // If invalid, change to 1
input.value = 1; // UPDATING THE INPUT VISIBLE VALUE ITSELF.
};
cartItems[index].quantity = parseInt(value);
localStorage.setItem('productsInCart', JSON.stringify(cartItems));
updateTotal()
};
// EMPTY WHOLE CART : EXTRA FEATURE
let emptyBtn = document.getElementById('emptyCart');
let content = document.getElementById('cartProducts');
emptyBtn.onclick = function() {
localStorage.clear();
content.remove()
updateTotal()
location.reload();
}
// UPDATE CART TOTAL
function updateTotal() {
let cartContainer = document.getElementById('cartProducts');
let cartRows = document.getElementsByClassName('cartProduct');
let total = 0;
for(let i = 0; i < cartRows.length; i++) {
let cartRow = cartRows[i];
let priceElement = cartRow.getElementsByClassName('price')[0];
let quantityElement = cartRow.getElementsByClassName('itemQuantity')[0];
let price = parseFloat(priceElement.innerText.replace('$', ''));
let quantity = quantityElement.value;
total = total + (price * quantity);
}
total = Math.round(total * 100) / 100;
document.getElementById('totalPrice').innerText = '$' + total;
};
// FORM VALIDATION / ORDER CONFIRMATION
let btn = document.getElementById('submitButton');
function checkform() {
// Order button is disabled unless form is filled
let form = document.getElementsByClassName('formInput');
let cansubmit = true;
for (let i = 0; i < form.length; i++) {
if (form[i] == 0) cansubmit = false;
}
if (cansubmit) {
btn.disabled = false;
}
else {
btn.disabled = true;
}
}
// Validation
function validateData(data) {
// contact details
let firstName = document.getElementById('firstName').value;
let lastName = document.getElementById('lastName').value;
let address = document.getElementById('address').value;
let city = document.getElementById('city').value;
let email = document.getElementById('email').value;
let contact = {
"firstName": firstName,
"lastName": lastName,
"address": address,
"city": city,
"email": email
};
localStorage.setItem("contact", JSON.stringify(contact));
// product details
let products = [];
let productsInCart = JSON.parse(localStorage.getItem("productsInCart"));
for(let i = 0; i < productsInCart.length; i++) {
//extracting ids from localstorage & pushing to "products" array for validation
let ids = productsInCart.map(a => a.id)[i];
products.push(ids)
};
// total price
let totalPrice = document.getElementById('totalPrice').innerText;
let total = localStorage.setItem("total", JSON.stringify(totalPrice));
// VALIDATION
fetch("http://localhost:3000/api/cameras/order", {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
contact: contact,
products: products, //stringifying the object
})
}).then(async result_ => {
const response = await result_.json() //waiting for the result before saving things
//contact and product details
data = {
contact: contact,
products: productsInCart,
orderId: response.orderId,
}
localStorage.setItem("orderResult", JSON.stringify(data)) //stocking the value inside 2 localstorages
window.location = "Confirmation.html"
})
.catch(error => {
console.error(error);
})
};
let form = document.getElementById('orderForm');
form.addEventListener("submit", function(e) {
e.preventDefault();
validateData();
});
| 7f9a723834d81df8f93c4dec0d7b0ecc7503c1b9 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | katiemayfaulkner/P5 | 280d631ce3e7a52096fc411cb6d4ea2f459d747a | 2423b3fa79573d9499a1e75d4d530da33712759c |
refs/heads/master | <file_sep>using System;
using UnityConstantsGenerator.SourceGenerator;
using UnityEngine;
using UnityEditor;
using UnityEngine.UIElements;
namespace UnityConstantsGenerator
{
public class UnityConstantsGeneratorSettingsProvider : SettingsProvider
{
private static class Styles
{
public static readonly GUIContent SourceGenerationLabel = new GUIContent("Source Generation", "Source code generation settings");
public static readonly GUIContent GenerateTargetsLabel = new GUIContent("Targets");
}
private GenerateSetting _generateSetting;
[SettingsProvider]
public static SettingsProvider Create()
{
var path = "Project/Constants Generator";
var provider = new UnityConstantsGeneratorSettingsProvider(path, SettingsScope.Project)
{
keywords = GetSearchKeywordsFromPath(UnityConstantsGeneratorSettings.SavePath)
};
return provider;
}
private UnityConstantsGeneratorSettingsProvider(string path, SettingsScope scopes) : base(path, scopes)
{ }
public override void OnActivate(string searchContext, VisualElement rootElement)
{
base.OnActivate(searchContext, rootElement);
var settings = UnityConstantsGeneratorSettings.Instance;
_generateSetting = settings.generateSetting;
}
private struct LabeledScope : IDisposable
{
public LabeledScope(GUIContent labelContent)
: this(labelContent, GUIStyle.none)
{
}
public LabeledScope(GUIContent labelContent, GUIStyle boxStyle)
{
if (boxStyle == GUIStyle.none)
EditorGUILayout.BeginVertical();
else
EditorGUILayout.BeginVertical(boxStyle);
EditorGUILayout.LabelField(labelContent, EditorStyles.boldLabel);
EditorGUI.indentLevel += 1;
}
public void Dispose()
{
EditorGUI.indentLevel -= 1;
EditorGUILayout.EndVertical();
}
}
public override void OnGUI(string searchContext)
{
using (new LabeledScope(Styles.SourceGenerationLabel))
{
EditorGUI.BeginChangeCheck();
_generateSetting.@namespace =
EditorGUILayout.TextField(new GUIContent("Namespace"), _generateSetting.@namespace);
_generateSetting.outputDir =
EditorGUILayout.TextField(new GUIContent("Output Directory"), _generateSetting.outputDir);
using (new LabeledScope(Styles.GenerateTargetsLabel))
{
_generateSetting.generateSceneValues = EditorGUILayout.Toggle(new GUIContent("Scene"),
_generateSetting.generateSceneValues);
_generateSetting.generateSortingLayerValues = EditorGUILayout.Toggle(new GUIContent("SortingLayer"),
_generateSetting.generateSortingLayerValues);
_generateSetting.generateLayerValues = EditorGUILayout.Toggle(new GUIContent("Layer"),
_generateSetting.generateLayerValues);
_generateSetting.generateTagValues =
EditorGUILayout.Toggle(new GUIContent("Tag"), _generateSetting.generateTagValues);
}
EditorGUILayout.Space();
if (EditorGUI.EndChangeCheck())
{
UnityConstantsGeneratorSettings.Save();
}
if (GUILayout.Button("Generate", EditorStyles.miniButtonRight))
{
using (AssetEditing.Scope())
{
UnityConstantValuesGenerator.UpdateUnityConstants();
UnityConstantValuesGenerator.UpdateSceneValues();
}
AssetDatabase.Refresh();
}
}
}
}
}
<file_sep>using System.IO;
using UnityConstantsGenerator.SourceGenerator;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Serialization;
namespace UnityConstantsGenerator
{
internal class UnityConstantsGeneratorSettings : ScriptableObject
{
public const string SavePath = "ProjectSettings/UnityConstantsGeneratorSettings.asset";
public GenerateSetting generateSetting = new GenerateSetting();
private static UnityConstantsGeneratorSettings _instance;
public static UnityConstantsGeneratorSettings Instance => _instance ? _instance : GetOrCreate();
UnityConstantsGeneratorSettings()
{
_instance = this;
}
private static UnityConstantsGeneratorSettings GetOrCreate()
{
InternalEditorUtility.LoadSerializedFileAndForget(SavePath);
if (_instance == null)
{
var instance = CreateInstance<UnityConstantsGeneratorSettings>();
instance.hideFlags = HideFlags.HideAndDontSave;
}
Debug.Assert(_instance != null);
return _instance;
}
public static void Save()
{
if (_instance == null)
{
Debug.Log("Cannot save " + nameof(UnityConstantsGeneratorSettings));
return;
}
string folderPath = Path.GetDirectoryName(SavePath);
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
InternalEditorUtility.SaveToSerializedFileAndForget(new Object[] {_instance}, SavePath, true);
}
internal static SerializedObject GetSerializedObject()
{
var serializedObject = new SerializedObject(Instance);
serializedObject.UpdateIfRequiredOrScript();
return serializedObject;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace UnityConstantsGenerator.SourceGenerator
{
internal enum CSharpTypeId
{
Class,
Enum,
Struct,
}
internal enum AccessModifier
{
Public,
Protected,
Internal,
Private,
}
[Flags]
internal enum Modifier
{
None = 0,
Const = 1 << 1,
Static = 1 << 2,
Readonly = 1 << 3,
StaticReadonly = Static | Readonly,
}
internal abstract class CSharpType
{
public readonly List<string> UsingNamespaces = new List<string>();
public abstract CSharpTypeId TypeId { get; }
public string Namespace { get; set; }
public string Comment { get; set; }
public AccessModifier AccessModifier { get; set; } = AccessModifier.Public;
public Modifier Modifier { get; set; }
public string TypeName { get; set; }
public readonly List<Variable> Fields = new List<Variable>();
public CSharpType(string nameSpace, string typeName)
{
Namespace = nameSpace;
TypeName = typeName;
}
public string GetClassDeclareString()
{
var sb = new StringBuilder(128);
sb.AppendAccessModifier(AccessModifier);
sb.AppendVariableDeclareModifier(Modifier);
sb.Append(TypeId.ToString().ToLower());
sb.Append(' ');
sb.Append(TypeName);
return sb.ToString();
}
}
internal class CSharpEnum : CSharpType
{
public override CSharpTypeId TypeId => CSharpTypeId.Enum;
public bool IsFlags { get; set; }
public CSharpEnum(string nameSpace, string typeName) : base(nameSpace, typeName)
{
}
}
internal class CSharpClass : CSharpType
{
public override CSharpTypeId TypeId => CSharpTypeId.Class;
public CSharpClass(string nameSpace, string typeName) : base(nameSpace, typeName)
{
}
}
internal class Variable
{
private string _name;
public AccessModifier AccessLevel { get; set; } = AccessModifier.Public;
public Modifier Modifier { get; set; }
public string TypeName { get; set; }
public string Name
{
get => _name;
set => _name = value.SanitizeForIdentifier();
}
public string Value { get; set; }
public string Comment { get; set; }
public Variable(string type, string name, string value, Modifier modifier = Modifier.None, string comment = null)
{
TypeName = type;
Name = name;
Value = value;
Modifier = modifier;
Comment = comment;
}
public string ToFieldDeclareString()
{
var sb = new StringBuilder(128);
sb.AppendAccessModifier(AccessLevel);
sb.AppendVariableDeclareModifier(Modifier);
sb.Append(TypeName);
sb.Append(' ');
sb.Append(Name);
sb.Append(" = ");
sb.Append(Value);
sb.Append(";");
return sb.ToString();
}
public string ToEnumDeclareString()
{
var sb = new StringBuilder(128);
sb.Append(Name);
if (!string.IsNullOrEmpty(Value))
{
sb.Append(" = ");
sb.Append(Value);
}
sb.Append(',');
return sb.ToString();
}
}
internal class MethodInfo
{
public string Name;
}
}
<file_sep># Unity Constants Generator
[](https://openupm.com/packages/com.xtaltools.unityconstantsgenerator/)
Constants values utitlity
## Install
### Package Manager
```manifest.json
{
"dependencies": {
"com.xtaltools.unityconstantsgenerator": "https://github.com/neptaco/UnityConstantsGenerator.git?path=Assets/ConstantsGenerator"
}
}
```
## Generate Unity constant values
Open `ProjectSettings -> Constants Generator` and set the generation target.

|Target|Generated classes|
|----|-------|
|Scene|SceneId<br/>SceneName<br/>ScenePath|
|Layer|LayerId<br/>LayerMaskValue|
|SortingLayer|SortingLyaerId<br/>SortingLayerName|
|Tag|TagName|
## Samples
```csharp:SceneValues.cs
public class SceneId
{
/// <summary>
/// <para>0: ProfileScene</para>
/// Assets/UniEnumDev/Scenes/ProfileScene.unity
/// </summary>
public const int ProfileScene = 0;
}
public class SceneName
{
/// <summary>
/// <para>0: ProfileScene</para>
/// Assets/UniEnumDev/Scenes/ProfileScene.unity
/// </summary>
public const string ProfileScene = "ProfileScene";
}
public class ScenePath
{
/// <summary>
/// <para>0: ProfileScene</para>
/// Assets/UniEnumDev/Scenes/ProfileScene.unity
/// </summary>
public const string ProfileScene = "Assets/UniEnumDev/Scenes/ProfileScene.unity";
}
```
```csharp:LayerValues.cs
public enum LayerId
{
/// <summary>
/// Default
/// </summary>
Default = 0,
/// <summary>
/// TransparentFX
/// </summary>
TransparentFX = 1,
/// <summary>
/// Ignore Raycast
/// </summary>
IgnoreRaycast = 2,
/// <summary>
/// Water
/// </summary>
Water = 4,
/// <summary>
/// UI
/// </summary>
UI = 5,
/// <summary>
/// アイウエオ
/// </summary>
アイウエオ = 17,
/// <summary>
/// !@#$%^&*()[]'/123 abcWXZ-11
/// </summary>
_123abcWXZ11 = 21,
}
[System.Flags]
public enum LayerMaskValue
{
/// <summary>
/// Default
/// </summary>
Default = 1 << 0,
/// <summary>
/// TransparentFX
/// </summary>
TransparentFX = 1 << 1,
/// <summary>
/// Ignore Raycast
/// </summary>
IgnoreRaycast = 1 << 2,
/// <summary>
/// Water
/// </summary>
Water = 1 << 4,
/// <summary>
/// UI
/// </summary>
UI = 1 << 5,
/// <summary>
/// アイウエオ
/// </summary>
アイウエオ = 1 << 17,
/// <summary>
/// !@#$%^&*()[]'/123 abcWXZ-11
/// </summary>
_123abcWXZ11 = 1 << 21,
}
```
```csharp:SortingLayerValues.cs
public class SortingLayerId
{
public static readonly int Default = SortingLayer.NameToID("Default");
}
public class SortingLayerName
{
public const string Default = "Default";
}
```
```csharp:TagValues.cs
public class TagName
{
/// <summary>
/// Untagged
/// </summary>
public static readonly string Untagged = "Untagged";
/// <summary>
/// Respawn
/// </summary>
public static readonly string Respawn = "Respawn";
/// <summary>
/// Finish
/// </summary>
public static readonly string Finish = "Finish";
/// <summary>
/// EditorOnly
/// </summary>
public static readonly string EditorOnly = "EditorOnly";
/// <summary>
/// MainCamera
/// </summary>
public static readonly string MainCamera = "MainCamera";
/// <summary>
/// Player
/// </summary>
public static readonly string Player = "Player";
/// <summary>
/// GameController
/// </summary>
public static readonly string GameController = "GameController";
/// <summary>
/// 12@hoge -##A
/// </summary>
public static readonly string _12hogeA = "12@hoge -##A";
}
```
### Generation timing
|Target|Timing|
|----|-------|
|Scene|When the scene list is changed in the Build Settings window|
|Layer<br />SortingLayer<br />Tag|When the Postprocessor detects a change in TagManager.asset|
### How to manually update scene variables on batch build
Call the following method.
```
UnityConstantValuesGenerator.UpdateSceneValues(EditorBuildSettingScenes[] scenes)
```
### License
This library is under the MIT License.<file_sep>#define CHECK_GENERATE_CLASS
using System.Collections;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using UnityConstantsGenerator.SourceGenerator;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEngine;
using UnityEngine.TestTools;
namespace UniEnumEditorTests
{
public class GenerateTests
{
const string TestBasePath = "Assets/ConstantsGenerator.Tests/Editor";
const string SceneDirPath = TestBasePath + "/Scenes";
const string OutputDirPath = TestBasePath + "/TestOutput";
[Test]
public void IdentifierTest()
{
Assert.AreEqual("hoge", "hoge".SanitizeForIdentifier());
Assert.AreEqual("_01234", "01234".SanitizeForIdentifier());
Assert.AreEqual("あいうえお", "あいうえお".SanitizeForIdentifier());
Assert.AreEqual("_123abcWXZ11", "!@#$%^&*()[]'/123 abcWXZ-11".SanitizeForIdentifier());
}
[Test]
public void ModifierTest()
{
var sb = new StringBuilder();
sb.Length = 0;
sb.AppendVariableDeclareModifier(Modifier.Const);
Assert.AreEqual("const ", sb.ToString());
sb.Length = 0;
sb.AppendVariableDeclareModifier(Modifier.Static);
Assert.AreEqual("static ", sb.ToString());
sb.Length = 0;
sb.AppendVariableDeclareModifier(Modifier.Readonly);
Assert.AreEqual("readonly ", sb.ToString());
sb.Length = 0;
sb.AppendVariableDeclareModifier(Modifier.Readonly | Modifier.Static);
Assert.AreEqual("static readonly ", sb.ToString());
}
[Test]
public void IndentTest()
{
var indent = new IndentState();
Assert.AreEqual("", indent.ToString());
indent.Indent += 1;
Assert.AreEqual(1, indent.Indent);
Assert.AreEqual(" ", indent.ToString());
indent.Indent += 1;
Assert.AreEqual(2, indent.Indent);
Assert.AreEqual(" ", indent.ToString());
indent.Indent -= 1;
Assert.AreEqual(1, indent.Indent);
Assert.AreEqual(" ", indent.ToString());
indent.Indent -= 1;
Assert.AreEqual(0, indent.Indent);
Assert.AreEqual("", indent.ToString());
indent.Indent -= 1;
Assert.AreEqual(0, indent.Indent);
Assert.AreEqual("", indent.ToString());
}
[UnityTest]
public IEnumerator SceneTest()
{
var sceneFiles = Directory.EnumerateFiles(SceneDirPath, "*.unity", SearchOption.AllDirectories)
.Select(v => new EditorBuildSettingsScene(v, true))
.ToArray();
var setting = new GenerateSetting()
{
@namespace = "UniEnumEditorTests",
outputDir = OutputDirPath,
};
AssetDatabase.DeleteAsset($"{setting.outputDir}/SceneValues.Generated.cs");
UnityConstantValuesGenerator.UpdateSceneValues(setting, sceneFiles);
yield return new RecompileScripts();
#if CHECK_GENERATE_CLASS
Assert.AreEqual("UniEnumTest_100", SceneName.UniEnumTest_100);
Assert.AreEqual("UniEnumTest_101", SceneName.UniEnumTest_101);
Assert.AreEqual("UniEnumTest_102", SceneName.UniEnumTest_102);
Assert.AreEqual(0, SceneId.UniEnumTest_100);
Assert.AreEqual(1, SceneId.UniEnumTest_101);
Assert.AreEqual(2, SceneId.UniEnumTest_102);
Assert.AreEqual($"{SceneDirPath}/UniEnumTest_100.unity", ScenePath.UniEnumTest_100);
Assert.AreEqual($"{SceneDirPath}/UniEnumTest_101.unity", ScenePath.UniEnumTest_101);
Assert.AreEqual($"{SceneDirPath}/UniEnumTest_102.unity", ScenePath.UniEnumTest_102);
#endif
}
[UnityTest]
public IEnumerator UnityConstantsTest()
{
var setting = new GenerateSetting()
{
@namespace = "UniEnumEditorTests",
outputDir = OutputDirPath,
};
AssetDatabase.DeleteAsset($"{setting.outputDir}/TagValues.Generated.cs");
AssetDatabase.DeleteAsset($"{setting.outputDir}/LayerValues.Generated.cs");
AssetDatabase.DeleteAsset($"{setting.outputDir}/SortingLayerValues.Generated.cs");
UnityConstantValuesGenerator.UpdateUnityConstants(setting);
yield return new RecompileScripts();
#if CHECK_GENERATE_CLASS
Assert.AreEqual("12@hoge -##A", TagName._12hogeA);
Assert.AreEqual(17, (int)LayerId.アイウエオ);
Assert.AreEqual((1 << 17), (int)LayerMaskValue.アイウエオ);
Assert.AreEqual(21, (int)LayerId._123abcWXZ11);
Assert.AreEqual((1 << 21), (int)LayerMaskValue._123abcWXZ11);
Assert.AreEqual(SortingLayer.NameToID("Default"), SortingLayerId.Default);
#endif
}
}
}
<file_sep>using System;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
namespace UnityConstantsGenerator.SourceGenerator
{
internal static class CSharpSourceUtility
{
private static readonly char[] IdentifierInvalidChars =
{
' ', '!', '"', '#', '$',
'%', '^', '\'', '(', ')',
'-', '=', '^', '~', '\\',
'[', '{', '&', '@', '`',
']', '}', ':', '*', ';',
'+', '/', '?', '.', '>',
',', '<',
};
public static string SanitizeForIdentifier(this string identifier)
{
var sb = new StringBuilder(identifier.Length + 1);
foreach (var c in identifier)
{
if (FindIndex(IdentifierInvalidChars, c) >= 0)
continue;
sb.Append(c);
}
if (char.IsDigit(sb[0]))
{
sb.Insert(0, '_');
}
return sb.ToString();
}
private static int FindIndex(char[] array, char v)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] == v)
return i;
}
return -1;
}
public static string ToQuoted(this string v)
{
return $"\"{v}\"";
}
public static void AppendAccessModifier(this StringBuilder sb, AccessModifier accessLevel)
{
sb.Append(accessLevel.ToString().ToLower());
sb.Append(' ');
}
public static void AppendVariableDeclareModifier(this StringBuilder sb, Modifier keyword)
{
if (keyword.HasFlag(Modifier.Const))
{
sb.Append("const ");
}
else
{
if (keyword.HasFlag(Modifier.Static))
sb.Append("static ");
if (keyword.HasFlag(Modifier.Readonly))
sb.Append("readonly ");
}
}
}
internal class AssetEditing : IDisposable
{
public static AssetEditing Scope() => new AssetEditing();
private AssetEditing()
{
AssetDatabase.StartAssetEditing();
}
public void Dispose()
{
AssetDatabase.StopAssetEditing();
}
}
internal class IndentState
{
private int _indent = 0;
private string _indentStr = string.Empty;
public int Indent
{
set
{
var delta = value - _indent;
_indent = value;
if (_indent < 0)
{
_indent = 0;
return;
}
if (delta > 0)
{
for (int i = 0; i < delta; i++)
_indentStr += " ";
}
else if (delta < 0)
{
_indentStr = _indentStr.Substring(0, _indent * 4);
}
}
get => _indent;
}
public override string ToString() => _indentStr;
public IndentScope Scope => new IndentScope(this);
public readonly struct IndentScope : IDisposable
{
private readonly IndentState _indent;
public IndentScope(IndentState indent)
{
_indent = indent;
_indent.Indent += 1;
}
public void Dispose()
{
_indent.Indent -= 1;
}
}
}
}
<file_sep># CHANGELOG
## [Unreleased]
### Added
### Change
### Deprecated
### Removed
### Fixed
### Security
## [1.0.1] - 2020/07/31
### Fixed
- Fixed a setting loading bug on reopen unity editor
## [1.0.0] - 2020/07/31
### Added
- Automatically generate constants values. (scene, SortingLayer, Layer, tags)
<file_sep>using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace UnityConstantsGenerator.SourceGenerator
{
class CSharpSourceGenerator
{
private readonly TextWriter _writer;
private readonly IndentState _indent = new IndentState();
private readonly List<CSharpType> _types = new List<CSharpType>();
public CSharpSourceGenerator(TextWriter writer)
{
_writer = writer;
}
public void AddCSharpType(CSharpType type) => _types.Add(type);
private void WriteOneLine(string text)
{
_writer.Write(_indent);
_writer.Write(text);
WriteNewLine();
}
private void WriteNewLine() => _writer.Write('\n');
public void Generate()
{
WriteTagComment("This file is auto-generated by UniEnum.", "auto-generated");
WriteUsingNamespaces(_types.SelectMany(v => v.UsingNamespaces).Distinct().ToList());
var nsGroups = _types.GroupBy(v => v.Namespace, v => v);
foreach (var nsGroup in nsGroups)
{
WriteOneLine("namespace " + nsGroup.Key);
WriteOneLine("{");
using (_indent.Scope)
{
foreach (var type in nsGroup)
{
switch (type)
{
case CSharpClass @class:
WriteClass(@class);
break;
case CSharpEnum @enum:
WriteEnum(@enum);
break;
}
WriteNewLine();
}
}
WriteOneLine("}");
WriteNewLine();
}
}
private void WriteUsingNamespaces(List<string> usingNamespaces)
{
foreach (var ns in usingNamespaces)
{
WriteOneLine("using " + ns + ";");
}
WriteNewLine();
}
private void WriteEnum(CSharpEnum @enum)
{
WriteSummaryComment(@enum.Comment);
if (@enum.IsFlags)
{
WriteOneLine("[System.Flags]");
}
WriteOneLine(@enum.GetClassDeclareString());
WriteOneLine("{");
using (_indent.Scope)
{
foreach (var field in @enum.Fields)
{
WriteSummaryComment(field.Comment);
WriteOneLine(field.ToEnumDeclareString());
WriteNewLine();
}
}
WriteOneLine("}");
}
private void WriteClass(CSharpClass @class)
{
WriteSummaryComment(@class.Comment);
WriteOneLine(@class.GetClassDeclareString());
WriteOneLine("{");
using (_indent.Scope)
{
foreach (var field in @class.Fields)
{
WriteSummaryComment(field.Comment);
WriteOneLine(field.ToFieldDeclareString());
WriteNewLine();
}
}
WriteOneLine("}");
}
private void WriteSummaryComment(string comment)
{
WriteTagComment(comment, "summary");
}
private void WriteTagComment(string comment, string tag)
{
if (string.IsNullOrEmpty(comment))
return;
var lines = comment.Split('\n');
WriteOneLine($"/// <{tag}>");
foreach (var line in lines)
{
WriteOneLine("/// " + line);
}
WriteOneLine($"/// </{tag}>");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace UnityConstantsGenerator.SourceGenerator
{
public class UnityConstantValuesGenerator : AssetPostprocessor
{
private const string TagManagerPath = "ProjectSettings/TagManager.asset";
private static GenerateSetting _settings;
private static GenerateSetting Settings
{
get
{
if (_settings == null)
{
_settings = UnityConstantsGeneratorSettings.Instance.generateSetting;
}
return _settings;
}
}
[InitializeOnLoadMethod]
private static void Initialize()
{
EditorBuildSettings.sceneListChanged -= OnSceneListChanged;
EditorBuildSettings.sceneListChanged += OnSceneListChanged;
}
private static void OnSceneListChanged()
{
EditorApplication.delayCall += () => UpdateSceneValues();
}
/// <summary>
/// Update scene values.
/// </summary>
/// <param name="scenes"></param>
public static void UpdateSceneValues(EditorBuildSettingsScene[] scenes = null)
{
UpdateSceneValues(Settings, scenes);
}
internal static void UpdateSceneValues(GenerateSetting setting, EditorBuildSettingsScene[] scenes)
{
if (!Settings.generateSceneValues)
return;
using (AssetEditing.Scope())
{
if (scenes == null)
{
scenes = EditorBuildSettings.scenes;
}
var sceneIds = new CSharpClass(setting.@namespace, "SceneId");
var sceneNames = new CSharpClass(setting.@namespace, "SceneName");
var scenePaths = new CSharpClass(setting.@namespace, "ScenePath");
for (int i = 0; i < scenes.Length; i++)
{
var scene = scenes[i];
var sceneName = Path.GetFileNameWithoutExtension(scene.path);
var comment = $"<para>{i}: {sceneName}</para>\n{scene.path}";
sceneIds.Fields.Add(new Variable("int", sceneName, i.ToString(), Modifier.Const, comment));
sceneNames.Fields.Add(new Variable("string", sceneName, sceneName.ToQuoted(), Modifier.Const, comment));
scenePaths.Fields.Add(new Variable("string", sceneName, scene.path.ToQuoted(), Modifier.Const, comment));
}
GenerateSourceCode(setting, "SceneValues.Generated", sceneIds, sceneNames, scenePaths);
}
}
private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets,
string[] movedFromAssetPaths)
{
if (Settings == null)
return;
if (Settings.generateLayerValues ||
Settings.generateSortingLayerValues ||
Settings.generateTagValues)
{
foreach (var asset in importedAssets)
{
if (asset == TagManagerPath)
{
UpdateUnityConstants();
}
}
}
}
public static void UpdateUnityConstants()
{
UpdateUnityConstants(Settings);
}
internal static void UpdateUnityConstants(GenerateSetting genSetting)
{
using (AssetEditing.Scope())
{
if (Settings.generateSortingLayerValues)
{
CreateSortingLayerValues(genSetting);
}
if (Settings.generateLayerValues)
{
CreateLayerValues(genSetting);
}
if (Settings.generateTagValues)
{
CreateTagValues(genSetting);
}
}
}
private static void CreateSortingLayerValues(GenerateSetting setting)
{
var idClass = new CSharpClass(setting.@namespace, "SortingLayerId");
var nameClass = new CSharpClass(setting.@namespace, "SortingLayerName");
idClass.UsingNamespaces.Add("UnityEngine");
foreach (var layer in SortingLayer.layers)
{
var idValue = $"SortingLayer.NameToID(\"{layer.name}\")";
idClass.Fields.Add(new Variable("int", layer.name, idValue, Modifier.StaticReadonly));
nameClass.Fields.Add(new Variable("string", layer.name, layer.name.ToQuoted(), Modifier.Const));
}
GenerateSourceCode(setting, "SortingLayerValues.Generated", idClass, nameClass);
}
private static void CreateLayerValues(GenerateSetting setting)
{
var layers = InternalEditorUtility.layers;
var layerIdClass = new CSharpEnum(setting.@namespace, "LayerId");
var layerMaskClass = new CSharpEnum(setting.@namespace, "LayerMaskValue")
{
IsFlags = true
};
foreach (var layer in layers)
{
var layerId = LayerMask.NameToLayer(layer);
layerIdClass.Fields.Add(new Variable("int", layer, layerId.ToString(), Modifier.StaticReadonly)
{
Comment = layer,
});
var mask = $"1 << {layerId}";
layerMaskClass.Fields.Add(new Variable("int", layer, mask, Modifier.StaticReadonly)
{
Comment = layer,
});
}
GenerateSourceCode(setting, "LayerValues.Generated", layerIdClass, layerMaskClass);
}
private static void CreateTagValues(GenerateSetting setting)
{
var tags = InternalEditorUtility.tags;
var tagNameClass = new CSharpClass(setting.@namespace, "TagName");
foreach (var tag in tags)
{
tagNameClass.Fields.Add(new Variable("string", tag, tag.ToQuoted(), Modifier.StaticReadonly)
{
Comment = tag,
});
}
GenerateSourceCode(setting, "TagValues.Generated", tagNameClass);
}
private static void GenerateSourceCode(GenerateSetting setting, string fileName, params CSharpType[] types)
{
var path = Path.Combine(setting.outputDir, fileName) + ".cs";
var parent = Path.GetDirectoryName(path);
if (!Directory.Exists(parent))
Directory.CreateDirectory(parent);
using (var writer = new StreamWriter(path))
{
var generator = new CSharpSourceGenerator(writer);
foreach (var type in types)
{
generator.AddCSharpType(type);
}
generator.Generate();
}
}
}
}
<file_sep>using UnityEngine.Serialization;
namespace UnityConstantsGenerator.SourceGenerator
{
[System.Serializable]
public class GenerateSetting
{
public string @namespace = "UnityConstantsGenerator";
public string outputDir = "Assets/Plugins/UnityConstantsGenerator/Generated";
public bool generateSceneValues;
public bool generateSortingLayerValues;
public bool generateLayerValues;
public bool generateTagValues;
}
}
| 4d70bf22d93ced5084232c345c275a06ff6f391f | [
"Markdown",
"C#"
] | 10 | C# | neptaco/UnityConstantsGenerator | 9bc5b34f32edbbe14fc52ddf1ee5697711301f22 | b4e41a10418f9e55f5fad0c3f6838327bdef0ec4 |
refs/heads/master | <file_sep>"""
Analytical least-mean-squares (ALMS) algorithm for signal recovery.
"""
from __future__ import division
import numpy as np
import numpy.linalg as npl
from scipy.linalg import toeplitz
from scipy.io import loadmat
from scipy.io.wavfile import write as wavwrite
################################################# MAIN
# Do you want to save and plot?
save_audio = False
plot_results = True
# Function for forming filter regression matrix given an array (data) and order (m)
regmat = lambda data, m: toeplitz(data, np.concatenate(([data[0]], np.zeros(m-1))))[m-1:]
# Unpack data
data = loadmat('audio_data.mat')
noisy_speech = data['reference'].flatten()
noise = data['primary'].flatten()
fs = data['fs'].flatten() # Hz
# Filter order
m = 100
# See http://www.cs.cmu.edu/~aarti/pubs/ANC.pdf page 7 last paragraph
X = regmat(noise, m)
y = noisy_speech[m-1:]
w = npl.pinv(X).dot(y)
# The error is the signal we seek
speech = y - X.dot(w)
################################################# RECORD
if save_audio:
wavwrite('recovered_ALMS.wav'.format(m), fs, speech)
################################################# VISUALIZATION
if plot_results:
# Compute performance surface for order 2
m2 = 2
X2 = regmat(noise, m2)
y2 = noisy_speech[m2-1:]
w2 = npl.pinv(X2).dot(y2)
print("Optimal weights for order 2: {}".format(w2))
w1_arr = np.arange(-10, 10)
w2_arr = np.arange(-10, 10)
trio = []
for i in w1_arr:
for j in w2_arr:
trio.append([i, j, np.mean(np.square(y2 - X2.dot([i, j])))])
# More imports for plotting
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as plt3
import matplotlib.cm as cm
fontsize = 30
# Performance surface
fig1 = plt.figure()
fig1.suptitle('Uniform Performance Surface (order: {})'.format(m2), fontsize=fontsize)
ax1 = plt3.Axes3D(fig1)
ax1.set_xlabel('Weight 1', fontsize=fontsize)
ax1.set_ylabel('Weight 2', fontsize=fontsize)
ax1.set_zlabel('Mean Square Error', fontsize=fontsize)
ax1.grid(True)
trio = np.array(trio)
ax1.plot_trisurf(trio[:, 0], trio[:, 1], trio[:, 2], cmap=cm.jet, linewidth=0.2)
ax1.plot([w[0]]*1000, [w[1]]*1000, np.linspace(0, np.max(trio[:, 2]), 1000), color='r', linewidth=1)
plt.show()
<file_sep>"""
Iterative normalized least-mean-squares (NLMS) algorithm for signal recovery.
"""
from __future__ import division
import numpy as np
import numpy.linalg as npl
from scipy.io import loadmat
from scipy.io.wavfile import write as wavwrite
################################################# MAIN
# Do you want to save and plot?
save_audio = False
plot_results = True
def regmat(x, m):
"""
Returns the order-m filter regression matrix of a timeseries x.
This is the matrix squareroot of the autocorrelation.
"""
# Number of order-m lags of the signal that can be fit into itself
nlags = len(x) - m
# Row-stack each set of m data points
X = np.zeros((nlags, m))
for i in xrange(nlags):
X[i, :] = x[i:(i+m)]
return X
def nlms(x, y, m, a, z=1):
"""
Returns the array of m weights of the (hopefully) MSE-optimal filter for a given input
data array x and a desired output data array y. Also returns a list of the errors, approximate
SNRs, and weights at each iteration. The algorithm used is gradient descent with stepsize a.
(The filter order is m of course). The timeseries is iterated through z times (number of "epochs").
"""
# Initialization
x = np.array(x, dtype=np.float64)
y = np.array(y, dtype=np.float64)
m = int(m); z = int(z)
w = np.zeros(m)
X = regmat(x, m)
e_list = []; snr_list = []; w_list = []
# Routine
for run in xrange(z):
for i in xrange(len(x) - m):
w_list.append(w)
xi = x[i:(i+m)]
yi = y[i+m-1]
e = yi - w.dot(xi)
w = w + a*(e*xi)/(xi.dot(xi))
e_list.append(e)
if not i%100:
snr_list.append((i, 10*np.log10(np.mean(np.square(y[m:(m+i+1)]))/np.mean(np.square(e_list[:i+1])))))
return w, e_list, snr_list, w_list
# Unpack data
data = loadmat('audio_data.mat')
noisy_speech = data['reference'].flatten()
noise = data['primary'].flatten()
fs = data['fs'].flatten() # Hz
# See http://www.cs.cmu.edu/~aarti/pubs/ANC.pdf
m = 100
a = 0.03
w, e_list, snr_list, w_list = nlms(noise, noisy_speech, m, a)
speech = np.array(e_list, dtype=np.float64)
se_arr = np.square(speech)
snr_arr = np.array(snr_list)
w_arr = np.array(w_list, dtype=np.float64)
################################################# RECORD
if save_audio:
wavwrite('recovered_NLMS.wav'.format(m), fs, speech)
################################################# VISUALIZATION
if plot_results:
# More imports for plotting
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as plt3
import matplotlib.cm as cm
fontsize = 30
# Performance contour
fig1 = plt.figure()
fig1.suptitle('Performance Contour (order: {}, stepsize: {})'.format(m, a), fontsize=fontsize)
ax1 = plt3.Axes3D(fig1)
ax1.set_xlabel('Weight 1', fontsize=fontsize)
ax1.set_ylabel('Weight 2', fontsize=fontsize)
ax1.set_zlabel('Square Error', fontsize=fontsize)
ax1.grid(True)
ax1.plot(w_arr[:, 0], w_arr[:, 1], se_arr)
# Weight tracks
fig2 = plt.figure()
fig2.suptitle('Weight Tracks (order: {}, stepsize: {})'.format(m, a), fontsize=fontsize)
ax2 = fig2.add_subplot(1, 1, 1)
ax2.set_xlabel('Iteration', fontsize=fontsize)
ax2.set_ylabel('Weight Value', fontsize=fontsize)
ax2.set_ylim((-3, 3))
ax2.grid(True)
ax2.plot(w_arr)
# Learning curve
fig2 = plt.figure()
fig2.suptitle('Learning Curve (order: {}, stepsize: {})'.format(m, a), fontsize=fontsize)
ax2 = fig2.add_subplot(1, 1, 1)
ax2.set_xlabel('Iteration', fontsize=fontsize)
ax2.set_ylabel('Square Error', fontsize=fontsize)
ax2.set_ylim((0, 50))
ax2.grid(True)
ax2.plot(se_arr)
# SNR Iteration
fig3 = plt.figure()
fig3.suptitle('Approximate SNR (order: {}, stepsize: {})'.format(m, a), fontsize=fontsize)
ax3 = fig3.add_subplot(1, 1, 1)
ax3.set_xlabel('Iteration', fontsize=fontsize)
ax3.set_ylabel('ERLE (dB)', fontsize=fontsize)
ax3.grid(True)
ax3.plot(snr_arr[:, 0], snr_arr[:, 1])
plt.show()
<file_sep>"""
Sliding-analytical least-mean-squares (SLMS) algorithm for signal recovery.
This is the ALMS with a sliding window carried out iteratively.
"""
from __future__ import division
import numpy as np
import numpy.linalg as npl
from scipy.linalg import toeplitz
from scipy.io import loadmat
from scipy.io.wavfile import write as wavwrite
# Function for forming filter regression matrix given an array (data) and order (m)
regmat = lambda data, m: toeplitz(data, np.concatenate(([data[0]], np.zeros(m-1))))[m-1:]
# Unpack data
data = loadmat('audio_data.mat')
noisy_speech = data['reference'].flatten()
noise = data['primary'].flatten()
fs = data['fs'].flatten()[0] # Hz
# Filter order
m = 100
# Window size must be larger than filter order
s = 10*m
assert s > m
# Prep
X = regmat(noise, m)
w_list = []
speech = []
# Slide window by window through the input data
# and find the analytically optimal weights for
# the output data, keeping the speech signal
# as the error for each sample in that window
for i in np.arange(0, len(noise)-s, s):
x = X[i:(i+s)]
y = noisy_speech[(i+m-1):(i+m-1+s)]
w = npl.pinv(x).dot(y)
e = y - x.dot(w)
w_list.append(w)
speech.extend(e)
# Save results
wavwrite('recovered_SLMS.wav'.format(m, s), fs, np.array(speech))
<file_sep># adaptive_filter
Some adaptive filter implementations for a class project.

| 151470136fb422859895900f1aa83f89fb419668 | [
"Markdown",
"Python"
] | 4 | Python | jnez71/adaptive_filter | 6d0b392e9dddc44b4ee3cab62e40ce978007540f | f1cbb4e32ba6d6e4e72fe4d829fb372c93339069 |
refs/heads/master | <file_sep><?php
require_once "HTTP/Request.php";
require_once dirname(__FILE__) . "/Common/DBConnection.php";
require_once dirname(__FILE__) . "/Common/Logger.php";
require_once dirname(__FILE__) . "/DB/MeowtubeDBAccessMgr.php";
$dbm = new MeowtubeDBAccessMgr();
if( isset($_GET['id']) )
{
// アクセスカウントの更新
$dbm->CountUpAccess($_GET['id']);
// 今日の猫動画取得
$result = $dbm->GetYoutubeById($_GET['id']);
}
// 最新3件の猫動画取得
$new_results = $dbm->GetYoutube("getdate DESC", 0, 3);
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="description" content="description">
<meta name="keywords" content="猫,cat,猫動画,meow,mew" />
<title>Today's Cat</title>
<!--[if lt IE 9]><script type="text/javascript" src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" src="js/pagetop.js"></script>
<script type="text/javascript" src="js/tipsy.js"></script>
<script type="text/javascript" src="js/slider.min.js"></script>
<script type="text/javascript" src="js/pull.out.js"></script>
<link rel="stylesheet" type="text/css" href="css/styles.css"/>
<?php include 'analyticsTracking.php';?>
</head>
<body id="back">
<header>
<?php include './header.php';?>
</header>
<section class="social">
<?php include "SocialButton.php"?>
</section>
<div class="wrapper">
<section class="blog_post_one_title">
<p><img src="img/common/todayscat.png"/></p>
</section>
<section class="blog_post_new_title">
<img src="img/common/recentcats.png" />
</section>
<section class="blog_post_one">
<time datetime="<?=$result['getdate'];?>"><?=date('Y年m月d日', strtotime($result['getdate']));?></time>
<h2><?=$result['title'];?></h2>
<iframe src="<?="http://www.youtube.com/embed/" . $result['id'] . "?&rel=0&theme=light&showinfo=0&autohide=1&color=white";?>" width="640" height="360" ></iframe>
<div class="example-twitter"><p><?=$result['description'];?></p></div>
<!-- Youtubeの投稿コメントを入れる -->
</section>
<section class="blog_post_new">
<?php foreach ($new_results as $new_result) : ?>
<time datetime="<?=$new_result['getdate'];?>"><?=date('Y年m月d日', strtotime($new_result['getdate']));?></time>
<h2><a href="?id=<?=$new_result['id'];?>"><?=mb_strimwidth($new_result['title'], 0, 20, '…', 'UTF-8');?></a></h2>
<a href="?id=<?=$new_result['id'];?>"><img src="<?=$new_result['thumbnail'];?>" alt="thumbnail" width="160"/></a>
<?php endforeach;?>
</section>
<section class="blog_post_one_title">
<a href="#" onClick="history.back(); return false;" class="text_btn" style="margin: 0 auto;">Back</a>
</section>
<div style="margin-top: 700px">
<script type="text/javascript">var a8='a13100744030_25ZXNC_1ELV76_249K_BUB81';var rankParam='<KEY>Sp<KEY>Yl<KEY>';var trackingParam='Oi7_qZSUA6oi_TDPqGJPqToTA82VPktQWkJ3Xkjxx';var bannerType='1';var bannerKind='item.variable.kind2';var vertical='1';var horizontal='4';var alignment='1';var frame='1';var ranking='1';var category='ペット用品';</script><script type="text/javascript" src="http://amz-ad.a8.net/amazon/amazon_ranking.js"></script>
</div>
</div>
<footer>
<?php include './footer.php';?>
</footer>
</body>
</html><file_sep><?php
require_once "HTTP/Request.php";
require_once dirname(__FILE__) . "/../Common/DBConnection.php";
require_once dirname(__FILE__) . "/../Common/Logger.php";
/**
* Youtubeの動画をWEBAPIから取得するクラス
*/
class YoutubeHandler
{
const URL = "http://gdata.youtube.com/feeds/api/videos?";
public $keyword;
public $max_results;
public $order_by; // relevance:関連性, published、viewCount、rating:評価
public $restriction; // JP:日本
public $time; // today(1 日)、this_week(7 日)、this_month(1 か月)、all_time(すべての期間)
public $category; // Music, Animals, Sports, Film, Autos, Travel, Games, Comedy, People, News, Entertainment, Education, Howto, Tech
public $format; // 1:モバイルH.263+AMR音声, 5:埋込み可能, 6:モバイルMPEG-4 SP+AAC
public function __construct() {}
/*
private function CreateQuery( $keyword, $max_result, $orderby, $restriction, $time, $option )
{
// 検索クエリの作成
$query = $this->url
. "vq=" . urldecode($keyword) // 検索キーワード
. "&max-results=" . $max_result // 検索結果最大数
. "&orderby=" . $orderby // 並べ替え順
. "&restriction=" . $restriction // 再生可能な国(etc. JP)
. "&time=" . $time // アップロードされた動画の時間範囲
. $option;
Logger::info($query);
return $query;
}
*/
/**
* 検索クエリ生成
* @return 検索クエリ文字列
*/
private function CreateQuery()
{
$param_ary = array( array("vq", urlencode($this->keyword)),
array("max-results", $this->max_results),
array("orderby", $this->orderby),
array("restriction", $this->restriction),
array("time", $this->time),
array("category", $this->category),
array("format", $this->format)
);
return $this->CreateQueryArray( $param_ary );
}
/**
* 検索クエリ生成
* @param $param_ary 検索パラメータy
* @return 検索クエリ文字列
*/
private function CreateQueryArray( $param_ary )
{
$str = $this::URL;
for( $i=0; $i<count($param_ary); $i++ )
{
$str .= ("&" . $param_ary[$i][0] . "=" . $param_ary[$i][1]);
}
Logger::info($str);
return $str;
}
/*
* 検索実行
* @return 検索結果(XML)
*/
public function SearchYoutube()
{
return simplexml_load_file( $this->CreateQuery() );
}
}
?><file_sep><?php
//---------------------------------------------------------------------
// Calendar_Month_Weeks を利用する場合
//---------------------------------------------------------------------
require_once 'Calendar/Month/Weeks.php';
# 曜日に表示する文字列とCSSクラス名を設定します。
$weekdayDefines = array(
array(
'日',
'sunday'),
array(
'月',
'monday'),
array(
'火',
'tuesday'),
array(
'水',
'wednesday'),
array(
'木',
'thursday'),
array(
'金',
'friday'),
array(
'土',
'saturday'));
# カレンダーの左側に表示させる曜日を設定します。
$weekdayBase = 0; // 0:日曜~6:土曜
# カレンダーに表示する年月を取得します。
// デフォルトの年月を設定
$year = (int)date('Y');
$month = (int)date('n');
// GETパラメータが指定されている場合は値を検証してから表示年月を取得
if( isset($_GET['year_month']) )
{
$yyyymm = trim($_GET['year_month']);
// YYYYMM形式であれば年月を取得
if( preg_match('/^([12]\d{3})(1[012]|0[1-9])$/', $yyyymm, $match) )
{
$year = (int)$match[1];
$month = (int)$match[2];
}
}
# カレンダーデータを生成します。
$calendar = new Calendar_Month_Weeks($year, $month, $weekdayBase);
$calendar->build();
# カレンダーの曜日部分を表示します。
$thisMonth = $calendar->thisMonth(TRUE); //今月
$prevMonth = $calendar->prevMonth(TRUE); //先月
$nextMonth = $calendar->nextMonth(TRUE); //来月
if( isset($_GET['id']) )
{
$id_str = '&id=' . urldecode($_GET['id']);
}
else
{
$id_str = "";
}
$prevMonthUrl = '?year_month=' . date('Ym', $prevMonth) . $id_str;
$nextMonthUrl = '?year_month=' . date('Ym', $nextMonth) . $id_str;
$thisMonthText = date('Y/m', $thisMonth);
?>
<table border="1">
<thead>
<tr>
<td><a href="<?php echo $prevMonthUrl;?>"><</a></td>
<th colspan="5"><?php echo $thisMonthText;?></th>
<td><a href="<?php echo $nextMonthUrl;?>">></a></td>
</tr>
<tr>
<?php
for( $i = 0; $i < 7; $i ++ )
{
$weekday = ($weekdayBase + $i) % 7;
$weekdayText = $weekdayDefines[$weekday][0];
$weekdayClass = $weekdayDefines[$weekday][1];
echo '<th class="' . $weekdayClass . '">', $weekdayText, '</th>';
}
?>
</tr>
</thead>
<tbody>
<?php
# 今月の動画データを検索します
$db = DBConnection::get()->handle();
// 猫動画データ取得(idと日付)
$sql = 'SELECT id, DATE_FORMAT(getdate, "%e") as getdate FROM youtube ' . 'WHERE getdate LIKE :month';
try
{
$stmt = $db->prepare($sql);
$stmt->bindValue(':month', date('Y-m', $thisMonth) . '%');
$stmt->execute();
$videoList = $stmt->fetchAll();
}
catch( PDOException $e )
{
var_dump($e->getMessage());
}
# カレンダーの日付部分を表示します。
while( $days = $calendar->fetch() )
{
$days->build();
$weekday = 0;
echo '<tr>';
while( $day = $days->fetch() )
{
$weekdayClass = $weekdayDefines[$weekday][1];
if( $day->isEmpty() )
{
$dayText = " ";
}
else
{
$dayText = $day->thisDay();
}
foreach( $videoList as $video )
{
if( $video['getdate'] == $dayText )
{
$dayText = '<a href="./TodaysCat.php?id=' . $video['id'] . '&year_month=' . date('Ym', $thisMonth) . '">' . $video['getdate'] . '</a>';
}
}
echo '<td class="' . $weekdayClass . '">', $dayText, '</td>';
$weekday ++;
}
echo '</tr>';
}
?>
</tbody>
</table><file_sep><?php
require_once "HTTP/Request.php";
require_once dirname(__FILE__) . "/../Common/DBConnection.php";
require_once dirname(__FILE__) . "/../Common/Logger.php";
require_once dirname(__FILE__) . "/../Util/YoutubeHandler.php";
require_once dirname(__FILE__) . "/../DB/NecotubeDBAccessMgr.php";
$db = DBConnection::get()->handle();
$select_sql = 'SELECT id FROM youtube';
$stmt = $db->query($select_sql);
$ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
$update_sql = 'UPDATE youtube '
.'SET getdate = date_sub(curdate(), interval :day day) '
.'WHERE id = :id';
for( $i=0; $i<count($ids); $i++ )
{
$stmt = $db->prepare( $update_sql );
$stmt->bindValue(':day', $i , PDO::PARAM_INT);
$stmt->bindValue(':id' , $ids[$i], PDO::PARAM_INT);
$stmt->execute();
}
?><file_sep>$(function(){
$(window).scroll(function(){
var bottomPos = $(document).height() - $(window).height() -600;
if ($(window).scrollTop() > bottomPos){
$('#interview').animate({'bottom':'0px'},500);
}else {
$('#interview').stop(true).animate({'bottom':'-165px'},200);
}
});
//closeをクリックして#interviewを消去
$('#interview .close').bind('click',function(){
$('#interview').remove();
});
});
<file_sep><?php
//----------------------------------------------------------------------
// Summary: ログ出力クラス
class Logger
{
private static $outputDir = "C:\Users\ayumi\Documents\php.log";
//------------------------------------------------------------------
// Summary :コンストラクタ
/*
public function __construct( $output_dir )
{
if( $output_dir )
{
$outputDir = $output_dir;
}
}
*/
public static function info( $msg )
{
Logger::outputLog( "INFO ", $msg );
}
public static function error( $msg )
{
Logger::outputLog( "ERROR", $msg );
}
public static function setOutputDir( $output_dir )
{
Logger::$outputDir = $output_dir;
}
//------------------------------------------------------------------
// Summary :ログ出力
private static function outputLog( $level, $msg )
{
$datetime = date( "Y/m/d (D) H:i:s", time() );
$client_ip = $_SERVER["REMOTE_ADDR"];
$request_url = $_SERVER["REQUEST_URI"];
$out = "[{$datetime}][$level][client {$client_ip}][url {$request_url}]{$msg}";
error_log( $out."\n", 3, Logger::$outputDir );
}
}
//----------------------------------------------------------------------
?><file_sep><?php
require_once "HTTP/Request.php";
require_once dirname(__FILE__) . "/Common/DBConnection.php";
require_once dirname(__FILE__) . "/Common/Logger.php";
require_once dirname(__FILE__) . "/Common/Pager.php";
require_once dirname(__FILE__) . "/DB/MeowtubeDBAccessMgr.php";
define("VIDEOS_PER_PAGE", 5);
$dbm = new MeowtubeDBAccessMgr();
// 動画のデータ取得
$blog_post_lr = array("blog_post left", "blog_post right");
if( isset($_GET['page']) and preg_match('/^[1-9][0-9]*$/', $_GET['page']) )
{
$page = (int)$_GET['page'];
}
else
{
$page = 1;
}
$offset = VIDEOS_PER_PAGE * ($page - 1);
$result = $dbm->GetYoutube( "getdate DESC", $offset, VIDEOS_PER_PAGE);
// アクセストップ5の猫動画データ取得
$top_result = $dbm->GetAccessYoutube("access.count DESC", 0, 5);
// ページングのリンクデータ取得
$count = $dbm->GetYoutubeCount();
$page_navi = new Pager('page', VIDEOS_PER_PAGE, $count);
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="description" content="今日も1日1猫動画。このサイトは毎日猫に関する動画を紹介します。" />
<meta name="keywords" content="猫,cat,猫動画,meow,mew" />
<meta name="author" content="MeowTube">
<meta name="copyright" content="Copyright © MeowTube">
<meta name="robots" content="index,follow" />
<title>MeowTube</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" src="js/pagetop.js"></script>
<script type="text/javascript" src="js/tipsy.js"></script>
<script type="text/javascript" src="js/slider.min.js"></script>
<script type="text/javascript" src="js/pull.out.js"></script>
<link rel="stylesheet" type="text/css" href="css/styles.css"/>
<link rel="sshortcut icon" href="favicon.ico"/>
<link rel="home" href="http://www.meowtube.net" title="meowtube" />
<?php include 'analyticsTracking.php';?>
</head>
<body id="back">
<header>
<?php include './header.php';?>
</header>
<section class="keyvisual">
<div id="slider">
<img class="image" src="img/key/visual01.jpg" alt="イメージ" />
<img class="image" src="img/key/visual02.jpg" alt="イメージ" />
<img class="image" src="img/key/visual03.jpg" alt="イメージ" />
<img class="image" src="img/key/visual04.jpg" alt="イメージ" />
<img class="image" src="img/key/visual05.jpg" alt="イメージ" />
<img class="image" src="img/key/visual06.jpg" alt="イメージ" />
</div>
<hgroup>
<h1><img src="img/common/logo.png" width="80" alt="sample logo" /></h1>
<h2>今日も1日1猫動画。このサイトは毎日猫に関する動画を紹介します。</h2>
</hgroup>
</section>
<section class="social">
<?php include 'SocialButton.php';?>
</section>
<div class="wrapper">
<section class="blog_post_new">
<!-- 画像(右上) -->
<a href="http://px.a8.net/svt/ejp?a8mat=25ZXNC+EJXH4I+2T0E+6AJV5" target="_blank">
<img border="0" width="200" height="200" alt="" src="http://www22.a8.net/svt/bgt?aid=131007000880&wid=001&eno=01&mid=s00000013091001057000&mc=1"></a>
<img border="0" width="1" height="1" src="http://www17.a8.net/0.gif?a8mat=25ZXNC+EJXH4I+2T0E+6AJV5" alt="">
<!-- カレンダー -->
<div class="calendar">
<img src="img/common/archives.png"/>
<?php include './Common/Calendar.php'; ?>
</div>
<br>
<!-- 人気5件 -->
<img src="img/common/popular_videos.png"/>
<?php foreach($top_result as $top):?>
<div class="item">
<time datetime="<?=$top['getdate'];?>"><?=date('Y年m月d日', strtotime($top['getdate']));?></time>
<p><a href="?id=<?=$top['id'];?>"><?=mb_strimwidth($top['title'], 0, 20, "…", "UTF-8");?></a></p>
<a href="./TodaysCat.php?id=<?=$top['id'];?>"><img src="<?=$top['thumbnail'];?>" alt="thumbnail" width="180"/></a>
</div>
<?php endforeach;?>
<!-- 画像(右下) -->
<div style="margin: 10px 0px auto">
<a href="http://px.a8.net/svt/ejp?a8mat=25ZXNC+EGYB3M+CHG+TWLPT" target="_blank">
<img border="0" width="160" height="600" alt="" src="http://www22.a8.net/svt/bgt?aid=131007000875&wid=001&eno=01&mid=s00000001618005023000&mc=1"></a>
<img border="0" width="1" height="1" src="http://www19.a8.net/0.gif?a8mat=25ZXNC+EGYB3M+CHG+TWLPT" alt="">
</div>
</section>
<?php for( $i=0; $i<count($result); $i++) :?>
<section class="blog_post_one">
<time datetime="<?=$result[$i]['getdate'];?>"><?=date('Y年m月d日', strtotime($result[$i]['getdate']));?></time>
<h2><a href="./TodaysCat.php?id=<?=$result[$i]['id'];?>"><?=$result[$i]['title'];?></a></h2>
<a href="./TodaysCat.php?id=<?=$result[$i]['id'];?>"><img src="<?=$result[$i]['thumbnail'];?>" alt="thumbnail" width="640" height="360"/></a>
<!--
<p><?=mb_strimwidth($result[$i]['description'], 0, 150, "…", "UTF-8");?></p>
-->
<a href="./TodaysCat.php?id=<?=$result[$i]['id'];?>" class="text_btn">View Video</a>
</section>
<?php endfor; ?>
<!-- 画像(リスト下段) -->
<section class="affiliate_2">
</section>
</div>
<div class="pagenavi">
<?=$page_navi->getPager();?>
</div>
<footer>
<?php include './footer.php';?>
</footer>
</body>
</html><file_sep><?php
require_once "HTTP/Request.php";
require_once dirname(__FILE__) . "/../Common/DBConnection.php";
require_once dirname(__FILE__) . "/../Common/Logger.php";
require_once dirname(__FILE__) . "/../Common/YoutubeHandler.php";
require_once dirname(__FILE__) . "/../DB/NecotubeDBAccessMgr.php";
Logger::info("get_todayscat.php START");
$dbm = new MeowtubeDBAccessMgr();
$result = $dbm->GetAccessYoutube("getdate DESC", 0, 1);
if( $result )
{
$youtube_array = array(
'id' => $result[0]['id'],
'title' => $result[0]['title'],
'credit' => $result[0]['credit'],
'player' => $result[0]['player'],
'thumbnail' => $result[0]['thumbnail'],
'description' => $result[0]['description'],
'getdate' => $result[0]['getdate']
);
$json_value = json_encode( $youtube_array );
header( 'Content-Type: text/javascript; charset=utf-8' );
echo $json_value;
}
Logger::info("get_todayscat.php END");
?><file_sep><?php
require_once dirname(__FILE__) . '/../Common/Logger.php';
require_once dirname(__FILE__) . '/../Common/Constant.php';
class DBConnection
{
private $_handle = null;
// ----------------------------------------------------------------
// Summary:コンストラクタ
// PDOのインスタンスを生成する
private function __construct()
{
try
{
$this->_handle = & new PDO(MYSQL_CONNECT, DB_USER, DB_PASSWORD);
$this->_handle->query("SET NAMES utf8");
}
catch( PDOException $e )
{
var_dump($e->getMessage());
}
}
public static function get()
{
static $db = null;
if( $db == null )
{
$db = new DBConnection();
}
return $db;
}
public function handle()
{
return $this->_handle;
}
}
?><file_sep><?php
require_once dirname(__FILE__) . "/../Common/DBConnection.php";
require_once dirname(__FILE__) . "/../Common/Logger.php";
class MeowtubeDBAccessMgr
{
private $dbh;
public function __construct()
{
$this->dbh = DBConnection::get()->handle();
}
/**
* @param $feed YoutubeAPIから返却された検索結果XML
* @return 登録した件数
*/
public function StoreYoutubeEntry( $feed, $max_count )
{
$count = 0;
foreach ($feed->entry as $entry)
{
// *** 取得したXMLデータから必要な項目を抜き出す ***
$media = $entry->children('http://search.yahoo.com/mrss/');
// ID
$id = end( explode('/',$entry->id) );
// タイトル
$title = $entry->title;
// 作者
$credit = $entry->author->name;
// 動画URL
$player = $media->group->content->attributes()->url;
// $player = $media->group->player->attributes()->url;
// サムネイルのURL
$attrs = $media->group->thumbnail[0]->attributes();
$thumbnail = $attrs['url'];
// 概要説明
$description = $media->group->description;
// 日付
$getdate = date('Y-m-d');
// 取得したXML文字列(デバッグ用)
$feed_str = $feed->asXML();
Logger::info("id($id), title($title), credit($credit), player($player), thumnail($thumbnail), description($description), date($getdate)");
if( $this->StoreYoutube( $id, $title, $credit, $player, $thumbnail, $description, $getdate, $feed_str ) )
{
$count++;
if( $count === $max_count )
{
Logger::info("break($count)");
break;
}
}
}
return $count;
}
/**
* youtubeテーブルへのINSERT
* @return 登録成功/失敗
*/
public function StoreYoutube( $id, $title, $credit, $player, $thumbnail, $description, $getdate, $feed_str )
{
try
{
$sql = 'INSERT INTO youtube '
. '(id, title, credit, player, thumbnail, description, getdate, feed) '
. 'VALUES (:id, :title, :credit, :player, :thumbnail, :description, :getdate, :feed) ';
$stmt = $this->dbh->prepare( $sql );
$stmt->bindParam(':id', $id);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':credit', $credit);
$stmt->bindParam(':player', $player);
$stmt->bindParam(':thumbnail', $thumbnail);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':getdate', $getdate);
$stmt->bindParam(':feed', $feed_str);
if( $stmt->execute() )
{
Logger::info("youtubeテーブルへのINSERT成功");
return true;
}
else {
Logger::info("youtubeテーブルへのINSERT失敗");
return false;
}
}
catch( PDOException $e )
{
var_dump($e->getMessage());
}
}
/**
* youtubeテーブルのデータ取得
* @return 取得結果の配列(FETCH_ASSOC)
*/
public function GetYoutube( $orderby, $offset, $row_count )
{
Logger::info("GetYoutube START");
$sql = 'SELECT * FROM youtube ';
if($orderby) $sql .= 'ORDER BY ' . $orderby;
$sql .= ' LIMIT :offset, :row_count ';
try
{
$stmt = $this->dbh->prepare( $sql );
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':row_count', $row_count, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Logger::info("GetYoutube END");
return $result;
}
catch( PDOException $e )
{
echo 'エラーが発生しました。管理者にご連絡ください';
Logger::error($e->getMessage());
}
}
/**
* youtubeテーブルのデータ取得(id指定)
* @return 取得結果の配列(FETCH_ASSOC)
*/
public function GetYoutubeById( $id )
{
$sql = 'SELECT * FROM youtube WHERE id = :id ';
try
{
$stmt = $this->dbh->prepare( $sql );
$stmt->bindValue(':id', $id);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
}
catch( PDOException $e )
{
echo 'エラーが発生しました。管理者にご連絡ください';
Logger::error($e->getMessage());
}
}
/**
* youtubeテーブルのデータ件数取得
* @return 件数
*/
public function GetYoutubeCount()
{
$sql = 'SELECT COUNT(*) AS count FROM youtube';
try
{
$stmt = $this->dbh->query( $sql );
$result = $stmt->fetch();
return $result['count'];
}
catch( PDOException $e )
{
echo 'エラーが発生しました。管理者にご連絡ください';
Logger::error($e->getMessage());
}
}
/**
* youtubeテーブルのデータ取得
* @return 取得結果の配列(FETCH_ASSOC)
*/
public function GetAccessYoutube($orderby, $offset, $row_count)
{
$sql = 'SELECT * FROM youtube '
. 'INNER JOIN access ON youtube.id = access.id ';
if($orderby) $sql .= 'ORDER BY ' . $orderby;
$sql .= ' LIMIT :row_count OFFSET :offset ';
try
{
$stmt = $this->dbh->prepare( $sql );
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':row_count', $row_count, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
catch( PDOException $e )
{
echo "エラーが発生しました。管理者にご連絡ください";
Logger::error($e->getMessage());
}
}
/**
* accessテーブルのカウントアップ
*/
public function CountUpAccess( $id )
{
$insert_sql = 'INSERT INTO access '
. '( id, count, last_access ) '
. 'VALUES ( :id , 1, now() )'
. 'on duplicate key update id=:id, count=count+1, last_access=now()';
try
{
$insert_stmt = $this->dbh->prepare( $insert_sql );
$insert_stmt->bindValue(':id', $id, PDO::PARAM_INT);
$insert_stmt->execute();
}
catch( PDOException $e )
{
echo "エラーが発生しました。管理者にご連絡ください";
Logger::error($e->getMessage());
}
}
}
?><file_sep><?php
define("MAX_DISP", "10");
class Pager
{
var $query; // ページを示すキー
var $rowCount; // 1ページあたりの件数
var $max; // 総件数
private $get = array(); // 引数の配列
private $page; // 現在のページ番号
private $href; // 引数なしのurl部分
private $pageCount; // 総ページ数
/*--------------------------------------------------
*
* コンストラクタ
* @param ページを示すキー : string
* 1ページあたりの件数 : int
* 総件数 : int
*
--------------------------------------------------*/
public function __construct( $query, $rowCount, $max )
{
$this->query = $query;
$this->rowCount = $rowCount;
$this->max = $max;
// URLとクエリを設定
$this->setRequestUri();
$this->page = ( isset( $this->get[$query] ) ) ? $this->get[$query] : '1';
$this->pageCount = ceil( $this->max / $this->rowCount );
}
/*--------------------------------------------------
*
* URLとクエリを取得、設定
*
--------------------------------------------------*/
protected function setRequestUri ()
{
$requestUri = explode( '?', $_SERVER['REQUEST_URI'] );
$this->href = $requestUri[0];
$this->get = $_GET;
}
/*--------------------------------------------------
*
* ページャhtml生成
* @param array(
* 'size' => 表示する数字の個数, : int
* 'firstMark' => 最初の記号, : string
* 'prevMark' => 前の記号, : string
* 'nextMark' => 次の記号, : strng
* 'lastMark' => 最後の記号 ) : string
* @return html : string
*
--------------------------------------------------*/
public function getPager( $_arr = array() )
{
$_ret = '';
if ( $this->rowCount )
{
// 引数の初期値
$default = array(
'size' => ($this->pageCount < MAX_DISP) ? $this->pageCount : MAX_DISP,
'firstMark' => '<<',
'prevMark' => '<',
'nextMark' => '>',
'lastMark' => '>>',
);
// パラメータを結合し決定
$_arr = array_merge( $default, $_arr );
$diff = floor( $_arr['size'] / 2 );
// 1ページしか無いときは出さない
if ( $this->pageCount > 1 )
{
// 最初のページ、前のページ
if ( $this->page > 1 )
{
// 最初のページ
$_ret .= '<span class="prev">'.$this->getLink ( 1, $_arr['firstMark'] )."</span>";
// 前のページ
$_ret .= '<span class="prev">'.$this->getLink ( $this->page - 1, $_arr['prevMark'] )."</span>";
}
// 繰り返し部分
if ( $this->page + $diff > $this->pageCount )
{
$start = $this->pageCount - $_arr['size'] + 1;
$start = ( $start < 0 ) ? 1 : $start;
$end = $this->pageCount;
}
elseif ( $this->page <= $diff )
{
$start = 1;
$end = $start + $_arr['size'] - 1;
}
else
{
$start = $this->page - $diff;
$end = $start + $_arr['size'] - 1;
}
for ( $i = $start; $i <= $end; $i ++ )
{
if ( $this->page == $i )
{
$_ret .= '<span class="current">'.$i.'</span> ';
}
else
{
$_ret .= '<span class="numbers">'.$this->getLink ( $i, $i ).'</span>';
}
}
// 次のページ、最後のページ
if( $this->page < $this->pageCount )
{
// 次のページ
$_ret .= '<span class="next">'.$this->getLink ( $this->page + 1, $_arr['nextMark'] ).'</span>';
// 最後のページ
$_ret .= '<span class="next">'.$this->getLink ( $this->pageCount, $_arr['lastMark'] ).'</span>';
}
// 出力タグ
$_ret = '
<p>
'.$_ret.'
</p>
';
}
}
return $_ret;
}
/*--------------------------------------------------
*
* リンク要素を生成
* @param ページ番号:num
* リンクさせる文字列:string
* @return リンク要素
*
--------------------------------------------------*/
protected function getLink ( $pageNum, $disp )
{
$_ret = '';
$get = $this->get;
$get[$this->query] = $pageNum;
$_ret .= '<a href="'.$this->href.'?'.http_build_query( $get ).'">'.$disp .'</a> ';
return $_ret;
}
}
?><file_sep><?php
// MYSQL接続
define("MYSQL_CONNECT", "mysql:host=127.0.0.1; dbname=MeowTube");
define("DB_USER" , "mysql_user");
define("DB_PASSWORD" , "<PASSWORD>");
// require用
define("BASEDIR",realpath(dirname(__FILE__))."/");
?><file_sep><?php
require_once "HTTP/Request.php";
require_once dirname(__FILE__) . "/../Common/DBConnection.php";
require_once dirname(__FILE__) . "/../Common/Logger.php";
require_once dirname(__FILE__) . "/../Util/YoutubeHandler.php";
require_once dirname(__FILE__) . "/../DB/MeowtubeDBAccessMgr.php";
Logger::info("YoutubeVideo START");
$youtube = new YoutubeHandler();
$youtube->keyword = "cat || 猫";
$youtube->max_results = 50;
$youtube->orderby = "rating";
// $youtube->orderby = "relevance_lang_ja";
$youtube->restriction = "JP";
$youtube->time = "this_month";
$youtube->category = "Animals";
$youtube->format = 5;
$feed = $youtube->SearchYoutube();
$dba = new MeowtubeDBAccessMgr();
$dba->StoreYoutubeEntry( $feed, 1 );
Logger::info("YoutubeVideo End");
?><file_sep> <ul>
<!-- twitter -->
<li><a href="https://twitter.com/share" class="twitter-share-button" data-lang="en" data-count="none">Tweet</a>
<script>!function(d,s,id){
var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){js=d.createElement(s);
js.id=id;js.src=p+'://platform.twitter.com/widgets.js';
fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
</script>
</li>
<!-- facebook -->
<li>
<div id="fb-root"></div>
<script>
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="http://<?=$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];?>"
data-width="The pixel width of the plugin" data-height="The pixel height of the plugin"
data-colorscheme="light" data-layout="button_count" data-action="like" data-show-faces="false" data-send="false"></div>
</li>
<!-- hatena bookmark -->
<li>
<a href="http://b.hatena.ne.jp/entry/<?='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];?>"
class="hatena-bookmark-button" data-hatena-bookmark-layout="standard-noballoon" data-hatena-bookmark-lang="en"
title="このエントリーをはてなブックマークに追加">
<img src="http://b.st-hatena.com/images/entry-button/button-only@2x.png" alt="このエントリーをはてなブックマークに追加"
width="20" height="20" style="border: none;" /></a>
<script type="text/javascript" src="http://b.st-hatena.com/js/bookmark_button.js" charset="utf-8" async="async"></script>
</li>
</ul><file_sep><?php
require_once "HTTP/Request.php";
require_once dirname(__FILE__) . "/Common/DBConnection.php";
require_once dirname(__FILE__) . "/Common/Logger.php";
$db = DBConnection::get()->handle();
// アクセストップ5の猫動画データ取得
$sql = 'SELECT youtube.id, thumbnail FROM youtube '
. 'INNER JOIN access ON youtube.id = access.id '
. 'ORDER BY access.count DESC '
. 'LIMIT 5';
try
{
$stmt = $db->prepare( $sql );
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch( PDOException $e )
{
echo "エラーが発生しました。管理者にご連絡ください";
Logger::error($e->getMessage());
}
?>
<section class="footer_top" id="footer">
<div class="footer_top_in">
<form name="searchform" id="searchform" method="get" action="http://www.google.co.jp/search">
<input name="q" id="keywords" value="" type="text" />
<input type="hidden" name="hl" value="ja">
<input type="hidden" name="as_sitesearch" value="<?="http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];?>">
<input id="searchbtn" type="image" src="img/common/btn_search.gif" alt="検索" />
</form>
<p class="copyright">Copyright © 2013 MeowTube.</p>
</div>
</section>
<section class="footer_bottom">
<div class="footer_bottom_in">
<div class="left">
<div class="title">ABOUT</div>
<p><img src="img/common/img_about.jpg" onmouseover="this.src='img/common/img_about2.jpg'" onmouseout="this.src='img/common/img_about.jpg'" alt="corona" width="250"/></p>
<p>このサイトは私「コロナ」が運営しています</p>
</div>
<div class="center">
<div class="title">Advertise</div>
<a href="http://px.a8.net/svt/ejp?a8mat=25ZXNE+5R6VAQ+2DUU+62MDD" target="_blank">
<img border="0" width="350" height="160" alt="" src="http://www23.a8.net/svt/bgt?aid=131007002348&wid=001&eno=01&mid=s00000011127001020000&mc=1"></a>
<img border="0" width="1" height="1" src="http://www10.a8.net/0.gif?a8mat=25ZXNE+5R6VAQ+2DUU+62MDD" alt="">
</div>
<div class="right">
<div class="title">LIKE SITE</div>
<div class="img_box"><a class="north" href="http://www.youtube.co.jp/" title="Youtube"><img alt="Youtube" src="img/site/youtube.jpg" /></a></div>
<div class="img_box"><a class="north" href="http://www.nekobiyori.jp/" title="猫びより"><img alt="猫びより" src="http://www.nekobiyori.jp/nekobiyori/60/header1.jpg" /></a></div>
<!--
<div class="img_box lasted"><a class="north" href="URL" title="サイト名"><img alt="サイト名" src="img/site/site_sample.jpg" /></a></div>
<div class="img_box"><a class="north" href="URL" title="サイト名"><img alt="サイト名" src="img/site/site_sample.jpg" /></a></div>
<div class="img_box"><a class="north" href="URL" title="サイト名"><img alt="サイト名" src="img/site/site_sample.jpg" /></a></div>
-->
</div>
</div>
</section>
<section class="footer_design">
<div class="footer_design_in">
<!--↓この囲いは消さないでください。消したい場合はご連絡ください。↓-->
<a class="north" href="http://creators-manual.com/" title="Webクリエイターズマニュアル"><img src="img/common/design.png" alt="Webクリエイターズマニュアル" /></a>
<!--↑この囲いは消さないでください。消したい場合はご連絡ください。↑-->
</div>
</section>
<!--
<section id="interview">
<div class="label">
<div class="title">
<div class="text">Popular videos TOP5</div>
<div class="close"><img title="Close" alt="Close" src="img/common/close.gif" /></div>
</div>
</div>
<div class="wrapper">
<?php foreach($result as $thumbnail):?>
<div class="item">
<a href="./TodaysCat.php?id=<?=$thumbnail['id'];?>"><img src="<?=$thumbnail['thumbnail'];?>" alt="thumbnail" /></a>
</div>
<?php endforeach;?>
</div>
</section>
-->
<div id="page-top" class="page_back"><a href="#back"><img src="img/common/btn_pagetop.png" alt="page-top" /></a></div> | 26e23ceff0ca4d19d3916a6625e65f44304d365b | [
"JavaScript",
"PHP"
] | 15 | PHP | hryord/meowtube | 14ebec6a8f2bf137d4ad11f7ed8327453b04186c | cbc2e869273072d8bdf03ea59493c485e3517952 |
refs/heads/master | <file_sep>package scripts.bbuu20_miner.main_tasks
import org.tribot.api.General
import org.tribot.api.Timing
import org.tribot.api2007.*
import scripts.bbuu20_api.Framework
import scripts.bbuu20_miner.data.Finals
import scripts.bbuu20_miner.data.PlayerInfo
import scripts.dax_api.api_lib.DaxWalker
import scripts.dax_api.shared.helpers.BankHelper
class WalkToRocks : Framework {
override fun shouldProceed(): Boolean {
return !Inventory.isFull()
&& !PlayerInfo.shouldUpgradePick()
&& (
PlayerInfo.currentRSRock == null
|| !PlayerInfo.currentRSRock!!.isOnScreen
|| !PlayerInfo.currentRSRock!!.isClickable
|| BankHelper.isInBank()
)
}
override fun proceed() {
if (BankHelper.isInBank()) {
if (Finals.MINING_GUILD_P2P.contains(Player.getPosition())) { //temporary fix until daxwalker supports mining guild
Walking.blindWalkTo(PlayerInfo.startingTile)
Timing.waitCondition({ Player.isMoving()}, General.randomLong(500, 2500)) //wait for player to start moving
Timing.waitCondition({!Player.isMoving()}, General.randomLong(500, 15000))
}
else {
if (!PlayerInfo.startingTile.isOnScreen || !PlayerInfo.startingTile.isClickable) {
DaxWalker.walkTo(PlayerInfo.startingTile)
}
else {
Walking.blindWalkTo(PlayerInfo.startingTile)
}
}
}
else if (PlayerInfo.currentRSRock != null) {
if (Finals.MINING_GUILD_P2P.contains(Player.getPosition())) { //temporary fix until daxwalker supports mining guild
Walking.blindWalkTo(PlayerInfo.currentRSRock)
Timing.waitCondition({ Player.isMoving()}, General.randomLong(500, 2500)) //wait for player to start moving
Timing.waitCondition({!Player.isMoving()}, General.randomLong(500, 15000))
}
else if (Player.getPosition().distanceTo(PlayerInfo.currentRSRock) > General.random(1, 15)) {
DaxWalker.walkTo(PlayerInfo.currentRSRock)
}
else {
Camera.turnToTile(PlayerInfo.currentRSRock)
if (!PlayerInfo.currentRSRock!!.isOnScreen || !PlayerInfo.currentRSRock!!.isClickable) {
DaxWalker.walkTo(PlayerInfo.startingTile)
}
}
}
else {
if (Player.getPosition().distanceTo(PlayerInfo.startingTile) > General.random(8, 12)) {
if (Player.getPosition().distanceTo(PlayerInfo.startingTile) > General.random(4, 15)) {
DaxWalker.walkTo(PlayerInfo.startingTile)
}
else {
Walking.blindWalkTo(PlayerInfo.startingTile)
}
}
}
}
}<file_sep>package scripts.bbuu20_api
interface Framework {
fun shouldProceed() : Boolean
fun proceed()
}<file_sep>package scripts.bbuu20_api.enums
enum class MainTask {
TRADITIONAL_MINING,
PROGRESSIVE_MINING,
TICK_MINING,
MOTHERLODE_MINING,
NULL
}<file_sep>package scripts.bbuu20_api.enums
enum class Rock(val ids: IntArray) {
RUNE_ESSENCE(intArrayOf()),
CLAY(intArrayOf(11362, 11363)),
COPPER(intArrayOf(10943, 11161)),
TIN(intArrayOf(11360, 11361)),
BLURITE(intArrayOf()),
LIMESTONE(intArrayOf(11382)),
IRON(intArrayOf(11364, 11365)),
SILVER(intArrayOf(11368, 11369)),
COAL(intArrayOf(11366, 11367)),
PURE_ESSENCE(intArrayOf(34773)),
SANDSTONE(intArrayOf(11386)),
GOLD(intArrayOf(11370, 11371)),
GEM(intArrayOf(11380, 11381)),
GRANITE(intArrayOf(11387)),
MITHRIL(intArrayOf(11372, 11373)),
LOVAKITE(intArrayOf()),
ADAMANTITE(intArrayOf(11374, 11375)),
RUNITE(intArrayOf(11376, 11377)),
AMETHYST(intArrayOf(11388, 11389)),
EMPTY(intArrayOf(11390, 11391)),
NULL(intArrayOf(-1))
}<file_sep>package scripts.bbuu20_miner.main_tasks
import org.tribot.api.DynamicClicking
import org.tribot.api.General
import org.tribot.api.Timing
import org.tribot.api2007.*
import org.tribot.api2007.types.RSArea
import org.tribot.api2007.types.RSTile
import scripts.bbuu20_api.Framework
import scripts.bbuu20_miner.data.PlayerInfo
import scripts.bbuu20_miner.data.Finals
import scripts.bbuu20_api.enums.MainTask
import scripts.dax_api.api_lib.DaxWalker
import scripts.dax_api.api_lib.WebWalkerServerApi
import scripts.dax_api.api_lib.models.PlayerDetails
import scripts.dax_api.api_lib.models.Point3D
import scripts.dax_api.shared.helpers.BankHelper
class Bank : Framework {
override fun shouldProceed(): Boolean {
return Inventory.isFull()
&& PlayerInfo.shouldBank
&& PlayerInfo.selectedTask != MainTask.TICK_MINING
&& !PlayerInfo.shouldEndFullInv
}
override fun proceed() {
val pathResult = WebWalkerServerApi.getInstance().getBankPath(Point3D.fromPositionable(Player.getPosition()), null, PlayerDetails.generate())
if (!BankHelper.isInBank() && !Finals.PORT_SARIM_DEPOSIT_AREA.contains(Player.getPosition())) {
when {
Finals.MINING_GUILD_P2P.contains(Player.getPosition()) -> { //temporary fix until daxwalker supports mining guild
Walking.blindWalkTo(
RSArea(
RSTile(3014, 9719, 0),
RSTile(3013, 9718, 0)
).randomTile)
Timing.waitCondition({Player.isMoving()}, General.randomLong(500, 2500)) //wait for player to start moving
Timing.waitCondition({!Player.isMoving()}, General.randomLong(500, 15000))
}
Player.getPosition().distanceTo(Finals.PORT_SARIM_DEPOSIT_TILE) < pathResult.toRSTilePath()[pathResult.toRSTilePath().size - 1].distanceTo(Player.getPosition()) -> {
DaxWalker.walkTo(Finals.PORT_SARIM_DEPOSIT_TILE)
}
else -> {
DaxWalker.walkToBank()
}
}
}
else if (!Banking.isBankScreenOpen() && BankHelper.isInBank()) {
Banking.openBank()
}
else if (!Banking.isDepositBoxOpen() && Finals.PORT_SARIM_DEPOSIT_AREA.contains(Player.getPosition())) {
if (!Finals.PORT_SARIM_DEPOSIT_BOX.isOnScreen || !Finals.PORT_SARIM_DEPOSIT_BOX.isClickable) {
Camera.turnToTile(Finals.PORT_SARIM_DEPOSIT_BOX)
}
DynamicClicking.clickRSTile(Finals.PORT_SARIM_DEPOSIT_BOX, "")
Timing.waitCondition({Banking.isDepositBoxOpen()}, General.randomLong(1500, 5500))
}
else if (Inventory.isFull()) {
Banking.depositAllExcept(*Finals.PICK_IDS)
if (Timing.waitCondition({!Inventory.isFull()}, General.randomLong(1500, 3500))) {
Banking.close()
}
}
}
}<file_sep>package scripts.bbuu20_miner.util
import org.tribot.api.DynamicClicking
import org.tribot.api.General
import org.tribot.api.input.Mouse
import org.tribot.api.util.abc.ABCUtil
import org.tribot.api2007.ChooseOption
import org.tribot.api2007.WorldHopper
import org.tribot.api2007.types.RSTile
import scripts.bbuu20_miner.util.worldhopping.Worlds
import scripts.bbuu20_miner.data.PlayerInfo
class AntiBan private constructor() {
private val abcInstance = ABCUtil()
private var averageMiningWaitTime: Long = 0
private var totalMiningWaitTime: Long = 0
private var totalMiningInstances: Long = 0
/*
***TIMED ACTIONS*** (25 pts)
*
* Checks timers based on our profile, performs timed action and prints action if bool returns true
*
* Our player is idling when we call this method
*/
fun idleTimedActions() {
if (abcInstance.shouldCheckTabs()) {
println("Checking tabs.")
abcInstance.checkTabs()
}
if (abcInstance.shouldCheckXP()) {
println("Checking xp.")
General.sleep(General.randomSD(1336, 542).toLong()) //sleep after checking xp
abcInstance.checkXP()
}
if (abcInstance.shouldExamineEntity()) {
println("Examining entity.")
abcInstance.examineEntity()
}
if (abcInstance.shouldMoveMouse()) {
println("Moving mouse.")
abcInstance.moveMouse()
}
if (abcInstance.shouldPickupMouse()) {
println("Picking up mouse.")
abcInstance.pickupMouse()
}
if (abcInstance.shouldRightClick()) {
println("Right clicking.")
abcInstance.rightClick()
}
if (abcInstance.shouldRotateCamera()) {
println("Rotating camera.")
abcInstance.rotateCamera()
}
if (abcInstance.shouldLeaveGame()) {
println("Leaving game.")
abcInstance.leaveGame()
}
}
/*
***Preferences*** (10 pts)
*
* Preferred ways of doing things based on our profile.
*
* Preferences implemented in this script:
* * Next target preference
*
* Preferences already handled by default in this script:
* * Walking preference
* * Open Bank Preference handled by default
* * Tab Switching Preference handled by default
*/
fun getNextTarget(tiles: HashSet<RSTile>?): RSTile? {
if (tiles.isNullOrEmpty()) {
return null
}
return abcInstance.selectNextTarget(tiles.toTypedArray()) as RSTile
}
/*
***Action Conditions*** (26 pts)
*
* Generates when something should be done based on our profile.
*
* Preferences implemented in this script:
* * Energy to activate run at
* * Resource switching upon high competition (in the form of optional world hopping)
* * Hovering over next target
*
* Action Conditions already handled by default in this script:
* * HP to eat at not applicable is not applicable to mining
* * Moving to anticipated is not applicable to mining
*/
fun getRunEnergyToActivate(): Int {
return abcInstance.generateRunActivation()
}
fun shouldHopPlayerCount(competitionCount: Int): Boolean {
if (abcInstance.shouldSwitchResources(competitionCount)) {
return hopWorlds()
}
return false
}
fun hopWorlds(): Boolean {
PlayerInfo.nextWorld = Worlds.getRandomWorld(PlayerInfo.isMembers)
var canHop = Worlds.canHopToWorld(PlayerInfo.nextWorld)
while (!canHop) {
PlayerInfo.nextWorld = Worlds.getRandomWorld(PlayerInfo.isMembers)
canHop = Worlds.canHopToWorld(PlayerInfo.nextWorld)
General.sleep(1)
}
println("Hopping to world ${PlayerInfo.nextWorld}")
PlayerInfo.currentRSRock = null
PlayerInfo.nextRSRock = null
return WorldHopper.changeWorld(PlayerInfo.nextWorld)
}
fun hoverTargetActions() {
if (PlayerInfo.nextRSRock != null) {
if (abcInstance.shouldHover() && Mouse.isInBounds()) {
PlayerInfo.nextRSRock!!.hover()
PlayerInfo.isHoveringNextRock = true
if (abcInstance.shouldOpenMenu()) {
General.sleep(
General.randomSD(
71,
542
).toLong()
) //generate time between hovering and opening menu
if (!ChooseOption.isOpen()) {
DynamicClicking.clickRSTile(PlayerInfo.nextRSRock, 3)
}
}
}
}
}
/*
***Reaction Times*** (40 pts)
*
* Generates reaction times using abc instead of using random sleeps
*
* Additional Reaction Time implemented in this script:
* * Generate current fatigue
*/
fun updateMiningStatistics(startedMining: Long) {
val lastMiningWaitTime = System.currentTimeMillis() - startedMining
totalMiningInstances++
totalMiningWaitTime += lastMiningWaitTime
averageMiningWaitTime = totalMiningWaitTime / totalMiningInstances
}
private fun generateCurrentFatigue(): Long {
val currentTime = System.currentTimeMillis() - PlayerInfo.startedRunTime
return (PlayerInfo.fatigueRate * currentTime).toLong()
}
private fun generateSupportingTrackerInfo() { //Called right after clicking a rock
abcInstance.generateTrackers(averageMiningWaitTime)
}
private fun generateReactionTime(waitingTime: Int): Int {
return abcInstance.generateReactionTime(abcInstance.generateBitFlags(waitingTime)) //return reaction time in ms
} //Called right after finishing mining a rock
fun generateAndSleep(startTime: Long) { //sleeps for the generated amount of time. Called after reaction time is generated
try {
generateSupportingTrackerInfo()
val time = generateReactionTime((System.currentTimeMillis() - startTime).toInt())
val adjustedTime: Long = ((time.toLong() / PlayerInfo.reactionTime) + generateCurrentFatigue()).toLong()
println("Sleeping for: $adjustedTime milliseconds.")
abcInstance.sleep(adjustedTime)
} catch (e: InterruptedException) {
println("The background thread interrupted the abc sleep.")
}
}
companion object {
private val antiban = AntiBan()
fun get(): AntiBan {
return antiban
}
}
}<file_sep>package test.linkedlist;
// Imports
// JUnit
// General
import linkedlist.LinkedList;
import linkedlist.Student;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.jupiter.api.Test;
import org.junit.runners.MethodSorters;
import java.util.List;
import java.util.ArrayList;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LinkedListTest {
/* -------------------------------------------------------------
* Setup
* -------------------------------------------------------------
*/
final int n_students = 10;
LinkedList<Student> L;
List<Student> students;
/*
* Method for generating objects used during the test
*/
@Before
public void setUp() throws Exception {
// Create an empty list of integers
L = new LinkedList<Student>();
// Create some students
students = new ArrayList<Student>();
for(int i = 0; i < n_students; i++) {
students.add(new Student(i, "s" + i));
}
}
/*
* Method for printing Students
*/
public static String printStudent(Student s) {
return "{" + s.getId() + ", " + s.getName() + "}";
}
/*
* Methods for printing expected verses received output
*/
public static String expectedOutput(Student exp, Student rec) {
String exp_string = "null";
String rec_string = "null";
if (exp != null) {
exp_string = printStudent(exp);
}
if (rec != null) {
rec_string = printStudent(rec);
}
return expectedOutput(exp_string, rec_string);
}
public static String expectedOutput(int exp, int rec) {
return expectedOutput(Integer.toString(exp), Integer.toString(rec));
}
public static String expectedOutput(String exp, String rec) {
return "Expected: " + exp + " but received " + rec;
}
/* -------------------------------------------------------------
* getSize() and getElement() after add() Tests
* -------------------------------------------------------------
*/
@Test
public void addEmptyList() {
// Add a single element
assert(L.add(students.get(0))) : "add() method should return true";
// Assert the size of the linked list is non-zero
assert(L.getSize() == 1) : expectedOutput(1, L.getSize());
}
@Test
public void addNonEmptyList() {
// Create an empty list of integers
LinkedList<Integer> L = new LinkedList<Integer>();
// Add integers 0 through 9 to the list
for(int i = 0; i < 10; i ++) {
L.add(i);
assert(L.getSize() == i+1) : expectedOutput(i+1, L.getSize());
}
}
@Test
public void getElementEmptyList() {
assert(L.getElement(0) == null);
}
@Test
public void getElementSingletonList() {
Student expected = students.get(0);
// Add a single element
L.add(expected);
// Assert the only element in the list is the Student s
Student received = L.getElement(0);
assert(expected.equals(received)) : expectedOutput(expected, received);
// Verify there are no other elements in the list
assert(L.getElement(1) == null);
}
/* -------------------------------------------------------------
* size() and getElement() after delete() Tests
* -------------------------------------------------------------
*/
@Test
public void deleteEmptyList() {
assert(!L.delete(0)) : "delete should return false when no element is removed";
}
@Test
public void deleteSingletonList() {
Student s = students.get(3);
// Add the student to the list
L.add(s);
// Remove it
assert(L.delete(0)) : "expected True but received false";
// Make sure it's still not in the list
assert(L.getSize() == 0) : expectedOutput(0, L.getSize());
for(int i = 0; i < L.getSize(); i++) {
assert(L.getElement(i) != s);
}
}
@Test
public void deleteMultiElementListFront() {
Student s0 = students.get(2);
Student s1 = students.get(4);
Student s2 = students.get(6);
// Add the students to the list
L.add(s0);
L.add(s1);
L.add(s2);
// Delete s0 from the list
assert(L.delete(0)) : "expected true but was false";
// Verify the size of the list
assert(L.getSize() == 2) : expectedOutput(2, L.getSize());
// Verify the order of the elements in the list
Student rec0 = L.getElement(0);
assert(s1.equals(rec0)) : expectedOutput(s1, rec0);
Student rec1 = L.getElement(1);
assert(s2.equals(rec1)) : expectedOutput(s2, rec1);
}
@Test
public void deleteMultiElementListEnd() {
Student s0 = students.get(2);
Student s1 = students.get(4);
Student s2 = students.get(6);
// Add the students to the list
L.add(s0);
L.add(s1);
L.add(s2);
// Delete s2 from the list
assert(L.delete(2)) : "expected true but was false";
// Verify the size of the list
assert(L.getSize() == 2) : expectedOutput(2, L.getSize());
// Verify the order of the elements in the list
Student rec0 = L.getElement(0);
assert(s0.equals(rec0)) : expectedOutput(s0, rec0);
Student rec1 = L.getElement(1);
assert(s1.equals(rec1)) : expectedOutput(s1, rec1);
}
/* -------------------------------------------------------------
* size() and getElement() after insert() Tests
* -------------------------------------------------------------
*/
@Test
public void insertEmptyListIndexEquals0() {
Student exp = students.get(7);
// Insert a single element into the list
L.insert(0, exp);
// Verify the size increases
assert(L.getSize() == 1) : expectedOutput(1, L.getSize());
// Verify the element was added correctly
Student rec = L.getElement(0);
assert(exp.equals(rec)) : expectedOutput(exp, rec);
}
@Test
public void insertEmptyListIndexTooLarge() {
Student exp = students.get(7);
// Insert a single element into the list
assert(!L.insert(15, exp)) : "insert should return false when index is too large";
// Verify the size increases
assert(L.getSize() == 0) : expectedOutput(0, L.getSize());
// Verify the element is not in the list
Student rec = L.getElement(0);
assert(rec == null);
}
@Test
public void insertSingletonListIndexTooLarge() {
Student exp = students.get(8);
// Insert an element in L
L.add(students.get(4));
// Try to insert at index 100
assert(!L.insert(100, exp)) : "insert should return false when index is too large";
// Verify the size of the list
assert(L.getSize() == 1) : expectedOutput(1, L.getSize());
// Verify the element wasnt added to the list
for(int i = 0; i < L.getSize(); i++) {
assert(!exp.equals(L.getElement(i))) : "found element that shouldnt be in the list!";
}
}
@Test
public void insertSingletonListAtEnd() {
Student exp0 = students.get(3);
Student exp1 = students.get(5);
// Add an element into the list
L.add(exp0);
// Insert at the front
L.insert(1, exp1);
// Verify the order of the list
Student rec0 = L.getElement(0);
assert(exp0.equals(rec0)) : expectedOutput(exp0, rec0);
Student rec1 = L.getElement(1);
assert(exp1.equals(rec1)) : expectedOutput(exp1, rec1);
}
@Test
public void insertMiddleMultiElementList() {
Student s0 = students.get(3);
Student s1 = students.get(5);
Student s2 = students.get(7);
// Add two elements into the list
L.add(s0);
L.add(s1);
// Insert s2 in between s0 and s1
L.insert(1, s2);
// Verify the order of the list
Student rec0 = L.getElement(0);
assert(s0.equals(rec0)) : expectedOutput(s0, rec0);
Student rec1 = L.getElement(1);
assert(s2.equals(rec1)) : expectedOutput(s2, rec1);
Student rec2 = L.getElement(2);
assert(s1.equals(rec2)) : expectedOutput(s1, rec2);
}
/* -------------------------------------------------------------
* search() Tests
* -------------------------------------------------------------
*/
@Test
public void searchEmptyList() {
Student s = students.get(5);
int i = L.search(s);
assert(i == -1) : expectedOutput(-1, i);
}
@Test
public void searchSingletonListWithElement() {
Student s = students.get(5);
// Add the element to the list
L.add(s);
// Search for the element in the list
int i = L.search(s);
assert(i == 0) : expectedOutput(0, i);
}
@Test
public void searchSingletonListWithoutElement() {
Student s1 = students.get(5);
Student s2 = students.get(8);
// Add the element to the list
L.add(s1);
// Search for the element in the list
int i = L.search(s2);
assert(i == -1) : expectedOutput(-1, i);
}
@Test
public void searchMultipleCopies() {
Student s1 = students.get(5);
Student s2 = students.get(8);
Student s3 = students.get(3);
// Add some students to the list including multiple duplicates
L.add(s1);
L.add(s2);
L.add(s1);
L.add(s3);
L.add(s3);
L.add(s2);
// Search for each student and ensure we find the right index
int i1 = L.search(s1);
assert(i1 == 0) : expectedOutput(0, i1);
int i2 = L.search(s2);
assert(i2 == 1) : expectedOutput(1, i2);
int i3 = L.search(s3);
assert(i3 == 3) : expectedOutput(3, i3);
}
/* -------------------------------------------------------------
* mixed Tests
* -------------------------------------------------------------
*/
@Test
public void mixedDeleteLastThenAdd() {
Student s0 = students.get(2);
Student s1 = students.get(4);
Student s2 = students.get(6);
Student s3 = students.get(9);
// Add the students to the list
L.add(s0);
L.add(s1);
L.add(s2);
// Delete s2 from the list
L.delete(2);
// Add s3 to the end of the list
assert(L.add(s3)) : "expected true but was false";
// Verify the size of the list
// Verify the order of the elements in the list
Student rec0 = L.getElement(0);
assert(s0.equals(rec0)) : expectedOutput(s0, rec0);
Student rec1 = L.getElement(1);
assert(s1.equals(rec1)) : expectedOutput(s1, rec1);
Student rec2 = L.getElement(2);
assert(s3.equals(rec2)) : expectedOutput(s3, rec2);
}
@Test
public void mixedDeleteLastThenInsertEnd() {
Student s0 = students.get(2);
Student s1 = students.get(4);
Student s2 = students.get(6);
Student s3 = students.get(9);
// Add the students to the list
L.add(s0);
L.add(s1);
L.add(s2);
// Delete s2 from the list
L.delete(2);
// Add s3 to the end of the list
assert(L.insert(2, s3)) : "expected true but was false";
// Verify the size of the list
// Verify the order of the elements in the list
Student rec0 = L.getElement(0);
assert(s0.equals(rec0)) : expectedOutput(s0, rec0);
Student rec1 = L.getElement(1);
assert(s1.equals(rec1)) : expectedOutput(s1, rec1);
Student rec2 = L.getElement(2);
assert(s3.equals(rec2)) : expectedOutput(s3, rec2);
}
@Test
public void mixedSearchDeleteSearch() {
Student s0 = students.get(2);
Student s1 = students.get(4);
Student s2 = students.get(6);
// Add the students to the list
L.add(s0);
L.add(s1);
L.add(s2);
// Search for s1
assert(L.search(s1) == 1) : expectedOutput(1, L.search(s1));
// Delete s1 from the list
L.delete(1);
// Search for s1 again and find nothing
assert(L.search(s1) == -1) : expectedOutput(-1, L.search(s1));
}
}<file_sep>package scripts.bbuu20_miner.data;
import org.tribot.api2007.types.RSArea;
import org.tribot.api2007.types.RSTile;
import org.tribot.util.Util;
public class Finals {
public static final String PATH_TO_BBUU20_FOLDER = Util.getWorkingDirectory().getAbsolutePath() + "/bbuu20";
public static final int SWAMP_TAR_ID = 1939;
public static final int GRINDING_ID = 5249;
public static final int[] HERB_IDS = {249, 251, 253, 255};
public static final int[] ORE_IDS = {434, 436, 438, 440, 442, 444, 447, 449, 451, 453, 1617, 1619, 1621, 1623, 1625, 1627, 1629, 1761, 3211, 6971, 6973, 6975, 6977, 6979, 6981, 6983, 21347};
public static final int[] PICK_IDS =
{
1265, //bronze pick
1267, //iron pick
1269, //steel pick
12297, //black pick
1273, //mithril pick
1271, //adamant pick
1275, //rune pick
11920 //dragon pick
};
public static final RSTile PORT_SARIM_DEPOSIT_BOX = new RSTile(3045, 3234);
public static final RSTile PORT_SARIM_DEPOSIT_TILE = new RSTile(3045, 3235);
public static final RSTile[][] TICK_ROCK_TILES =
{
{ //East Ardougne iron mine
new RSTile(2714, 3330) /* Rock 1 */,
new RSTile(2715, 3331) /* Rock 2 */,
new RSTile(2712, 3329) /* Rock 3 */,
new RSTile(2713, 3332) /* Rock 4 */,
},
{ //Sandstone/Granite
new RSTile(3167, 2915) /* Rock 1 */,
new RSTile(3167, 2913) /* Rock 2 */,
new RSTile(3166, 2915) /* Rock 3 */,
new RSTile(3166, 2913) /* Rock 4 */,
},
{ //Granite
new RSTile(3165, 2910) /* Rock 1 */,
new RSTile(3167, 2911) /* Rock 2 */,
new RSTile(3165, 2908) /* Rock 3 */,
new RSTile(3165, 2909) /* Rock 4 */,
}
};
public static final RSArea PORT_SARIM_DEPOSIT_AREA = new RSArea(
new RSTile(3052, 3237, 0),
new RSTile(3040, 3234, 0)
);
public static final RSArea MINING_GUILD_P2P = new RSArea(
new RSTile(3060, 9729, 0),
new RSTile(3008, 9697, 0)
);
}<file_sep>package scripts.bbuu20_miner.data
import org.tribot.api2007.Equipment
import org.tribot.api2007.Inventory
import org.tribot.api2007.Objects
import org.tribot.api2007.Player
import org.tribot.api2007.types.RSTile
import scripts.bbuu20_api.enums.MainTask
import scripts.bbuu20_api.enums.Rock
import scripts.bbuu20_api.extensions.findNearest
import scripts.bbuu20_api.enums.Pick
import scripts.bbuu20_miner.gui.GUI
import scripts.bbuu20_miner.gui.MainGUIFXML
import scripts.bbuu20_miner.util.AntiBan
import scripts.bbuu20_miner.util.ProgressiveTask
import java.io.File
object PlayerInfo {
val gui = GUI(MainGUIFXML.get)
var profile = File("")
var taskKey = -1
var shouldShowGui = true
var shouldEndFullInv = false
var isMembers = false
var shouldBank = false
var isHoveringNextRock = false
var shouldHopHighCompetition = false
var shouldHopOnChat = false
var shouldHopDepleted = false
var shouldUseAntiPK = false
var shouldCheckGuideOnOccasion = false
var shouldOpenMapOnTraverse = false
var shouldPaint = false
var shouldDrawDebug = false
var reactionTime = 25.0
var fatigueRate = 0.0
val startedRunTime = System.currentTimeMillis()
var nextWorld = -1
var miningRadius = 0
var levelToStartAt = 0
var levelToEndAt = 100
var currentOrePrice = 0
var gpMade = 0
var startingTile = RSTile(-1, -1)
var progressiveTasks = HashSet<ProgressiveTask>()
var availableRocks = HashSet<RSTile>()
var possibleNextRocks = HashSet<RSTile>()
var selectedRockTypes: List<Rock> = listOf()
var nonEmptyRocks = HashSet<RSTile>()
var selectedPick = Pick.ANY_PICK
var currentPick = Pick.ANY_PICK
var currentRSRock: RSTile ?= null
var nextRSRock: RSTile ?= null
lateinit var selectedTask: MainTask
private fun updateRocks() {
val nearbyRocks = if (currentRSRock != null) {
Objects().findNearest(
miningRadius + Player.getPosition().distanceTo(
currentRSRock
), selectedRockTypes.toList())
} else {
Objects().findNearest(25, selectedRockTypes.toList())
}
val nearbyRockTiles = HashSet<RSTile>(10)
nearbyRocks.forEach { rock ->
nearbyRockTiles.add(rock.position)
if (rock.position.distanceToDouble(startingTile) <= miningRadius) {
availableRocks.add(rock.position)
nonEmptyRocks.add(rock.position)
possibleNextRocks.add(rock.position)
}
}
nonEmptyRocks = nonEmptyRocks.intersect(nearbyRockTiles).toHashSet()
possibleNextRocks = nonEmptyRocks.intersect(nearbyRockTiles).toHashSet()
}
private fun updateCurrentRock() {
if (!nonEmptyRocks.contains(currentRSRock)) {
if (nextRSRock == null) {
currentRSRock = AntiBan.get().getNextTarget(
nonEmptyRocks
)
}
else {
currentRSRock =
nextRSRock; nextRSRock = null
}
}
possibleNextRocks.remove(currentRSRock)
}
private fun updateNextRock() {
if (nextRSRock == null || !possibleNextRocks.contains(
nextRSRock!!)) {
nextRSRock = AntiBan.get().getNextTarget(
possibleNextRocks
)
}
}
fun shouldUpgradePick(): Boolean {
return (selectedPick != currentPick && selectedPick != Pick.ANY_PICK) || currentPick == Pick.NO_PICK
}
fun updateAllRocks() {
updateRocks()
updateCurrentRock()
updateNextRock()
}
fun updateCurrentPick() {
if (Inventory.getCount(Pick.INFERNAL_PICK.id) > 0 || Equipment.isEquipped(Pick.INFERNAL_PICK.id)) {
currentPick = Pick.INFERNAL_PICK
}
else if (Inventory.getCount(Pick.DECORATED_DRAGON_PICK.id) > 0 || Equipment.isEquipped(Pick.DECORATED_DRAGON_PICK.id)) {
currentPick = Pick.DECORATED_DRAGON_PICK
}
else if (Inventory.getCount(Pick.DRAGON_PICK.id) > 0 || Equipment.isEquipped(Pick.DRAGON_PICK.id)) {
currentPick = Pick.DRAGON_PICK
}
else if (Inventory.getCount(Pick.RUNE_PICK.id) > 0 || Equipment.isEquipped(Pick.RUNE_PICK.id)) {
currentPick = Pick.RUNE_PICK
}
else if (Inventory.getCount(Pick.ADAMANT_PICK.id) > 0 || Equipment.isEquipped(Pick.ADAMANT_PICK.id)) {
currentPick = Pick.ADAMANT_PICK
}
else if (Inventory.getCount(Pick.MITHRIL_PICK.id) > 0 || Equipment.isEquipped(Pick.MITHRIL_PICK.id)) {
currentPick = Pick.MITHRIL_PICK
}
else if (Inventory.getCount(Pick.BLACK_PICK.id) > 0 || Equipment.isEquipped(Pick.BLACK_PICK.id)) {
currentPick = Pick.BLACK_PICK
}
else if (Inventory.getCount(Pick.STEEL_PICK.id) > 0 || Equipment.isEquipped(Pick.STEEL_PICK.id)) {
currentPick = Pick.STEEL_PICK
}
else if (Inventory.getCount(Pick.IRON_PICK.id) > 0 || Equipment.isEquipped(Pick.IRON_PICK.id)) {
currentPick = Pick.IRON_PICK
}
else if (Inventory.getCount(Pick.BRONZE_PICK.id) > 0 || Equipment.isEquipped(Pick.BRONZE_PICK.id)) {
currentPick = Pick.BRONZE_PICK
}
else {
currentPick = Pick.NO_PICK
}
}
}<file_sep>package scripts.bbuu20_miner.util;
import org.tribot.api2007.types.RSTile;
import scripts.bbuu20_api.enums.Pick;
import scripts.bbuu20_api.enums.Rock;
import java.util.ArrayList;
import java.util.List;
public class ProgressiveTask {
private String taskName; //The name entered by the user, and displayed in the Progressive Mining tab
private boolean shouldEndFullInv;
private boolean shouldBank;
private boolean shouldHop;
private boolean isMembers;
private boolean shouldWalkOnStart; //whether we should walk to tileToTraverse
private int radius;
private int levelToStartAt;
private int levelToEndAt;
private RSTile tileToTraverse;
private Pick selectedPick;
private List<Rock> selectedRocks; //The rock(s) selected by the user
public ProgressiveTask() {
}
public ProgressiveTask(String taskName, List<Rock> selectedRocks, Pick selectedPick, int radius, int levelToStartAt, int levelToEndAt, boolean shouldEndFullInv, boolean shouldBank, boolean shouldHop, boolean isMembers, boolean shouldWalkOnStart, RSTile tileToTraverse) {
this.taskName = taskName;
this.selectedPick = selectedPick;
this.radius = radius;
this.levelToStartAt = levelToStartAt;
this.levelToEndAt = levelToEndAt;
this.shouldEndFullInv = shouldEndFullInv;
this.shouldBank = shouldBank;
this.shouldHop = shouldHop;
this.isMembers = isMembers;
this.shouldWalkOnStart = shouldWalkOnStart;
this.tileToTraverse = tileToTraverse;
List<Rock> clonedRocks = new ArrayList<>(selectedRocks);
this.selectedRocks = clonedRocks;
}
public String getTaskName() {
return taskName;
}
public List<Rock> getSelectedRocks() {
return selectedRocks;
}
public Pick getSelectedPick() {
return selectedPick;
}
public int getRadius() {
return radius;
}
public int getLevelToStartAt() {
return levelToStartAt;
}
public int getLevelToEndAt() {
return levelToEndAt;
}
public boolean isShouldEndFullInv() {
return shouldEndFullInv;
}
public boolean isShouldBank() {
return shouldBank;
}
public boolean isShouldHop() {
return shouldHop;
}
public boolean isMembers() {
return isMembers;
}
public boolean isShouldWalkOnStart() {
return shouldWalkOnStart;
}
public RSTile getTileToTraverse() {
return tileToTraverse;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public void setShouldEndFullInv(boolean shouldEndFullInv) {
this.shouldEndFullInv = shouldEndFullInv;
}
public void setShouldBank(boolean shouldBank) {
this.shouldBank = shouldBank;
}
public void setShouldHop(boolean shouldHop) {
this.shouldHop = shouldHop;
}
public void setMembers(boolean members) {
isMembers = members;
}
public void setShouldWalkOnStart(boolean shouldWalkOnStart) {
this.shouldWalkOnStart = shouldWalkOnStart;
}
public void setRadius(int radius) {
this.radius = radius;
}
public void setLevelToStartAt(int levelToStartAt) {
this.levelToStartAt = levelToStartAt;
}
public void setLevelToEndAt(int levelToEndAt) {
this.levelToEndAt = levelToEndAt;
}
public void setTileToTraverse(RSTile tileToTraverse) {
this.tileToTraverse = tileToTraverse;
}
public void setSelectedPick(Pick selectedPick) {
this.selectedPick = selectedPick;
}
public void setSelectedRocks(List<Rock> selectedRocks) {
this.selectedRocks = selectedRocks;
}
@Override
public String toString() {
return taskName + " with " + selectedPick + " (From Levels " + levelToStartAt + " -> " + levelToEndAt + ")";
}
}
<file_sep>package scripts.bbuu20_miner.main_tasks
import org.tribot.api2007.Inventory
import scripts.bbuu20_api.Framework
import scripts.bbuu20_miner.data.Finals
import scripts.bbuu20_miner.data.PlayerInfo
import scripts.bbuu20_api.enums.MainTask
class Drop : Framework {
override fun shouldProceed(): Boolean {
return Inventory.isFull()
&& !PlayerInfo.shouldBank
&& PlayerInfo.selectedTask != MainTask.TICK_MINING
&& !PlayerInfo.shouldEndFullInv
}
override fun proceed() {
while (Inventory.getCount(*Finals.ORE_IDS) > 0) {
Inventory.dropAllExcept(*Finals.PICK_IDS)
}
}
}<file_sep>package scripts.bbuu20_miner.main_tasks
import org.tribot.api.General
import org.tribot.api.Timing
import org.tribot.api2007.Banking
import org.tribot.api2007.Inventory
import org.tribot.api2007.Player
import org.tribot.api2007.Walking
import org.tribot.api2007.types.RSArea
import org.tribot.api2007.types.RSTile
import scripts.bbuu20_api.Framework
import scripts.bbuu20_miner.data.Finals
import scripts.bbuu20_miner.data.PlayerInfo
import scripts.dax_api.api_lib.DaxWalker
import scripts.dax_api.shared.helpers.BankHelper
class UpgradePick : Framework {
override fun shouldProceed(): Boolean {
return PlayerInfo.shouldUpgradePick()
}
override fun proceed() {
if (!BankHelper.isInBank()) {
if (Finals.MINING_GUILD_P2P.contains(Player.getPosition())) { //temporary fix until daxwalker supports mining guild
Walking.blindWalkTo(
RSArea(
RSTile(3014, 9719, 0),
RSTile(3013, 9718, 0)
).randomTile)
Timing.waitCondition({ Player.isMoving()}, General.randomLong(500, 2500)) //wait for player to start moving
Timing.waitCondition({!Player.isMoving()}, General.randomLong(500, 15000))
}
else {
DaxWalker.walkToBank()
}
}
else if (!Banking.isBankScreenOpen()) {
Banking.openBank()
}
else if (Inventory.getCount(*Finals.PICK_IDS) > 0) {
Banking.depositByIds(1, Finals.PICK_IDS.asList())
}
else {
Banking.withdraw(1, PlayerInfo.selectedPick.id)
if (Timing.waitCondition({Inventory.getCount(PlayerInfo.selectedPick.id) > 0}, General.randomLong(1500, 3500))) {
Banking.close()
}
}
}
}<file_sep>package scripts.bbuu20_miner.util;
import org.apache.commons.io.FileUtils;
import org.tribot.api2007.types.RSTile;
import scripts.bbuu20_miner.data.Finals;
import scripts.bbuu20_api.enums.Pick;
import scripts.bbuu20_api.enums.Rock;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
public class MinerProfile {
//Profile Settings
private String profileName;
//traditional mining
private boolean shouldEndFullInv;
private boolean isMembers;
private boolean shouldBank;
private boolean shouldHopDepleted;
private int miningRadius;
private Pick selectedPick;
private RSTile startingTile;
private int levelToStartAt;
private int levelToEndAt;
private List<Rock> selectedRockTypes;
//progressive mining
private List<ProgressiveTask> progressiveTasks;
//universal settings
private boolean shouldHopHighCompetition;
private boolean shouldHopOnChat;
private boolean shouldUseAntiPK;
private boolean shouldPaint;
private boolean shouldDrawDebug;
private double reactionTime;
private double fatigueRate;
//getters
public String getProfileName() {
return this.profileName;
}
public boolean isShouldEndFullInv() {
return shouldEndFullInv;
}
public boolean isMembers() {
return isMembers;
}
public boolean isShouldBank() {
return shouldBank;
}
public boolean isShouldHopDepleted() {
return shouldHopDepleted;
}
public int getMiningRadius() {
return miningRadius;
}
public Pick getSelectedPick() {
return selectedPick;
}
public RSTile getStartingTile() {
return startingTile;
}
public int getLevelToStartAt() {
return levelToStartAt;
}
public int getLevelToEndAt() {
return levelToEndAt;
}
public List<Rock> getSelectedRockTypes() {
return selectedRockTypes;
}
public List<ProgressiveTask> getProgressiveTasks() {
return progressiveTasks;
}
public boolean isShouldHopHighCompetition() {
return shouldHopHighCompetition;
}
public boolean isShouldHopOnChat() {
return shouldHopOnChat;
}
public boolean isShouldUseAntiPK() {
return shouldUseAntiPK;
}
public boolean isShouldPaint() {
return shouldPaint;
}
public boolean isShouldDrawDebug() {
return shouldDrawDebug;
}
public double getReactionTime() {
return reactionTime;
}
public double getFatigueRate() {
return fatigueRate;
}
//override methods
@Override
public String toString() {
return profileName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MinerProfile that = (MinerProfile) o;
return profileName.equals(that.profileName);
}
@Override
public int hashCode() {
return Objects.hash(profileName);
}
//constructors
public MinerProfile() {
this.profileName = "";
this.shouldEndFullInv = false;
this.isMembers = false;
this.shouldBank = false;
this.shouldHopDepleted = false;
this.miningRadius = 1;
this.selectedPick = Pick.ANY_PICK;
this.selectedRockTypes = new ArrayList<>();
this.startingTile = new RSTile(0, 0);
this.levelToStartAt = 1;
this.levelToEndAt = 100;
this.progressiveTasks = new ArrayList<>();
this.shouldHopHighCompetition = false;
this.shouldHopOnChat = false;
this.shouldUseAntiPK = false;
this.shouldPaint = false;
this.shouldDrawDebug = false;
this.reactionTime = 25;
this.fatigueRate = 0;
}
public MinerProfile(String profileName, boolean shouldEndFullInv, boolean isMembers, boolean shouldBank, boolean shouldHopDepleted, int miningRadius, Pick selectedPick, List<Rock> selectedRockTypes, RSTile startingTile, int levelToStartAt, int levelToEndAt, List<ProgressiveTask> progressiveTasks, boolean shouldHopHighCompetition, boolean shouldHopOnChat, boolean shouldUseAntiPK, boolean shouldPaint, boolean shouldDrawDebug, double reactionTime, double fatigueRate) {
this.profileName = profileName;
this.shouldEndFullInv = shouldEndFullInv;
this.isMembers = isMembers;
this.shouldBank = shouldBank;
this.shouldHopDepleted = shouldHopDepleted;
this.miningRadius = miningRadius;
this.selectedPick = selectedPick;
this.selectedRockTypes = selectedRockTypes;
this.startingTile = startingTile;
this.levelToStartAt = levelToStartAt;
this.levelToEndAt = levelToEndAt;
this.progressiveTasks = progressiveTasks;
this.shouldHopHighCompetition = shouldHopHighCompetition;
this.shouldHopOnChat = shouldHopOnChat;
this.shouldUseAntiPK = shouldUseAntiPK;
this.shouldPaint = shouldPaint;
this.shouldDrawDebug = shouldDrawDebug;
this.reactionTime = reactionTime;
this.fatigueRate = fatigueRate;
}
//file methods
public void deleteMinerProfile(File minerProfile) throws IOException {
FileUtils.forceDelete(minerProfile);
}
public boolean saveMinerProfile() throws IOException {
File profileDirectory = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName);
File traditionalMiningDirectory = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName + "/traditionalMining");
File progressiveMiningDirectory = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName + "/progressiveMining");
File profileSettings = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName + "/profileSettings.txt");
File universalSettings = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName + "/universalSettings.txt");
if (profileDirectory.exists()) {
deleteMinerProfile(profileDirectory);
}
if (!profileDirectory.mkdirs()) {
return false;
}
if (!profileSettings.exists()) {
if (!profileSettings.createNewFile()) {
return false;
}
FileWriter localWriter = new FileWriter(profileSettings);
localWriter.write(profileName);
localWriter.close();
}
if (!traditionalMiningDirectory.exists()) {
File traditionalMining = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName + "/traditionalMining/traditionalMining.txt");
File selectedRocks = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName + "/traditionalMining/selectedRocks.txt");
if (!traditionalMiningDirectory.mkdirs()) {
return false;
}
if (!traditionalMining.exists()) {
if (!traditionalMining.createNewFile()) {
return false;
}
FileWriter localWriter = new FileWriter(traditionalMining);
if (shouldEndFullInv) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (isMembers) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (shouldBank) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (shouldHopDepleted) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
localWriter.write(miningRadius + "\n");
localWriter.write(startingTile.getX() + "\n");
localWriter.write(startingTile.getY() + "\n");
localWriter.write(levelToStartAt + "\n");
localWriter.write(levelToEndAt + "\n");
localWriter.write(selectedPick.toString() + "\n");
localWriter.close();
}
if (!selectedRocks.exists()) {
if (!selectedRocks.createNewFile()) {
return false;
}
FileWriter localWriter = new FileWriter(selectedRocks);
for (Rock rock : selectedRockTypes) {
localWriter.write(rock.toString() + "\n");
}
localWriter.close();
}
}
if (!progressiveMiningDirectory.exists()) {
if (!progressiveMiningDirectory.mkdirs()) {
return false;
}
for (ProgressiveTask progressiveTask : progressiveTasks) {
File currentTaskDirectory = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName + "/progressiveMining/" + progressiveTask.getTaskName());
File currentTaskFile = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName + "/progressiveMining/" + progressiveTask.getTaskName() + "/" + progressiveTask.getTaskName() + ".txt");
File selectedRocks = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName + "/progressiveMining/" + progressiveTask.getTaskName() + "/selectedRocks.txt");
if (!currentTaskDirectory.exists()) {
if (!currentTaskDirectory.mkdirs()) {
return false;
}
if (!currentTaskFile.exists()) {
if (!currentTaskFile.createNewFile()) {
return false;
}
FileWriter localWriter = new FileWriter(currentTaskFile);
if (progressiveTask.isShouldEndFullInv()) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (progressiveTask.isShouldBank()) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (progressiveTask.isShouldHop()) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (progressiveTask.isMembers()) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (progressiveTask.isShouldWalkOnStart()) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
localWriter.write(progressiveTask.getRadius() + "\n");
localWriter.write(progressiveTask.getLevelToStartAt() + "\n");
localWriter.write(progressiveTask.getLevelToEndAt() + "\n");
localWriter.write(progressiveTask.getTileToTraverse().getX() + "\n");
localWriter.write(progressiveTask.getTileToTraverse().getY() + "\n");
localWriter.write(progressiveTask.getSelectedPick().toString() + "\n");
localWriter.close();
}
if (!selectedRocks.exists()) {
if (!selectedRocks.createNewFile()) {
return false;
}
FileWriter localWriter = new FileWriter(selectedRocks);
for (Rock rock : progressiveTask.getSelectedRocks()) {
localWriter.write(rock.toString() + "\n");
}
localWriter.close();
}
}
}
}
if (!universalSettings.exists()) {
if (!universalSettings.createNewFile()) {
return false;
}
FileWriter localWriter = new FileWriter(universalSettings);
if (shouldHopHighCompetition) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (shouldHopOnChat) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (shouldUseAntiPK) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (shouldPaint) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
if (shouldDrawDebug) {
localWriter.write("1\n");
}
else {
localWriter.write("0\n");
}
localWriter.write(reactionTime + "\n");
localWriter.write(fatigueRate + "\n");
localWriter.close();
}
return true;
}
public boolean loadProfile(String profileName) throws FileNotFoundException {
this.profileName = profileName;
Scanner localReader;
String PATH_TO_PROFILE_FOLDER = Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + profileName;
File profileDirectory = new File(PATH_TO_PROFILE_FOLDER);
File progressiveMiningDirectory = new File(PATH_TO_PROFILE_FOLDER + "/progressiveMining");
File traditionalMiningFile = new File(PATH_TO_PROFILE_FOLDER + "/traditionalMining/traditionalMining.txt");
File traditionalMiningRocks = new File(PATH_TO_PROFILE_FOLDER + "/traditionalMining/selectedRocks.txt");
File universalSettings = new File(PATH_TO_PROFILE_FOLDER + "/universalSettings.txt");
if (!profileDirectory.exists() || !traditionalMiningFile.exists() || !traditionalMiningRocks.exists() || !universalSettings.exists() || !progressiveMiningDirectory.exists()) {
return false;
}
/**
* Local Loading
*/
localReader = new Scanner(traditionalMiningFile);
this.shouldEndFullInv = Integer.parseInt(localReader.nextLine()) == 1;
this.isMembers = Integer.parseInt(localReader.nextLine()) == 1;
this.shouldBank = Integer.parseInt(localReader.nextLine()) == 1;
this.shouldHopDepleted = Integer.parseInt(localReader.nextLine()) == 1;
this.miningRadius = Integer.parseInt(localReader.nextLine());
this.startingTile = new RSTile(Integer.parseInt(localReader.nextLine()), Integer.parseInt(localReader.nextLine()));
this.levelToStartAt = Integer.parseInt(localReader.nextLine());
this.levelToEndAt = Integer.parseInt(localReader.nextLine());
switch (localReader.nextLine()) {
case "ANY_PICK":
this.selectedPick = Pick.ANY_PICK;
break;
case "BRONZE_PICK":
this.selectedPick = Pick.BRONZE_PICK;
break;
case "IRON_PICK":
this.selectedPick = Pick.IRON_PICK;
break;
case "STEEL_PICK":
this.selectedPick = Pick.STEEL_PICK;
break;
case "BLACK_PICK":
this.selectedPick = Pick.BLACK_PICK;
break;
case "MITHRIL_PICK":
this.selectedPick = Pick.MITHRIL_PICK;
break;
case "ADAMANT_PICK":
this.selectedPick = Pick.ADAMANT_PICK;
break;
case "RUNE_PICK":
this.selectedPick = Pick.RUNE_PICK;
break;
case "DRAGON_PICK":
this.selectedPick = Pick.DRAGON_PICK;
break;
case "DECORATED_DRAGON_PICK":
this.selectedPick = Pick.DECORATED_DRAGON_PICK;
break;
case "INFERNAL_PICK":
this.selectedPick = Pick.INFERNAL_PICK;
break;
}
localReader.close();
localReader = new Scanner(traditionalMiningRocks);
while (localReader.hasNextLine()) {
switch (localReader.nextLine()) {
case "CLAY":
this.selectedRockTypes.add(Rock.CLAY);
break;
case "COPPER":
this.selectedRockTypes.add(Rock.COPPER);
break;
case "TIN":
this.selectedRockTypes.add(Rock.TIN);
break;
case "LIMESTONE":
this.selectedRockTypes.add(Rock.LIMESTONE);
break;
case "IRON":
this.selectedRockTypes.add(Rock.IRON);
break;
case "SILVER":
this.selectedRockTypes.add(Rock.SILVER);
break;
case "COAL":
this.selectedRockTypes.add(Rock.COAL);
break;
case "PURE_ESSENCE":
this.selectedRockTypes.add(Rock.PURE_ESSENCE);
break;
case "SANDSTONE":
this.selectedRockTypes.add(Rock.SANDSTONE);
break;
case "GOLD":
this.selectedRockTypes.add(Rock.GOLD);
break;
case "GEM":
this.selectedRockTypes.add(Rock.GEM);
break;
case "GRANITE":
this.selectedRockTypes.add(Rock.GRANITE);
break;
case "MITHRIL":
this.selectedRockTypes.add(Rock.MITHRIL);
break;
case "ADAMANTITE":
this.selectedRockTypes.add(Rock.ADAMANTITE);
break;
case "RUNITE":
this.selectedRockTypes.add(Rock.RUNITE);
break;
case "AMETHYST":
this.selectedRockTypes.add(Rock.AMETHYST);
break;
}
}
localReader.close();
/**
* Progressive Loading
*/
for (File taskFile : Objects.requireNonNull(progressiveMiningDirectory.listFiles())) {
File progressiveFile = new File(taskFile.getAbsolutePath() + "/" + taskFile.getName() + ".txt");
File rocksFile = new File(taskFile.getAbsolutePath() + "/selectedRocks.txt");
if (!progressiveFile.exists() || !rocksFile.exists()) {
return false;
}
ProgressiveTask progressiveTask = new ProgressiveTask();
localReader = new Scanner(progressiveFile);
progressiveTask.setTaskName(taskFile.getName());
progressiveTask.setShouldEndFullInv(Integer.parseInt(localReader.nextLine()) == 1);
progressiveTask.setShouldBank(Integer.parseInt(localReader.nextLine()) == 1);
progressiveTask.setShouldHop(Integer.parseInt(localReader.nextLine()) == 1);
progressiveTask.setMembers(Integer.parseInt(localReader.nextLine()) == 1);
progressiveTask.setShouldWalkOnStart(Integer.parseInt(localReader.nextLine()) ==1);
progressiveTask.setRadius(Integer.parseInt(localReader.nextLine()));
progressiveTask.setLevelToStartAt(Integer.parseInt(localReader.nextLine()));
progressiveTask.setLevelToEndAt(Integer.parseInt(localReader.nextLine()));
progressiveTask.setTileToTraverse(new RSTile(Integer.parseInt(localReader.nextLine()), Integer.parseInt(localReader.nextLine())));
switch (localReader.nextLine()) {
case "ANY_PICK":
progressiveTask.setSelectedPick(Pick.ANY_PICK);
break;
case "BRONZE_PICK":
progressiveTask.setSelectedPick(Pick.BRONZE_PICK);
break;
case "IRON_PICK":
progressiveTask.setSelectedPick(Pick.IRON_PICK);
break;
case "STEEL_PICK":
progressiveTask.setSelectedPick(Pick.STEEL_PICK);
break;
case "BLACK_PICK":
progressiveTask.setSelectedPick(Pick.BLACK_PICK);
break;
case "MITHRIL_PICK":
progressiveTask.setSelectedPick(Pick.MITHRIL_PICK);
break;
case "ADAMANT_PICK":
progressiveTask.setSelectedPick(Pick.ADAMANT_PICK);
break;
case "RUNE_PICK":
progressiveTask.setSelectedPick(Pick.RUNE_PICK);
break;
case "DRAGON_PICK":
progressiveTask.setSelectedPick(Pick.DRAGON_PICK);
break;
case "DECORATED_DRAGON_PICK":
progressiveTask.setSelectedPick(Pick.DECORATED_DRAGON_PICK);
break;
case "INFERNAL_PICK":
progressiveTask.setSelectedPick(Pick.INFERNAL_PICK);
break;
}
localReader.close();
localReader = new Scanner(rocksFile);
List<Rock> localRocks = new ArrayList<>();
while (localReader.hasNextLine()) {
switch (localReader.nextLine()) {
case "CLAY":
localRocks.add(Rock.CLAY);
break;
case "COPPER":
localRocks.add(Rock.COPPER);
break;
case "TIN":
localRocks.add(Rock.TIN);
break;
case "LIMESTONE":
localRocks.add(Rock.LIMESTONE);
break;
case "IRON":
localRocks.add(Rock.IRON);
break;
case "SILVER":
localRocks.add(Rock.SILVER);
break;
case "COAL":
localRocks.add(Rock.COAL);
break;
case "PURE_ESSENCE":
localRocks.add(Rock.PURE_ESSENCE);
break;
case "SANDSTONE":
localRocks.add(Rock.SANDSTONE);
break;
case "GOLD":
localRocks.add(Rock.GOLD);
break;
case "GEM":
localRocks.add(Rock.GEM);
break;
case "GRANITE":
localRocks.add(Rock.GRANITE);
break;
case "MITHRIL":
localRocks.add(Rock.MITHRIL);
break;
case "ADAMANTITE":
localRocks.add(Rock.ADAMANTITE);
break;
case "RUNITE":
localRocks.add(Rock.RUNITE);
break;
case "AMETHYST":
localRocks.add(Rock.AMETHYST);
break;
}
}
progressiveTask.setSelectedRocks(localRocks);
localReader.close();
this.progressiveTasks.add(progressiveTask);
}
/**
* Universal Settings Loading
*/
localReader = new Scanner(universalSettings);
this.shouldHopHighCompetition = Integer.parseInt(localReader.nextLine()) == 1;
this.shouldHopOnChat = Integer.parseInt(localReader.nextLine()) == 1;
this.shouldUseAntiPK = Integer.parseInt(localReader.nextLine()) == 1;
this.shouldPaint = Integer.parseInt(localReader.nextLine()) == 1;
this.shouldDrawDebug = Integer.parseInt(localReader.nextLine()) == 1;
this.reactionTime = Double.parseDouble(localReader.nextLine());
this.fatigueRate = Double.parseDouble(localReader.nextLine());
localReader.close();
return true;
}
}<file_sep>package scripts.bbuu20_miner.gui;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import org.tribot.api.Timing;
import scripts.bbuu20_miner.data.Finals;
import javax.swing.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class GUI extends Application {
private GUIController controller;
private Stage stage;
private Scene scene;
private boolean isOpen = false;
private String fxml;
public GUI(String fxml) {
this.fxml = fxml;
// We have to start the JFX thread from the EDT otherwise tribot will end it.
SwingUtilities.invokeLater(() -> {
new JFXPanel(); // we have to init the toolkit
Platform.runLater(() -> {
try {
final Stage stage = new Stage();
start(stage);
} catch (Exception e) {
e.printStackTrace();
}
});
});
waitForInit();
}
public Scene getScene() {
return this.scene;
}
public Stage getStage() {
return this.stage;
}
/**
* The main entry point for all JavaFX applications. The start method is called
* after the init method has returned, and after the system is ready for the
* application to begin running.
* <p>
* <p>
* NOTE: This method is called on the JavaFX Application Thread.
* </p>
*
* @param stage
* the primary stage for this application, onto which the application
* scene can be set. The primary stage will be embedded in the
* browser if the application was launched as an applet. Applications
* may create other stages, if needed, but they will not be primary
* stages and will not be embedded in the browser.
*/
@Override
public void start(Stage stage) throws Exception {
File bbuu20Directory = new File(Finals.PATH_TO_BBUU20_FOLDER);
File guiStyleSheet = new File(Finals.PATH_TO_BBUU20_FOLDER + "/gui.css");
this.stage = stage;
stage.setTitle("Bbuu20's AIO Miner");
stage.setAlwaysOnTop(false);
Platform.setImplicitExit(false);
FXMLLoader loader = new FXMLLoader();
loader.setClassLoader(this.getClass().getClassLoader());
Parent box = loader.load(new ByteArrayInputStream(fxml.getBytes()));
controller = loader.getController();
controller.setGUI(this);
scene = new Scene(box);
scene.setFill(Color.TRANSPARENT);
if (!bbuu20Directory.exists()) {
bbuu20Directory.mkdirs();
}
if (!guiStyleSheet.exists()) {
guiStyleSheet.createNewFile();
writeGuiStyleSheet(guiStyleSheet);
}
scene.getStylesheets().add(guiStyleSheet.toURI().toURL().toExternalForm());
stage.getIcons().add(new Image("https://i.imgur.com/wBTvlNv.png"));
stage.setScene(scene);
stage.setResizable(false);
}
@SuppressWarnings("unchecked")
public <T extends GUIController> T getController() {
return (T) this.controller;
}
public void show() {
if (stage == null)
return;
isOpen = true;
Platform.runLater(() -> stage.show());
}
public void close() {
if (stage == null)
return;
isOpen = false;
Platform.runLater(() -> stage.close());
}
public boolean isOpen() {
return isOpen;
}
private void waitForInit() {
Timing.waitCondition(() -> stage != null, 5000);
}
private void writeGuiStyleSheet(File styleSheetPath) throws IOException {
FileWriter styleSheetWriter = new FileWriter(styleSheetPath);
styleSheetWriter.write("/*\n" +
" * This is an adjustment of the original modena.css for a consistent dark theme.\n" +
" * Original modena.css here: https://gist.github.com/maxd/63691840fc372f22f470.\n" +
" */\n" +
"\n" +
"/* Redefine base colors */\n" +
".root {\n" +
" -fx-base: rgb(50, 50, 50);\n" +
" -fx-background: rgb(50, 50, 50);\n" +
"\n" +
" /* make controls (buttons, thumb, etc.) slightly lighter */\n" +
" -fx-color: derive(-fx-base, 10%);\n" +
"\n" +
" /* text fields and table rows background */\n" +
" -fx-control-inner-background: rgb(20, 20, 20);\n" +
" /* version of -fx-control-inner-background for alternative rows */\n" +
" -fx-control-inner-background-alt: derive(-fx-control-inner-background, 2.5%);\n" +
"\n" +
" /* text colors depending on background's brightness */\n" +
" -fx-light-text-color: rgb(220, 220, 220);\n" +
" -fx-mid-text-color: rgb(100, 100, 100);\n" +
" -fx-dark-text-color: rgb(20, 20, 20);\n" +
"\n" +
" /* A bright blue for highlighting/accenting objects. For example: selected\n" +
" * text; selected items in menus, lists, trees, and tables; progress bars */\n" +
" -fx-accent: rgb(0, 80, 100);\n" +
"\n" +
" /* color of non-focused yet selected elements */\n" +
" -fx-selection-bar-non-focused: rgb(50, 50, 50);\n" +
"}\n" +
"\n" +
"/* Fix derived prompt color for text fields */\n" +
".text-input {\n" +
" -fx-prompt-text-fill: derive(-fx-control-inner-background, +50%);\n" +
"}\n" +
"\n" +
"/* Keep prompt invisible when focused (above color fix overrides it) */\n" +
".text-input:focused {\n" +
" -fx-prompt-text-fill: transparent;\n" +
"}\n" +
"\n" +
"/* Fix scroll bar buttons arrows colors */\n" +
".scroll-bar > .increment-button > .increment-arrow,\n" +
".scroll-bar > .decrement-button > .decrement-arrow {\n" +
" -fx-background-color: -fx-mark-highlight-color, rgb(220, 220, 220);\n" +
"}\n" +
"\n" +
".scroll-bar > .increment-button:hover > .increment-arrow,\n" +
".scroll-bar > .decrement-button:hover > .decrement-arrow {\n" +
" -fx-background-color: -fx-mark-highlight-color, rgb(240, 240, 240);\n" +
"}\n" +
"\n" +
".scroll-bar > .increment-button:pressed > .increment-arrow,\n" +
".scroll-bar > .decrement-button:pressed > .decrement-arrow {\n" +
" -fx-background-color: -fx-mark-highlight-color, rgb(255, 255, 255);\n" +
"}");
styleSheetWriter.close();
}
}
<file_sep>package scripts.bbuu20_miner.main_tasks
import org.tribot.api.DynamicClicking
import org.tribot.api.General
import org.tribot.api2007.*
import scripts.bbuu20_api.Framework
import scripts.bbuu20_miner.data.PlayerInfo
import scripts.bbuu20_api.enums.Rock
import scripts.bbuu20_miner.util.AntiBan
import scripts.dax_api.shared.helpers.BankHelper
import scripts.wastedbro.api.rsitem_services.GrandExchange
class Mine : Framework {
override fun shouldProceed(): Boolean {
return !Inventory.isFull()
&& !PlayerInfo.shouldUpgradePick()
&& PlayerInfo.currentRSRock != null
&& PlayerInfo.currentRSRock!!.isOnScreen
&& PlayerInfo.currentRSRock!!.isClickable
&& !BankHelper.isInBank()
}
override fun proceed() {
val localCurrentRock = PlayerInfo.currentRSRock
if (localCurrentRock != null) {
if (ChooseOption.isOpen()) {
ChooseOption.select("Mine")
}
else {
val objsAtTile = Objects.getAt(localCurrentRock)
if (objsAtTile.isNotEmpty()) {
DynamicClicking.clickRSObject(objsAtTile[0], "")
}
}
val startingTime = System.currentTimeMillis() + General.randomLong(2500, 7500)
AntiBan.get().hoverTargetActions()
if (PlayerInfo.shouldPaint) {
Objects.getAt(PlayerInfo.currentRSRock).forEach eachObj@{ rsObject ->
PlayerInfo.selectedRockTypes.forEach { rockType ->
rockType.ids.forEach { rockId ->
if (rsObject.id == rockId) {
var itemId = 0
when (rockType) {
Rock.CLAY -> itemId = 434
Rock.COPPER -> itemId = 436
Rock.TIN -> itemId = 438
Rock.LIMESTONE -> itemId = 3211
Rock.IRON -> itemId = 440
Rock.SILVER -> itemId = 442
Rock.COAL -> itemId = 453
Rock.PURE_ESSENCE -> itemId = 7936
Rock.SANDSTONE -> itemId = 6971
Rock.GOLD -> itemId = 444
Rock.GEM -> itemId = 1625 //needs work, multiple gem rocks
Rock.GRANITE -> itemId = 6979
Rock.MITHRIL -> itemId = 447
Rock.ADAMANTITE -> itemId = 449
Rock.RUNITE -> itemId = 451
Rock.AMETHYST -> itemId = 21347
Rock.RUNE_ESSENCE -> TODO()
Rock.BLURITE -> TODO()
Rock.LOVAKITE -> TODO()
Rock.EMPTY -> TODO()
Rock.NULL -> TODO()
}
PlayerInfo.currentOrePrice = GrandExchange.getPrice(itemId)
return@eachObj
}
}
}
}
}
while (((Player.isMoving() || Player.getAnimation() == -1) && localCurrentRock == PlayerInfo.currentRSRock) && startingTime > System.currentTimeMillis()) {
PlayerInfo.updateAllRocks()
General.sleep(10)
}
val startXp = Skills.getXP(Skills.SKILLS.MINING)
val startedMining: Long = System.currentTimeMillis()
while (localCurrentRock == PlayerInfo.currentRSRock && Player.getAnimation() != -1) {
if (!PlayerInfo.isHoveringNextRock) {
AntiBan.get().idleTimedActions()
}
PlayerInfo.updateAllRocks()
General.sleep(1)
}
if (startXp != Skills.getXP(Skills.SKILLS.MINING)) {
PlayerInfo.gpMade += PlayerInfo.currentOrePrice
}
AntiBan.get().updateMiningStatistics(startedMining)
AntiBan.get().generateAndSleep(startedMining)
}
}
}<file_sep>package scripts.bbuu20_api.extensions
import org.tribot.api2007.Objects
import org.tribot.api2007.types.RSObject
import scripts.bbuu20_api.enums.Rock
fun Objects.findNearest(distance: Int, rocksList: List<Rock>): Array<RSObject> {
var arraySize = 0
for (rocks in rocksList) {
for (id in rocks.ids) {
arraySize++
}
}
val ids = IntArray(arraySize)
var index = 0
for (rocks in rocksList) {
for (id in rocks.ids) {
ids[index] = id
index++
}
}
return Objects.findNearest(distance, *ids)
}<file_sep>package linkedlist;
import java.util.Objects;
public class Node<E> {
/* ------------------------------------------------------------------
* Instance Variables and Constructor
* ------------------------------------------------------------------
*/
private E data;
private Node<E> next;
private Node<E> previous;
public Node(E data) {
this.data = data;
this.next = null;
this.previous = null;
}
/* ------------------------------------------------------------------
* Getters and Setters
* ------------------------------------------------------------------
*/
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
public Node<E> getPrevious() {
return previous;
}
public void setPrevious(Node<E> previous) {
this.previous = previous;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node<?> node = (Node<?>) o;
return Objects.equals(data, node.data) &&
Objects.equals(next, node.next) &&
Objects.equals(previous, node.previous);
}
@Override
public int hashCode() {
return Objects.hash(data, next, previous);
}
@Override
public String toString() {
return data.toString();
}
}
<file_sep>package scripts.bbuu20_api.enums
enum class RockStatus {
EMPTY,
AVAILABLE,
NULL
}<file_sep>package scripts.bbuu20_api.enums
enum class Pick(val id: Int) {
ANY_PICK(-1),
BRONZE_PICK(1265),
IRON_PICK(1267),
STEEL_PICK(1269),
BLACK_PICK(12297),
MITHRIL_PICK(1273),
ADAMANT_PICK(1271),
RUNE_PICK(1275),
DRAGON_PICK(11920),
DECORATED_DRAGON_PICK(12797),
INFERNAL_PICK(13243),
NO_PICK(-1)
}<file_sep>package scripts.bbuu20_miner.gui;
import com.allatori.annotations.DoNotRename;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import org.tribot.api2007.Player;
import org.tribot.api2007.types.RSTile;
import org.tribot.util.Util;
import scripts.bbuu20_miner.data.Finals;
import scripts.bbuu20_miner.data.PlayerInfo;
import scripts.bbuu20_api.enums.MainTask;
import scripts.bbuu20_api.enums.Pick;
import scripts.bbuu20_api.enums.Rock;
import scripts.bbuu20_miner.util.MinerProfile;
import scripts.bbuu20_miner.util.ProgressiveTask;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
@DoNotRename
public class GUIController implements Initializable {
private GUI gui;
private final File PATH_TO_PROFILES = new File(Util.getWorkingDirectory().getAbsolutePath() + "/bbuu20/miner/");
public void setGUI(GUI gui) {
this.gui = gui;
}
public GUI getGUI() {
return this.gui;
}
@DoNotRename @FXML
public TabPane tabPane;
@DoNotRename @FXML
public void traditionalTabChanged() {
if (startMiningButton != null) {
PlayerInfo.INSTANCE.setSelectedTask(MainTask.TRADITIONAL_MINING);
startMiningButton.setText("Start Traditional Mining");
startMiningButton.setDisable(false);
}
}
@DoNotRename @FXML
public void progressiveTabChanged() {
if (startMiningButton != null) {
PlayerInfo.INSTANCE.setSelectedTask(MainTask.PROGRESSIVE_MINING);
startMiningButton.setText("Start Progressive Mining");
startMiningButton.setDisable(false);
}
}
@DoNotRename @FXML
public void antibanTabChanged() {
if (startMiningButton != null) {
startMiningButton.setDisable(true);
}
}
@DoNotRename @FXML
public void saveLoadTabChanged() {
if (startMiningButton != null) {
startMiningButton.setDisable(true);
}
}
@DoNotRename @FXML
public Button tribotButton;
@DoNotRename @FXML
public ImageView tribotImage;
@DoNotRename @FXML
public Button discordButton;
@DoNotRename @FXML
public ImageView discordImage;
@DoNotRename @FXML
public void tribotButtonPressed() throws IOException, URISyntaxException {
Desktop.getDesktop().browse(new URL("https://tribot.org/forums/topic/81450-bbuu20s-aio-miner-beta-3-tick-mining-world-hopping-abc2-level-10/").toURI());
}
@DoNotRename @FXML
public void discordButtonPressed() throws IOException, URISyntaxException {
Desktop.getDesktop().browse(new URL("https://discord.gg/nF7fsjx").toURI());
}
private ColorAdjust brightenImage = new ColorAdjust();
private ColorAdjust darkenImage = new ColorAdjust();
@DoNotRename @FXML
public ImageView copperOreImage;
@DoNotRename @FXML
public void copperMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.COPPER)) {
selectedRocksListView.getItems().add(Rock.COPPER);
copperOreImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.COPPER);
copperOreImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView tinOreImage;
@DoNotRename @FXML
public void tinMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.TIN)) {
selectedRocksListView.getItems().add(Rock.TIN);
tinOreImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.TIN);
tinOreImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView clayImage;
@DoNotRename @FXML
public void clayMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.CLAY)) {
selectedRocksListView.getItems().add(Rock.CLAY);
clayImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.CLAY);
clayImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView limestoneImage;
@DoNotRename @FXML
public void limestoneMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.LIMESTONE)) {
selectedRocksListView.getItems().add(Rock.LIMESTONE);
limestoneImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.LIMESTONE);
limestoneImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView ironOreImage;
@DoNotRename @FXML
public void ironMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.IRON)) {
selectedRocksListView.getItems().add(Rock.IRON);
ironOreImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.IRON);
ironOreImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView silverOreImage;
@DoNotRename @FXML
public void silverMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.SILVER)) {
selectedRocksListView.getItems().add(Rock.SILVER);
silverOreImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.SILVER);
silverOreImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView coalImage;
@DoNotRename @FXML
public void coalMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.COAL)) {
selectedRocksListView.getItems().add(Rock.COAL);
coalImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.COAL);
coalImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView sandstoneImage;
@DoNotRename @FXML
public void sandstoneMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.SANDSTONE)) {
selectedRocksListView.getItems().add(Rock.SANDSTONE);
sandstoneImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.SANDSTONE);
sandstoneImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView goldOreImage;
@DoNotRename @FXML
public void goldMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.GOLD)) {
selectedRocksListView.getItems().add(Rock.GOLD);
goldOreImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.GOLD);
goldOreImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView gemImage;
@DoNotRename @FXML
public void gemMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.GEM)) {
selectedRocksListView.getItems().add(Rock.GEM);
gemImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.GEM);
gemImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView graniteImage;
@DoNotRename @FXML
public void graniteMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.GRANITE)) {
selectedRocksListView.getItems().add(Rock.GRANITE);
graniteImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.GRANITE);
graniteImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView mithrilOreImage;
@DoNotRename @FXML
public void mithrilMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.MITHRIL)) {
selectedRocksListView.getItems().add(Rock.MITHRIL);
mithrilOreImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.MITHRIL);
mithrilOreImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView adamantiteOreImage;
@DoNotRename @FXML
public void adamantiteMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.ADAMANTITE)) {
selectedRocksListView.getItems().add(Rock.ADAMANTITE);
adamantiteOreImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.ADAMANTITE);
adamantiteOreImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView runiteOreImage;
@DoNotRename @FXML
public void runiteMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.RUNITE)) {
selectedRocksListView.getItems().add(Rock.RUNITE);
runiteOreImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.RUNITE);
runiteOreImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView amethystImage;
@DoNotRename @FXML
public void amethystMouseClicked() {
if (!selectedRocksListView.getItems().contains(Rock.AMETHYST)) {
selectedRocksListView.getItems().add(Rock.AMETHYST);
amethystImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.AMETHYST);
amethystImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ImageView essenceImage;
@DoNotRename @FXML
public void essenceImageClicked() {
if (!selectedRocksListView.getItems().contains(Rock.PURE_ESSENCE)) {
selectedRocksListView.getItems().add(Rock.PURE_ESSENCE);
essenceImage.setEffect(darkenImage);
}
else {
selectedRocksListView.getItems().remove(Rock.PURE_ESSENCE);
essenceImage.setEffect(brightenImage);
}
}
@DoNotRename @FXML
public ListView<Rock> selectedRocksListView;
@DoNotRename @FXML
public Spinner<Integer> tileSpinnerX;
@DoNotRename @FXML
public Spinner<Integer> tileSpinnerY;
@DoNotRename @FXML
public Spinner<Integer> radiusSpinner;
@DoNotRename @FXML
public CheckBox walkToTileCheckBox;
@DoNotRename @FXML
public CheckBox bankCheckBox;
@DoNotRename @FXML
public CheckBox hopWorldsCheckBox;
@DoNotRename @FXML
public CheckBox membersCheckBox;
@DoNotRename @FXML
public CheckBox endFullInvCheckBox;
@DoNotRename @FXML
public void walkToTileClicked() {
tileSpinnerX.setDisable(!tileSpinnerX.isDisabled());
tileSpinnerY.setDisable(!tileSpinnerY.isDisabled());
}
@DoNotRename @FXML
public ChoiceBox<Pick> picksChoiceBox;
@DoNotRename @FXML
public CheckBox drawPaintCheckBox;
@DoNotRename @FXML
public CheckBox drawDebugCheckBox;
@DoNotRename @FXML
public Button startMiningButton;
@DoNotRename @FXML
public void startMiningButtonPressed() {
if (!canInitializeVars()) {
return;
}
PlayerInfo.INSTANCE.getGui().close();
}
@DoNotRename @FXML
public CheckBox useLevelRangeCheckBox;
@DoNotRename @FXML
public Spinner<Integer> highLevelSpinner;
@DoNotRename @FXML
public Spinner<Integer> lowLevelSpinner;
@DoNotRename @FXML
public void useLevelRangeClicked() {
lowLevelSpinner.setDisable(!lowLevelSpinner.isDisabled());
highLevelSpinner.setDisable(!highLevelSpinner.isDisabled());
}
@DoNotRename @FXML
public TextField taskTextField;
@DoNotRename @FXML
public Button addTaskButton;
@DoNotRename @FXML
public void addTaskButtonPressed() {
ProgressiveTask taskToAdd;
if (!tileSpinnerX.isDisabled() && !tileSpinnerY.isDisabled()) {
taskToAdd = new ProgressiveTask(taskTextField.getText(), selectedRocksListView.getItems(), picksChoiceBox.getSelectionModel().getSelectedItem(), radiusSpinner.getValue(), lowLevelSpinner.getValue(), highLevelSpinner.getValue(), endFullInvCheckBox.isSelected(), bankCheckBox.isSelected(), hopWorldsCheckBox.isSelected(), membersCheckBox.isSelected(), walkToTileCheckBox.isSelected(), new RSTile(tileSpinnerX.getValue(), tileSpinnerY.getValue()));
}
else {
taskToAdd = new ProgressiveTask(taskTextField.getText(), selectedRocksListView.getItems(), picksChoiceBox.getSelectionModel().getSelectedItem(), radiusSpinner.getValue(), lowLevelSpinner.getValue(), highLevelSpinner.getValue(), endFullInvCheckBox.isSelected(), bankCheckBox.isSelected(), hopWorldsCheckBox.isSelected(), membersCheckBox.isSelected(), walkToTileCheckBox.isSelected(), new RSTile(0, 0));
}
selectedTaskListView.getItems().add(taskToAdd);
}
@DoNotRename @FXML
public ListView<ProgressiveTask> selectedTaskListView;
@DoNotRename @FXML
public Button deselectTaskButton;
@DoNotRename @FXML
public void deselectTaskButtonPressed() {
ProgressiveTask taskToDeselect = selectedTaskListView.getSelectionModel().getSelectedItem();
if (taskToDeselect != null) {
selectedTaskListView.getItems().remove(taskToDeselect);
}
}
@DoNotRename @FXML
public Slider reactionTimeSlider;
@DoNotRename @FXML
public Slider fatigueRateSlider;
@DoNotRename @FXML
public CheckBox hopPlayerCountCheckBox;
@DoNotRename @FXML
public CheckBox hopOnChatCheckBox;
@DoNotRename @FXML
public CheckBox antiPkCheckBox;
@DoNotRename @FXML
public TextField profileTextField;
@DoNotRename @FXML
public Button saveProfileButton;
@DoNotRename @FXML
public ListView<MinerProfile> profilesListView;
@DoNotRename @FXML
public Button loadProfileButton;
@DoNotRename @FXML
public Button deleteProfileButton;
@DoNotRename @FXML
public void saveProfileButtonPressed() {
MinerProfile minerProfile = new MinerProfile(profileTextField.getText(), endFullInvCheckBox.isSelected(), membersCheckBox.isSelected(), bankCheckBox.isSelected(), hopWorldsCheckBox.isSelected(), radiusSpinner.getValue(), picksChoiceBox.getSelectionModel().getSelectedItem(), selectedRocksListView.getItems(), new RSTile(tileSpinnerX.getValue(), tileSpinnerY.getValue()), lowLevelSpinner.getValue(), highLevelSpinner.getValue(), selectedTaskListView.getItems(), hopPlayerCountCheckBox.isSelected(), hopOnChatCheckBox.isSelected(), antiPkCheckBox.isSelected(), drawPaintCheckBox.isSelected(), drawDebugCheckBox.isSelected(), reactionTimeSlider.getValue(), fatigueRateSlider.getValue());
try {
if (minerProfile.getProfileName().equals("") || profilesListView.getItems().contains(minerProfile)) {
System.out.println("Profile wasn't created");
return;
}
if (!minerProfile.saveMinerProfile()) {
System.out.println("Profile wasn't created");
return;
}
} catch (IOException e) {
e.printStackTrace();
}
profilesListView.getItems().add(minerProfile);
}
@DoNotRename @FXML
public void loadProfileButtonPressed() {
MinerProfile minerProfile = profilesListView.getSelectionModel().getSelectedItem();
if (minerProfile != null) {
loadProfile(minerProfile);
}
}
@DoNotRename @FXML
public void deleteProfileButtonPressed() throws IOException {
for (MinerProfile currentProfile : profilesListView.getItems()) {
if (currentProfile.equals(profilesListView.getSelectionModel().getSelectedItem())) {
currentProfile.deleteMinerProfile(new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner/" + currentProfile.getProfileName()));
profilesListView.getItems().remove(currentProfile);
return;
}
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
tribotImage.setImage(new Image("https://i.imgur.com/KL7M0Ie.png"));
discordImage.setImage(new Image("https://i.imgur.com/MzWqh1Z.png"));
copperOreImage.setImage(new Image("https://i.imgur.com/W4u25Cg.png"));
tinOreImage.setImage(new Image("https://i.imgur.com/MKowMjI.png"));
clayImage.setImage(new Image("https://i.imgur.com/8juqenJ.png"));
limestoneImage.setImage(new Image("https://i.imgur.com/1mQWkRD.png"));
ironOreImage.setImage(new Image("https://i.imgur.com/ON9eeHd.png"));
silverOreImage.setImage(new Image("https://i.imgur.com/xynYpRG.png"));
coalImage.setImage(new Image("https://i.imgur.com/kU97uUG.png"));
sandstoneImage.setImage(new Image("https://i.imgur.com/CfJPSKc.png"));
goldOreImage.setImage(new Image("https://i.imgur.com/N2uTpxa.png"));
gemImage.setImage(new Image("https://i.imgur.com/2QI7UWf.png"));
graniteImage.setImage(new Image("https://i.imgur.com/r0HaTAR.png"));
mithrilOreImage.setImage(new Image("https://i.imgur.com/wQlOD8P.png"));
adamantiteOreImage.setImage(new Image("https://i.imgur.com/1Kq39qc.png"));
runiteOreImage.setImage(new Image("https://i.imgur.com/M02GIoT.png"));
amethystImage.setImage(new Image("https://i.imgur.com/0L5NUMn.png"));
essenceImage.setImage(new Image("https://i.imgur.com/SBYYN2w.png"));
tileSpinnerX.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 10000, 0));
tileSpinnerY.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 10000, 0));
radiusSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 25, 1));
lowLevelSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 99, 1));
highLevelSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(2, 100, 100));
for (Pick pick : Pick.values()) {
picksChoiceBox.getItems().add(pick);
}
picksChoiceBox.getSelectionModel().select(Pick.ANY_PICK);
if (PlayerInfo.INSTANCE.getShouldShowGui()) {
PlayerInfo.INSTANCE.setSelectedTask(MainTask.TRADITIONAL_MINING);
}
tileSpinnerX.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
tileSpinnerX.increment(0);
}
});
tileSpinnerY.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
tileSpinnerY.increment(0);
}
});
lowLevelSpinner.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
lowLevelSpinner.increment(0);
}
});
highLevelSpinner.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
highLevelSpinner.increment(0);
}
});
File pathToProfiles = new File(Finals.PATH_TO_BBUU20_FOLDER + "/miner");
if (!pathToProfiles.exists()) {
pathToProfiles.mkdirs();
}
File[] profilesList = Objects.requireNonNull(pathToProfiles.listFiles());
if (profilesList.length > 0) {
for (File profile : profilesList) {
MinerProfile minerProfile = new MinerProfile();
try {
minerProfile.loadProfile(profile.getName());
profilesListView.getItems().add(minerProfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
brightenImage.setBrightness(0.0);
darkenImage.setBrightness(-0.6);
}
private boolean canInitializeVars() {
switch (PlayerInfo.INSTANCE.getSelectedTask()) {
case TRADITIONAL_MINING:
if (selectedRocksListView.getItems().size() < 1) {
return false;
}
PlayerInfo.INSTANCE.setShouldEndFullInv(endFullInvCheckBox.isSelected());
PlayerInfo.INSTANCE.setMembers(membersCheckBox.isSelected());
PlayerInfo.INSTANCE.setShouldBank(bankCheckBox.isSelected());
PlayerInfo.INSTANCE.setShouldHopDepleted(hopWorldsCheckBox.isSelected());
PlayerInfo.INSTANCE.setMiningRadius(radiusSpinner.getValue());
PlayerInfo.INSTANCE.setSelectedPick(picksChoiceBox.getSelectionModel().getSelectedItem());
PlayerInfo.INSTANCE.setSelectedRockTypes(new ArrayList<>(selectedRocksListView.getItems()));
if (walkToTileCheckBox.isSelected()) {
PlayerInfo.INSTANCE.setStartingTile(new RSTile(tileSpinnerX.getValue(), tileSpinnerY.getValue()));
}
else {
PlayerInfo.INSTANCE.setStartingTile(Player.getPosition());
}
if (useLevelRangeCheckBox.isSelected()) {
PlayerInfo.INSTANCE.setLevelToStartAt(lowLevelSpinner.getValue());
PlayerInfo.INSTANCE.setLevelToEndAt(highLevelSpinner.getValue());
}
break;
case PROGRESSIVE_MINING:
PlayerInfo.INSTANCE.setProgressiveTasks(new HashSet<>(selectedTaskListView.getItems()));
break;
}
PlayerInfo.INSTANCE.setShouldHopHighCompetition(hopPlayerCountCheckBox.isSelected());
PlayerInfo.INSTANCE.setShouldHopOnChat(hopOnChatCheckBox.isSelected());
PlayerInfo.INSTANCE.setShouldUseAntiPK(antiPkCheckBox.isSelected());
PlayerInfo.INSTANCE.setShouldPaint(drawPaintCheckBox.isSelected());
PlayerInfo.INSTANCE.setShouldDrawDebug(drawDebugCheckBox.isSelected());
PlayerInfo.INSTANCE.setReactionTime(reactionTimeSlider.getValue());
PlayerInfo.INSTANCE.setFatigueRate(fatigueRateSlider.getValue());
return true;
}
private void loadProfile(MinerProfile minerProfile) {
endFullInvCheckBox.setSelected(minerProfile.isShouldEndFullInv());
membersCheckBox.setSelected(minerProfile.isMembers());
bankCheckBox.setSelected(minerProfile.isShouldBank());
hopWorldsCheckBox.setSelected(minerProfile.isShouldHopDepleted());
radiusSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 25, minerProfile.getMiningRadius()));
picksChoiceBox.getSelectionModel().select(minerProfile.getSelectedPick());
tileSpinnerX.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 10000, minerProfile.getStartingTile().getX()));
tileSpinnerY.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 10000, minerProfile.getStartingTile().getY()));
lowLevelSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 99, minerProfile.getLevelToStartAt()));
highLevelSpinner.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(2, 100, minerProfile.getLevelToEndAt()));
selectedRocksListView.getItems().clear();
selectedRocksListView.getItems().addAll(minerProfile.getSelectedRockTypes());
selectedTaskListView.getItems().clear();
selectedTaskListView.getItems().addAll(minerProfile.getProgressiveTasks());
hopPlayerCountCheckBox.setSelected(minerProfile.isShouldHopHighCompetition());
hopOnChatCheckBox.setSelected(minerProfile.isShouldHopOnChat());
antiPkCheckBox.setSelected(minerProfile.isShouldUseAntiPK());
drawPaintCheckBox.setSelected(minerProfile.isShouldPaint());
drawDebugCheckBox.setSelected(minerProfile.isShouldDrawDebug());
reactionTimeSlider.setValue(minerProfile.getReactionTime());
fatigueRateSlider.setValue(minerProfile.getFatigueRate());
for (Rock rock : selectedRocksListView.getItems()) {
switch (rock) {
case CLAY:
clayImage.setEffect(darkenImage);
break;
case LIMESTONE:
limestoneImage.setEffect(darkenImage);
break;
case SANDSTONE:
sandstoneImage.setEffect(darkenImage);
break;
case GRANITE:
graniteImage.setEffect(darkenImage);
break;
case COPPER:
copperOreImage.setEffect(darkenImage);
break;
case TIN:
tinOreImage.setEffect(darkenImage);
break;
case IRON:
ironOreImage.setEffect(darkenImage);
break;
case COAL:
coalImage.setEffect(darkenImage);
break;
case SILVER:
silverOreImage.setEffect(darkenImage);
break;
case GOLD:
goldOreImage.setEffect(darkenImage);
break;
case PURE_ESSENCE:
essenceImage.setEffect(darkenImage);
break;
case GEM:
gemImage.setEffect(darkenImage);
break;
case MITHRIL:
mithrilOreImage.setEffect(darkenImage);
break;
case ADAMANTITE:
adamantiteOreImage.setEffect(darkenImage);
break;
case RUNITE:
runiteOreImage.setEffect(darkenImage);
break;
case AMETHYST:
amethystImage.setEffect(darkenImage);
break;
}
}
}
public static void argsStart() throws FileNotFoundException {
MinerProfile minerProfile = new MinerProfile();
if (!minerProfile.loadProfile(PlayerInfo.INSTANCE.getProfile().getName())) {
System.out.println("Failed to load profile");
}
switch (PlayerInfo.INSTANCE.getSelectedTask()) {
case TRADITIONAL_MINING:
PlayerInfo.INSTANCE.setShouldEndFullInv(minerProfile.isShouldEndFullInv());
PlayerInfo.INSTANCE.setMembers(minerProfile.isMembers());
PlayerInfo.INSTANCE.setShouldBank(minerProfile.isShouldBank());
PlayerInfo.INSTANCE.setShouldHopDepleted(minerProfile.isShouldHopDepleted());
PlayerInfo.INSTANCE.setMiningRadius(minerProfile.getMiningRadius());
PlayerInfo.INSTANCE.setSelectedPick(minerProfile.getSelectedPick());
PlayerInfo.INSTANCE.setSelectedRockTypes(minerProfile.getSelectedRockTypes());
if (!minerProfile.getStartingTile().equals(new RSTile(0, 0))) {
PlayerInfo.INSTANCE.setStartingTile(new RSTile(minerProfile.getStartingTile().getX(), minerProfile.getStartingTile().getY()));
}
else {
PlayerInfo.INSTANCE.setStartingTile(Player.getPosition());
}
if (minerProfile.getLevelToStartAt() != 1 || minerProfile.getLevelToEndAt() != 100) {
PlayerInfo.INSTANCE.setLevelToStartAt(minerProfile.getLevelToStartAt());
PlayerInfo.INSTANCE.setLevelToEndAt(minerProfile.getLevelToEndAt());
}
break;
case PROGRESSIVE_MINING:
PlayerInfo.INSTANCE.setProgressiveTasks(new HashSet<>(minerProfile.getProgressiveTasks()));
break;
}
PlayerInfo.INSTANCE.setShouldHopHighCompetition(minerProfile.isShouldHopHighCompetition());
PlayerInfo.INSTANCE.setShouldHopOnChat(minerProfile.isShouldHopOnChat());
PlayerInfo.INSTANCE.setShouldUseAntiPK(minerProfile.isShouldUseAntiPK());
PlayerInfo.INSTANCE.setShouldPaint(minerProfile.isShouldPaint());
PlayerInfo.INSTANCE.setShouldDrawDebug(minerProfile.isShouldDrawDebug());
PlayerInfo.INSTANCE.setReactionTime(minerProfile.getReactionTime());
PlayerInfo.INSTANCE.setFatigueRate(minerProfile.getFatigueRate());
}
}
<file_sep>package scripts.bbuu20_miner
import org.tribot.api.General
import org.tribot.api.Timing
import org.tribot.api2007.*
import org.tribot.api2007.ext.Filters
import org.tribot.api2007.types.RSTile
import org.tribot.script.Script
import org.tribot.script.ScriptManifest
import org.tribot.script.interfaces.Arguments
import org.tribot.script.interfaces.MessageListening07
import org.tribot.script.interfaces.Painting
import org.tribot.util.Util
import scripts.bbuu20_api.Framework
import scripts.bbuu20_api.Paint
import scripts.bbuu20_miner.data.PlayerInfo
import scripts.bbuu20_api.enums.MainTask
import scripts.bbuu20_miner.gui.GUIController
import scripts.bbuu20_miner.main_tasks.*
import scripts.bbuu20_miner.util.AntiBan
import scripts.dax_api.api_lib.DaxWalker
import scripts.dax_api.api_lib.models.DaxCredentials
import scripts.dax_api.api_lib.models.DaxCredentialsProvider
import scripts.fluffeepaint.FluffeesPaint
import java.awt.Color
import java.awt.Font
import java.awt.Graphics
import java.io.File
import java.text.DecimalFormat
import java.util.HashMap
@ScriptManifest(
name = "Bbuu20's Miner",
description = "Bbuu20's Miner. Join my discord, or leave a comment on the forum post for help/feedback.",
category = "Mining",
authors = ["bbuu20"],
version = 3.2
)
class AIOMiner : Script(), Painting, MessageListening07, Arguments {
private var tasks = ArrayList<Framework>()
private var df: DecimalFormat? = DecimalFormat("#.##")
private var font = Font("Helvetica Plain", Font.PLAIN, 14)
private var startTime: Long = System.currentTimeMillis()
private var startLvl = Skills.getActualLevel(Skills.SKILLS.MINING)
private var startXP = Skills.getXP(Skills.SKILLS.MINING)
override fun run() {
initialize()
while (shouldProceed()) {
onLoop()
General.sleep(5)
}
}
override fun onPaint(graphics: Graphics?) {
if (PlayerInfo.shouldDrawDebug) {
if (PlayerInfo.startingTile.isOnScreen) {
graphics?.drawPolygon(Projection.getTileBoundsPoly(PlayerInfo.startingTile, 0))
}
graphics?.color = Color(220, 240, 255)
PlayerInfo.nonEmptyRocks.forEach { tile ->
val objs = Objects.getAt(tile)
if (objs.isNotEmpty()) {
objs[0].model.triangles.forEach { triangle ->
graphics?.drawPolygon(triangle)
}
}
}
graphics?.color = Color(20, 200, 100)
var objs = Objects.getAt(PlayerInfo.currentRSRock)
if (objs.isNotEmpty()) {
objs[0].model.triangles.forEach { triangle ->
graphics?.drawPolygon(triangle)
}
}
graphics?.color = Color(240, 225, 70)
objs = Objects.getAt(PlayerInfo.nextRSRock)
if (objs.isNotEmpty()) {
objs[0].model.triangles.forEach { triangle ->
graphics?.drawPolygon(triangle)
}
}
}
if (PlayerInfo.shouldPaint) {
val timeRan: Long = System.currentTimeMillis() - startTime
val currentLvl = Skills.getActualLevel(Skills.SKILLS.MINING)
val gainedLvl: Int = currentLvl - startLvl
val gainedXP: Double = Skills.getXP(Skills.SKILLS.MINING) - startXP.toDouble()
val xpToLevel = Skills.getXPToNextLevel(Skills.SKILLS.MINING)
val xpPerHour: Double = gainedXP * 3600 / timeRan
val gpPerHour: Double = (PlayerInfo.gpMade * 3600 / timeRan).toDouble()
graphics!!.color = Color.BLACK
graphics.drawRect(10, 20, 230, 120)
graphics.color = FluffeesPaint.makeTransparentColor(Color.GRAY, 50)
graphics.fillRect(10, 20, 230, 120)
graphics.font = font
graphics.color = Color.WHITE
graphics.drawString("Runtime: " + Timing.msToString(timeRan), 20, 35)
graphics.drawString("Current lvl: $currentLvl (+$gainedLvl)", 20, 55)
graphics.drawString("XP Gained: $gainedXP", 20, 75)
graphics.drawString("GP Made: ${PlayerInfo.gpMade}", 20, 95)
graphics.drawString("XP/H: " + df?.format(xpPerHour) + "k", 20, 115)
graphics.drawString("GP/H: " + df?.format(gpPerHour) + "k", 20, 135)
graphics.drawString("XP to next level: $xpToLevel", 55, 167)
graphics.drawImage(Paint.getProgressBar(Skills.SKILLS.MINING, 230, 25, false), 10, 150, null)
}
}
private fun addTasks() {
tasks.add(UpgradePick())
tasks.add(Drop())
tasks.add(Bank())
tasks.add(Mine())
tasks.add(WalkToRocks())
}
private fun handleTasks() {
for (task in tasks) {
if (task.shouldProceed()) {
task.proceed()
break
}
}
}
private fun initialize() {
DaxWalker.setCredentials(object : DaxCredentialsProvider() {
override fun getDaxCredentials(): DaxCredentials {
return DaxCredentials("sub_DPjXXzL5DeSiPf", "PUBLIC-KEY")
}
})
addTasks()
if (PlayerInfo.shouldShowGui) {
PlayerInfo.gui.show()
while (PlayerInfo.gui.isOpen) {
General.sleep(50)
}
}
else {
when (PlayerInfo.taskKey) {
0 -> PlayerInfo.selectedTask = MainTask.TRADITIONAL_MINING
1 -> PlayerInfo.selectedTask = MainTask.PROGRESSIVE_MINING
}
GUIController.argsStart()
}
if (PlayerInfo.startingTile == RSTile(-1, -1, 0) || PlayerInfo.startingTile == RSTile(0, 0, 0)) {
PlayerInfo.startingTile = Player.getPosition()
}
if (PlayerInfo.selectedTask == MainTask.PROGRESSIVE_MINING) {
PlayerInfo.levelToEndAt = 0
}
}
private fun onLoop() {
PlayerInfo.updateCurrentPick()
PlayerInfo.updateAllRocks()
handleTasks()
handleWorldHopping()
}
private fun shouldHopAntiPK(): Boolean {
if (Login.getLoginState() == Login.STATE.INGAME) {
val lowCombat = Player.getRSPlayer().combatLevel - Combat.getWildernessLevel()
val highCombat = Player.getRSPlayer().combatLevel + Combat.getWildernessLevel()
val players =
Players.getAll(Filters.Players.nameNotEquals(Player.getRSPlayer().name))
for (player in players) {
if (player.combatLevel in lowCombat..highCombat) {
while (Login.getLoginState() == Login.STATE.INGAME) {
Login.logout()
General.sleep(5)
}
return true
}
}
}
else {
return true
}
return false
}
private fun handleWorldHopping() {
val players = Players.getAll()
var playersOnTile = -1 //set to -1 to account for our player
players.forEach { player ->
if (player.position == Player.getPosition()) {
playersOnTile++
}
}
if ((PlayerInfo.shouldHopDepleted && PlayerInfo.nonEmptyRocks.isEmpty() && !Inventory.isFull() && Player.getPosition().distanceTo(
PlayerInfo.startingTile) <= PlayerInfo.miningRadius)
|| (PlayerInfo.shouldHopHighCompetition && AntiBan.get().shouldHopPlayerCount(playersOnTile))
|| (PlayerInfo.shouldUseAntiPK && shouldHopAntiPK())) {
AntiBan.get().hopWorlds()
Login.login() //check if we're logged out
General.sleep(100, 500) //wait for new rocks to render
}
}
private fun shouldProceed(): Boolean {
if (PlayerInfo.shouldEndFullInv) {
if (Inventory.isFull()) {
println("Inventory is full")
return false
}
}
if (PlayerInfo.selectedTask == MainTask.TRADITIONAL_MINING) {
if (Skills.SKILLS.MINING.actualLevel !in PlayerInfo.levelToStartAt until PlayerInfo.levelToEndAt) {
println("Player is not in the specified mining level bracket.")
Login.logout()
return false
}
}
else if (PlayerInfo.selectedTask == MainTask.PROGRESSIVE_MINING) {
if (Skills.SKILLS.MINING.actualLevel !in PlayerInfo.levelToStartAt until PlayerInfo.levelToEndAt) {
println(Skills.SKILLS.MINING.actualLevel)
println(PlayerInfo.levelToStartAt)
println(PlayerInfo.levelToEndAt)
PlayerInfo.progressiveTasks.forEach { progressiveTask ->
if (Skills.SKILLS.MINING.actualLevel in progressiveTask.levelToStartAt until progressiveTask.levelToEndAt) {
PlayerInfo.levelToStartAt = progressiveTask.levelToStartAt
PlayerInfo.levelToEndAt = progressiveTask.levelToEndAt
PlayerInfo.shouldEndFullInv = progressiveTask.isShouldEndFullInv
PlayerInfo.isMembers = progressiveTask.isMembers
PlayerInfo.shouldBank = progressiveTask.isShouldBank
PlayerInfo.shouldHopDepleted = progressiveTask.isShouldHop
PlayerInfo.miningRadius = progressiveTask.radius
PlayerInfo.selectedPick = progressiveTask.selectedPick
PlayerInfo.selectedRockTypes = progressiveTask.selectedRocks
if (progressiveTask.tileToTraverse != RSTile(0, 0) && progressiveTask.tileToTraverse != RSTile(-1, -1)) {
PlayerInfo.startingTile = progressiveTask.tileToTraverse
}
return true
}
}
return false
}
return true
}
return true
}
override fun playerMessageReceived(name: String?, message: String?) {
if (PlayerInfo.shouldHopOnChat) {
AntiBan.get().hopWorlds()
}
}
override fun passArguments(profileMap: HashMap<String, String>?) {
if (profileMap?.get("custom_input")?.isNotEmpty()!!) {
val fullText = profileMap["custom_input"]
val strArr = fullText?.split(":")
val profileName = strArr?.get(0)
val taskKey = strArr?.get(1)
PlayerInfo.profile = File(Util.getWorkingDirectory().absolutePath + "/bbuu20/miner/" + profileName)
PlayerInfo.taskKey = Integer.parseInt(taskKey)
PlayerInfo.shouldShowGui = false
}
}
} | f2bb0cba5ecb505e81c120630a8b5328375ab686 | [
"Java",
"Kotlin"
] | 21 | Kotlin | zperkins11/Java-Freshman | 23fea7da81d0116fefc6cb792a581b171ef8d870 | b65f494ad8a6fcb5f7275d1a259050db029d7b8c |
refs/heads/master | <repo_name>dnaithani/pgintegration<file_sep>/src/com/capgent/cpt/MonerisResponseServlet.java
package com.capgent.cpt;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Enumeration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MonerisResponseServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/plain");
response.getWriter().println("DOGET: Moneris Response Receiver");
processRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/plain");
response.getWriter().println("DOPOST: Moneris Response Receiver");
processRequest(request, response);
}
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException
{
Enumeration en = request.getParameterNames();
StringBuilder cmd = new StringBuilder("");
String paramName;
String paramValue;
String charset = request.getParameter("charset");
while (en.hasMoreElements())
{
paramName = (String) en.nextElement();
paramValue = request.getParameter(paramName);
cmd.append("&").append(paramName).append("=");
if (charset == null || charset.length() == 0)
{
cmd.append(paramValue);
}
else
{
cmd.append(URLEncoder.encode(paramValue, charset));
}
}
response.getWriter().println(cmd.toString());
}
}
| 8990bf10d14a093d31cce76cbeb60d8b18a57745 | [
"Java"
] | 1 | Java | dnaithani/pgintegration | 67898e7a9d31c1ea456d37d2e5e76b9264f5cc77 | c06012d40807ff626640f17bcbbee37c0a80750a |
refs/heads/master | <repo_name>cnlien/React-Todo<file_sep>/src/components/TodoComponents/TodoList.js
// your components will all go in this `component` directory.
// feel free to change this component.js into TodoList.js
import React from "react";
import { Container, Row, Button } from "reactstrap";
import 'bootstrap/dist/css/bootstrap.css'
import "./Todo.css";
import TodoItem from "./TodoItem";
const TodoList = props => {
return (
<Container>
<Row className="todo-list">
{props.todolist.map (item => (
<TodoItem
key={item.id}
item={item}
toggleComplete={props.toggleComplete}
/>
))}
<Button className="clear-list" onClick={props.clearComplete}>Clear Completed</Button>
</Row>
</Container>
);
}
export default TodoList;<file_sep>/src/components/TodoComponents/TodoItem.js
import React from "react";
import { Card } from "reactstrap";
import 'bootstrap/dist/css/bootstrap.css'
import CheckBoxOutlineBlankIcon from '@material-ui/icons/CheckBoxOutlineBlank';
import "./Todo.css";
const TodoItem = props => {
let cardClass = "toDoItem"
if (props.item.completed) {
cardClass = cardClass + " complete"
}
const handleClick = () => {
props.toggleComplete(props.item.id);
}
return (
<Card onClick={handleClick} className={cardClass}>
<h4>{props.item.task}</h4>
</Card>
);
}
export default TodoItem;<file_sep>/src/components/TodoComponents/TodoForm.js
import React from "react";
import {Form, Input, Button, Col, Row} from "reactstrap";
import "./Todo.css";
class TodoForm extends React.Component {
constructor() {
super();
this.state = {
taskName:""
};
}
handleChange = e => {
this.setState({
taskName: e.target.value
});
};
handleSubmit = e => {
e.preventDefault();
this.props.addTask(this.state.taskName);
this.setState({
taskName: ""
});
// if (this.state.taskName !== "") {
// this.props.addTask(this.state.taskName);
// this.setState({
// taskname: ""
// });
// }
};
render() {
return (
<Form onSubmit = {this.handleSubmit}>
<Row className="newTaskForm">
<Col>
<Input
onChange = {this.handleChange}
placeholder = "What Do You Need To Do?"
type = "text"
name = "task"
value = {this.state.taskName}
/>
</Col>
<Col>
<Button>Add Task</Button>
</Col>
</Row>
</Form>
);
}
}
export default TodoForm;
<file_sep>/src/App.js
import React from 'react';
import {Container, Card} from 'reactstrap'
import TodoList from './components/TodoComponents/TodoList';
import TodoForm from './components/TodoComponents/TodoForm';
import './components/TodoComponents/Todo.css';
const todoData = [];
class App extends React.Component {
// you will need a place to store your state in this component.
state = {
todolist: todoData,
};
toggleComplete = itemId => {
console.log("toggleComplete: ", itemId);
this.setState({
todolist: this.state.todolist.map(item => {
if (item.id === itemId) {
return {
...item,
completed: !item.completed
};
}
return item;
})
});
};
clearComplete = () => {
console.log("clearPurchased");
this.setState ({
todolist: this.state.todolist.filter(item =>{
return !item.completed;
})
});
};
addTask = taskName => {
console.log ("add item: ", taskName);
this.setState({
todolist: [
...this.state.todolist,
{
task: taskName,
id: Date.now(),
completed: false
}
]
});
};
render() {
return(
<Container className="main-container">
<Card className="add-task">
<h1>Add a Task</h1>
<TodoForm addTask={this.addTask} />
</Card>
<Card className ="task-list">
<h1>To Do List</h1>
<TodoList
todolist = {this.state.todolist}
toggleComplete={this.toggleComplete}
clearComplete={this.clearComplete}
/>
</Card>
{console.log(this.addTask)}
{console.log(this.state.todolist)}
</Container>
);
}
}
// design `App` to be the parent component of your application.
// this component is going to take care of state, and any change handlers you need to work with your state
export default App;
| 29ab4effcf2979bd6f6f9e1a1b0ecd05c60e13cc | [
"JavaScript"
] | 4 | JavaScript | cnlien/React-Todo | 8867d03622ed672130bf1887d6601cbd3e0cfa55 | d15a6ee8db568fcfda5a23a36d5a5804cde66426 |
refs/heads/master | <file_sep>from fastapi import FastAPI, Request
from twilio.rest import Client
import re
import Movie_database
account_sid = 'AC<KEY>'
auth_token = '<KEY>'
client = Client(account_sid, auth_token)
app = FastAPI()
@app.post("/")
async def sms_reply(request: Request):
item = await request.body()
item_name = str(item)
print(item_name)
match = re.search(r'Body=([\w+%]+)&', item_name)
keywords = match.group(1).split('+')
match2 = re.findall(r'From=([\w%]+)&', item_name)
sent_by = match2[0][3:]
list = set
if len(keywords) == 2:
if str(keywords[1]) == 'ACTORS':
list = Movie_database.all_actors_list()
else:
list = Movie_database.all_movies_list()
elif len(keywords) == 5:
if keywords[-3] == 'ACTOR':
list = Movie_database.actors_movie_list(keywords[-1])
else:
list = Movie_database.movie_actor_list(keywords[-1])
else:
if keywords[-3] == 'DIRECTOR':
list = Movie_database.actor_director_list(keywords[3], keywords[-1])
elif keywords[-3] == 'ACTOR':
list = Movie_database.actors_common_list(keywords[3], keywords[-1])
else:
list = {'Try Something Else'}
message = str
for i in list:
message += str(i) + " "
client.messages.create(
body= f"{message}",
from_= 'XXXXXXXXXXX', # your Twilio Phone Number
to= f'+{sent_by}'
)
return str(list)
<file_sep>from arango import ArangoClient
client = ArangoClient()
db = client.db('Movies', username='root', password='<PASSWORD>')
if not db.has_graph('movies_element'):
db.create_graph('movies_element')
movies_element = db.graph('movies_element')
elements = ['actors', 'movies', 'directors']
for i in elements:
if not movies_element.has_vertex_collection(i):
movies_element.create_vertex_collection(i)
actors = movies_element.vertex_collection('actors')
movies = movies_element.vertex_collection('movies')
directors = movies_element.vertex_collection('directors')
actors_list = ['Aamir', 'Anushka', 'Sushant', 'Salmaan']
movies_list = ['PK', '3Idiots', 'Lagaan', 'Dangal', 'Sultan', 'MSDhoni']
directors_list = ['Hirani', 'Nitesh', 'Abbas', 'Neeraj']
for i in actors_list:
if not actors.has(i):
actors.insert({
'_key' : f"{i}",
'name' : i
})
for i in movies_list:
if not movies.has(i):
movies.insert({
'_key' : i,
'name' : i
})
for i in directors_list:
if not directors.has(i):
directors.insert({
'_key' : i,
'name' : i
})
if not movies_element.has_edge_definition('actor_movies'):
movies_element.create_edge_definition(
edge_collection='actor_movies',
from_vertex_collections=['actors'],
to_vertex_collections=['movies']
)
actor_movies = movies_element.edge_collection('actor_movies')
actor_movies.truncate()
actor_movies.insert({
'_key' : 'Sushant-PK',
'_from' : 'actors/Sushant',
'_to' : 'movies/PK',
'movie' : 'PK',
'directors' : 'Hirani'
})
actor_movies.insert({
'_key' : 'Aamir-PK',
'_from' : 'actors/Aamir',
'_to' : 'movies/PK',
'movie' : 'PK',
'directors' : 'Hirani'
})
actor_movies.insert({
'_key' : 'Aamir-3Idiots',
'_from' : 'actors/Aamir',
'_to' : 'movies/3Idiots',
'movie' : '3Idiots',
'directors' : 'Hirani'
})
actor_movies.insert({
'_key' : 'Aamir-Lagaan',
'_from' : 'actors/Aamir',
'_to' : 'movies/Lagaan',
'movie' : 'Lagaan',
'directors' : 'Ashutosh'
})
actor_movies.insert({
'_key' : 'Aamir-Dangal',
'_from' : 'actors/Aamir',
'_to' : 'movies/Dangal',
'movie' : 'Dangal',
'directors' : 'Nitesh'
})
actor_movies.insert({
'_key' : '<KEY>',
'_from' : 'actors/Anushka',
'_to' : 'movies/PK',
'movie' : 'PK',
'directors' : 'Hirani'
})
actor_movies.insert({
'_key' : 'Anushka-Sultan',
'_from' : 'actors/Anushka',
'_to' : 'movies/Sultan',
'movie' : 'Sultan',
'directors' : 'Abbas'
})
actor_movies.insert({
'_key' : 'Sushant-MSDhoni',
'_from' : 'actors/Sushant',
'_to' : 'movies/MSDhoni',
'movie' : 'MSDhoni',
'directors' : 'Neeraj'
})
actor_movies.insert({
'_key' : 'Salmaan-Sultan',
'_from' : 'actors/Salmaan',
'_to' : 'movies/Sultan',
'movie' : 'Sultan',
'directors' : 'Abbas'
})
if not movies_element.has_edge_definition('director_movies'):
movies_element.create_edge_definition(
edge_collection='director_movies',
from_vertex_collections=['directors'],
to_vertex_collections=['movies']
)
director_movies = movies_element.edge_collection('director_movies')
director_movies.truncate()
director_movies.insert({
'_key' : 'Hirani-PK',
'_from' : 'directors/Hirani',
'_to' : 'movies/PK',
'movie' : 'PK'
})
director_movies.insert({
'_key' : 'Hirani-3Idiots',
'_from' : 'directors/Hirani',
'_to' : 'movies/3Idiots',
'movie' : '3Idiots'
})
director_movies.insert({
'_key' : 'Nitesh-Dangal',
'_from' : 'directors/Nitesh',
'_to' : 'movies/Dangal',
'movie' : 'Dangal'
})
director_movies.insert({
'_key' : 'Abbas-Sultan',
'_from' : 'directors/Abbas',
'_to' : 'movies/Sultan',
'movie' : 'Sultan'
})
director_movies.insert({
'_key' : 'Neeraj-MSDhoni',
'_from' : 'directors/Neeraj',
'_to' : 'movies/MSDhoni',
'movie' : 'MSDhoni'
})
def actors_movie_list(actor):
edge_list = actor_movies.edges(f'actors/{actor}', direction='out')['edges']
movie_list = {i['movie'] for i in edge_list}
return movie_list
def movie_actor_list(movie):
edge_list = actor_movies.edges(f'movies/{movie}', direction='in')['edges']
actor_list = {i['_from'].split('/')[-1] for i in edge_list}
return actor_list
def actors_common_list(actor1, actor2):
list1 = actors_movie_list(actor1)
list2 = actors_movie_list(actor2)
common_list = list1.intersection(list2)
return common_list
def actor_director_list(actor, director):
edge_list = actor_movies.edges(f'actors/{actor}', direction='out')['edges']
movie_list = {i['movie'] for i in edge_list if i['directors'] == director}
return movie_list
def director_list(actor):
edge_list = actor_movies.edges(f'actors/{actor}', direction='out')['edges']
list = {i['directors'] for i in edge_list}
return list
def all_actors_list():
cursor = db.aql.execute('FOR doc IN actors RETURN doc')
all_actors = {doc['name'] for doc in cursor}
return all_actors
def all_movies_list():
cursor = db.aql.execute('FOR doc IN movies RETURN doc')
all_movies = {doc['name'] for doc in cursor}
return all_movies
<file_sep># Mini-Project-using-FastAPI-ArangoDB-Python
Send a list of movies/actors/director to the mobile number as a reply to the msg sent to a Twilio Number
# Messaging Options that you can use are -
1. GET ACTORS - to get all the actors list in the database
2. GET MOVIES - to get all the movies list in the database
3. GET MOVIES ACTOR : name // input - to get all the movies of the given actor
4. GET ACTORS MOVIE : name // input - to get all the actors of the given movie
5. GET DIRECTOR : name ACTOR : name - to get all the movies of the actor done with the given director
6. GET ACTOR : name ACTOR : name - to get all the common movies done by both the actors
| 32dc4ab2740e9be3119bb11449f3c1a51f7e0ec4 | [
"Markdown",
"Python"
] | 3 | Python | akshatdalton/Mini-Project-using-FastAPI-ArangoDB-Python | 2bef0f0e9cc6e58b6d609135a892b522f12a148e | 0c8ef8182599c7d240b246906e73bf9c8fc5b7b2 |
refs/heads/master | <file_sep>import React, { Component } from "react";
import {
View,
Text,
AsyncStorage,
StyleSheet,
TouchableOpacity,
Alert
} from "react-native";
import * as Font from "expo-font";
import axios from "axios";
class PatientPanicButton extends Component {
static navigationOptions = {
header: null
};
state = {
token: "",
fontLoaded: false
};
async componentDidMount() {
await Font.loadAsync({
"Butler-Light": require("../assets/fonts/Butler_Light.otf")
});
this.setState({
token: await AsyncStorage.getItem("userToken")
});
}
twilioCall = () => {
Alert.alert("Your Caregiver has been alerted. Stay where you are.");
//make axios call here.
axios
.post("http://192.168.3.11:3000/api/text", {
number: 6476362359,
location: `University of Toronto, https://www.google.com/maps/search/?api=1&query=${43.660768},${-79.396563}`
})
.then(function(response) {
console.log(response.data);
console.log(response.status);
})
.catch(function(error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log("Error", error.message);
}
console.log(error.config);
});
};
render() {
return (
<View
style={{
flex: 1,
alignItems: "center",
justifyContent: "center",
backgroundColor: "#FFBD59"
}}
>
{/* <Text
style={{
color: "white",
marginBottom: 20,
fontFamily: "Butler-Light"
}}
>
Press button to inform Caregiver of your location.
</Text> */}
<TouchableOpacity
onLongPress={() => {
this.twilioCall();
}}
>
<View style={styles.panicBtn}>
<Text
style={{
position: "absolute",
top: "45%",
left: "28%",
fontFamily: "Butler-Light",
fontSize: 20
}}
>
<Text style={{ fontWeight: "bold" }}>Hold</Text>
<Text> until safe</Text>
</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
panicBtn: {
backgroundColor: "white",
borderRadius: 130,
height: 260,
width: 260,
shadowColor: "#000",
shadowOffset: { width: 0, height: 9 },
shadowRadius: 7,
shadowOpacity: 0.26,
elevation: 9
},
panicText: {
fontSize: 55,
fontWeight: "bold",
textAlign: "center",
margin: 35,
color: "#FFFFE0"
}
});
export default PatientPanicButton;
<file_sep>import React, {Component} from 'react'
import {
AsyncStorage,
Button,
Modal,
SafeAreaView,
ScrollView,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native'
import moment from 'moment';
import {Ionicons} from '@expo/vector-icons'
class CaregiverEvents extends Component {
static navigationOptions = {
header: null
};
state = {
// token: "",
modalVisible: false,
data: {
"Monday": [
{
title: "Walk the dog",
location: "Too Good Park",
start: new Date(2020, 0, 13, 19, 20),
end: new Date(2020, 0, 13, 20, 20)
},
{
title: "Eat dinner",
location: "Subway",
start: new Date(2020, 0, 13, 20, 20),
end: new Date(2020, 0, 13, 21, 20)
}
],
"Tuesday": [
{
title: "Walk the Dog",
location: "Roxbury Park",
start: new Date(2020, 0, 13, 19, 20),
end: new Date(2020, 0, 13, 20, 20)
},
{
title: "Swim",
location: "Community Pool",
start: new Date(2020, 0, 13, 18, 20),
end: new Date(2020, 0, 13, 19, 20)
}
],
"Wednesday": [
{
title: "Walk the Dog",
location: "Crescent Park",
start: new Date(2020, 0, 14, 19, 20),
end: new Date(2020, 0, 14, 20, 20)
},
{
title: "Visit Children",
location: "Ottawa",
start: new Date(2020, 0, 14, 17, 20),
end: new Date(2020, 0, 14, 21, 20)
}
],
"Thursday": [
{
title: "Walk the Dog",
location: "Mifflin Park",
start: new Date(2020, 0, 15, 19, 20),
end: new Date(2020, 0, 15, 20, 20)
},
{
title: "Water Plants",
location: "Home",
start: new Date(2020, 0, 15, 19, 0),
end: new Date(2020, 0, 15, 19, 20)
}
],
"Friday": [
{
title: "Walk the Dog",
location: "Now Here Park",
start: new Date(2020, 0, 16, 19, 20),
end: new Date(2020, 0, 16, 20, 20)
},
{
title: "Regular Checkup",
location: "Walk-in Clinic",
start: new Date(2020, 0, 16, 20, 20),
end: new Date(2020, 0, 16, 21, 20)
}
],
"Saturday": [
{
title: "Walk the Dog",
location: "Nowhere Park",
start: new Date(2020, 0, 17, 19, 20),
end: new Date(2020, 0, 17, 20, 20)
},
{
title: "Go for Icecream",
location: "Baskin Robbins",
start: new Date(2020, 0, 17, 9, 20),
end: new Date(2020, 0, 17, 10, 30)
}
],
"Sunday": [
{
title: "Walk the Dog",
location: "Roxbury Park",
start: new Date(2020, 0, 18, 19, 20),
end: new Date(2020, 0, 18, 20, 20)
},
{
title: "Bingo",
location: "Community Centre",
start: new Date(2020, 0, 18, 20, 20),
end: new Date(2020, 0, 18, 21, 20)
}
]
}
};
async componentDidMount() {
this.setState({
token: await AsyncStorage.getItem("userToken")
})
}
render() {
return (
<SafeAreaView>
<Modal visible={this.state.modalVisible} animationType="slide">
<View style={{flex: 1, alignItems: 'center', marginTop: 80}}>
<Text style={{fontFamily: "Butler-Light", fontSize: 30}}>Create Event</Text>
<TextInput
placeholder="Event Title"
style={{width: '80%', borderBottomColor: 'black', borderBottomWidth: 1, padding: 10, marginVertical: 15}}
//add and set onchangetext and value props
/>
<TextInput
placeholder="Location"
style={{width: '80%', borderBottomColor: 'black', borderBottomWidth: 1, padding: 10, marginVertical: 15}}
//add and set onchangetext and value props
/>
<TextInput
placeholder="Start Time"
style={{width: '80%', borderBottomColor: 'black', borderBottomWidth: 1, padding: 10, marginVertical: 15}}
//add and set onchangetext and value props
/>
<TextInput
placeholder="End Time"
style={{width: '80%', borderBottomColor: 'black', borderBottomWidth: 1, padding: 10, marginVertical: 15}}
//add and set onchangetext and value props
/>
<View style={{flexDirection: "row", justifyContent: 'space-between'}}>
<Button title="Cancel" color="red" onPress={() => this.setState({modalVisible: false})}/>
<Button title="Add" onPress={() => /*update state here*/ this.setState({modalVisible: false})} />
</View>
</View>
</Modal>
<ScrollView style={{height: '100%'}}>
<View style={{flex: 1, justifyContent: 'center', marginTop: 30}}>
<Text style={{fontSize: 20, fontWeight: 'bold', marginLeft: 20}}>Monday</Text>
<ScrollView style={{flexDirection: 'row'}} horizontal={true}
showsHorizontalScrollIndicator={false}>
<TouchableOpacity onPress={() => this.setState({modalVisible: true})}>
<View style={{
marginLeft: 20,
marginTop: 20,
}}>
<Ionicons name="ios-add-circle" size={40} style={{position: 'relative', top: -8}}/>
</View>
</TouchableOpacity>
{this.state.data.Monday.map((event, index) => {
return (
<View key={index}>
<View style={styles.event}>
<Text style={styles.eventTitle}>{event.title}</Text>
<Text style={styles.eventBody}>{event.location}</Text>
<Text
style={styles.eventBody}>{moment(event.start).format("h:mm A")} - {moment(event.end).format("h:mm A")}</Text>
</View>
<Ionicons name={"ios-close-circle"} size={40}
style={{position: "absolute", right: 5, top: 13}} />
</View>
);
})}
</ScrollView>
</View>
<View style={{flex: 1, justifyContent: 'center', marginTop: 30}}>
<Text style={{fontSize: 20, fontWeight: 'bold', marginLeft: 20}}>Tuesday</Text>
<ScrollView style={{flexDirection: 'row'}} horizontal={true}
showsHorizontalScrollIndicator={false}>
<TouchableOpacity onPress={() => this.setState({modalVisible: true})}>
<View style={{
marginLeft: 20,
marginTop: 20,
}}>
<Ionicons name="ios-add-circle" size={40} style={{position: 'relative', top: -8}} color="#FFBD59"/>
</View>
</TouchableOpacity>
{this.state.data.Tuesday.map((event, index) => {
return (
<View key={index}>
<View style={styles.event2}>
<Text style={styles.eventTitle2}>{event.title}</Text>
<Text style={styles.eventBody2}>{event.location}</Text>
<Text
style={styles.eventBody2}>{moment(event.start).format("h:mm A")} - {moment(event.end).format("h:mm A")}</Text>
</View>
<Ionicons name={"ios-close-circle"} size={40}
style={{position: "absolute", right: 5, top: 13}} color="#FFBD59"/>
</View>
);
})}
</ScrollView>
</View>
<View style={{flex: 1, justifyContent: 'center', marginTop: 30}}>
<Text style={{fontSize: 20, fontWeight: 'bold', marginLeft: 20}}>Wednesday</Text>
<ScrollView style={{flexDirection: 'row'}} horizontal={true}
showsHorizontalScrollIndicator={false}>
<TouchableOpacity onPress={() => this.setState({modalVisible: true})}>
<View style={{
marginLeft: 20,
marginTop: 20,
}}>
<Ionicons name="ios-add-circle" size={40} style={{position: 'relative', top: -8}}/>
</View>
</TouchableOpacity>
{this.state.data.Wednesday.map((event, index) => {
return (
<View key={index}>
<View style={styles.event}>
<Text style={styles.eventTitle}>{event.title}</Text>
<Text style={styles.eventBody}>{event.location}</Text>
<Text
style={styles.eventBody}>{moment(event.start).format("h:mm A")} - {moment(event.end).format("h:mm A")}</Text>
</View>
<Ionicons name={"ios-close-circle"} size={40}
style={{position: "absolute", right: 5, top: 13}}/>
</View>
);
})}
</ScrollView>
</View>
<View style={{flex: 1, justifyContent: 'center', marginTop: 30}}>
<Text style={{fontSize: 20, fontWeight: 'bold', marginLeft: 20}}>Thursday</Text>
<ScrollView style={{flexDirection: 'row'}} horizontal={true}
showsHorizontalScrollIndicator={false}>
<TouchableOpacity onPress={() => this.setState({modalVisible: true})}>
<View style={{
marginLeft: 20,
marginTop: 20,
}}>
<Ionicons name="ios-add-circle" size={40} style={{position: 'relative', top: -8}} color="#FFBD59"/>
</View>
</TouchableOpacity>
{this.state.data.Thursday.map((event, index) => {
return (
<View key={index}>
<View style={styles.event2}>
<Text style={styles.eventTitle2}>{event.title}</Text>
<Text style={styles.eventBody2}>{event.location}</Text>
<Text
style={styles.eventBody2}>{moment(event.start).format("h:mm A")} - {moment(event.end).format("h:mm A")}</Text>
</View>
<Ionicons name={"ios-close-circle"} size={40}
style={{position: "absolute", right: 5, top: 13}} color="#FFBD59"/>
</View>
);
})}
</ScrollView>
</View>
<View style={{flex: 1, justifyContent: 'center', marginTop: 30}}>
<Text style={{fontSize: 20, fontWeight: 'bold', marginLeft: 20}}>Friday</Text>
<ScrollView style={{flexDirection: 'row'}} horizontal={true}
showsHorizontalScrollIndicator={false}>
<TouchableOpacity onPress={() => this.setState({modalVisible: true})}>
<View style={{
marginLeft: 20,
marginTop: 20,
}}>
<Ionicons name="ios-add-circle" size={40} style={{position: 'relative', top: -8}}/>
</View>
</TouchableOpacity>
{this.state.data.Friday.map((event, index) => {
return (
<View key={index}>
<View style={styles.event}>
<Text style={styles.eventTitle}>{event.title}</Text>
<Text style={styles.eventBody}>{event.location}</Text>
<Text
style={styles.eventBody}>{moment(event.start).format("h:mm A")} - {moment(event.end).format("h:mm A")}</Text>
</View>
<Ionicons name={"ios-close-circle"} size={40}
style={{position: "absolute", right: 5, top: 13}}/>
</View>
);
})}
</ScrollView>
</View>
<View style={{flex: 1, justifyContent: 'center', marginTop: 30}}>
<Text style={{fontSize: 20, fontWeight: 'bold', marginLeft: 20}}>Saturday</Text>
<ScrollView style={{flexDirection: 'row'}} horizontal={true}
showsHorizontalScrollIndicator={false}>
<TouchableOpacity onPress={() => this.setState({modalVisible: true})}>
<View style={{
marginLeft: 20,
marginTop: 20,
}}>
<Ionicons name="ios-add-circle" size={40} style={{position: 'relative', top: -8}} color="#FFBD59"/>
</View>
</TouchableOpacity>
{this.state.data.Saturday.map((event, index) => {
return (
<View key={index}>
<View style={styles.event2}>
<Text style={styles.eventTitle2}>{event.title}</Text>
<Text style={styles.eventBody2}>{event.location}</Text>
<Text
style={styles.eventBody2}>{moment(event.start).format("h:mm A")} - {moment(event.end).format("h:mm A")}</Text>
</View>
<Ionicons name={"ios-close-circle"} size={40}
style={{position: "absolute", right: 5, top: 13}} color="#FFBD59"/>
</View>
);
})}
</ScrollView>
</View>
<View style={{flex: 1, justifyContent: 'center', marginTop: 30}}>
<Text style={{fontSize: 20, fontWeight: 'bold', marginLeft: 20}}>Sunday</Text>
<ScrollView style={{flexDirection: 'row'}} horizontal={true}
showsHorizontalScrollIndicator={false}>
<TouchableOpacity onPress={() => this.setState({modalVisible: true})}>
<View style={{
marginLeft: 20,
marginTop: 20,
}}>
<Ionicons name="ios-add-circle" size={40} style={{position: 'relative', top: -8}}/>
</View>
</TouchableOpacity>
{this.state.data.Sunday.map((event, index) => {
return (
<View key={index}>
<View style={styles.event}>
<Text style={styles.eventTitle}>{event.title}</Text>
<Text style={styles.eventBody}>{event.location}</Text>
<Text
style={styles.eventBody}>{moment(event.start).format("h:mm A")} - {moment(event.end).format("h:mm A")}</Text>
</View>
<Ionicons name={"ios-close-circle"} size={40}
style={{position: "absolute", right: 5, top: 13}}/>
</View>
);
})}
</ScrollView>
</View>
</ScrollView>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
event: {
width: 180,
height: 200,
marginTop: 20,
backgroundColor: '#FFBD59',
marginRight: 10,
marginLeft: 20,
borderRadius: 40,
paddingLeft: 35,
justifyContent: 'center',
marginBottom: 15,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 7,
},
shadowOpacity: 0.26,
shadowRadius: 6,
},
eventBody: {
fontSize: 15,
color: 'white',
marginLeft: -25,
// marginBottom: 2,
},
eventBody2: {
fontSize: 15,
color: '#ffbd59',
marginLeft: -25,
},
eventTitle: {
fontSize: 28,
color: 'white',
fontWeight: 'bold',
width: 120,
marginLeft: -25,
marginBottom: 3,
flexWrap: "wrap",
fontFamily: "Butler-Light"
},
event2: {
width: 180,
height: 200,
marginTop: 20,
borderRadius: 1,
borderColor: '#FFBD59',
backgroundColor: 'white',
marginRight: 10,
marginLeft: 20,
borderRadius: 40,
paddingLeft: 35,
justifyContent: 'center',
marginBottom: 15,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 7,
},
shadowOpacity: 0.26,
shadowRadius: 6,
},
eventTitle2: {
fontSize: 28,
color: '#FFBD59',
fontWeight: "bold",
width: 120,
marginLeft: -25,
marginBottom: 3,
flexWrap: "wrap",
fontFamily: "Butler-Light"
}
});
export default CaregiverEvents;
<file_sep>import React from "react";
import {
AsyncStorage,
Button,
View,
TouchableOpacity,
Text,
StyleSheet
} from "react-native";
export default class SignInScreen extends React.Component {
static navigationOptions = {
title: "Please sign in"
};
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<TouchableOpacity onPress={this._signInCaregiver}>
<View style={styles.caregiverBtn}>
<Text style={styles.careText}>Sign in as Caregiver</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this._signInPatient}>
<View style={styles.patientBtn}>
<Text style={styles.patientText}>Sign in as Patient</Text>
</View>
</TouchableOpacity>
</View>
);
}
_signInCaregiver = async () => {
await AsyncStorage.setItem("userToken", "<PASSWORD>");
this.props.navigation.navigate("Caregiver");
};
_signInPatient = async () => {
await AsyncStorage.setItem("userToken", "<PASSWORD>");
this.props.navigation.navigate("Patient");
};
}
const styles = StyleSheet.create({
caregiverBtn: {
backgroundColor: "#FFBD59",
borderRadius: 30,
height: 60,
width: 200,
shadowColor: "black",
shadowOffset: { width: 0, height: 7 },
shadowRadius: 6,
shadowOpacity: 0.1
},
careText: {
flex: 1,
textAlign: "center",
marginTop: 20,
color: "white"
},
patientBtn: {
backgroundColor: "white",
borderColor: "#FFEE7E",
borderWidth: 2,
borderRadius: 30,
height: 60,
width: 200,
marginVertical: 15,
shadowColor: "black",
shadowOffset: { width: 0, height: 7 },
shadowRadius: 6,
shadowOpacity: 0.1
},
patientText: {
flex: 1,
textAlign: "center",
marginTop: 20,
color: "black"
}
});
<file_sep>import React from 'react';
import {createAppContainer, createSwitchNavigator} from 'react-navigation';
import CaregiverTabNavigator from './CaregiverTabNavigator';
import PatientTabNavigator from './PatientTabNavigator'
import AuthLoadingScreen from "../screens/AuthLoadingScreen";
import SignInScreen from "../screens/SignInScreen";
export default createAppContainer(
// createSwitchNavigator({
// // You could add another route here for authentication.
// // Read more at https://reactnavigation.org/docs/en/auth-flow.html
// Main: MainTabNavigator,
// })
createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
Caregiver: CaregiverTabNavigator,
Patient: PatientTabNavigator,
Auth: SignInScreen,
},
{
initialRouteName: 'AuthLoading',
}
)
);
<file_sep>import React, { Component } from "react";
import { AsyncStorage, Text, View } from "react-native";
import moment from "moment";
class PatientHome extends Component {
async componentDidMount() {
this.setState({
token: await AsyncStorage.getItem("userToken")
});
}
_signOutAsync = async () => {
await AsyncStorage.clear();
this.props.navigation.navigate("Auth");
};
render() {
const currentEvent = {
title: "Walk the dog",
location: "Too Good Park",
start: new Date(2020, 0, 13, 19, 20),
end: new Date(2020, 0, 13, 20, 20)
};
const nextEvent = {
title: "Eat dinner",
location: "Walmart",
start: new Date(2020, 0, 13, 20, 20),
end: new Date(2020, 0, 13, 21, 20)
};
return (
<View style={{ flex: 1, marginTop: 50, marginLeft: 20 }}>
<Text
style={{
fontFamily: "Butler-Light",
fontSize: 45,
fontWeight: "bold"
}}
>
Hi, Beatrice
</Text>
<View>
<Text style={{ fontSize: 25, fontFamily: "Avenir" }}>
Current Task
</Text>
<View
style={{
width: "94%",
height: 180,
backgroundColor: "#FFBD59",
borderRadius: 25
}}
>
<Text
style={{
fontSize: 25,
fontFamily: "Butler-Light",
color: "white",
textAlign: "center",
marginTop: 20
}}
>
{currentEvent.title}
</Text>
<Text
style={{
fontSize: 25,
fontFamily: "Butler-Light",
color: "white",
textAlign: "center",
marginTop: 20
}}
>
{currentEvent.location}
</Text>
<Text
style={{
fontSize: 25,
fontFamily: "Butler-Light",
color: "white",
textAlign: "center",
marginTop: 20
}}
>
{moment(currentEvent.start).format("h:mm A")} -{" "}
{moment(currentEvent.end).format("h:mm A")}
</Text>
</View>
</View>
<View style={{ marginTop: 20 }}>
<Text style={{ fontSize: 25, fontFamily: "Avenir" }}>Up Next</Text>
<View
style={{
width: "94%",
height: 180,
borderColor: "#FFBD59",
borderWidth: 1,
borderRadius: 25
}}
>
<Text
style={{
fontSize: 25,
fontFamily: "Butler-Light",
color: "#FFBD59",
textAlign: "center",
marginTop: 20
}}
>
{nextEvent.title}
</Text>
<Text
style={{
fontSize: 25,
fontFamily: "Butler-Light",
color: "#FFBD59",
textAlign: "center",
marginTop: 20
}}
>
{nextEvent.location}
</Text>
<Text
style={{
fontSize: 25,
fontFamily: "Butler-Light",
color: "#FFBD59",
textAlign: "center",
marginTop: 20
}}
>
{moment(nextEvent.start).format("h:mm A")} -{" "}
{moment(nextEvent.end).format("h:mm A")}
</Text>
</View>
</View>
</View>
);
}
}
export default PatientHome;
<file_sep>// import React, { Component } from "react";
// import { ExpoConfigView } from "@expo/samples";
// import { AsyncStorage, Button, Text, View } from "react-native";
// export default class SettingsScreen extends Component {
// state = {
// token: ""
// };
// async componentDidMount() {
// this.setState({
// token: await AsyncStorage.getItem("userToken")
// });
// }
// _signOutAsync = async () => {
// await AsyncStorage.clear();
// this.props.navigation.navigate("Auth");
// };
// render() {
// return (
// <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
// <Text>Hi {this.state.token}</Text>
// <Button title="Actually, sign me out :)" onPress={this._signOutAsync} />
// </View>
// );
// }
// }
// SettingsScreen.navigationOptions = {
// title: "app.json"
// };
import React from "react";
import styled from "styled-components";
import {
Button,
TouchableOpacity,
View,
Switch,
Image,
Slider,
Text,
AsyncStorage
} from "react-native";
import * as Font from "expo-font";
export default class SettingsScreen extends React.Component {
state = {
value: false,
fontLoaded: false,
slideValue: 0,
name: "",
email: ""
};
async componentDidMount() {
await Font.loadAsync({
"Butler-Light": require("../assets/fonts/Butler_Light.otf")
});
if (await AsyncStorage.getItem("userToken") == "caregiver")
{
this.setState({name:"Ariel", email:"<EMAIL>"});
}
else
{
this.setState({name:"Beatrice", email:"<EMAIL>"});
}
this.setState({ fontLoaded: true });
}
toggleSwitch = value => {
//onValueChange of the switch this function will be called
this.setState({ value: value });
//state changes according to switch
//which will result in re-render the text
};
_signOutAsync = async () => {
await AsyncStorage.clear();
this.props.navigation.navigate("Auth");
};
render() {
return (
<Container>
<TitleBar>
{this.state.fontLoaded ? (
<Title style={{ fontFamily: "Butler-Light" }}>Settings</Title>
) : null}
{/* <Image
source={require("../assets/icon.png")}
style={{ position: "absolute", top: -62, right: -46 }}
/> */}
</TitleBar>
<NameContainer>
<ViewText style={{ marginTop: 0 }}>
<Name>Name</Name>
<TextName>
{this.state.name}
</TextName>
</ViewText>
<ViewText>
<Name>Email</Name>
<TextName>{this.state.email}</TextName>
</ViewText>
<ViewText>
<Name>Password</Name>
<TextName>***************</TextName>
</ViewText>
</NameContainer>
<AlertsContainer>
<TextName style={{ paddingTop: 0 }}>Email Notifications</TextName>
<View style={{ flex: 1, flexDirection: "row" }}></View>
<Switch
style={{ marginRight: 40 }}
onValueChange={this.toggleSwitch}
value={this.state.value}
// thumbColor="#ffd36f"
trackColor={{ true: "#ffd36f" }}
/>
</AlertsContainer>
<BtnContainer>
<TouchableOpacity
style={{
width: 280,
height: 45,
borderRadius: 22,
backgroundColor: "#FFD36F",
alignItems: "center",
justifyContent: "center",
marginTop: 30
}}
onPress={() => this._signOutAsync()}
>
<BtnText>Log Out</BtnText>
</TouchableOpacity>
</BtnContainer>
</Container>
);
}
}
SettingsScreen.navigationOptions = {
header: null
};
const Container = styled.View`
margin-left: 40px;
`;
const TitleBar = styled.View`
margin-top: 100px;
`;
const Title = styled.Text`
font-size: 40px;
`;
const NameContainer = styled.View`
margin-top: 40px;
`;
const TextName = styled.Text`
font-size: 25px;
color: #ffd36f;
padding-top: 10px;
`;
const Name = styled.Text`
font-weight: 100;
/* font-family: "Avenir"; */
`;
const AlertsContainer = styled.View`
margin-top: 30px;
flex-direction: row;
justify-content: space-between;
`;
const BtnContainer = styled.View``;
const BtnText = styled.Text`
color: white;
font-size: 20px;
font-weight: bold;
`;
const ViewText = styled.View`
margin-top: 30px;
`;
const Align = styled.View`
justify-content: space-between;
flex-direction: row;
`;
| 445204e959926ab95b38d0095f67649f4bab8539 | [
"JavaScript"
] | 6 | JavaScript | RageItalic/Flare | 9437bf2e942febda236968efab354fa1f1674715 | e6a605ab99936c2b769bc7d661526377d77f93cf |
refs/heads/master | <repo_name>Farforr/overlord<file_sep>/overlord/minions/migrations/0008_auto_20160720_1955.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('minions', '0007_auto_20160629_2101'),
]
operations = [
migrations.RemoveField(
model_name='minionrequest',
name='owner',
),
migrations.RemoveField(
model_name='minionrequestbody',
name='request',
),
migrations.RemoveField(
model_name='minionrequestheader',
name='request',
),
migrations.RemoveField(
model_name='miniondata',
name='request',
),
migrations.DeleteModel(
name='MinionRequest',
),
migrations.DeleteModel(
name='MinionRequestBody',
),
migrations.DeleteModel(
name='MinionRequestHeader',
),
]
<file_sep>/overlord/minions/migrations/0003_auto_20160627_2235.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('minions', '0002_auto_20160627_1928'),
]
operations = [
migrations.AddField(
model_name='miniondata',
name='created',
field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2016, 6, 27, 22, 35, 6, 126028, tzinfo=utc), verbose_name='created'),
preserve_default=False,
),
migrations.AddField(
model_name='miniondata',
name='last_modified',
field=models.DateTimeField(auto_now=True, default=datetime.datetime(2016, 6, 27, 22, 35, 10, 430142, tzinfo=utc), verbose_name='last modified'),
preserve_default=False,
),
migrations.AddField(
model_name='minionrequestbody',
name='created',
field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2016, 6, 27, 22, 35, 19, 582085, tzinfo=utc), verbose_name='created'),
preserve_default=False,
),
migrations.AddField(
model_name='minionrequestbody',
name='last_modified',
field=models.DateTimeField(auto_now=True, default=datetime.datetime(2016, 6, 27, 22, 35, 25, 342014, tzinfo=utc), verbose_name='last modified'),
preserve_default=False,
),
migrations.AddField(
model_name='minionrequestheader',
name='created',
field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2016, 6, 27, 22, 35, 29, 933939, tzinfo=utc), verbose_name='created'),
preserve_default=False,
),
migrations.AddField(
model_name='minionrequestheader',
name='last_modified',
field=models.DateTimeField(auto_now=True, default=datetime.datetime(2016, 6, 27, 22, 35, 35, 590038, tzinfo=utc), verbose_name='last modified'),
preserve_default=False,
),
]
<file_sep>/overlord/core/api.py
from django.conf.urls import url
from overlord.users import views as user_views
from django.conf.urls import include
urlpatterns = [
# url confs for users app
url(
regex=r'^users/$',
view=user_views.UserList.as_view(),
name='user_rest_api'
),
url(
regex=r'^users/(?P<pk>[0-9]+)/$',
view=user_views.UserDetail.as_view(),
name='user_rest_api'
),
]
<file_sep>/overlord/minions/tests/test_models.py
from test_plus.test import TestCase
from ..models import (
Minion,
MinionData
)
class TestMinionModel(TestCase):
def setUp(self):
self.user = self.make_user()
self.minion_parent = Minion(name='parent')
self.minion_child = Minion(name='child', parent=self.minion_parent)
self.minion_data = MinionData(
pk=1,
field_name='test_field_name',
field_value='test_field_value',
minion=self.minion_parent
)
def test_minion__str__(self):
self.assertEqual(
self.minion_parent.__str__(),
"parent" # This is the default username for self.make_user()
)
def test_minion_get_absolute_url(self):
self.assertEqual(
self.minion_parent.get_absolute_url(),
'/minions/minion/' + self.minion_parent.name + '/'
)
def test_minion_is_top_level_negative(self):
self.assertFalse(self.minion_child.is_top_level())
def test_minion_is_top_level_positive(self):
self.assertTrue(self.minion_parent.is_top_level())
def test_minion_is_top_level_positive(self):
self.assertTrue(self.minion_parent.is_top_level())
def test_minionData_get_absolute_url(self):
self.assertEqual(
self.minion_data.get_absolute_url(),
'/minions/data/' + str(self.minion_data.pk) + '/'
)
def test_minionData__str__(self):
self.assertEqual(
self.minion_data.__str__(),
'test_field_name : test_field_value'
)
<file_sep>/overlord/minions/migrations/0006_remove_minion_top_level.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('minions', '0005_auto_20160628_0005'),
]
operations = [
migrations.RemoveField(
model_name='minion',
name='top_level',
),
]
<file_sep>/overlord/minions/tests/test_views.py
from unittest.mock import patch, MagicMock
from django.core.urlresolvers import reverse
from django.test import RequestFactory
from test_plus.test import TestCase
from ..models import (
Minion,
MinionData
)
from ..views import(
MinionCreateView,
MinionDetailView
)
class TestMinionCreateView(TestCase):
def setUp(self):
self.user = self.make_user()
self.factory = RequestFactory()
def test_get(self):
request = self.factory.get(reverse('minions:minion-create'))
request.user = self.user
response = MinionCreateView.as_view()(request)
self.assertEqual(response.status_code, 200)
# self.assertEqual(response.context_data['user'], self.data)
# self.assertEqual(response.context_data['request'], request)
@patch('Minion.save', MagicMock(name="save"))
def test_post(self):
data = {
'name': 'test_minion'
}
request = self.factory.post(reverse('minions:minion-create'), data)
request.user = self.user
response = MinionCreateView.as_view()(request)
self.assertEqual(response.status_code, 302)
self.assertTrue(Minion.save.called)
self.assertEqual(Minion.save.call_count, 1)
<file_sep>/overlord/minions/models.py
from overlord.core.models import DatedModel, NamedModel
# from django.core.validators import ValidationError
from django.core.urlresolvers import reverse
from django.db import models
from overlord.users.models import User
class Minion(DatedModel, NamedModel):
owner = models.ForeignKey(User, related_name='minions')
parent = models.ForeignKey(
'self',
related_name='minions',
blank=True,
null=True
)
def get_absolute_url(self):
return reverse("minions:minion-detail", kwargs={"name": self.name})
def is_top_level(self):
return self.parent is None
class MinionData(DatedModel):
minion = models.ForeignKey(Minion, related_name='data')
field_name = models.CharField(max_length=80)
field_value = models.CharField(max_length=80)
def get_absolute_url(self):
return reverse("minions:data-detail", kwargs={"pk": self.pk})
def __str__(self):
return self.field_name + ' : ' + self.field_value
<file_sep>/overlord/minions/api/v1/serializers.py
from rest_framework import serializers
from ...models import Minion, MinionData
class MinionSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Minion
fields = ('pk', 'name', 'last_modified', 'data', 'url')
extra_kwargs = {'url': {'view_name': 'minions:api:minion-detail'}}
data = serializers.HyperlinkedRelatedField(
many=True,
view_name='minions:api:data-detail',
read_only=True,
lookup_field='pk'
)
class MinionDataSerializer(serializers.HyperlinkedModelSerializer):
minion = serializers.HyperlinkedRelatedField(
view_name='minions:api:minion-detail',
read_only=True,
lookup_field='pk'
)
class Meta:
model = MinionData
fields = ('minion', 'url', 'field_name',
'field_value', 'last_modified')
extra_kwargs = {'url': {'view_name': 'minions:api:data-detail'}}
<file_sep>/overlord/minions/views.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.views.generic import DetailView, ListView, RedirectView, UpdateView, CreateView
from braces.views import LoginRequiredMixin
from rest_framework.generics import ListCreateAPIView
from rest_framework.generics import RetrieveUpdateDestroyAPIView
from rest_framework import permissions
from overlord.core.permissions import IsOwnerOrReadOnly
from .models import Minion, MinionData
# class MinionActionMixin(object):
# fields = ['name']
# @property
# def success_msg(self):
# return NotImplemented
# def form_valid(self, form):
# messages.info(self.request, self.success_msg)
# return super(MinionActionMixin, self).form_valid(form)
class MinionListView(LoginRequiredMixin, ListView):
model = Minion
# These next two lines tell the view to index lookups by name
# slug_field = "name"
# slug_url_kwarg = "name"
class MinionCreateView(LoginRequiredMixin, CreateView):
model = Minion
success_msg = 'Minion Created!'
template_name_suffix = '_create_form'
fields = ['name', 'parent']
def form_valid(self, form):
form.instance.owner = self.request.user
return super(MinionCreateView, self).form_valid(form)
class MinionDetailView(LoginRequiredMixin, DetailView):
model = Minion
# These next two lines tell the view to index lookups by name
slug_field = "name"
slug_url_kwarg = "name"
def get_context_data(self, **kwargs):
context = super(MinionDetailView, self).get_context_data(**kwargs)
context["minion_list"] = Minion.objects.filter(parent=self.object.pk)
context["data_list"] = MinionData.objects.filter(minion=self.object.pk)
return context
# class MinionDataListView(LoginRequiredMixin, ListView):
# model = MinionData
# template_name = "minions/minion_data_list.html"
# slug_field = "name"
# slug_url_kwarg = "name"
class MinionDataDetailView(LoginRequiredMixin, DetailView):
model = MinionData
template_name = "minions/minion_data_detail.html"
slug_field = "pk"
slug_url_kwarg = "pk"
# class MinionRedirectView(LoginRequiredMixin, RedirectView):
# permanent = False
# def get_redirect_url(self):
# return reverse("minions:detail",
# kwargs={"name": self.request.minion.name})
# class MinionUpdateView(LoginRequiredMixin, MinionActionMixin, UpdateView):
# fields = ['name']
# success_msg = 'Minion Updated!'
# model = Minion
# # send the user back to the network page after a successful update
# def get_success_url(self):
# return reverse("minions:detail",
# kwargs={"name": self.request.minion.name})
<file_sep>/overlord/core/admin.py
from django.contrib import admin
class abstractAdmin(admin.ModelAdmin):
# I dont know why, but if the admin imports this class, everything breaks
# so for now I have to keep it duplicated :(
readonly_fields = ['created', 'last_modified']
fieldsets = [
('Basic Information', {'fields': ['name']}),
('Date Information', {
'fields': ['created', 'last_modified'], 'classes': ['collapse']}),
]
inlines = []
<file_sep>/overlord/minions/api/v1/urls.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
router = DefaultRouter()
router.register(r'minion', views.MinionViewSet, 'minion')
router.register(r'data', views.MinionDataViewSet, 'data')
urlpatterns = [
url(
r'^',
include(router.urls)
),
]
<file_sep>/.coveragerc
[run]
include = overlord/*
omit = *migrations*
<file_sep>/overlord/minions/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Minion',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
('name', models.SlugField(validators=[django.core.validators.MinLengthValidator(1)], max_length=45)),
('created', models.DateTimeField(verbose_name='created', auto_now_add=True)),
('last_modified', models.DateTimeField(auto_now=True, verbose_name='last modified')),
('top_level', models.BooleanField(default=True)),
('owner', models.ForeignKey(related_name='minions', to=settings.AUTH_USER_MODEL)),
('parent', models.ForeignKey(to='minions.Minion', blank=True, related_name='minions')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='MinionData',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
('field_name', models.CharField(max_length=80)),
('field_value', models.CharField(max_length=80)),
('owner', models.ForeignKey(related_name='data', to='minions.Minion')),
],
),
migrations.CreateModel(
name='MinionRequest',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
('created', models.DateTimeField(verbose_name='created', auto_now_add=True)),
('last_modified', models.DateTimeField(auto_now=True, verbose_name='last modified')),
('response', models.BooleanField(default=True)),
('direction', models.CharField(choices=[('inc', 'incoming'), ('out', 'outgoing')], max_length=8)),
('owner', models.ForeignKey(related_name='requests', to='minions.Minion')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='MinionRequestBody',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
('value', models.TextField()),
('request', models.OneToOneField(to='minions.MinionRequest', related_name='body')),
],
),
migrations.CreateModel(
name='MinionRequestHeader',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
('name', models.CharField(max_length=80)),
('value', models.CharField(max_length=80)),
('request', models.ForeignKey(related_name='headers', to='minions.MinionRequest')),
],
),
migrations.AddField(
model_name='miniondata',
name='source',
field=models.ForeignKey(related_name='data', to='minions.MinionRequest'),
),
]
<file_sep>/overlord/minions/urls.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import include, url
from . import views
urlpatterns = [
# URL pattern for the MinionListView
url(
regex=r'^$',
view=views.MinionListView.as_view(),
name='minion-list'
),
# URL pattern for the MinionCreateView
url(
regex=r'^~create/$',
view=views.MinionCreateView.as_view(),
name='minion-create'
),
# URL pattern for the MinionDetailView
url(
regex=r'^minion/(?P<name>[\w]+)/$',
view=views.MinionDetailView.as_view(),
name='minion-detail'
),
# URL pattern for the MinionDataDetailView
url(
regex=r'^data/(?P<pk>[0-9]+)/$',
view=views.MinionDataDetailView.as_view(),
name='data-detail'
),
# # URL pattern for the MinionRedirectView
# url(
# regex=r'^~redirect/$',
# view=views.MinionRedirectView.as_view(),
# name='redirect'
# ),
# # URL pattern for the MinionUpdateView
# url(
# regex=r'^~update/$',
# view=views.MinionUpdateView.as_view(),
# name='update'
# ),
url(r'^api/v1/', include("overlord.minions.api.v1.urls", namespace="api")),
]
<file_sep>/functional_tests/tests.py
from django.test import LiveServerTestCase
from selenium import webdriver
from allauth.account.models import EmailAddress
class AbstractTestCase(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def click_button_with_text_from_list(self, text, buttons):
for button in buttons:
if (button.text == text):
button.click()
break
def verify_navbar_links(self, navbar_links, logged_in=False):
navbar_links = [link.text for link in navbar_links]
self.assertIn('Home', navbar_links)
self.assertIn('About', navbar_links)
if (logged_in == True):
self.assertIn('My Minions', navbar_links)
self.assertIn('My Profile', navbar_links)
self.assertIn('Logout', navbar_links)
self.assertNotIn('Sign Up', navbar_links)
self.assertNotIn('Log In', navbar_links)
else:
self.assertIn('Sign Up', navbar_links)
self.assertIn('Log In', navbar_links)
self.assertNotIn('My Minions', navbar_links)
self.assertNotIn('My Profile', navbar_links)
self.assertNotIn('Logout', navbar_links)
class NewVisitorTest(AbstractTestCase):
def test_can_create_an_account_and_login(self):
# New user heads to the homepage of the myOverlord Site
self.browser.get(self.live_server_url)
# Overlord appears in the website title
self.assertIn('overlord', self.browser.title)
# is invited to Sign Up
navbar_links = self.browser.find_elements_by_xpath(
"//div[@id='bs-navbar-collapse-1']/nav/a"
)
self.verify_navbar_links(navbar_links)
# navigates to the sign up page by clicking the Sign Up button
self.click_button_with_text_from_list("Sign Up", navbar_links)
# The sign up page includes a form with the following fields:
# Username, E-mail, Password, Password (again)
username_field = self.browser.find_element_by_id("id_username")
email_field = self.browser.find_element_by_id("id_email")
password_field = self.browser.find_element_by_id("id_password1")
password_again_field = self.browser.find_element_by_id("id_password2")
self.assertEqual(
"Username",
username_field.get_attribute('placeholder')
)
self.assertEqual(
"E-mail address",
email_field.get_attribute('placeholder')
)
self.assertEqual(
"Password",
password_field.get_attribute('placeholder')
)
self.assertEqual(
"Password (again)",
password_again_field.get_attribute('placeholder')
)
# There is also a submit button
buttons = self.browser.find_elements_by_class_name("btn-primary")
self.assertIn("Sign Up »", [button.text for button in buttons])
username = "some_user"
email = "<EMAIL>"
password = "<PASSWORD>"
# fills out the form
username_field.send_keys(username)
email_field.send_keys(email)
password_field.send_keys(<PASSWORD>)
password_again_field.send_keys(<PASSWORD>)
# clicks the submit button
self.click_button_with_text_from_list("Sign Up »", buttons)
# a request for email verification appears
# verifies email address
# (This is a bit of a hack to avoid having to actually send the email
# confirmation for now)
email = EmailAddress.objects.get(email=email)
email.verified = True
email.save()
# navigates back to home page
self.browser.get(self.live_server_url)
# the user is not yet logged in
navbar_links = self.browser.find_elements_by_xpath(
"//div[@id='bs-navbar-collapse-1']/nav/a"
)
self.verify_navbar_links(navbar_links)
# navigates to the sign up page by clicking the Sign Up button
self.click_button_with_text_from_list("Log In", navbar_links)
# logs in by filling out the login form
username_field = self.browser.find_element_by_id("id_login")
password_field = self.browser.find_element_by_id("id_password")
buttons = self.browser.find_elements_by_class_name(
"btn-primary"
)
username_field.send_keys(username)
password_field.send_keys(password)
self.click_button_with_text_from_list("Sign In", buttons)
# The Sign Up and Log In links have been replaced by 3 new ones:
# My Minions, My Profile, and Logout
navbar_links = self.browser.find_elements_by_xpath(
"//div[@id='bs-navbar-collapse-1']/nav/a"
)
self.verify_navbar_links(navbar_links, True)
class NewMinionTest(AbstractTestCase):
def test_can_create_minion_and_view_it_later(self):
self.username = "some_user"
self.email = "<EMAIL>"
self.password = "<PASSWORD>"
self.first_minion_name = "some_minion_name"
self.generate_new_user()
self.login()
# clicks on the minions tab
navbar_links = self.browser.find_elements_by_xpath(
"//div[@id='bs-navbar-collapse-1']/nav/a"
)
self.click_button_with_text_from_list("My Minions", navbar_links)
# The user is taken to a page which invites them to add a minion
create = self.browser.find_element_by_link_text("Create a new Minion")
# It would list the existing minions present for the user, but the user
# is new and haven't made any yet
minion_list = self.browser.find_element_by_class_name("list-group")
self.assertEqual(0, len(minion_list.find_elements_by_tag_name("div")))
self.assertEqual(0, len(minion_list.find_elements_by_tag_name("a")))
# clicks the "Create a new Minion link"
create.click()
# the user is taken to a form page to create the new minion
# the form includes a Name field, a Parent field (with no options), and
# a "Create" button
form = self.browser.find_element_by_tag_name("form")
inputs = form.find_elements_by_tag_name("input")
parent_select = form.find_element_by_tag_name("select")
self.assertEqual(3, len(inputs))
self.assertEqual(
"csrfmiddlewaretoken",
inputs[0].get_attribute("name")
)
self.assertEqual("id_name", inputs[1].get_attribute("id"))
name_input = inputs[1]
self.assertEqual("id_parent", parent_select.get_attribute("id"))
# There are no options available for parents yet (besides the default)
parent_options = parent_select.find_elements_by_tag_name("option")
self.assertEqual(
1,
len(parent_options)
)
self.assertEqual("", parent_options[0].get_attribute("value"))
self.assertEqual("submit", inputs[2].get_attribute("type"))
submit_button = inputs[2]
# The user gives a name to their new minion
name_input.send_keys(self.first_minion_name)
# The user confirms the submission
submit_button.click()
# The user is redirected to a detail page of the minion that was just
# created
container = self.browser.find_element_by_class_name("col-sm-12")
# the detail page begins with the name of the minion
self.assertEqual(
self.first_minion_name,
container.find_element_by_tag_name("h2").text
)
# The rest of the page is broken up into 2 sections
sections = container.find_elements_by_tag_name("div")
headers = container.find_elements_by_tag_name("h4")
self.assertEqual(2, len(sections))
self.assertEqual(2, len(headers))
# there is one section which lists any children the minion has
self.assertEqual(
"Minions",
headers[0].text
)
# this section is currently empty
self.assertEqual(0, len(sections[0].find_elements_by_tag_name("a")))
self.assertEqual(0, len(sections[0].find_elements_by_tag_name("div")))
# there is a final section with any data the minion has accumulated
self.assertEqual(
"Data",
headers[1].text
)
# this section is also currently empty
self.assertEqual(0, len(sections[1].find_elements_by_tag_name("a")))
self.assertEqual(0, len(sections[1].find_elements_by_tag_name("div")))
# The user backs out to the listing page
navbar_links = self.browser.find_elements_by_xpath(
"//div[@id='bs-navbar-collapse-1']/nav/a"
)
self.click_button_with_text_from_list("My Minions", navbar_links)
# The user now sees the minion that they had created on the listing
# page
minion_list = self.browser.find_element_by_class_name("list-group")
self.assertEqual(1, len(minion_list.find_elements_by_tag_name("a")))
self.browser.find_element_by_link_text(self.first_minion_name)
def generate_new_user(self):
# Go to the signup page
self.browser.get(self.live_server_url + "/accounts/signup/")
# submit the form
self.complete_and_submit_signup_form()
# verify email address
self.verify_email_address()
def complete_and_submit_signup_form(self):
username_field = self.browser.find_element_by_id("id_username")
email_field = self.browser.find_element_by_id("id_email")
password_field = self.browser.find_element_by_id("id_password1")
password_again_field = self.browser.find_element_by_id("id_password2")
username_field.send_keys(self.username)
email_field.send_keys(self.email)
password_field.send_keys(<PASSWORD>)
password_again_field.send_keys(<PASSWORD>.password)
# clicks the submit button
buttons = self.browser.find_elements_by_class_name("btn-primary")
self.click_button_with_text_from_list("Sign Up »", buttons)
def verify_email_address(self):
# verifies email address
# (This is a bit of a hack to avoid having to actually send the email
# confirmation for now)
email = EmailAddress.objects.get(email=self.email)
email.verified = True
email.save()
def login(self):
# Go to the login page
self.browser.get(self.live_server_url + "/accounts/login/")
# logs in by filling out the login form
username_field = self.browser.find_element_by_id("id_login")
password_field = self.browser.find_element_by_id("id_password")
buttons = self.browser.find_elements_by_class_name(
"btn-primary"
)
username_field.send_keys(self.username)
password_field.send_keys(<PASSWORD>)
self.click_button_with_text_from_list("Sign In", buttons)
<file_sep>/overlord/minions/api/v1/views.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from rest_framework import viewsets, permissions
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from overlord.core.permissions import IsOwnerOrReadOnly
from ... models import Minion, MinionData
from . serializers import MinionSerializer, MinionDataSerializer
class MinionViewSet(viewsets.ModelViewSet):
serializer_class = MinionSerializer
queryset = Minion.objects.all()
permission_classes = (
# permissions.IsAuthenticatedOrReadOnly,
# IsOwnerOrReadOnly
)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class MinionDataViewSet(viewsets.ModelViewSet):
serializer_class = MinionDataSerializer
queryset = MinionData.objects.all()
permission_classes = (
# permissions.IsAuthenticatedOrReadOnly,
# IsOwnerOrReadOnly
)
# def perform_create(self, serializer):
# serializer.save(minion=Minion.objects.get(pk=14))
<file_sep>/overlord/templates/minions/minion_detail.html
{% extends "base.html" %}
{% load static %}
{% block title %}Minion: {{ object.name }}{% endblock %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-sm-12">
<h2>{{ object.name }}</h2>
<h4>Minions</h4>
<div class="list-group">
{% for minion in minion_list %}
<a href="{% url 'minions:minion-detail' minion.name %}" class="list-group-item">
<h4 class="list-group-item-heading">{{ minion.name }}</h4>
</a>
{% endfor %}
</div>
<h4>Data</h4>
<div class="list-group">
{% for data in data_list %}
<a href="{% url 'minions:data-detail' data.pk %}" class="list-group-item">Data Object</a>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock content %}
<file_sep>/overlord/minions/migrations/0007_auto_20160629_2101.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('minions', '0006_remove_minion_top_level'),
]
operations = [
migrations.RenameField(
model_name='miniondata',
old_name='owner',
new_name='minion',
),
migrations.RenameField(
model_name='miniondata',
old_name='source',
new_name='request',
),
migrations.AlterField(
model_name='minionrequest',
name='direction',
field=models.CharField(choices=[('inc', 'Incoming'), ('out', 'Outgoing')], max_length=8),
),
]
<file_sep>/overlord/minions/admin.py
from django.contrib import admin
from .models import Minion, MinionData
class MinionInline(admin.TabularInline):
model = Minion
fieldsets = [
('Overview', {'fields': ('name',)})
]
extra = 3
class MinionDataInline(admin.TabularInline):
model = MinionData
fields = ('field_name', 'field_value')
extra = 3
@admin.register(Minion)
class MinionAdmin(admin.ModelAdmin):
readonly_fields = ['created', 'last_modified']
fieldsets = [
('Overview', {'fields': ['name', 'owner', 'parent']}),
('Date Information', {
'fields': ['created', 'last_modified'], 'classes': ['collapse']}),
]
inlines = [MinionInline, MinionDataInline]
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for obj in formset.deleted_objects:
obj.delete()
for instance in instances:
instance.owner = request.user
instance.save()
formset.save_m2m()
@admin.register(MinionData)
class MinionDataAdmin(admin.ModelAdmin):
readonly_fields = ['created', 'last_modified']
fieldsets = [
('Overview', {'fields': [
'minion', 'request', 'field_name', 'field_value']}),
('Date Information', {
'fields': ['created', 'last_modified'], 'classes': ['collapse']}),
]
<file_sep>/overlord/core/models.py
from django.db import models
from django.core.validators import MinLengthValidator
class NamedModel(models.Model):
name = models.SlugField(max_length=45, validators=[MinLengthValidator(1)])
def __str__(self):
return self.name
class Meta:
abstract = True
class DatedModel(models.Model):
created = models.DateTimeField('created', auto_now_add=True)
last_modified = models.DateTimeField('last modified', auto_now=True)
class Meta:
abstract = True
<file_sep>/overlord/users/serializers.py
from overlord.users.models import User
from overlord.minions.models import Minion
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
minions = serializers.PrimaryKeyRelatedField(many=True, queryset=Minion.objects.all())
class Meta:
model = User
fields = ('username', 'name', 'minions')
| 2d7d9318e83c0dc9b524c2b37bbc0ce471c6d168 | [
"Python",
"HTML",
"INI"
] | 21 | Python | Farforr/overlord | f46027a13a668e41dec655582c2da8ecc1cd3960 | 1f012c88918d03659295137bbb68866f2ea183d6 |
refs/heads/master | <file_sep>namespace WildRydes
{
public class Unicorn
{
public string Name { get; set; }
public string Color { get; set; }
public string Gender { get; set; }
}
}<file_sep>using System;
using Amazon.DynamoDBv2.DataModel;
namespace WildRydesWebApi.Entities
{
public class Ride
{
[DynamoDBHashKey]
public string RideId { get; set; }
public string User { get; set; }
public Unicorn Unicorn { get; set; }
public string UnicornName { get; set; }
public DateTime RequestTime { get; set; }
}
}<file_sep>using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Serialization;
using WildRydesWebApi.Extensions;
using WildRydesWebApi.Middlewares;
using WildRydesWebApi.Services;
namespace WildRydesWebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDynamoDb();
services.AddCors(options =>
{
options.AddDefaultPolicy(builder => builder.AllowAnyOrigin());
});
services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
// To use Camel casing
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors();
app.UseHttpsRedirection();
app.UseClaimsTransformation();
app.UseMvc();
}
}
}<file_sep>namespace WildRydes
{
public class RideRequest
{
public GeoLocation PickupLocation { get; set; }
}
}<file_sep>using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
namespace WildRydesWebApi.Services
{
public class ClaimsTransformer: IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var ci = (ClaimsIdentity) principal.Identity;
if (!ci.HasClaim(c => c.Type == ClaimTypes.Name) && ci.HasClaim(c => c.Type == "cognito:username"))
{
ci.AddClaim(new Claim(ClaimTypes.Name, ci.Claims.First(c=>c.Type== "cognito:username").Value));
}
return Task.FromResult(principal);
}
}
}<file_sep>using WildRydesWebApi.Entities;
namespace WildRydesWebApi.Models
{
public class RideResponse
{
public string RideId { get; set; }
public string Rider { get; set; }
public Unicorn Unicorn { get; set; }
public string UnicornName { get; set; }
public string Eta { get; set; }
}
}<file_sep>using Amazon.Lambda.AspNetCoreServer;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Formatting.Json;
namespace WildRydesWebApi
{
public class LambdaFunction : APIGatewayProxyFunction<Startup>
{
protected override void Init(IWebHostBuilder builder)
{
builder
.ConfigureLogging(logging => logging.ClearProviders())
.UseSerilog((hostingContext, loggerConfiguration) =>
{
loggerConfiguration
// Serilog.Settings.Configuration is required
.ReadFrom.Configuration(hostingContext.Configuration)
.WriteTo.Console(new JsonFormatter(renderMessage: true));
});
}
}
}<file_sep>using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace WildRydesWebApi.Middlewares
{
public static class ClaimsTransformationMiddlewareExtensions
{
public static IApplicationBuilder UseClaimsTransformation(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<ClaimsTransformationMiddleware>();
}
}
public class ClaimsTransformationMiddleware
{
private readonly RequestDelegate _next;
private readonly IClaimsTransformation _claimsTransformer;
public ClaimsTransformationMiddleware(RequestDelegate next, IClaimsTransformation claimsTransformer)
{
_next = next;
_claimsTransformer = claimsTransformer;
}
public async Task InvokeAsync(HttpContext context)
{
await _claimsTransformer.TransformAsync(context.User);
await _next(context);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Newtonsoft.Json;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace WildRydes
{
public class Function
{
// This const is the name of the environment variable that the serverless.template will use to set
// the name of the DynamoDB table used to store blog posts.
// ReSharper disable once InconsistentNaming
private const string TABLENAME_ENVIRONMENT_VARIABLE_LOOKUP = "RidesTable";
private readonly IDynamoDBContext _dbContext;
private readonly Unicorn[] _fleets = new[]
{
new Unicorn{
Name= "Bucephalus",
Color= "Golden",
Gender= "Male",
},
new Unicorn{
Name= "Shadowfax",
Color= "White",
Gender= "Male",
},
new Unicorn{
Name= "Rocinante",
Color= "Yellow",
Gender= "Female",
},
};
public Function()
{
// Check to see if a table name was passed in through environment variables and if so
// add the table mapping.
var tableName = Environment.GetEnvironmentVariable(TABLENAME_ENVIRONMENT_VARIABLE_LOOKUP);
if (!string.IsNullOrEmpty(tableName))
{
AWSConfigsDynamoDB.Context.TypeMappings[typeof(Ride)] = new Amazon.Util.TypeMapping(typeof(Ride), tableName);
}
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
_dbContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);
}
/// <summary>
/// A simple function that takes a string and does a ToUpper
/// </summary>
/// <param name="request"></param>
/// <param name="context"></param>
/// <returns></returns>
public async Task<APIGatewayProxyResponse> FunctionHandlerAsync(APIGatewayProxyRequest request, ILambdaContext context)
{
if (request.RequestContext.Authorizer == null)
{
return Error("Authorization not configured", context.AwsRequestId);
}
var rideId = Guid.NewGuid().ToString();
context.Logger.LogLine($"Received request ({rideId}): {JsonConvert.SerializeObject(request)}");
// Because we're using a Cognito User Pools authorizer, all of the claims
// included in the authentication token are provided in the request context.
// This includes the username as well as other attributes.
var username = request.RequestContext.Authorizer.Claims["cognito:username"];
// The body field of the event in a proxy integration is a raw string.
// In order to extract meaningful values, we need to first parse this string
// into an object. A more robust implementation might inspect the Content-Type
// header first and use a different parsing strategy based on that value.
var requestBody = JsonConvert.DeserializeObject<RideRequest>(request.Body);
var pickupLocation = requestBody.PickupLocation;
var unicorn = FindUnicorn(pickupLocation);
try
{
await _dbContext.SaveAsync(new Ride
{
RideId = rideId,
RequestTime = DateTime.UtcNow,
Unicorn = unicorn,
UnicornName = unicorn.Name,
User = username
});
var rider = new RideResponse
{
Eta = "30 seconds",
RideId = rideId,
Rider = username,
Unicorn = unicorn,
UnicornName = unicorn.Name
};
return Created(rider);
}
catch (Exception e)
{
Console.WriteLine(e);
return Error(e.Message, context.AwsRequestId);
}
}
// This is where you would implement logic to find the optimal unicorn for
// this ride (possibly invoking another Lambda function as a microservice.)
// For simplicity, we'll just pick a unicorn at random.
private Unicorn FindUnicorn(GeoLocation pickupLocation)
{
var r = new Random();
Console.WriteLine($"Finding unicorn for {pickupLocation.Latitude}, {pickupLocation.Longitude}");
return _fleets[r.Next(0, _fleets.Length)];
}
private APIGatewayProxyResponse Error(string errorMessage, string awsRequestId)
{
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.InternalServerError,
Body = JsonConvert.SerializeObject(new { Error = errorMessage, Reference = awsRequestId }),
Headers = new Dictionary<string, string>
{
{"Access-Control-Allow-Origin", "*"}
}
};
}
private APIGatewayProxyResponse Created<T>(T data)
{
return new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.Created,
Body = JsonConvert.SerializeObject(data),
Headers = new Dictionary<string, string>
{
{ "Content-Type", "application/json" },
{"Access-Control-Allow-Origin", "*"}
}
};
}
}
}
<file_sep>using System;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Microsoft.Extensions.DependencyInjection;
using WildRydesWebApi.Entities;
namespace WildRydesWebApi.Extensions
{
public static class DynamoDbServiceCollectionExtensions
{
public static IServiceCollection AddDynamoDb(this IServiceCollection services)
{
// ReSharper disable once InconsistentNaming
const string TABLENAME_ENVIRONMENT_VARIABLE_LOOKUP = "RidesTable";
// Check to see if a table name was passed in through environment variables and if so
// add the table mapping.
var tableName = Environment.GetEnvironmentVariable(TABLENAME_ENVIRONMENT_VARIABLE_LOOKUP);
if (!string.IsNullOrEmpty(tableName))
{
AWSConfigsDynamoDB.Context.TypeMappings[typeof(Ride)] = new Amazon.Util.TypeMapping(typeof(Ride), tableName);
}
services.AddSingleton<IAmazonDynamoDB, AmazonDynamoDBClient>();
services.AddSingleton(sp => new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 });
var config = new DynamoDBContextConfig { Conversion = DynamoDBEntryConversion.V2 };
// TODO: singleton ??
services.AddTransient<IDynamoDBContext>(sp => new DynamoDBContext(new AmazonDynamoDBClient(), config));
return services;
}
}
}
<file_sep># .Net Version of Wild Rydes Lambda Function
This project is a .Net version of the Lambda function used for [How to Build a Serverless Web Application with AWS Lambda, Amazon API Gateway, Amazon S3, Amazon DynamoDB, and Amazon Cognito | AWS](https://aws.amazon.com/getting-started/projects/build-serverless-web-app-lambda-apigateway-s3-dynamodb-cognito/)
## WildRydes
This project is a C# project created using template *AWS Lambda Project (.NET Core - C#)* (Empty Function)
## WildRydesWebApi
This project is an ASP.NET Core Web API project using [Amazon.Lambda.AspNetCoreServer](https://github.com/aws/aws-lambda-dotnet/tree/master/Libraries/src/Amazon.Lambda.AspNetCoreServer)<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Amazon.DynamoDBv2.DataModel;
using Amazon.Lambda.AspNetCoreServer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using WildRydesWebApi.Entities;
using WildRydesWebApi.Models;
namespace WildRydesWebApi.Controllers
{
//[Route("api/[controller]")]
[Route("[controller]")]
[ApiController]
public class RideController : ControllerBase
{
private readonly ILogger<RideController> _logger;
private readonly IDynamoDBContext _dbContext;
private readonly IConfiguration _configuration;
public RideController(ILogger<RideController> logger, IDynamoDBContext dbContext, IConfiguration configuration)
{
_logger = logger;
_dbContext = dbContext;
_configuration = configuration;
}
[HttpPost]
public async Task<ActionResult<RideResponse>> Post(RideRequest request)
{
_logger.LogDebug("{@Configuration}", _configuration.AsEnumerable().Select(kv => $"{kv.Key} - {kv.Value}").ToList());
_logger.LogDebug("{@LambdaContext}", Request.HttpContext.Items[AbstractAspNetCoreFunction.LAMBDA_CONTEXT]);
_logger.LogDebug("{@LambdaRequestObject}", Request.HttpContext.Items[AbstractAspNetCoreFunction.LAMBDA_REQUEST_OBJECT]);
_logger.LogDebug("{@IdentityDetails}", GetIdentityDetails().ToList());
var rideId = Guid.NewGuid().ToString();
var username = User.Identity.Name;
var unicorn = FindUnicorn(request.PickupLocation);
await _dbContext.SaveAsync(new Ride
{
RideId = rideId,
RequestTime = DateTime.UtcNow,
Unicorn = unicorn,
UnicornName = unicorn.Name,
User = username
});
var response = new RideResponse
{
Eta = "30 seconds",
RideId = rideId,
Rider = username,
Unicorn = unicorn,
UnicornName = unicorn.Name
};
return CreatedAtAction(nameof(Post), response);
}
private Unicorn FindUnicorn(GeoLocation pickupLocation)
{
var r = new Random();
_logger.LogInformation("Finding unicorn for {@PickupLocation}", pickupLocation);
return _fleets[r.Next(0, _fleets.Length)];
}
private readonly Unicorn[] _fleets = new[]
{
new Unicorn{
Name= "Bucephalus",
Color= "Golden",
Gender= "Male",
},
new Unicorn{
Name= "Shadowfax",
Color= "White",
Gender= "Male",
},
new Unicorn{
Name= "Rocinante",
Color= "Yellow",
Gender= "Female",
},
};
public IEnumerable<string> GetIdentityDetails()
{
var identityDetails = new List<string>();
var id = (ClaimsIdentity)User.Identity;
identityDetails.Add($"Name: {id.Name}");
identityDetails.Add($"AuthenticationType: {id.AuthenticationType}");
identityDetails.Add($"IsAuthenticated: {id.IsAuthenticated}");
identityDetails.Add($"NameClaimType: {id.NameClaimType}");
identityDetails.Add($"RoleClaimType: {id.RoleClaimType}");
return id.Claims.Select(c => $"{c.Type}: {c.Value}").Concat(identityDetails);
}
}
}
| d0b25a82b709685dcc3036a72c9a05aea849ce33 | [
"Markdown",
"C#"
] | 12 | C# | seongbaehwang/WildRydes | 0c01f066a2fbf99f57d9f1452f2e5c8ee1eb135a | 36832618d151745924737b0636b32798690a419f |
refs/heads/main | <file_sep>
//ADD YOUR FIREBASE LINKS HERE
var firebaseConfig = {
apiKey: "<KEY>",
authDomain: "chats-app-5c1c6.firebaseapp.com",
databaseURL: "https://chats-app-5c1c6-default-rtdb.firebaseio.com",
projectId: "chats-app-5c1c6",
storageBucket: "chats-app-5c1c6.appspot.com",
messagingSenderId: "1014072461514",
appId: "1:1014072461514:web:53200410b6d2e763cb4c33",
measurementId: "G-3QJBLWKQKF"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
function getData() {firebase.database().ref("/").on('value', function(snapshot) {document.getElementById("output").innerHTML = "";snapshot.forEach(function(childSnapshot) {childKey = childSnapshot.key;
Room_names = childKey;
//Start code
//End code
});});}
getData();
| d0cac77f841fc0e86063c199319ea19c5eeba3f2 | [
"JavaScript"
] | 1 | JavaScript | bobcataryan/blog33 | 6447cd0d137019ce28baec5526724fc94cb7a210 | 939a93f5b60b566efbe5b9d467a4e6a0c81e7980 |
refs/heads/master | <repo_name>marigold48/cgibin<file_sep>/mkCypher_Orden.sh
#!/bin/bash
# Clases:
# Magnoliopsida
# Filicopsida
# Liliopsida
# Ophioglossopsida
# Coniferopsida
init=$1;
qry="select distinct orden from flora where clase=\"$init\"";
lista=$(echo $qry | sqlite3 ~/RETO/apps/Agro/sqlite/repoAgro.sqlite)
printf "MATCH (c:Clase {nom:\"$init\"})\n"
printf "CREATE"
# Crea los nodos Orden
i=1
for item in $lista
do
printf "(o$i:Orden {nom:\"$item\"}),\n";
let i=i+1
done
# Crea las relaciones con la Clase
i=1
for item in $lista
do
if [ "$i" -gt 1 ]; then
printf ","
fi
printf "\n(o$i)-[:ES]->(c)";
let i=i+1
done
printf "\n\n"
<file_sep>/k1TreeFichs.sh
#!/bin/bash
olddir=$PWD;
declare -i dirdepth=1;
function listfiles {
cd "$1";
for file in *
do
## Print directories with brackets ([directory])
if [ -d "$file" ]
then
printf "$dirdepth::";
printf "[$file]\n";
else
printf "$dirdepth::";
printf "$file\n";
fi
##Work our way thru the system recursively
if [ -d "$file" ]
then
dirdepth=$dirdepth+1;
listfiles "$file";
cd ..;
fi
done
##Done with this directory - moving on to next file
let dirdepth=$dirdepth-1;
}
cd "$1"
echo "0::[$PWD]"
cd $olddir
listfiles "$1";
##Go back to where we started
cd $olddir;
unset i dirdepth;
<file_sep>/mkCypher_Familia.sh
#!/bin/bash
#Ordenes:
#Scrophulariales
#Sapindales
#Ranunculales
#Pteridiales
#Cyperales
#Rosales
#Alismatales
#Liliales
#Capparales
#Asterales
#Fabales
#Caryophyllales
#Arales
#Rubiales
#Aspidiales
#Solanales
#Ophioglossales
#Umbellales
#Euphorbiales
#Lamiales
#Campanulales
#Dipsacales
#Violales
#Poales
#Asparagales
#Primulales
#Orchidales
#Myrtales
#Apiales
#Ericales
#Geraniales
#Celastrales
#Fagales
#Rhamnales
#Gentianales
#Asparagales
#Theales
#Juncales
#Coniferales
#Plumbaginales
#Linales
#Papaverales
#Plantaginales
#Najadales
#Dennstaedtiales
#Polygonales
#Salicales
#Taxales
#Santalales
#Malvales
#Typhales
#Urticales
init=$1;
qry="select distinct familia from flora where orden=\"$init\"";
lista=$(echo $qry | sqlite3 ~/RETO/apps/Agro/sqlite/repoAgro.sqlite)
printf "MATCH (c:Orden {nom:\"$init\"})\n"
printf "CREATE"
# Crea los nodos Orden
i=1
for item in $lista
do
printf "(f$i:Familia {nom:\"$item\"}),\n";
let i=i+1
done
# Crea las relaciones con la Clase
i=1
for item in $lista
do
if [ "$i" -gt 1 ]; then
printf ","
fi
printf "\n(f$i)-[:ES]->(c)";
let i=i+1
done
printf "\n\n"
<file_sep>/k1GetQryMSQL.cgi
#!/bin/bash
#[NOM:t2GetQueryMSQL.cgi][INFO:Ejecuta la sentencia SQL en MySQL]
id=$1
bd=$2
stmt=$3
usr=$4
pwd=$5
temp="apps/Pauet/temp"
ahora=$(date +%Y%m%d-%H%M%S)
echo "[id0:$id][hora:$ahora][cgi:$0][fich:$bd]" >> $temp/trazas.txt
echo $stmt > "$temp/base64_$id.txt"
cgibin/base64.sh -a decode -f "$temp/base64_$id.txt" > "$temp/stmt_$id.sql"
cat "$temp/stmt_$id.sql" | mysql --user=$usr --password=$pwd $bd | sed 's/\t/\|/g'
echo "[error:$?]"
#rm -f temp/"aux1_$id.txt"
#rm -f temp/"stmt_$id.sql"
<file_sep>/k1CypherNeo4j.cgi
#!/bin/bash
#[NOM:k1GetQueryLite.cgi][INFO:Ejecuta la sentencia SQL en SQLite3]
id=$1
usr=$2
pwd=$3
stmt=$4
path=$5
#echo "-u $usr -p $pwd"
ahora=$(date +%Y%m%d-%H%M%S)
echo "[id0:$id][hora:$ahora][cgi:$0][fich:$usr]" >> $path/trazas
temp="$path/temp"
echo $stmt > "$temp/base64_$id.txt"
cgibin/base64.sh -a decode -f "$temp/base64_$id.txt" >> "$temp/stmt_$id.cypher"
cat "$temp/stmt_$id.cypher" \
| cypher-shell -u $usr -p $pwd --format verbose \
| grep -v "+-----"
mv "$temp/stmt_$id.cypher" "$temp/stmt.cypher"
#rm "$temp/base64_$id.txt"
echo "[error:$?]"
<file_sep>/gnuEscac.cgi
#!/bin/bash
#[NOM:gnuEscac.cgi][INFO:interfaz para GNU Chess]
pgn=$1
mov=$2
gnuchess
replay $pgn
$mov
pgnsave $pgn
quit<file_sep>/mkCypher_Genero.sh
#!/bin/bash
#Ordenes:
#Acanthaceae
#Aceraceae
#Adiantaceae
#Alismataceae
#Amaryllidaceae
#Apiaceae
#Apocynaceae
#Aquifoliaceae
#Araceae
#Araliaceae
#Asclepiadaceae
#Aspidiaceae
#Aspleniaceae
#Asteraceae
#Berberidaceae
#Boraginaceae
#Botrychiaceae
#Buxaceae
#Campanulaceae
#Caprifoliaceae
#Caryophyllaceae
#Celastraceae
#Cistaceae
#Compositae
#Convolvulaceae
#Crassulaceae
#Cruciferae
#Cupressaceae
#Cyperaceae
#Dioscoreaceae
#Dipsacaceae
#Ericaceae
#Euphorbiaceae
#Fabaceae
#Fagaceae
#Gentianaceae
#Geraniaceae
#Gesneriaceae
#Globulariaceae
#Guttiferae
#Hypolepidaceae
#Iridaceae
#Juncaceae
#Labiatae
#Lamiaceae
#Leguminosae
#Lentibulariaceae
#Liliaceae
#Linaceae
#Oleaceae
#Onagraceae
#Orchidaceae
#Orobanchaceae
#Oxalidaceae
#Papaveraceae
#Pinaceae
#Plantaginaceae
#Plumbaginaceae
#Poaceae
#Polygalaceae
#Polygonaceae
#Potamogetonaceae
#Primulaceae
#Ranunculaceae
#Rhamnaceae
#Rosaceae
#Rubiaceae
#Salicaceae
#Santalaceae
#Saxifragaceae
#Scrophulariaceae
#Smilacaceae
#Solanaceae
#Taxaceae
#Thymelaeaceae
#Tiliaceae
#Typhaceae
#Ulmaceae
#Umbelliferae
#Valerianaceae
#Violaceae
init=$1;
qry="select distinct genero from flora where familia=\"$init\"";
lista=$(echo $qry | sqlite3 ~/RETO/apps/Agro/sqlite/repoAgro.sqlite)
printf "MATCH (c:Familia {nom:\"$init\"})\n"
printf "CREATE"
# Crea los nodos Orden
i=1
for item in $lista
do
printf "(f$i:Genero {nom:\"$item\"}),\n";
let i=i+1
done
# Crea las relaciones con la Familia
i=1
for item in $lista
do
if [ "$i" -gt 1 ]; then
printf ","
fi
printf "\n(f$i)-[:ES]->(c)";
let i=i+1
done
printf "\n\n"
<file_sep>/qry_treeOfLife.sh
#!/bin/bash
qry="select a.node_id,a.node_name,b.node_id,b.node_name \
from tol_nodos a,tol_nodos b,tol_arcos c \
where a.node_id=$1 \
and a.node_id=c.source_node_id \
and b.node_id=c.target_node_id;"
lista=$(echo $qry | sqlite3 ~/RETO/apps/Agro/sqlite/repoAgro.sqlite)
for item in $lista
do
printf "($item)\n";
done
| 61e74a6a0541b2a674e873c78191a0be8bde8e09 | [
"Shell"
] | 8 | Shell | marigold48/cgibin | ec61046f6f4327c590628fc77d692d2f7b2da57a | 933d92df45a7b39d41c6efeaa0af32680a042a8b |
refs/heads/master | <repo_name>yangfan45/big-data-hadoop<file_sep>/README.md
# big-data-hadoop
大数据开发笔记
xsync:分发脚本
time-sync:系统时间同步脚本
xcall:全局执行命令
hadoop-server:hadoop服务群起脚本
<file_sep>/HiveSql、SparkSql合并小文件方法.sql
--****************************************************************
-- 功能描述: HiveSql、SparkSql合并小文件方法
-- 创建者 : yangfan48
-- 创建日期: 2020-03-16
-- 修改日志:
-- 2020-03-16 yangfan48 初始版本,增加3种合并小文件的方法
--****************************************************************
--****************************************************************
-- 一、HiveSql合并小文件方法(不太推荐,效率较低)
--****************************************************************
-- 一、开启纯map任务文件合并,mapreduce任务文件合并,设置触发文件合并的平均文件大小、合并后的文件大小。开启这种方法会在任务结束后,再次开启一个新的任务用于合并文件,因此效率会比较低
set hive.merge.mapfiles=true; -- 是否在纯Map的任务(没有reduce task)后开启小文件合并
set hive.merge.mapredfiles=true; -- 是否在mapreduce任务后开启小文件合并
set hive.merge.smallfiles.avgsize=256000000; -- 如果原先输出的文件平均大小小于这个值,则开启小文件合并。
set hive.merge.size.per.task=256000000; -- 合并后文件的大小。
--****************************************************************
--****************************************************************
-- 二、SparkSql合并小文件方法(推荐,效率较高)
--****************************************************************
-- 方法一:手动计算分区的数据量大小,根据需要设置每个分区的文件个数,开启动态分区后,支持多分区的文件合并
set spark.sql.output.auto.merge=true; -- 开启文件合并
set spark.sql.output.target.num=5; -- 目标文件个数
-- set hive.exec.dynamic.partition.mode=nonstrict; -- 开启动态分区
------------------------------------------------------------------
-- 方法二:关闭输出文件合并,设置Shuffle读文件的字节数,这里是256M,这种设置对没有Shuffle的sql也有一定效果
set spark.sql.adaptive.shuffle.targetPostShuffleInputSize=268435456;
set spark.sql.output.auto.merge=false;
-- set hive.exec.dynamic.partition.mode=nonstrict; -- 开启动态分区
--****************************************************************
-- 其他参数(尚未明确是否有效,可以自行测试)
set spark.sql.output.default.limit=1000000;
set spark.sql.output.target.records=1500000; -- 输出文件行数
set spark.sql.output.targetSize=262144000; -- 输出文件大小
set spark.sql.files.maxPartitionBytes=268435456; -- 分区的最大字节数
set spark.sql.files.openCostInBytes=8194304;
set spark.sql.adaptive.shuffle.targetPostShuffleInputSize=134217728; -- Shuffle每个task读取文件的最大字节数
set spark.sql.adaptive.shuffle.targetPostShuffleRowCount=5000000; -- Shuffle每个task读取文件的最大行数<file_sep>/hadoop-servers
#!/bin/bash
#hadoop服务群起脚本
COMMAND=$1
HADOOP_HOME=/opt/module/hadoop-2.7.2
function print_usage()
{
cat <<'EOF'
Usage: hadoop-servers [选项]
start 启动hadoop集群
stop 停止hadoop集群
EOF
}
case $COMMAND in
"start")
echo "================ 正在启动HDFS ==========="
ssh yangfan@hadoop102 '$HADOOP_HOME/sbin/start-dfs.sh'
echo "================ 正在启动YARN ==========="
ssh yangfan@hadoop103 '$HADOOP_HOME/sbin/start-yarn.sh'
;;
"stop")
echo "================ 正在停止YARN ==========="
ssh yangfan@hadoop103 '$HADOOP_HOME/sbin/stop-yarn.sh'
echo "================ 正在停止HDFS ==========="
ssh yangfan@hadoop102 '$HADOOP_HOME/sbin/stop-dfs.sh'
;;
*)
print_usage
;;
esac
<file_sep>/xcall
#!/bin/bash
#全局执行命令
for i in hadoop102 hadoop103 hadoop104
do
echo "================ $i ================"
ssh $i "source /etc/profile; $1"
done
| aa2101a2650ff1c3414ebdb453fe71670b6ca4d4 | [
"Markdown",
"SQL",
"Shell"
] | 4 | Markdown | yangfan45/big-data-hadoop | 93e7d7ef3dee20880cea218d153be89be2d76e56 | 805801969bc0135f389fd16770f1c64fd884162b |
refs/heads/master | <file_sep>#!/usr/bin/env bash
for i in $(seq 12); do
wget -c "http://nyctaxitrips.blob.core.windows.net/data/trip_data_${i}.csv.zip"
wget -c "http://nyctaxitrips.blob.core.windows.net/data/trip_fare_${i}.csv.zip"
done
for i in *.zip; do
unzip -o "${i}"
done
for i in trip_data_*.csv; do
mongoimport -d nyctaxi -c data --file "${i}" --headerline --type=csv --drop
done
for i in trip_fare_*.csv; do
mongoimport -d nyctaxi -c fare --file "${i}" --headerline --type=csv --drop
done
mongo nyctaxi --eval '
db.data.find({pickup_datetime: {$type: 2}}).forEach(function(doc) {
doc.pickup_datetime = new ISODate(doc.pickup_datetime);
doc.dropoff_datetime = new ISODate(doc.dropoff_datetime);
doc.pickup = { "type": "Point", "coordinates": [doc.pickup_longitude, doc.pickup_latitude] };
delete doc.pickup_longitude;
delete doc.pickup_latitude;
doc.dropoff = { "type": "Point", "coordinates": [doc.dropoff_longitude, doc.dropoff_latitude] };
delete doc.dropoff_longitude;
delete doc.dropoff_latitude;
db.data.update({_id: doc._id}, doc);
});
'
mongo nyctaxi --eval '
db.fare.find({pickup_datetime: {$type: 2}}).forEach(function(doc) {
doc.pickup_datetime = new ISODate(doc.pickup_datetime);
db.fare.update({_id: doc._id}, doc);
});
'
<file_sep>nyctaxitrips
============
| 0e60b6c08d1002643b4d8e82621659ab017403d9 | [
"Markdown",
"Shell"
] | 2 | Shell | vinipsmaker/nyctaxitrips | dca3e3f36fcb1fae41df6e2c6bba7bf0902fe931 | 81a0a8e6a45dcec0d4dd7cd2f0c889def7a24bf3 |
refs/heads/master | <repo_name>eligocs/devionic<file_sep>/src/app/pages/menu/loan/loan.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { LoanPageRoutingModule } from './loan-routing.module';
import { LoanPage } from './loan.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
LoanPageRoutingModule
],
declarations: [LoanPage]
})
export class LoanPageModule {
// timeCalc(d1, d2){
// let date1 = new Date(d1).getTime();
// let date2 = new Date(d2).getTime();
// let msec = date2 - date1;
// let mins = Math.floor(msec / 60000);
// let hrs = Math.floor(mins / 60);
// let days = Math.floor(hrs / 24);
// mins = mins % 60;
// let tValue1= `In hours: ${hrs} hours, ${mins} minutes`
// let tValue2= `In days: ${days} days, ${hrs} hours, ${mins} minutes`
// return tValue1
// // return tValue2
// }
}
<file_sep>/src/app/pages/home/pl/pl.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { PlPageRoutingModule } from './pl-routing.module';
import { PlPage } from './pl.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
PlPageRoutingModule
],
declarations: [PlPage]
})
export class PlPageModule {}
<file_sep>/src/providers/apihelper/apihelper.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ToastController, LoadingController } from '@ionic/angular';
import { CollectionListModel } from '../Models/collectionList';
import { Storage } from '@ionic/storage';
import { UserResponse } from '../../providers/Models/UserDetails';
import { RdResponse } from '../../providers/Models/MemberRD';
import { DdResponse } from '../../providers/Models/MemberDD';
import { FdResponse } from '../../providers/Models/MemberFD';
import { OlResponse } from '../../providers/Models/MemberOL';
import { SavingResponse } from '../../providers/Models/saving_details';
import { MemberSavingResponse } from '../../providers/Models/MemberSaving';
import { TransactionResponse } from '../../providers/Models/TransactionDetails';
import { ProfileResponse } from '../Models/ProfileDetails';
/*
Generated class for the ApihelperProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class ApihelperProvider {
private RootURL: string = "http://localhost:3000/api/";
loading: any;
HeaderConfig : any = [];
Saving: any = [];
DD: any = [];
RD: any = [];
FD: any = [];
OL: any = [];
DL: any = [];
GL: any = [];
FL: any = [];
PL: any = [];
constructor(public http: HttpClient, private toastCtrl: ToastController, public loadingCtrl : LoadingController, private storage: Storage) {
}
// toast message
// user login
UserLogin(username:string, password : string){
let postData = new FormData();
postData.append('username' , username);
postData.append('password' , <PASSWORD>);
// call Api
// console.log(this.RootURL + 'sign-in');
return this.http.post(this.RootURL + 'sign-in',postData);
}
// set header values
SetHeader(token:string,userid:string){
let header = {
'Authorization': 'Bearer ' + token,
'user-id': userid,
}
this.HeaderConfig = { headers: new HttpHeaders(header)};
console.log("headerasd ", header);
}
UserPanel(){
console.log('header',this.HeaderConfig);
let postData = new FormData();
let data =this.http.post(this.RootURL + 'member/dashboard',postData,this.HeaderConfig);
return data;
}
User_details(data){
let response : UserResponse = [];
console.log('data', data);
this.FD = data.fixed_deposits;
this.OL = data.other_loan_accounts;
this.Saving= data.saving_accounts;
let rdDD = data.recurring_deposits;
let current_member = data.current_member;
/* All Loan Accounts */
this.DL = data.deposit_loan_accounts;
this.GL = data.gold_loan_accounts;
this.FL = data.fixed_loan_accounts;
this.PL = data.property_loan_accounts;
rdDD.forEach(element => {
if(element.is_dds == true){
this.DD.push(element);
}
if(element.is_dds == false){
this.RD.push(element);
}
})
// console.log('response', response)
response = {
Saving: this.Saving,
RD: this.RD,
DD: this.DD,
FD: this.FD,
OL: this.OL,
current_member: current_member
}
return response;
}
//Account Details
MemberRD(type:string, slug:string){
let postData = new FormData();
postData.append('account_type' , type);
postData.append('slug' , slug);
console.log(this.HeaderConfig);
return this.http.post(this.RootURL + 'member/account',postData,this.HeaderConfig);
}
MemberRD_Details(data){
let response : RdResponse = [];
if(data.status==true){
response = {
details : data.details,
transactions : data.transactions,
}
}else{
response = [];
}
return response;
}
MemberDD(type:string, slug:string){
let postData = new FormData();
postData.append('account_type' , type);
postData.append('slug' , slug);
return this.http.post(this.RootURL + 'member/account',postData,this.HeaderConfig);
}
MemberDD_Details(data){
let response : DdResponse = [];
if(data.status==true){
response = {
details : data.details,
transactions : data.transactions,
}
}else{
response = [];
}
return response;
}
MemberFD(type:string, slug:string){
let postData = new FormData();
postData.append('account_type' , type);
postData.append('slug' , slug);
return this.http.post(this.RootURL + 'member/account',postData,this.HeaderConfig);
}
MemberFD_Details(data){
let response : FdResponse = [];
if(data.status==true){
response = {
details : data.details,
transactions : data.transactions,
}
}else{
response = [];
}
return response;
}
MemberOL(type:string, slug:string){
let postData = new FormData();
postData.append('account_type' , type);
postData.append('slug' , slug);
return this.http.post(this.RootURL + 'member/account',postData,this.HeaderConfig);
}
MemberOL_Details(data){
let response : OlResponse = [];
if(data.status==true){
response = {
details : data.details,
transactions : data.transactions,
}
}else{
response = [];
}
return response;
}
MemberGL(type:string, slug:string){
let postData = new FormData();
postData.append('account_type' , type);
postData.append('slug' , slug);
return this.http.post(this.RootURL + 'member/account',postData,this.HeaderConfig);
}
MemberGL_Details(data){
let response : any = [];
if(data.status==true){
response = {
details : data.details,
transactions : data.transactions,
}
}else{
response = [];
}
return response;
}
MemberDL(type:string, slug:string){
let postData = new FormData();
postData.append('account_type' , type);
postData.append('slug' , slug);
return this.http.post(this.RootURL + 'member/account',postData,this.HeaderConfig);
}
MemberDL_Details(data){
let response : any = [];
if(data.status==true){
response = {
details : data.details,
transactions : data.transactions,
}
}else{
response = [];
}
return response;
}
MemberRL(type:string, slug:string){
let postData = new FormData();
postData.append('account_type' , type);
postData.append('slug' , slug);
return this.http.post(this.RootURL + 'member/account',postData,this.HeaderConfig);
}
MemberRL_Details(data){
let response : any = [];
if(data.status==true){
response = {
details : data.details,
transactions : data.transactions,
}
}else{
response = [];
}
return response;
}
MemberPL(type:string, slug:string){
let postData = new FormData();
postData.append('account_type' , type);
postData.append('slug' , slug);
return this.http.post(this.RootURL + 'member/account',postData,this.HeaderConfig);
}
MemberPL_Details(data){
let response : any = [];
if(data.status==true){
response = {
details : data.details,
transactions : data.transactions,
}
}else{
response = [];
}
return response;
}
Loan(type:string){
let postData = new FormData();
postData.append('account_type' , type);
return this.http.post(this.RootURL + 'member/account/passbook',postData,this.HeaderConfig);
}
Loan_Details(data){
let response : any = [];
if(data.status==true){
response = {
details : data.details,
}
}else{
response = [];
}
return response;
}
//Saving Details
MemberSaving(type:string, slug:string){
let postData = new FormData();
postData.append('account_type' , type);
postData.append('slug' , slug);
return this.http.post(this.RootURL + 'member/account',postData,this.HeaderConfig);
}
MemberSaving_Details(data){
let response : MemberSavingResponse = [];
if(data.status==true){
response = {
details : data.details,
transactions : data.transactions,
}
}else{
response = [];
}
return response;
}
//Pasbook_Details
Pasbook_Details(type:string, slug:string){
let postData = new FormData();
postData.append('account_type' , type);
postData.append('slug' , slug);
return this.http.post(this.RootURL + 'member/account',postData,this.HeaderConfig);
}
Pasbook_Details_Details(data){
let response : MemberSavingResponse = [];
if(data.status==true){
response = {
details : data.details,
transactions : data.transactions,
}
}else{
response = [];
}
return response;
}
//End
// Daily Transaction data from API
DailyTransaction(){
// let postData = new FormData();
// return this.http.post(this.RootURL + 'member/rd_data',postData,this.HeaderConfig);
const Transaction = [
{
"transaction_acc": "Saving Account",
"transaction_type": "Credit",
"transaction_amt": "9000/-",
"payment_method": "Cash"
},
{
"transaction_acc": "RD Account",
"transaction_type": "Credit",
"transaction_amt": "6000/-",
"payment_method": "Net Banking"
},
{
"transaction_acc": "DD Account",
"transaction_type": "Debit",
"transaction_amt": "4000/-",
"payment_method": "Cash"
},
{
"transaction_acc": "OL Account",
"transaction_type": "Debit",
"transaction_amt": "8000/-",
"payment_method": "UPI"
},
]
return Transaction;
}
DailyTransaction_Details(DailyTransaction){
var response : TransactionResponse = [];
response = {
transaction_acc : DailyTransaction.transaction_acc,
transaction_amt : DailyTransaction.transaction_amt,
transaction_type : DailyTransaction.transaction_type,
payment_method : DailyTransaction.payment_method,
}
return response;
}
// Saving Account Details
SavingTransaction_Details(SavingTransaction){
var response : SavingResponse = [];
console.log(response);
SavingTransaction.forEach(element => {
let transaction = {
transaction_amt : element.transaction_amt,
transaction_date : element.transaction_date,
transaction_type : element.transaction_type,
payment_method : element.payment_method,
account : element.account,
updated : element.updated,
}
response.push(transaction);
});
return response;
}
// Profile details
ProfileImage(){
// alert(file);
// let postData = new FormData();
// postData.append('file' , file);
// // call Api
// return this.http.post(this.RootURL + 'member/profile',postData,this.HeaderConfig);
const ProfileData =
{
"name": "<NAME>",
"phone": "9876756456",
"email": "<EMAIL>",
"address": "House no-24, main bazar Bada gaon",
"distt": "Shimla",
"pin_code": "171011",
}
return ProfileData;
}
// Profile Details
ProfileData(ProfileData){
console.log(ProfileData);
var response : ProfileResponse = [];
response = {
name : ProfileData.name,
phone : ProfileData.phone,
email : ProfileData.email,
address : ProfileData.address,
distt : ProfileData.distt,
pin_code : ProfileData.pin_code
}
return response;
}
// Forgot Password
ForgotPass(phone,username){
let postData = new FormData();
postData.append('username' , username);
postData.append('phone' , phone);
return this.http.post(this.RootURL + 'password/forgot',postData);
}
// End Forgot Password
//change Password
ChangePwd(current :string,newpwd : string){
let postData = new FormData();
postData.append('current_password' , current);
postData.append('password' , <PASSWORD>);
postData.append('password_confirmation' , <PASSWORD>);
// call Api
return this.http.post(this.RootURL + 'password/reset',postData,this.HeaderConfig);
}
// Account details
AccountsDetails(accountid:string,accounttype:string){
let postData = new FormData();
postData.append('account_id' , accountid);
postData.append('account_type' , accounttype);
console.log(accountid);console.log(accounttype);
// call Api
return this.http.post(this.RootURL + 'get-account-data',postData,this.HeaderConfig);
}
// Save Payment informations
SavePaymentINformation(accountid:string,accounttype:string,
transaction_type:string,data:any){
let postData = new FormData();
postData.append('account_id' , accountid);
postData.append('account_type' , accounttype);
postData.append('transaction_type' , transaction_type);
// postData.append('daily_transaction_transaction_date' , data.transectiondate);
postData.append('amount' , data.amount);
postData.append('message' , data.remarks);
// postData.append('daily_transaction[payment_mode]' , data.payMode);
// call Api
return this.http.post(this.RootURL + 'single-collection-transaction',postData,this.HeaderConfig);
}
// collection list by date
CollectionListByDate(fdate:string){
let postData = new FormData();
postData.append('transaction_date_eq' , fdate);
// call Api
return this.http.post(this.RootURL + 'daily-collection-transaction',postData,this.HeaderConfig);
}
// Mappe Collection into model
CollectionResponseMappe(data){
var response : CollectionListModel = [];
if(data != undefined){
data.data.forEach(element => {
let l = {
transaction_date : element.transaction_date,
payment_mode : element.payment_mode,
amount : element.amount,
transaction_type : element.transaction_type,
message : element.message,
transaction_status : element.transaction_status,
account_type : element.account_type,
tranx_id : element.tranx_id,
account_number : element.account_number,
name:element.name,
fname:element.fname,
mobile:element.mobile,
total_balance: element.total_balance,
collectedBy:element.collectedBy
}
response.push(l);
});
}
return response;
}
async presentToastWithOptions(Message) {
const toast = await this.toastCtrl.create({
// header: 'Toast header',
message: Message,
position: 'top',
buttons: [{
text: 'Done',
icon: 'close',
role: 'cancel',
handler: () => {
// console.log('Cancel clicked');
}
}
]
});
toast.present();
}
async presentLoading() {
const loading = await this.loadingCtrl.create({
// cssClass: 'my-custom-class',
message: 'Please wait...',
duration: 1300
});
await loading.present();
}
}
<file_sep>/src/providers/Models/collectionList.ts
export interface CollectionListModel{
[x : string] : any;
[index : number] : {
transaction_date : string;
payment_mode : string;
amount : string;
transaction_type : string;
message : string;
transaction_status : string;
account_type : string;
account_number:string;
name:string;
fname:string;
mobile:string;
total_balance:string;
collectedBy:string;
tranx_id : string;
}
}
<file_sep>/src/app/app.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicModule, NavParams } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { CreatePdf } from 'src/providers/CreatePdf';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { IonicStorageModule } from '@ionic/storage';
import { Network } from '@ionic-native/network/ngx';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';
import { File } from '@ionic-native/file/ngx';
import { WebView } from '@ionic-native/ionic-webview/ngx';
import { FilePath } from '@ionic-native/file-path/ngx';
import { Crop } from '@ionic-native/crop/ngx';
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
import {HTTP} from "@ionic-native/http/ngx";
import { Keyboard } from '@ionic-native/keyboard/ngx';
import { SMS } from '@ionic-native/sms/ngx';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, IonicModule.forRoot(), IonicStorageModule.forRoot(), AppRoutingModule,HttpClientModule, FormsModule
],
bootstrap: [AppComponent],
entryComponents: [
AppComponent,
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: ErrorHandler},
ApihelperProvider,
Network,
NativeStorage,
File,
FileOpener,
FingerprintAIO,
WebView,
FilePath,
Crop,
AndroidPermissions,
HTTP,
NavParams,
CreatePdf,
Keyboard,
Storage,
SMS
]
})
export class AppModule {}<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Storage } from '@ionic/storage';
import { NavController } from '@ionic/angular';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { CreatePdf } from 'src/providers/CreatePdf';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
public selectedIndex = 0;
public appPages = [
{
title: 'My Profile',
url: '/dashboard/profile',
iconsrc: './assets/icon/profile.svg',
icon: 'mail'
},
{
title: 'Change Password',
url: '/dashboard/cpassword',
iconsrc: './assets/icon/password.svg',
icon: 'paper-plane'
},
{
title: 'Update Bank Details',
url: '/dashboard/bank',
iconsrc: './assets/icon/bank-details.svg',
icon: 'heart'
},
{
title: 'Passbook',
url: '/dashboard/passbook',
iconsrc: './assets/icon/Passbook.svg',
icon: 'archive'
},
{
title: 'My Loan',
url: '/dashboard/loan',
iconsrc: './assets/icon/loan.svg',
icon: 'trash'
},
{
title: 'Terms & Conditions',
url: '/dashboard/tandc',
iconsrc: './assets/icon/TermsandCondition.svg',
icon: 'warning'
},
{
title: 'Security Tips',
url: '/dashboard/security',
iconsrc: './assets/icon/security.svg',
icon: 'warning'
},
{
title: 'Help & Support',
url: '/dashboard/support',
iconsrc: './assets/icon/support.svg',
icon: 'warning'
},
{
title: 'Logout',
url: '',
class:'logout',
iconsrc: './assets/icon/password.svg',
icon: 'warning'
},
];
public href: string = "";
public username : string = "";
public password : string = "";
public isUsernameValid: boolean;
public isPasswordValid: boolean;
private LoginReponse : any;
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private storage: Storage,
public navCtrl: NavController,
private provider : ApihelperProvider,
private memberdetail: CreatePdf
) {
this.isUsernameValid= true;
this.isPasswordValid = true;
console.log('chla')
this.initializeApp();
}
initializeApp() {
// this.platform.ready().then(() => {
this.platform.backButton.subscribe(() => {
this.navCtrl.navigateRoot('/dashboard/home');
});
if (navigator.onLine) {
if(window.location.pathname == '/forgot'){
this.navCtrl.navigateRoot('/forgot');
}else{
// if(this.platform.is('cordova')){
console.log('USer Details is');
this.storage.get('offline-user').then((val) => {
if(val){
this.provider.presentLoading();
this.provider.UserLogin( val.username, val.password).subscribe(data=>{
this.LoginReponse = data;
console.log('dfdfd',this.LoginReponse);
// set header values
this.provider.SetHeader(this.LoginReponse.token,this.LoginReponse.user_id);
this.statusBar.styleDefault();
this.splashScreen.hide();
}
,(err)=> {
this.provider.presentToastWithOptions('There are some technical issue please try again!')});
// this.navCtrl.navigateRoot('/login');
}else
{
this.navCtrl.navigateRoot('/login');
}
});
// }
}
}else{
this.provider.presentToastWithOptions('Its look like you are offline!')
this.navCtrl.navigateRoot('/login');
}
// });
}
public ProfileImg: any;
ngOnInit() {
this.ProfileImg = this.memberdetail.getMember();
console.log("sdfsdf", this.ProfileImg);
const path = window.location.pathname.split('dashboard/')[1];
if (path !== undefined) {
this.selectedIndex = this.appPages.findIndex(page => page.title.toLowerCase() === path.toLowerCase());
}
}
logout(){
this.storage.remove('offline-user');
this.storage.remove('current_member');
this.navCtrl.navigateRoot('/');
}
}
<file_sep>/src/app/pages/home/dd/ddview/ddview.page.ts
import { Component, OnInit } from '@angular/core';
import { NavParams, NavController, Platform } from '@ionic/angular';
import { Router, ActivatedRoute } from '@angular/router';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { DdResponse } from 'src/providers/Models/MemberDD';
import * as moment from 'moment';
import { File } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { CreatePdf } from 'src/providers/CreatePdf';
@Component({
selector: 'app-ddview',
templateUrl: './ddview.page.html',
styleUrls: ['./ddview.page.scss'],
})
export class DdviewPage implements OnInit {
tableHeader= ['tranx_id', 'amount','transaction_type', 'transaction_date', 'payment_mode', 'transaction_type']
DdResponse: DdResponse;
constructor(
public navParams: NavParams,
public navCtrl: NavController,
private route: ActivatedRoute,
private provider : ApihelperProvider,
private pdfmake : CreatePdf
) { }
DdDetails: any;
DdTransactions: any = [];
dddata: any;
momentjs: any = moment;
MemberDdTransactions: any = [];
end_date: '';
start_date: '';
pdfObj = null;
ngOnInit() {
}
ionViewDidEnter() {
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.dddata = JSON.parse(params.special);
this.provider.MemberDD(this.dddata.type,this.dddata.slug).subscribe(data=>{
this.DdResponse = this.provider.MemberDD_Details(data);
if(this.DdResponse.length != 0){
this.DdDetails = this.DdResponse.details;
this.DdTransactions = this.DdResponse.transactions;
console.log(this.DdDetails);
console.log(this.DdTransactions);
if(this.DdTransactions){
this.DdTransactions = this.DdResponse.transactions;
}else{
this.DdTransactions = '';
}
}
});
}
});
}
StartDate(){
if(!this.start_date){
console.log(this.start_date);
}
return this.start_date;
}
EndDate(){
if(!this.end_date){
console.log(this.end_date);
}
return this.end_date;
}
Apply_Date(){
if((this.start_date == undefined || this.start_date == '') || (this.end_date == undefined || this.end_date == '') ){
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.dddata = JSON.parse(params.special);
this.provider.MemberDD(this.dddata.type,this.dddata.slug).subscribe(data=>{
this.MemberDdTransactions = this.provider.MemberDD_Details(data);
if(this.MemberDdTransactions.length != 0){
this.DdTransactions = this.MemberDdTransactions.transactions;
}
else{
console.log(this.MemberDdTransactions);
this.DdTransactions = [];
}
});
}
});
this.provider.presentToastWithOptions('Please select date first!');
}else{
let start_date = this.momentjs(this.start_date).format("YYYY-MM-DD")
let end_date = this.momentjs(this.end_date).format("YYYY-MM-DD");
this.provider.presentLoading();
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.dddata = JSON.parse(params.special);
this.provider.MemberDD(this.dddata.type,this.dddata.slug).subscribe(data=>{
this.DdResponse = this.provider.MemberDD_Details(data);
if(this.DdResponse.length != 0){
let DdTransactions1 = this.DdResponse.transactions;
this.DdTransactions = DdTransactions1.filter((item: any) => {
let date = new Date(item.transaction_date);
date = this.momentjs(date).format("YYYY-MM-DD");
return date >= start_date && date <= end_date;
});
if(this.DdTransactions==''){
this.DdTransactions == [];
}
}else{
this.DdTransactions == [];
}
});
}
});
}
}
createPdf() {
this.pdfmake.createPdf(this.DdTransactions);
}
}
<file_sep>/src/providers/Models/UserDetails.ts
export interface UserResponse{
[x : string] : any;
[index : number] : {
modules : any;
username : string;
todays_interest : string;
total_balance : string;
account_no : string;
interest_rate : string;
//DD Details
dd_interest_rate : string;
dd_total_amt : string;
dd_maturity_amt : string;
dd_maturity_date : string;
dd_account_no : string;
//RD Details
rd_interest_rate : string;
rd_total_amt : string;
rd_maturity_amt : string;
rd_maturity_date : string;
rd_account_no : string;
//FD Details
fd_interest_rate : string;
fd_total_amt : string;
fd_maturity_amt : string;
fd_maturity_date : string;
fd_account_no : string;
//OL Details
ol_interest_rate : string;
ol_total_amt : string;
ol_maturity_amt : string;
ol_maturity_date : string;
ol_account_no : string;
}
}<file_sep>/src/app/pages/home/saving/saving.page.ts
import { Component, OnInit } from '@angular/core';
import { NavParams, NavController } from '@ionic/angular';
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { SavingResponse } from '../../../../providers/Models/saving_details';
import { MemberSavingResponse } from '../../../../providers/Models/MemberSaving';
import * as moment from 'moment';
import { CreatePdf } from 'src/providers/CreatePdf';
import { ActivatedRoute } from '@angular/router';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
@Component({
selector: 'app-saving',
templateUrl: './saving.page.html',
styleUrls: ['./saving.page.scss'],
})
export class SavingPage implements OnInit {
letterObj = {
trans_type:[],
trans_amt: [],
text: '',
}
data = [];
momentjs: any = moment;
end_date: '';
start_date: '';
pdfObj = null;
SavingResponse: any = [];
MemberSavingResponse: MemberSavingResponse;
fileTransfer: any;
savingdata: any;
SavingDetails: any;
SavingTransactions: any = [];
MemberSavingTransactions: any = [];
constructor(public navParams: NavParams,
public navCtrl: NavController,
private route: ActivatedRoute,
private provider: ApihelperProvider,
private pdfmake: CreatePdf
) {
}
ionViewDidEnter() {
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.savingdata = JSON.parse(params.special);
this.provider.MemberSaving(this.savingdata.type,this.savingdata.slug).subscribe(data=>{
this.MemberSavingResponse = this.provider.MemberSaving_Details(data);
this.SavingDetails = this.MemberSavingResponse.details;
console.log(this.SavingDetails);
this.SavingResponse = this.MemberSavingResponse.transactions;
console.log(this.SavingTransactions);
});
}
});
}
ngOnInit(){
this.provider.presentLoading();
}
StartDate(){
if(!this.start_date){
console.log(this.start_date);
}
return this.start_date;
}
EndDate(){
if(!this.end_date){
console.log(this.end_date);
}
return this.end_date;
}
Apply_Date(){
this.SavingTransactions= [];
if((this.start_date == undefined || this.start_date == '') || (this.end_date == undefined || this.end_date == '') ){
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.savingdata = JSON.parse(params.special);
this.provider.MemberSaving(this.savingdata.type,this.savingdata.slug).subscribe(data=>{
this.MemberSavingTransactions = this.provider.MemberSaving_Details(data);
this.SavingDetails = this.MemberSavingTransactions.details;
this.SavingTransactions = this.MemberSavingTransactions.transactions;
});
}
});
this.provider.presentToastWithOptions('Please select date first!');
}else{
let start_date = this.momentjs(this.start_date).format("YYYY-MM-DD")
let end_date = this.momentjs(this.end_date).format("YYYY-MM-DD");
this.provider.presentLoading();
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.savingdata = JSON.parse(params.special);
this.provider.MemberSaving(this.savingdata.type,this.savingdata.slug).subscribe(data=>{
this.SavingResponse = this.provider.MemberSaving_Details(data);
let SavingTransactions1 = this.SavingResponse.transactions;
this.SavingTransactions = SavingTransactions1.filter((item: any) => {
let date = new Date(item.transaction_date);
date = this.momentjs(date).format("YYYY-MM-DD");
return date >= start_date && date <= end_date;
});
if(this.SavingTransactions==''){
this.SavingTransactions == '';
}
});
}
});
}
}
createPdf() {
this.pdfmake.createPdf(this.SavingResponse);
}
//END PDF CODE
}
<file_sep>/src/app/pages/home/dl/dl.page.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { NavParams, NavController, IonInfiniteScroll } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import * as moment from 'moment';
import { CreatePdf } from 'src/providers/CreatePdf';
@Component({
selector: 'app-dl',
templateUrl: './dl.page.html',
styleUrls: ['./dl.page.scss'],
})
export class DlPage implements OnInit {
DlResponse: any = [];
@ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;
constructor(
public navParams: NavParams,
public navCtrl: NavController,
private route: ActivatedRoute,
private provider : ApihelperProvider,
private pdfmake: CreatePdf
) {
}
data: any;
DlDetails: any;
DlTransactions: any = [];
fddata: any;
momentjs: any = moment;
MemberDlTransactions: any = [];
end_date: '';
start_date: '';
pdfObj = null;
show = 20;
ngOnInit(){
this.provider.presentLoading();
}
ionViewDidEnter() {
this.loadData(event);
}
loadData(event) {
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.data = JSON.parse(params.special);
this.provider.MemberDL(this.data.type,this.data.slug).subscribe(data=>{
this.DlResponse = this.provider.MemberDL_Details(data);
if(this.DlResponse){
this.DlDetails = this.DlResponse.details;
this.DlTransactions = this.DlResponse.transactions;
console.log("ol",this.DlDetails);
console.log(this.DlTransactions);
if(this.DlTransactions){
this.DlTransactions = this.DlResponse.transactions;
}else{
this.DlTransactions = [];
}
}
});
}
});
}
showmore(length){
this.show = length;
this.provider.presentLoading();
}
StartDate(){
if(!this.start_date){
console.log(this.start_date);
}
return this.start_date;
}
EndDate(){
if(!this.end_date){
console.log(this.end_date);
}
return this.end_date;
}
Apply_Date(){
if((this.start_date == undefined || this.start_date == '') || (this.end_date == undefined || this.end_date == '') ){
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.fddata = JSON.parse(params.special);
this.provider.MemberSaving(this.fddata.type,this.fddata.slug).subscribe(data=>{
this.MemberDlTransactions = this.provider.MemberSaving_Details(data);
if(this.MemberDlTransactions.length != 0){
this.DlTransactions = this.MemberDlTransactions.transactions;
}else{
this.DlTransactions = [];
}
});
}
});
this.provider.presentToastWithOptions('Please select date first!');
}else{
let start_date = this.momentjs(this.start_date).format("YYYY-MM-DD")
let end_date = this.momentjs(this.end_date).format("YYYY-MM-DD");
this.provider.presentLoading();
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.fddata = JSON.parse(params.special);
this.provider.MemberDL(this.fddata.type,this.fddata.slug).subscribe(data=>{
this.DlResponse = this.provider.MemberDL_Details(data);
if(this.DlResponse.length != 0){
let DlTransactions1 = this.DlResponse.transactions;
this.DlTransactions = DlTransactions1.filter((item: any) => {
let date = new Date(item.transaction_date);
date = this.momentjs(date).format("YYYY-MM-DD");
return date >= start_date && date <= end_date;
});
if(this.DlTransactions==''){
this.DlTransactions == '';
}
}else{
this.DlTransactions == [];
}
});
}
});
}
}
createPdf() {
this.pdfmake.createPdf(this.DlTransactions);
}
}
<file_sep>/src/providers/Models/ProfileDetails.ts
export interface ProfileResponse{
[x : string] : any;
[index : number] : {
name : string;
phone : string;
email : string;
address : string;
distt : string;
pin_code : string;
}
}<file_sep>/src/app/pages/menu/cpassword/cpassword.page.ts
import { Component, OnInit } from '@angular/core';
import { NavController, NavParams } from '@ionic/angular';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { Storage } from '@ionic/storage';
import { CreatePdf } from 'src/providers/CreatePdf';
@Component({
selector: 'app-cpassword',
templateUrl: './cpassword.page.html',
styleUrls: ['./cpassword.page.scss'],
})
export class CpasswordPage {
currentPwd : string = '';
newPwd : string = '';
confirmPwd : string = '';
ProfileResponse: any;
constructor( private storage: Storage,public navCtrl: NavController,private memberdetail: CreatePdf, public navParams: NavParams, private apihelper : ApihelperProvider) {
}
ionViewDidEnter() {
this.ProfileResponse = this.memberdetail.getMember();
console.log('memm',this.ProfileResponse);
}
changePassword(){
if(this.currentPwd ===''){
this.apihelper.presentToastWithOptions("Missing Current Password");
}else if(this.newPwd ===''){
this.apihelper.presentToastWithOptions("Missing New Password");
}else if(this.confirmPwd ===''){
this.apihelper.presentToastWithOptions("Missing Confirm Password");
}
else if(this.confirmPwd != this.newPwd){
this.apihelper.presentToastWithOptions("Password not match!");
}else{
this.apihelper.presentLoading();
this.apihelper.ChangePwd(this.currentPwd,this.newPwd).subscribe((data)=>{
let result : any = data;
console.log(result);
console.log(result.message);
if(result.status == true){
alert("Password Reset Successfully! You can now login");
this.storage.remove('offline-user');
this.storage.remove('current_member');
this.navCtrl.navigateRoot('/');
}else{
this.apihelper.presentToastWithOptions(result.message);
}
this.currentPwd = '';
this.newPwd = '';
this.confirmPwd = '';
},(erro)=>{console.log(erro);})
}
}
}
<file_sep>/src/app/pages/menu/profile/profile.page.ts
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { Platform, LoadingController } from '@ionic/angular';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { CreatePdf } from 'src/providers/CreatePdf';
@Component({
selector: 'app-profile',
templateUrl: './profile.page.html',
styleUrls: ['./profile.page.scss'],
})
export class ProfilePage {
public ProfileResponse: any;
constructor( private providor: ApihelperProvider ,private memberdetail: CreatePdf, private platform: Platform) { }
ionViewDidEnter() {
// User Details From API
this.ProfileResponse = this.memberdetail.getMember();
console.log('memm',this.ProfileResponse);
}
}<file_sep>/src/app/pages/home/home.page.ts
import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';
import { NavController } from '@ionic/angular';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import * as $ from 'jquery';
import { UserResponse } from '../../../providers/Models/UserDetails';
import { TransactionResponse } from '../../../providers/Models/TransactionDetails';
import * as moment from 'moment';
import { Router, NavigationExtras } from '@angular/router';
@Component({
selector: 'app-tabs',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
moment: any = moment;
slideOptsOne : any ;
public UserResponse: UserResponse;
public RdResponse: any = [];
public DdResponse: any = [];
public FdResponse: any = [];
public OlResponse: any = [];
public Saving: any = [];
public RdPercent: any = [];
public FdPercent: any = [];
public DdPercent: any = [];
public OlPercent: any = [];
public today_interest: number;
public TransactionResponse: TransactionResponse;
constructor(
private storage: Storage,
public navCtrl: NavController,
public provider : ApihelperProvider,
private router: Router
){
}
ionViewDidEnter() {
// User Details From API
this.UserApi();
}
UserApi(){
this.provider.UserPanel().subscribe(data=>{
this.UserResponse = this.provider.User_details(data);
if(this.UserResponse){
this.RdResponse = this.UserResponse.RD;
this.DdResponse = this.UserResponse.DD;
this.FdResponse = this.UserResponse.FD;
this.OlResponse = this.UserResponse.OL;
this.Saving = this.UserResponse.Saving;
this.RdResponse.forEach((data) => {
this.RdPercent.push(this.getPercent(data.maturity_amount, data.total_amount))
});
this.DdResponse.forEach((data) => {
this.DdPercent.push(this.getPercent(data.maturity_amount, data.total_amount))
});
this.FdResponse.forEach((data) => {
this.FdPercent.push(this.getPercent(data.maturity_amount, data.total_amount))
});
this.OlResponse.forEach((data) => {
this.OlPercent.push(this.getPercent(data.loan_amount, data.current_debt))
});
let interest = this.Saving[0].interest_rate;
let blc = this.Saving[0].balance_available;
if(blc == ''){
blc = 0;
}else{
blc= parseInt(blc);
}
if(interest == ''){
interest = 0;
}else{
interest= parseInt(interest);
}
this.today_interest = (blc*interest)/100;
setTimeout(function(){
var max = 150.72259521484375;
$.each($('.progress_cal'), function( index, value ){
var percent = $(value).data('progress');
$(value).children('.fill').attr('style', 'stroke-dashoffset: ' + ((100 - percent) / 100) * max);
$(value).children('.value').text(percent + '%');
});
}, 1);
}
});
}
getPercent(totalAmt, PaidAmt){
var percentamt: number = 0;
if(totalAmt != 0 && PaidAmt != 0){
percentamt = (PaidAmt/totalAmt)*100;
}
if(percentamt == 0){
return percentamt;
}
return percentamt.toFixed(2);
}
ngOnInit() {
// this.provider.presentLoading();
this.slideOptsOne = {
initialSlide: 1,
slidesPerView: 1,
autoplay:true,
pager: true
};
}
//Saving Click
saving: any;
SavingClick(type:string,slug:string){
this.saving = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.saving)
}
};
this.router.navigate(['dashboard/saving'], navigationExtras);
}
//End Saving Click
//DD Click
dd: any;
DdClick(type:string,slug:string){
this.dd = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.dd)
}
};
this.router.navigate(['/dashboard/dd/ddview'], navigationExtras);
}
//End DD Click
//RD Click
rd : any;
RdClick(type:string,slug:string){
this.rd = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.rd)
}
};
this.router.navigate(['/dashboard/rd/rdview'], navigationExtras);
}
// End RD CLick
//FD Click
fd : any;
FdClick(type:string,slug:string){
this.fd = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.fd)
}
};
this.router.navigate(['/dashboard/fd/fdview'], navigationExtras);
}
// End FD CLick
//OL Click
ol : any;
OlClick(type:string,slug:string){
this.ol = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.ol)
}
};
this.router.navigate(['/dashboard/ol'], navigationExtras);
}
// End OL CLick
logout(){
this.storage.remove('offline-user');
this.navCtrl.navigateRoot('/');
}
}<file_sep>/src/app/pages/home/gl/gl.page.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { NavParams, NavController, IonInfiniteScroll } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import * as moment from 'moment';
import { CreatePdf } from 'src/providers/CreatePdf';
@Component({
selector: 'app-gl',
templateUrl: './gl.page.html',
styleUrls: ['./gl.page.scss'],
})
export class GlPage implements OnInit {
GlResponse: any = [];
@ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;
constructor(
public navParams: NavParams,
public navCtrl: NavController,
private route: ActivatedRoute,
private provider : ApihelperProvider,
private pdfmake: CreatePdf
) {
}
data: any;
GlDetails: any;
GlTransactions: any = [];
fddata: any;
momentjs: any = moment;
MemberGlTransactions: any = [];
end_date: '';
start_date: '';
pdfObj = null;
show = 20;
ngOnInit(){
this.provider.presentLoading();
}
ionViewDidEnter() {
this.loadData(event);
}
loadData(event) {
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.data = JSON.parse(params.special);
this.provider.MemberGL(this.data.type,this.data.slug).subscribe(data=>{
this.GlResponse = this.provider.MemberGL_Details(data);
if(this.GlResponse){
this.GlDetails = this.GlResponse.details;
this.GlTransactions = this.GlResponse.transactions;
console.log("ol",this.GlDetails);
console.log(this.GlTransactions);
if(this.GlTransactions){
this.GlTransactions = this.GlResponse.transactions;
}else{
this.GlTransactions = [];
}
}
});
}
});
}
showmore(length){
this.show = length;
this.provider.presentLoading();
}
StartDate(){
if(!this.start_date){
console.log(this.start_date);
}
return this.start_date;
}
EndDate(){
if(!this.end_date){
console.log(this.end_date);
}
return this.end_date;
}
Apply_Date(){
if((this.start_date == undefined || this.start_date == '') || (this.end_date == undefined || this.end_date == '') ){
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.fddata = JSON.parse(params.special);
this.provider.MemberSaving(this.fddata.type,this.fddata.slug).subscribe(data=>{
this.MemberGlTransactions = this.provider.MemberSaving_Details(data);
if(this.MemberGlTransactions.length != 0){
this.GlTransactions = this.MemberGlTransactions.transactions;
}else{
this.GlTransactions = [];
}
});
}
});
this.provider.presentToastWithOptions('Please select date first!');
}else{
let start_date = this.momentjs(this.start_date).format("YYYY-MM-DD")
let end_date = this.momentjs(this.end_date).format("YYYY-MM-DD");
this.provider.presentLoading();
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.fddata = JSON.parse(params.special);
this.provider.MemberGL(this.fddata.type,this.fddata.slug).subscribe(data=>{
this.GlResponse = this.provider.MemberGL_Details(data);
if(this.GlResponse.length != 0){
let GlTransactions1 = this.GlResponse.transactions;
this.GlTransactions = GlTransactions1.filter((item: any) => {
let date = new Date(item.transaction_date);
date = this.momentjs(date).format("YYYY-MM-DD");
return date >= start_date && date <= end_date;
});
if(this.GlTransactions==''){
this.GlTransactions == '';
}
}else{
this.GlTransactions == [];
}
});
}
});
}
}
createPdf() {
this.pdfmake.createPdf(this.GlTransactions);
}
}
<file_sep>/android/app/build/intermediates/merged_assets/debug/out/public/cordova_plugins.js
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"id": "cordova-plugin-camera.Camera",
"file": "plugins/cordova-plugin-camera/www/CameraConstants.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"Camera"
]
},
{
"id": "cordova-plugin-camera.CameraPopoverHandle",
"file": "plugins/cordova-plugin-camera/www/CameraPopoverHandle.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"CameraPopoverHandle"
]
},
{
"id": "cordova-plugin-camera.CameraPopoverOptions",
"file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"CameraPopoverOptions"
]
},
{
"id": "cordova-plugin-network-information.Connection",
"file": "plugins/cordova-plugin-network-information/www/Connection.js",
"pluginId": "cordova-plugin-network-information",
"clobbers": [
"Connection"
]
},
{
"id": "cordova-plugin-inappbrowser.inappbrowser",
"file": "plugins/cordova-plugin-inappbrowser/www/inappbrowser.js",
"pluginId": "cordova-plugin-inappbrowser",
"clobbers": [
"cordova.InAppBrowser.open"
]
},
{
"id": "cordova-plugin-advanced-http.http",
"file": "plugins/cordova-plugin-advanced-http/www/advanced-http.js",
"pluginId": "cordova-plugin-advanced-http",
"clobbers": [
"cordova.plugin.http"
]
},
{
"id": "cordova-plugin-file-opener2.FileOpener2",
"file": "plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js",
"pluginId": "cordova-plugin-file-opener2",
"clobbers": [
"cordova.plugins.fileOpener2"
]
},
{
"id": "cordova-plugin-fingerprint-aio.Fingerprint",
"file": "plugins/cordova-plugin-fingerprint-aio/www/Fingerprint.js",
"pluginId": "cordova-plugin-fingerprint-aio",
"clobbers": [
"Fingerprint"
]
},
{
"id": "cordova-plugin-nativestorage.mainHandle",
"file": "plugins/cordova-plugin-nativestorage/www/mainHandle.js",
"pluginId": "cordova-plugin-nativestorage",
"clobbers": [
"NativeStorage"
]
},
{
"id": "com-badrit-base64.Base64",
"file": "plugins/com-badrit-base64/www/Base64.js",
"pluginId": "com-badrit-base64",
"clobbers": [
"navigator.Base64"
]
},
{
"id": "cordova-plugin-camera.camera",
"file": "plugins/cordova-plugin-camera/www/Camera.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"navigator.camera"
]
},
{
"id": "cordova-plugin-network-information.network",
"file": "plugins/cordova-plugin-network-information/www/network.js",
"pluginId": "cordova-plugin-network-information",
"clobbers": [
"navigator.connection",
"navigator.network.connection"
]
},
{
"id": "cordova-pdf-generator.pdf",
"file": "plugins/cordova-pdf-generator/www/pdf.js",
"pluginId": "cordova-pdf-generator",
"clobbers": [
"cordova.plugins.pdf",
"pugin.pdf",
"pdf"
]
},
{
"id": "cordova-plugin-crop.CropPlugin",
"file": "plugins/cordova-plugin-crop/www/crop.js",
"pluginId": "cordova-plugin-crop",
"clobbers": [
"plugins.crop"
]
},
{
"id": "cordova-plugin-file.DirectoryEntry",
"file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryEntry"
]
},
{
"id": "cordova-plugin-file.DirectoryReader",
"file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryReader"
]
},
{
"id": "cordova-plugin-file.Entry",
"file": "plugins/cordova-plugin-file/www/Entry.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Entry"
]
},
{
"id": "cordova-plugin-file.File",
"file": "plugins/cordova-plugin-file/www/File.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.File"
]
},
{
"id": "cordova-plugin-file.FileEntry",
"file": "plugins/cordova-plugin-file/www/FileEntry.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileEntry"
]
},
{
"id": "cordova-plugin-file.FileError",
"file": "plugins/cordova-plugin-file/www/FileError.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileError"
]
},
{
"id": "cordova-plugin-filepath.FilePath",
"file": "plugins/cordova-plugin-filepath/www/FilePath.js",
"pluginId": "cordova-plugin-filepath",
"clobbers": [
"window.FilePath"
]
},
{
"id": "cordova-plugin-file.FileReader",
"file": "plugins/cordova-plugin-file/www/FileReader.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileReader"
]
},
{
"id": "cordova-plugin-file.FileSystem",
"file": "plugins/cordova-plugin-file/www/FileSystem.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileSystem"
]
},
{
"id": "cordova-plugin-file-transfer.FileTransfer",
"file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js",
"pluginId": "cordova-plugin-file-transfer",
"clobbers": [
"window.FileTransfer"
]
},
{
"id": "cordova-plugin-file-transfer.FileTransferError",
"file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js",
"pluginId": "cordova-plugin-file-transfer",
"clobbers": [
"window.FileTransferError"
]
},
{
"id": "cordova-plugin-file.FileUploadOptions",
"file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadOptions"
]
},
{
"id": "cordova-plugin-file.FileUploadResult",
"file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadResult"
]
},
{
"id": "cordova-plugin-file.FileWriter",
"file": "plugins/cordova-plugin-file/www/FileWriter.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileWriter"
]
},
{
"id": "cordova-plugin-file.Flags",
"file": "plugins/cordova-plugin-file/www/Flags.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Flags"
]
},
{
"id": "cordova-plugin-file.LocalFileSystem",
"file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.LocalFileSystem"
],
"merges": [
"window"
]
},
{
"id": "cordova-plugin-file.Metadata",
"file": "plugins/cordova-plugin-file/www/Metadata.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Metadata"
]
},
{
"id": "cordova-plugin-file.ProgressEvent",
"file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.ProgressEvent"
]
},
{
"id": "cordova-plugin-file.requestFileSystem",
"file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.requestFileSystem"
]
},
{
"id": "cordova-sms-plugin.Sms",
"file": "plugins/cordova-sms-plugin/www/sms.js",
"pluginId": "cordova-sms-plugin",
"clobbers": [
"window.sms"
]
},
{
"id": "cordova-plugin-advanced-http.cookie-handler",
"file": "plugins/cordova-plugin-advanced-http/www/cookie-handler.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.dependency-validator",
"file": "plugins/cordova-plugin-advanced-http/www/dependency-validator.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.error-codes",
"file": "plugins/cordova-plugin-advanced-http/www/error-codes.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.global-configs",
"file": "plugins/cordova-plugin-advanced-http/www/global-configs.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.helpers",
"file": "plugins/cordova-plugin-advanced-http/www/helpers.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.js-util",
"file": "plugins/cordova-plugin-advanced-http/www/js-util.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.local-storage-store",
"file": "plugins/cordova-plugin-advanced-http/www/local-storage-store.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.lodash",
"file": "plugins/cordova-plugin-advanced-http/www/lodash.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.messages",
"file": "plugins/cordova-plugin-advanced-http/www/messages.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.ponyfills",
"file": "plugins/cordova-plugin-advanced-http/www/ponyfills.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.public-interface",
"file": "plugins/cordova-plugin-advanced-http/www/public-interface.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.tough-cookie",
"file": "plugins/cordova-plugin-advanced-http/www/umd-tough-cookie.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-advanced-http.url-util",
"file": "plugins/cordova-plugin-advanced-http/www/url-util.js",
"pluginId": "cordova-plugin-advanced-http"
},
{
"id": "cordova-plugin-file.fileSystems",
"file": "plugins/cordova-plugin-file/www/fileSystems.js",
"pluginId": "cordova-plugin-file"
},
{
"id": "cordova-plugin-file.isChrome",
"file": "plugins/cordova-plugin-file/www/browser/isChrome.js",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"id": "cordova-plugin-file.fileSystems-roots",
"file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"id": "cordova-plugin-nativestorage.LocalStorageHandle",
"file": "plugins/cordova-plugin-nativestorage/www/LocalStorageHandle.js",
"pluginId": "cordova-plugin-nativestorage"
},
{
"id": "cordova-plugin-nativestorage.NativeStorageError",
"file": "plugins/cordova-plugin-nativestorage/www/NativeStorageError.js",
"pluginId": "cordova-plugin-nativestorage"
},
{
"id": "cordova-plugin-file.fileSystemPaths",
"file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
"pluginId": "cordova-plugin-file",
"merges": [
"cordova"
],
"runs": true
},
{
"id": "cordova-plugin-file.androidFileSystem",
"file": "plugins/cordova-plugin-file/www/android/FileSystem.js",
"pluginId": "cordova-plugin-file",
"merges": [
"FileSystem"
]
},
{
"id": "cordova-plugin-file.resolveLocalFileSystemURI",
"file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
"pluginId": "cordova-plugin-file",
"merges": [
"window"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"com-badrit-base64": "0.2.0",
"cordova-pdf-generator": "2.1.1",
"cordova-plugin-advanced-http": "3.0.0",
"cordova-plugin-android-support-v4": "21.0.1",
"cordova-plugin-camera": "4.1.0",
"cordova-plugin-crop": "0.3.1",
"cordova-plugin-file": "6.0.2",
"cordova-plugin-file-opener2": "3.0.2",
"cordova-plugin-file-transfer": "1.7.1",
"cordova-plugin-filepath": "1.5.8",
"cordova-plugin-fingerprint-aio": "3.0.1",
"cordova-plugin-inappbrowser": "4.0.0",
"cordova-plugin-nativestorage": "2.3.2",
"cordova-plugin-network-information": "2.0.2",
"cordova-sms-plugin": "1.0.0"
};
// BOTTOM OF METADATA
});
<file_sep>/src/app/pages/menu/loan/loan.page.html
<ion-toolbar>
<!--- acconts header-->
<div class="accounts-header ">
<ion-row>
<ion-col size="1">
<div class="back-button">
<ion-back-button defaultHref="dashboard/home" name="chevron-back-outline"></ion-back-button></div>
</ion-col>
<ion-col size="2">
<img src="../../assets/imgs/logo.png"/>
</ion-col>
<ion-col size="7">
</ion-col>
<ion-col size="1">
<img src="../../assets/icon/bellb.svg"/>
</ion-col>
<ion-col size="1" class="blue-wallet">
<img src="../../assets/icon/walletb.svg"/>
</ion-col>
</ion-row>
</div>
<!--- accounts header end-->
</ion-toolbar>
<div class="acoounts-header">
<h1>My Loan Accounts</h1>
</div>
<!-- Other Loan -->
<a *ngIf="OL" >
<div *ngFor="let OL of OL">
<ion-row class="amount-details md hydrated first-column" *ngIf="OL.status == 'Active'" (click)="olclick('ol', OL.slug)">
<ion-col size="8" class="md hydrated" style="flex: 0 0 calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%);">
<p class="fade-text-one">
OL current Debit
</p>
<p class="blue-text-nm">
₹{{OL.current_debt}}/-
</p>
<p class="fade-text-one">
Total Amount
</p>
<h2 class="amount-blue">₹{{OL.loan_amount}}/-</h2>
</ion-col>
<ion-col size="4" class="md hydrated" style="flex: 0 0 calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%);">
<p class="blue-text-nm">
{{OL.account_number}}
</p>
<p class="fade-text-two">
Open Date
</p>
<p class="blue-text-nm">
{{OL.open_date}}
</p>
<p class="fade-text-two">
Status
</p>
<p class="blue-text-nm">
{{OL.status}}
</p>
</ion-col>
</ion-row>
<ion-row *ngIf="OL.status != 'Active'" class="amount-details md hydrated first-column closed" >
<ion-col size="8" class="md hydrated" style="flex: 0 0 calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%);">
<p class="fade-text-one">
OL current Debit
</p>
<p class="blue-text-nm">
₹{{OL.current_debt}}/-
</p>
<p class="fade-text-one">
Total Amount
</p>
<h2 class="amount-blue">₹{{OL.loan_amount}}/-</h2>
</ion-col>
<ion-col size="4" class="md hydrated" style="flex: 0 0 calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%);">
<p class="blue-text-nm">
{{OL.account_number}}
</p>
<p class="fade-text-two">
Open Date
</p>
<p class="blue-text-nm">
{{OL.open_date}}
</p>
<p class="fade-text-two">
Status
</p>
<p class="blue-text-nm">
{{OL.status}}
</p>
</ion-col>
</ion-row>
</div>
</a>
<!-- Deposit Loan -->
<a *ngIf="DL" >
<div *ngFor="let DL of DL">
<ion-row class="amount-details md hydrated first-column" *ngIf="DL.status == 'Active'" (click)="dlclick('dl', DL.slug)">
<ion-col size="8" class="md hydrated" style="flex: 0 0 calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%);">
<p class="fade-text-one">
DL current Debit
</p>
<p class="blue-text-nm">
₹{{DL.current_debt}}/-
</p>
<p class="fade-text-one">
Total Amount
</p>
<h2 class="amount-blue">₹{{DL.loan_amount}}/-</h2>
</ion-col>
<ion-col size="4" class="md hydrated" style="flex: 0 0 calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%);">
<p class="blue-text-nm">
{{DL.account_number}}
</p>
<p class="fade-text-two">
Open Date
</p>
<p class="blue-text-nm">
{{DL.open_date}}
</p>
<p class="fade-text-two">
Status
</p>
<p class="blue-text-nm">
{{DL.status}}
</p>
</ion-col>
</ion-row>
<ion-row *ngIf="DL.status != 'Active'" class="amount-details md hydrated first-column closed" >
<ion-col size="8" class="md hydrated" style="flex: 0 0 calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%);">
<p class="fade-text-one">
DL current Debit
</p>
<p class="blue-text-nm">
₹{{DL.current_debt}}/-
</p>
<p class="fade-text-one">
Total Amount
</p>
<h2 class="amount-blue">₹{{DL.loan_amount}}/-</h2>
</ion-col>
<ion-col size="4" class="md hydrated" style="flex: 0 0 calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%);">
<p class="blue-text-nm">
{{DL.account_number}}
</p>
<p class="fade-text-two">
Open Date
</p>
<p class="blue-text-nm">
{{DL.open_date}}
</p>
<p class="fade-text-two">
Status
</p>
<p class="blue-text-nm">
{{DL.status}}
</p>
</ion-col>
</ion-row>
</div>
</a>
<!-- Gold Loan -->
<a *ngIf="GL" >
<div *ngFor="let GL of GL">
<ion-row class="amount-details md hydrated first-column" *ngIf="GL.status == 'Active'" (click)="glclick('gl', GL.slug)">
<ion-col size="8" class="md hydrated" style="flex: 0 0 calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%);">
<p class="fade-text-one">
GL current Debit
</p>
<p class="blue-text-nm">
₹{{GL.current_debt}}/-
</p>
<p class="fade-text-one">
Total Amount
</p>
<h2 class="amount-blue">₹{{GL.loan_amount}}/-</h2>
</ion-col>
<ion-col size="4" class="md hydrated" style="flex: 0 0 calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%);">
<p class="blue-text-nm">
{{GL.account_number}}
</p>
<p class="fade-text-two">
Open Date
</p>
<p class="blue-text-nm">
{{GL.open_date}}
</p>
<p class="fade-text-two">
Status
</p>
<p class="blue-text-nm">
{{GL.status}}
</p>
</ion-col>
</ion-row>
<ion-row *ngIf="GL.status != 'Active'" class="amount-details md hydrated first-column closed" >
<ion-col size="8" class="md hydrated" style="flex: 0 0 calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%);">
<p class="fade-text-one">
GL current Debit
</p>
<p class="blue-text-nm">
₹{{GL.current_debt}}/-
</p>
<p class="fade-text-one">
Total Amount
</p>
<h2 class="amount-blue">₹{{GL.loan_amount}}/-</h2>
</ion-col>
<ion-col size="4" class="md hydrated" style="flex: 0 0 calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%);">
<p class="blue-text-nm">
{{GL.account_number}}
</p>
<p class="fade-text-two">
Open Date
</p>
<p class="blue-text-nm">
{{GL.open_date}}
</p>
<p class="fade-text-two">
Status
</p>
<p class="blue-text-nm">
{{GL.status}}
</p>
</ion-col>
</ion-row>
</div>
</a>
<!-- Fixed Loan -->
<a *ngIf="FL" >
<div *ngFor="let FL of FL">
<ion-row class="amount-details md hydrated first-column" *ngIf="FL.status == 'Active'" (click)="flclick('fl', FL.slug)">
<ion-col size="8" class="md hydrated" style="flex: 0 0 calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%);">
<p class="fade-text-one">
FL current Debit
</p>
<p class="blue-text-nm">
₹{{FL.current_debt}}/-
</p>
<p class="fade-text-one">
Total Amount
</p>
<h2 class="amount-blue">₹{{FL.loan_amount}}/-</h2>
</ion-col>
<ion-col size="4" class="md hydrated" style="flex: 0 0 calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%);">
<p class="blue-text-nm">
{{FL.account_number}}
</p>
<p class="fade-text-two">
Open Date
</p>
<p class="blue-text-nm">
{{FL.open_date}}
</p>
<p class="fade-text-two">
Status
</p>
<p class="blue-text-nm">
{{FL.status}}
</p>
</ion-col>
</ion-row>
<ion-row *ngIf="FL.status != 'Active'" class="amount-details md hydrated first-column closed" >
<ion-col size="8" class="md hydrated" style="flex: 0 0 calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%);">
<p class="fade-text-one">
FL current Debit
</p>
<p class="blue-text-nm">
₹{{FL.current_debt}}/-
</p>
<p class="fade-text-one">
Total Amount
</p>
<h2 class="amount-blue">₹{{FL.loan_amount}}/-</h2>
</ion-col>
<ion-col size="4" class="md hydrated" style="flex: 0 0 calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%);">
<p class="blue-text-nm">
{{FL.account_number}}
</p>
<p class="fade-text-two">
Open Date
</p>
<p class="blue-text-nm">
{{FL.open_date}}
</p>
<p class="fade-text-two">
Status
</p>
<p class="blue-text-nm">
{{FL.status}}
</p>
</ion-col>
</ion-row>
</div>
</a>
<!-- Property Loan -->
<a *ngIf="PL" >
<div *ngFor="let PL of PL">
<ion-row class="amount-details md hydrated first-column" *ngIf="PL.status == 'Active'" (click)="plclick('fl', FL.slug)">
<ion-col size="8" class="md hydrated" style="flex: 0 0 calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%);">
<p class="fade-text-one">
PL current Debit
</p>
<p class="blue-text-nm">
₹{{PL.current_debt}}/-
</p>
<p class="fade-text-one">
Total Amount
</p>
<h2 class="amount-blue">₹{{PL.loan_amount}}/-</h2>
</ion-col>
<ion-col size="4" class="md hydrated" style="flex: 0 0 calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%);">
<p class="blue-text-nm">
{{PL.account_number}}
</p>
<p class="fade-text-two">
Open Date
</p>
<p class="blue-text-nm">
{{PL.open_date}}
</p>
<p class="fade-text-two">
Status
</p>
<p class="blue-text-nm">
{{PL.status}}
</p>
</ion-col>
</ion-row>
<ion-row *ngIf="PL.status != 'Active'" class="amount-details md hydrated first-column closed" >
<ion-col size="8" class="md hydrated" style="flex: 0 0 calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(8 / var(--ion-grid-columns, 12)) * 100%);">
<p class="fade-text-one">
PL current Debit
</p>
<p class="blue-text-nm">
₹{{PL.current_debt}}/-
</p>
<p class="fade-text-one">
Total Amount
</p>
<h2 class="amount-blue">₹{{PL.loan_amount}}/-</h2>
</ion-col>
<ion-col size="4" class="md hydrated" style="flex: 0 0 calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%); max-width: calc(calc(4 / var(--ion-grid-columns, 12)) * 100%);">
<p class="blue-text-nm">
{{PL.account_number}}
</p>
<p class="fade-text-two">
Open Date
</p>
<p class="blue-text-nm">
{{PL.open_date}}
</p>
<p class="fade-text-two">
Status
</p>
<p class="blue-text-nm">
{{PL.status}}
</p>
</ion-col>
</ion-row>
</div>
</a><file_sep>/src/app/pages/login/login.page.ts
import { Component } from '@angular/core';
import {ModalController, NavController, Platform } from '@ionic/angular';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { Storage } from '@ionic/storage';
import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';
import { Keyboard } from '@ionic-native/keyboard/ngx';
@Component({
selector: 'page-login',
templateUrl: 'login.page.html',
styleUrls: ['login.page.scss'],
})
export class LoginPage {
public username : string = "";
public password : string = "";
public isUsernameValid: boolean;
public isPasswordValid: boolean;
private LoginReponse : any;
clsaa: any = '';
clsaa2: any= '';
constructor(
// private androidPermissions: AndroidPermissions,
public navCtrl: NavController,
private modalController: ModalController,
public keyboard: Keyboard,
private storage: Storage,
private faio: FingerprintAIO,
private platform: Platform,
private provider : ApihelperProvider) {
this.isUsernameValid= true;
this.isPasswordValid = true;
}
ngOnInit() {
this.platform.backButton.subscribe(() => {
console.log('Another handler was called!');
this.navCtrl.navigateRoot('login');
});
if (navigator.onLine) {
if(window.location.pathname == '/forgot'){
this.navCtrl.navigateRoot('/forgot');
}else{
this.storage.get('offline-user').then((val) => {
if(val){
this.provider.presentLoading();
this.provider.UserLogin( val.username, val.password).subscribe(data=>{
this.LoginReponse = data;
if(this.LoginReponse){
this.faio.isAvailable().then(result =>{
if(result = true)
{
let result=false;
this.faio.show({
title: 'Fingerprint Authentication', // (Android Only) | optional | Default: "<APP_NAME> Biometric Sign On"
})
.then((result: any) => {
this.provider.SetHeader(this.LoginReponse.token,this.LoginReponse.user_id);
this.navCtrl.navigateRoot('/dashboard/home');
})
.catch((error: any) => console.log(error));
}else{
this.navCtrl.navigateRoot('/login');
}
});
}
}
,(err)=> {
this.provider.presentToastWithOptions('There are some technical issue please try again!')});
// this.navCtrl.navigateRoot('/login');
}
else
{
this.navCtrl.navigateRoot('/login');
}
});
}
}else{
this.provider.presentToastWithOptions('Its look like you are offline!')
this.navCtrl.navigateRoot('/login');
}
}
doLogin(){
if(this.validate()){
//this.navCtrl.setRoot('PrinterPage');
// show processing
this.provider.presentLoading();
this.provider.UserLogin(this.username,this.password).subscribe(data=>{
this.LoginReponse = data;
// set header values
this.provider.SetHeader(this.LoginReponse.token,this.LoginReponse.user_id);
// call next APi
let offline_user = { "username":this.username, "password": <PASSWORD> };
// console.log(offline_user);
// set a key/value
this.storage.set('offline-user', offline_user);
// Save Member Details
this.provider.UserPanel().subscribe(data=>{
let UserResponse = this.provider.User_details(data);
this.storage.set('current_member', UserResponse.current_member)
});
// End Of Member Details
// to get a key/value pair
this.navCtrl.navigateRoot('/dashboard/home');
}
,(err)=> {
this.provider.presentToastWithOptions('Some technical problem there please try again later!')});
}
}
validate():boolean {
this.isUsernameValid = true;
this.isPasswordValid = true;
if (!this.username ||this.username.length == 0) {
this.isUsernameValid = false;
this.provider.presentToastWithOptions("Username is blank");
}
if (!this.password || this.password.length == 0) {
this.isPasswordValid = false;
this.provider.presentToastWithOptions("Password is blank");
}
return this.isPasswordValid && this.isUsernameValid ;
}
ForgotPass(){
this.navCtrl.navigateRoot('forgot');
}
focusInput(event){
this.clsaa = 'pushup';
this.clsaa2 = 'bottom_part1';
window.addEventListener('keyboardDidHide', () => {
var element = document.getElementById("log_card");
var element2 = document.getElementById("bot_part");
element.classList.remove("pushup");
element2.classList.remove("bottom_part1");
});
}
focusOut(event){
this.clsaa = '';
this.clsaa2 = '';
}
public showFingerprintAuthDlg(){
}
}
<file_sep>/src/app/pages/login/forgot/forgot.page.ts
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { Storage } from '@ionic/storage';
import { NavController } from '@ionic/angular';
@Component({
selector: 'app-forgot',
templateUrl: './forgot.page.html',
styleUrls: ['./forgot.page.scss'],
})
export class ForgotPage implements OnInit {
title = 'FormValidation';
mobNumberPattern = "^((\\+91-?)|0)?[0-9]{10}$";
isValidFormSubmitted = false;
mobileNumber:any = '';
username: any='';
otpval: any = '';
constructor(
public provider: ApihelperProvider,
private storage: Storage,
public navCtrl: NavController,
) { }
ngOnInit() {
}
onSubmit(form: NgForm) {
this.isValidFormSubmitted = false;
if (form.invalid) {
return;
}
this.provider.ForgotPass(this.mobileNumber, this.username).subscribe(res =>{
let result : any = res;
if(result.status == true){
alert("Password Sent to your mobile successfully, You can login now!");
this.storage.remove('current_member');
this.navCtrl.navigateRoot('/');
}else{
this.provider.presentToastWithOptions(result.message);
}
})
this.isValidFormSubmitted = true;
form.resetForm();
}
}<file_sep>/src/app/pages/home/fd/fdview/fdview.page.ts
import { Component, OnInit } from '@angular/core';
import { NavParams, NavController, Platform } from '@ionic/angular';
import { Router, ActivatedRoute } from '@angular/router';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { FdResponse } from 'src/providers/Models/MemberFD';
import * as moment from 'moment';
import { CreatePdf } from 'src/providers/CreatePdf';
@Component({
selector: 'app-fdview',
templateUrl: './fdview.page.html',
styleUrls: ['./fdview.page.scss'],
})
export class FdviewPage implements OnInit {
tableHeader= ['tranx_id', 'amount','transaction_type', 'transaction_date', 'payment_mode', 'transaction_type']
FdResponse: any = [];
constructor(
public navParams: NavParams,
public navCtrl: NavController,
private router: Router,
private route: ActivatedRoute,
private provider : ApihelperProvider,
private pdfmake: CreatePdf
) { }
FdDetails: any;
FdTransactions: any = [];
fddata: any;
momentjs: any = moment;
MemberFdTransactions: any = [];
end_date: '';
start_date: '';
pdfObj = null;
ngOnInit() {
}
ionViewDidEnter() {
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.fddata = JSON.parse(params.special);
this.provider.MemberFD(this.fddata.type,this.fddata.slug).subscribe(data=>{
this.provider.presentLoading();
this.FdResponse = this.provider.MemberFD_Details(data);
if(this.FdResponse){
this.FdDetails = this.FdResponse.details;
this.FdTransactions = this.FdResponse.transactions;
if(this.FdTransactions){
this.FdTransactions = this.FdResponse.transactions;
}else{
this.FdTransactions = '';
}
}
});
}
});
}
StartDate(){
if(!this.start_date){
console.log(this.start_date);
}
return this.start_date;
}
EndDate(){
if(!this.end_date){
console.log(this.end_date);
}
return this.end_date;
}
Apply_Date(){
if((this.start_date == undefined || this.start_date == '') || (this.end_date == undefined || this.end_date == '') ){
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.fddata = JSON.parse(params.special);
this.provider.MemberFD(this.fddata.type,this.fddata.slug).subscribe(data=>{
this.MemberFdTransactions = this.provider.MemberFD_Details(data);
if(this.MemberFdTransactions.length != 0){
this.FdTransactions = this.MemberFdTransactions.transactions;
}else{
this.FdTransactions = [];
}
});
}
});
this.provider.presentToastWithOptions('Please select date first!');
}else{
let start_date = this.momentjs(this.start_date).format("YYYY-MM-DD")
let end_date = this.momentjs(this.end_date).format("YYYY-MM-DD");
this.provider.presentLoading();
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.fddata = JSON.parse(params.special);
this.provider.MemberFD(this.fddata.type,this.fddata.slug).subscribe(data=>{
this.FdResponse = this.provider.MemberFD_Details(data);
if(this.FdResponse.length != 0){
let FdTransactions1 = this.FdResponse.transactions;
this.FdTransactions = FdTransactions1.filter((item: any) => {
let date = new Date(item.transaction_date);
date = this.momentjs(date).format("YYYY-MM-DD");
return date >= start_date && date <= end_date;
});
if(this.FdTransactions==''){
this.FdTransactions == '';
}
}else{
this.FdTransactions == [];
}
});
}
});
}
}
createPdf() {
this.pdfmake.createPdf(this.FdTransactions);
}
}<file_sep>/src/providers/Models/MemberRD.ts
export interface RdResponse{
[x : string] : any;
[index : number] : {
member_name : string;
interest_rate : string;
total_amt : string;
maturity_amt : string;
maturity_date : string;
account_no : string;
}
}<file_sep>/src/providers/Models/saving_details.ts
export interface SavingResponse{
[x : string] : any;
[index : number] : {
transaction_type : string;
payment_method : string;
transaction_date : string;
transaction_amt : string;
account : string;
updated : string;
}
}<file_sep>/src/app/pages/home/rd/rdview/rdview.page.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { RdviewPage } from './rdview.page';
describe('RdviewPage', () => {
let component: RdviewPage;
let fixture: ComponentFixture<RdviewPage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ RdviewPage ],
imports: [IonicModule.forRoot()]
}).compileComponents();
fixture = TestBed.createComponent(RdviewPage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/src/app/pages/menu/passbook/passbook.page.ts
import { Component, OnInit } from '@angular/core';
import { PDFGenerator } from '@ionic-native/pdf-generator/ngx';
import { File } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { Platform, NavController } from '@ionic/angular';
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
import { Network } from '@ionic-native/network/ngx';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { ActivatedRoute } from '@angular/router';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
import * as moment from 'moment';
import { CreatePdf } from 'src/providers/CreatePdf';
@Component({
selector: 'app-passbook',
templateUrl: './passbook.page.html',
styleUrls: ['./passbook.page.scss'],
})
export class PassbookPage implements OnInit {
letterObj = {
trans_type: '',
trans_amt: '',
text: ''
}
radioValue: any;
pdfObj = null;
data: any;
Response: any = [];
Transactions: any = [];
type: any;
slug: any;
end_date: '';
start_date: '';
// pdfObj = null;
show = 20;
momentjs: any = moment;
constructor(private pdfGenerator: PDFGenerator,
private provider: ApihelperProvider,
public navCtrl: NavController,
private route: ActivatedRoute,
private network: Network,
private pdfmake: CreatePdf,
private plt: Platform, private file: File, private fileOpener: FileOpener
) {
}
// this.pdfGenerator.fromURL('http://localhost:8300/dashboard/saving', options).then(base64String => console.log(base64String))
createPdf() {
this.pdfmake.createPdf(this.Transactions);
}
ngOnInit() {
}
showValue(){
console.log(this.radioValue);
this.provider.Loan(this.radioValue).subscribe(data=>{
this.Response = this.provider.Loan_Details(data);
if(this.Response){
this.Response = this.Response.details
this.Transactions = [];
}else{
this.Response = [];
}
});
}
account_click(type:string,slug:string){
this.type = type
this.slug = slug
this.provider.Pasbook_Details(type, slug).subscribe(data=>{
this.Transactions = this.provider.Pasbook_Details_Details(data);
if(this.Transactions){
this.Transactions = this.Transactions.transactions
}else{
this.Transactions = [];
}
});
}
StartDate(){
if(!this.start_date){
}
return this.start_date;
}
EndDate(){
if(!this.end_date){
}
return this.end_date;
}
Apply_Date(){
if((this.start_date == undefined || this.start_date == '') || (this.end_date == undefined || this.end_date == '') ){
this.provider.Pasbook_Details(this.type, this.slug).subscribe(data=>{
this.Transactions = this.provider.Pasbook_Details_Details(data);
if(this.Transactions){
this.Transactions = this.Transactions.transactions
}else{
this.Transactions = [];
}
});
this.provider.presentToastWithOptions('Please select date first!');
}else{
let start_date = this.momentjs(this.start_date).format("YYYY-MM-DD")
let end_date = this.momentjs(this.end_date).format("YYYY-MM-DD");
this.provider.presentLoading();
this.provider.Pasbook_Details(this.type, this.slug).subscribe(data=>{
this.Transactions = this.provider.Pasbook_Details_Details(data);
if(this.Transactions.length != 0){
let OlTransactions1 = this.Transactions.transactions;
this.Transactions = OlTransactions1.filter((item: any) => {
let date = new Date(item.transaction_date);
date = this.momentjs(date).format("YYYY-MM-DD");
return date >= start_date && date <= end_date;
});
if(this.Transactions==''){
this.Transactions == '';
}
}else{
this.Transactions == [];
}
});
}
}
}
<file_sep>/src/providers/Models/MemberSaving.ts
export interface MemberSavingResponse{
[x : string] : any;
[index : number] : {
details : any;
status : string;
transactions : any;
}
}<file_sep>/src/app/pages/home/home-routing.module.ts
// tablinks-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomePage } from './home.page';
const routes: Routes = [
{
path: '',
component: HomePage
},
{
path: 'saving',
loadChildren: () => import('./saving/saving.module').then( m => m.SavingPageModule)
},
{
path: 'ol',
loadChildren: () => import('./ol/ol.module').then( m => m.OlPageModule)
},
{
path: 'rl',
loadChildren: () => import('./rl/rl.module').then( m => m.RlPageModule)
},
{
path: 'dl',
loadChildren: () => import('./dl/dl.module').then( m => m.DlPageModule)
},
{
path: 'pl',
loadChildren: () => import('./pl/pl.module').then( m => m.PlPageModule)
},
{
path: 'gl',
loadChildren: () => import('./gl/gl.module').then( m => m.GlPageModule)
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class HomePageRoutingModule { }
<file_sep>/src/app/pages/menu/loan/loan.page.ts
import { Component, OnInit } from '@angular/core';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { Router, NavigationExtras } from '@angular/router';
@Component({
selector: 'app-loan',
templateUrl: './loan.page.html',
styleUrls: ['./loan.page.scss'],
})
export class LoanPage implements OnInit {
public UserResponse: any=[];
OL: any = [];
DL: any = [];
GL: any = [];
FL: any = [];
PL: any = [];
constructor(
public provider : ApihelperProvider,
private router: Router
) {
}
ngOnInit() {
}
ionViewDidEnter() {
// User Details From API
this.LoanFetch();
}
LoanFetch(){
this.provider.UserPanel().subscribe(data=>{
this.UserResponse = this.provider.User_details(data);
if(this.UserResponse){
this.OL = this.UserResponse.OL;
console.log(this.OL);
this.DL = this.UserResponse.DL;
this.GL = this.UserResponse.GL;
this.FL = this.UserResponse.FL;
this.PL = this.UserResponse.PL;
}
})
}
//OL Click
ol : any;
olclick(type:string,slug:string){
this.ol = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.ol)
}
};
this.router.navigate(['/dashboard/ol'], navigationExtras);
}
// End OL CLick
//DL Click
dl : any;
dlclick(type:string,slug:string){
this.dl = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.dl)
}
};
this.router.navigate(['/dashboard/dl'], navigationExtras);
}
// End dl CLick
//GL Click
gl : any;
glclick(type:string,slug:string){
this.gl = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.gl)
}
};
this.router.navigate(['/dashboard/gl'], navigationExtras);
}
// End gl CLick
//gL Click
rl : any;
rlclick(type:string,slug:string){
this.rl = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.rl)
}
};
this.router.navigate(['/dashboard/rl'], navigationExtras);
}
// End rl CLick
//PL Click
pl : any;
plclick(type:string,slug:string){
this.pl = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.pl)
}
};
this.router.navigate(['/dashboard/pl'], navigationExtras);
}
// End PL CLick
//PL Click
fl : any;
flclick(type:string,slug:string){
this.fl = {
type: type,
slug: slug
};
let navigationExtras: NavigationExtras = {
queryParams: {
special: JSON.stringify(this.fl)
}
};
this.router.navigate(['/dashboard/fl'], navigationExtras);
}
// End PL CLick
}
<file_sep>/src/app/pages/menu/passbook/passbook.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { PassbookPageRoutingModule } from './passbook-routing.module';
import { PassbookPage } from './passbook.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
PassbookPageRoutingModule
],
declarations: [PassbookPage]
})
export class PassbookPageModule {}
<file_sep>/src/app/pages/menu/tandc/tandc.page.html
<ion-toolbar>
<!--- acconts header-->
<div class="accounts-header ">
<ion-row>
<ion-col size="1">
<div class="back-button">
<ion-back-button defaultHref="dashboard/home" name="chevron-back-outline"></ion-back-button></div>
</ion-col>
<ion-col size="2">
<img src="../../assets/imgs/logo.png"/>
</ion-col>
<ion-col size="7">
</ion-col>
<ion-col size="1">
<img src="../../assets/icon/bellb.svg"/>
</ion-col>
<ion-col size="1" class="blue-wallet">
<img src="../../assets/icon/walletb.svg"/>
</ion-col>
</ion-row>
</div>
<!--- accounts header end-->
</ion-toolbar>
<ion-content>
Mobile Banking Services - Terms and Conditions
TERMS OF USE
These terms and conditions explain the rights and obligations pertaining to the Mobile Banking Service (defined below) and information that the Customer may use or request from the Bank or that the Bank may provide to the Customer through the Mobile Banking Service.
The Bank reserves the right to add, amend, revise, change or cancel any of these terms and conditions and also reserves the right to modify any features of any products or services offered by the Bank.
The Customer unconditionally accepts these terms and conditions applicable to such Account (defined below) and the services relating thereto and shall always be bound by and abide with them and their amendments from time to time.
The Customer understands and acknowledges that this Mobile Banking Service is an extension of the OLB (defined below) provided by the Bank and the Customer accessing such Mobile Banking Service shall also be bound by the terms and conditions that govern the OLB.
These terms and conditions are in addition to and not in substitution / derogation of the general business terms and conditions; the wealth management terms and conditions; and such other terms as may be prescribed by the Bank from time to time in relation to the Services.
DEFINITIONS
Account shall mean the bank account maintained by the Customer with the Bank for which the Mobile Banking Service is being offered.
Applicable Laws shall mean and include any statute, law, regulation or a stipulation by the RBI or any other regulatory authority whether in effect as on date or as amended from time to time.
Application shall mean the mobile application which will be downloaded on the mobile phone of the Customer to access and use the Mobile Banking Service.
Bank shall mean Deutsche Bank AG.
Customer shall mean the existing holder of an Account with the Bank or the holder of the Bank’s debit / credit cards who has made an application to the Bank to use the Mobile Banking Service and / or downloaded the MyBank India - Mobile Banking App and thereby agreed to these terms and conditions.
Customer Identification Data shall mean the Customer account number / card number, mobile phone number, user ID and other information that are to be used by the Customer to authenticate themselves prior to accessing the Mobile Banking Service which may be the same as the information used by the Customer for accessing the OLB services.
Mobile Banking Service means any and all of the Services offered by the Bank to the Customer on phone and / or any electronic gadgets owned by the Customer.
Mobile Phone Number shall mean the number registered by the Customer in relation to the use of Services offered by the Bank.
OLB means Online Banking Services provided by the Bank on its website.
RBI shall mean the Reserve Bank of India.
Service shall mean current / savings account related operations including inter alia wealth management services and / or such additional features as may be added / removed from time to time.
SMS shall mean Short Messaging Service, being a service offered by Telephone Service Providers and / or any other similar method of electronic communication that may now or at anytime in the future be offered by Telephone Service Provider(s).
SMS Banking means a service that allows Customers to access their account information via Mobile phone using SMS messaging.
Telephone Service Provider shall mean the provider of the mobile phone connectivity services and Mobile Phone Number used by the Customer on their mobile phones.
Website shall mean the domain of the Bank located at url www.deutschebank.co.in owned and controlled by the Bank.
ACCEPTANCE OF TERMS AND CONDITIONS
• On the terms and conditions hereinafter provided, the Bank offers the Mobile Banking Service to the Customer. These terms and conditions made by the Bank and accepted by the Customer shall form the contract between the Customer. These terms and conditions shall be in addition to and not in derogation of other terms and conditions relating to any Account or Service of the Customer and / or the respective product provided by the Bank unless otherwise specifically stated.
• To access the Mobile Banking Service, the Customer is required to download the Application on their mobile phone and / or any electronic gadgets owned by the Customer provided such mobile phone and / or any electronic gadgets is compatible with the Application.
• In order to transact under the Mobile Banking Service, there are transaction data verification / re-authentication requirements for the Customer. The Customer may use the OLB credentials or the Customer Identification Data to effect such verification / re-authentication. The Customer will use the same Customer Identification Data for both the OLB and Mobile Banking Service. The Customer must strictly adhere to privacy procedures to ensure safe keeping of the log in credentials.
USAGE OF FACILITY
• By accepting the terms and conditions on the mobile phone while registering for the Mobile Banking Service, the Customer:
a) agrees to use the Mobile Banking Service for financial and non-financial transactions offered by the Bank from time to time,
b) irrevocably authorizes the Bank to debit the Accounts which have been enabled for Mobile Banking Service for all transactions / services undertaken by using Customer Identification Data,
c) authorizes the Bank to map the account number, User ID and Mobile Phone Number for the smooth operation of Mobile Banking Service offered by Bank and to preserve the mapping record in its own server or server of any other third party and to use such data at its discretion for providing / enhancing further banking / technology products that it may offer,
d) agrees to the usage of the Customer Identification Data as an authentication factor for the Mobile Banking Service,
e) confirms to the acceptance of the terms and condition of the Mobile Banking Service offered by the Bank,
f) agrees that the Mobile Banking Service will enable him / her to transact using Customer Identification Data within the limit prescribed by the Bank and will be deemed as bonafide transaction,
g) agrees that the transactions originated using the mobile phones are non-retractable as these are instantaneous / real time,
h) understands and explicitly agrees that the Bank has the absolute and unfettered right to revise the prescribed ceilings from time to time which will be binding, and
i) agrees that while the Information Technology Act, 2000 (IT Act) prescribes that a subscriber may authenticate an electronic record by affixing his digital signature which has been given legal recognition under the Act, the Bank is authenticating the Customer by using Mobile Phone Number, Customer Identification Data or any other method decided at the discretion of the Bank which may not be recognized under the IT Act for authentication of electronic records and this is acceptable and binding to the Customer and hence the Customer is solely responsible for maintenance of the secrecy and confidentiality of the Customer Identification Data without any liability to the Bank.
• The guidelines issued by the RBI on “Know Your Customer (KYC)”, “Anti Money Laundering (AML)” and “Combating the Financing of Terrorism (CFT)” from time to time would be applicable to the Mobile Banking Service.
• The Bank shall file “Suspicious Transaction Report (STR)” to the “Financial Intelligence Unit – India (FIU-IND)” for mobile banking transactions as in the case of normal banking transactions
</ion-content>
https://www.deutschebank.co.in/mobile-banking-tnc.html<file_sep>/src/providers/CreatePdf.ts
import { NavParams, NavController,Platform } from '@ionic/angular';
import { Router, ActivatedRoute } from '@angular/router';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { RdResponse } from 'src/providers/Models/MemberRD';
import * as moment from 'moment';
import { File } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import pdfMake from 'pdfmake/build/pdfmake';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable()
export class CreatePdf {
RdResponse: RdResponse = [];
public pdfData: any=[];
tableHeader= ['transaction_date', 'payment_mode','amount', 'transaction_type','tranx_id']
tableHead= ['Date', 'Payment Mode','Amount', 'Type','Transaction ID']
memberheader= ['first_name', 'last_name','father_name', 'member_number']
membertableHead= ['First Name','Last Name', 'Father Name','Account Number']
constructor(
public navParams: NavParams,
public navCtrl: NavController,
private storage: Storage,
private router: Router,
private route: ActivatedRoute,
private provider : ApihelperProvider,
private plt: Platform, private file: File, private fileOpener: FileOpener,
) {
this.provider.presentLoading();
this.storage.get('current_member').then((val) => {
console.log('val',val);
this.MemberPDf.push(val);
});
}
rddata: any;
RdDetails: any;
RdTransactions: any = [];
newarray: any= [];
MemberRdTransactions: any = [];
momentjs: any = moment;
end_date: '';
start_date: '';
pdfObj = null;
MemberPDf = [];
ngOnInit(){
}
ionViewDidEnter() {
// this.RdResponse = this.getapidata();
this.getapidata()
}
getMember(){
return this.MemberPDf;
}
getapidata(){
let res: any = [];
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.rddata = JSON.parse(params.special);
this.provider.MemberRD(this.rddata.type,this.rddata.slug).subscribe(data=>{
this.RdResponse = this.provider.MemberRD_Details(data);
if(this.RdResponse){
this.RdDetails = this.RdResponse.details;
this.RdTransactions = this.RdResponse.transactions;
if(this.RdTransactions){
this.RdTransactions = this.RdResponse.transactions;
}else{
this.RdTransactions = [];
}
}
});
}
});
}
//PDF CODE START
StartDate(){
if(!this.start_date){
}
return this.start_date;
}
EndDate(){
if(!this.end_date){
}
return this.end_date;
}
Apply_Date(){
if((this.start_date == undefined || this.start_date == '') || (this.end_date == undefined || this.end_date == '') ){
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.rddata = JSON.parse(params.special);
this.provider.MemberSaving(this.rddata.type,this.rddata.slug).subscribe(data=>{
this.MemberRdTransactions = this.provider.MemberSaving_Details(data);
this.RdDetails = this.MemberRdTransactions.details;
this.RdTransactions = this.MemberRdTransactions.transactions;
});
}
});
this.provider.presentToastWithOptions('Please select date first!');
}else{
let start_date = this.momentjs(this.start_date).format("YYYY-MM-DD")
let end_date = this.momentjs(this.end_date).format("YYYY-MM-DD");
this.provider.presentLoading();
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.rddata = JSON.parse(params.special);
this.provider.MemberRD(this.rddata.type,this.rddata.slug).subscribe(data=>{
this.RdResponse = this.provider.MemberRD_Details(data);
let RdTransactions1 = this.RdResponse.transactions;
this.RdTransactions = RdTransactions1.filter((item: any) => {
let date = new Date(item.transaction_date);
date = this.momentjs(date).format("YYYY-MM-DD");
return date >= start_date && date <= end_date;
});
if(this.RdTransactions==''){
this.RdTransactions == '';
}
});
}
});
}
}
// fetchEvent(){
// let neww = this.RdTransactions;
// console.log('neww', neww);
// return this.table(neww, this.tableHeader,this.tableHead,)
// }
buildTableBody(data, columns, tableHeader) {
console.log('tabledata', data);
var body = [];
var column= [];
for(var i=0; i<tableHeader.length; i++){
var rem_und = tableHeader[i].replace('_', ' ');
var final= rem_und.charAt(0).toUpperCase() + rem_und.substr(1).toLowerCase();
column.push(final);
}
body.push(column);
data.forEach(function(row) {
var dataRow = [];
columns.forEach(function(column) {
dataRow.push(row[column].toString());
})
body.push(dataRow);
});
return body;
}
table(data, columns, tableHeader) {
console.log('dataa',data)
return {
table: {
headerRows: 1,
body: this.buildTableBody(data, columns, tableHeader)
},
style: 'tableHeader'
};
}
createPdf(obj) {
let neww = obj;
var result = neww.filter(function(result1) {
delete result1.change_installments;
delete result1.collection_user_id;
delete result1.commission_status;
delete result1.company_branch_id;
delete result1.company_id;
delete result1.created_at;
delete result1.id;
delete result1.is_processed;
delete result1.message;
delete result1.payment_status;
delete result1.rd_account_id;
delete result1.reference_type;
delete result1.slug;
delete result1.transaction_info;
delete result1.updated_at;
return result1;
});
var resultMember = this.MemberPDf.filter(function(result1) {
delete result1.company_branch_id;
delete result1.company_id;
delete result1.dob;
delete result1.enrollment_date;
delete result1.gender;
delete result1.nominee_name;
delete result1.id;
delete result1.title;
delete result1.user_id;
delete result1.member_image
return result1;
});
// result.orderBy(result.transaction_date,result.payment_mode,result.amount,result.transaction_type,result.tranx_id,result.transaction_status)
this.pdfData = [this.table(resultMember,this.memberheader, this.membertableHead),this.table(result, this.tableHeader, this.tableHead)];
let pdf = {
content: [
{ text: 'Your Transaction Details', style: 'header' },
this.pdfData
]
}
var docDefinition = {
content: [
// {
// columns: [
// [
// { text: 'BITCOIN', style: 'header' },
// { text: 'Cryptocurrency Payment System', style: 'sub_header' },
// { text: 'WEBSITE: https://bitcoin.org/', style: 'url' },
// ]
// ],
// },
this.table(resultMember,this.memberheader, this.membertableHead),
this.table(result, this.tableHeader, this.tableHead)
],
styles: {
tableHeader:{
// fontSize: 18,
margin: [ 5, 2, 10, 20 ]
},
// headerRows:{
// fontSize: 68,
// }
},
pageSize: 'A4',
pageOrientation: 'portrait'
};
// pdfMake.createPdf(docDefinition).open();
if(this.plt.is('cordova')){
this.pdfObj = pdfMake.createPdf(docDefinition).getBlob(buffer => {
this.file.resolveDirectoryUrl(this.file.externalDataDirectory)
.then(dirEntry => {
this.file.getFile(dirEntry, 'Transaction.pdf', { create: true })
.then(fileEntry => {
fileEntry.createWriter(writer => {
writer.onwrite = () => {
this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
.then(res => {
console.log("res",res );
})
.catch(err => {
console.log("Bad" );
});
}
writer.write(buffer);
})
})
.catch(err => {
console.log("Bad" );
});
})
.catch(err => {
console.log("Bad" );
});
});
}else{
pdfMake.createPdf(docDefinition).open();
}
}
//END PDF CODE
}
<file_sep>/src/app/pages/bottom-nav/bottom-nav-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BottomNavPage } from './bottom-nav.page';
const routes: Routes = [
{
path: '',
component: BottomNavPage,
children: [
{
path: 'home',
loadChildren: () => import('../home/home.module').then(m => m.HomePageModule)
},
// Routes For Menu Bar
{
path: 'profile',
loadChildren: () => import('../menu/profile/profile.module').then(m => m.ProfilePageModule)
},
{
path: 'cpassword',
loadChildren: () => import('../menu/cpassword/cpassword.module').then(m => m.CpasswordPageModule)
},
{
path: 'loan',
loadChildren: () => import('../menu/loan/loan.module').then(m => m.LoanPageModule)
},
{
path: 'passbook',
loadChildren: () => import('../menu/passbook/passbook.module').then(m => m.PassbookPageModule)
},
{
path: 'security',
loadChildren: () => import('../menu/security/security.module').then(m => m.SecurityPageModule)
},
{
path: 'support',
loadChildren: () => import('../menu/support/support.module').then(m => m.SupportPageModule)
},
{
path: 'tandc',
loadChildren: () => import('../menu/tandc/tandc.module').then(m => m.TandcPageModule)
},
// End Routes For Menu Bar
{
path: 'saving',
loadChildren: () => import('../home/saving/saving.module').then(m => m.SavingPageModule)
},
{
path: 'ol',
loadChildren: () => import('../home/ol/ol.module').then(m => m.OlPageModule)
},
{
path: 'dd/ddview',
loadChildren: () => import('../home/dd/ddview/ddview.module').then(m => m.DdviewPageModule)
},
{
path: 'fd/fdview',
loadChildren: () => import('../home/fd/fdview/fdview.module').then(m => m.FdviewPageModule)
},
{
path: 'rd/rdview',
loadChildren: () => import('../home/rd/rdview/rdview.module').then(m => m.RdviewPageModule)
},
{
path: '/',
redirectTo: 'home'
}
]
},
{
path: '/',
redirectTo: 'home',
pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class BottomNavPageRoutingModule {}
<file_sep>/src/app/pages/login/forgot/cpass/cpass.page.ts
import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-cpass',
templateUrl: './cpass.page.html',
styleUrls: ['./cpass.page.scss'],
})
export class CpassPage implements OnInit {
constructor() { }
ngOnInit() {
$(".toggle-password").click(function() {
$(this).toggleClass("fa-eye fa-eye-slash");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
}
}
<file_sep>/src/app/pages/home/rd/rdview/rdview.page.ts
import { Component, OnInit } from '@angular/core';
import { NavParams, NavController,Platform } from '@ionic/angular';
import { Router, ActivatedRoute } from '@angular/router';
import { ApihelperProvider } from 'src/providers/apihelper/apihelper';
import { CreatePdf } from 'src/providers/CreatePdf';
import { RdResponse } from 'src/providers/Models/MemberRD';
import * as moment from 'moment';
@Component({
selector: 'app-rdview',
templateUrl: './rdview.page.html',
styleUrls: ['./rdview.page.scss'],
})
export class RdviewPage implements OnInit {
RdResponse: RdResponse = [];
constructor(
public navParams: NavParams,
public navCtrl: NavController,
private route: ActivatedRoute,
private provider : ApihelperProvider,
private pdfmake : CreatePdf
) { }
rddata: any;
RdDetails: any;
RdTransactions: any = [];
MemberRdTransactions: any = [];
momentjs: any = moment;
end_date: '';
start_date: '';
pdfObj = null;
ngOnInit(){
this.provider.presentLoading();
}
ionViewDidEnter() {
this.getapidata()
}
getapidata(){
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.rddata = JSON.parse(params.special);
this.provider.MemberRD(this.rddata.type,this.rddata.slug).subscribe(data=>{
this.RdResponse = this.provider.MemberRD_Details(data);
if(this.RdResponse){
this.RdDetails = this.RdResponse.details;
this.RdTransactions = this.RdResponse.transactions;
if(this.RdTransactions){
this.RdTransactions = this.RdResponse.transactions;
}else{
this.RdTransactions = [];
}
}
});
}
});
}
//PDF CODE START
StartDate(){
if(!this.start_date){
console.log(this.start_date);
}
return this.start_date;
}
EndDate(){
if(!this.end_date){
console.log(this.end_date);
}
return this.end_date;
}
Apply_Date(){
if((this.start_date == undefined || this.start_date == '') || (this.end_date == undefined || this.end_date == '') ){
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.rddata = JSON.parse(params.special);
this.provider.MemberSaving(this.rddata.type,this.rddata.slug).subscribe(data=>{
this.MemberRdTransactions = this.provider.MemberSaving_Details(data);
if(this.MemberRdTransactions.length != 0){
this.RdTransactions = this.MemberRdTransactions.transactions;
}else{
this.RdTransactions = [];
}
});
}
});
this.provider.presentToastWithOptions('Please select date first!');
}else{
let start_date = this.momentjs(this.start_date).format("YYYY-MM-DD")
let end_date = this.momentjs(this.end_date).format("YYYY-MM-DD");
this.provider.presentLoading();
this.route.queryParams.subscribe(params => {
if (params && params.special) {
this.rddata = JSON.parse(params.special);
this.provider.MemberRD(this.rddata.type,this.rddata.slug).subscribe(data=>{
this.RdResponse = this.provider.MemberRD_Details(data);
if(this.RdResponse.length != 0){
let RdTransactions1 = this.RdResponse.transactions;
this.RdTransactions = RdTransactions1.filter((item: any) => {
let date = new Date(item.transaction_date);
date = this.momentjs(date).format("YYYY-MM-DD");
return date >= start_date && date <= end_date;
});
if(this.RdTransactions==''){
this.RdTransactions == [];
}
}else{
this.RdTransactions == [];
}
});
}
});
}
}
createPdf() {
this.pdfmake.createPdf(this.RdTransactions);
}
}
<file_sep>/src/providers/Models/Login.ts
export interface loginresponse{
[x : string] : any;
[index : number] : {
status : string;
user_id : string;
type : string;
token : string;
}
} | ce1178b75385236e8ebdfbc5c3d3ff740f1cc4c2 | [
"JavaScript",
"TypeScript",
"HTML"
] | 34 | TypeScript | eligocs/devionic | b87f4e32c8ea610f902b355181b25d5e5c256755 | 630ce47204bf1083a066b67f538239df6425e2bc |
refs/heads/main | <file_sep># go-playground
可以方便运行、格式化和分享 Go 代码,可以实现没有 Go 环境运行 Go 代码。

<file_sep>// Copyright (c) 2020 HigKer
// Open Source: MIT License
// Author: SDing <<EMAIL>>
// Date: 2020/12/15 - 7:49 下午 - UTC/GMT+08:00
package router
import "github.com/gin-gonic/gin"
const (
port = ":8080"
)
//Start 运行Web
func Start() {
r := gin.Default()
mappingView(r)
_ = r.Run(port)
}
<file_sep>// Copyright (c) 2020 HigKer
// Open Source: MIT License
// Author: SDing <<EMAIL>>
// Date: 2020/12/15 - 7:39 下午 - UTC/GMT+08:00
package main
import "github.com/higker/go-playground/router"
func main() {
router.Start()
}<file_sep>package handler
import "github.com/gin-gonic/gin"
var _ gin.HandlerFunc = Compile
// Compile provide function for compile go code
func Compile(ctx *gin.Context) {
//TODO
}
<file_sep>// Copyright (c) 2020 HigKer
// Open Source: MIT License
// Author: SDing <<EMAIL>>
// Date: 2020/12/15 - 7:58 下午 - UTC/GMT+08:00
package router
import (
"github.com/gin-gonic/gin"
"net/http"
)
var (
linkView = func(c *gin.Context) {
c.HTML(http.StatusOK, "link.html", gin.H{})
}
editorView = func(c *gin.Context) {
c.HTML(http.StatusOK, "editor.html", gin.H{})
}
)
// mappingView 映射view视图
func mappingView(r *gin.Engine) {
r.StaticFS("/static", http.Dir("static"))
//加载模板
r.LoadHTMLGlob("template/*")
r.GET("/", editorView)
r.GET("/index.html", editorView)
r.GET("/link", linkView)
}
<file_sep>package router
import (
"github.com/gin-gonic/gin"
"github.com/higker/go-playground/handler"
)
// mappingCompiler mapping router for go compiler
func mappingCompiler(r *gin.Engine) {
//TODO
r.POST("/compile", handler.Compile)
}
| 72ad7e08771cb02ccb2fd79721319287e5f42020 | [
"Markdown",
"Go"
] | 6 | Markdown | k8battleship/go-playground | 46337339450d38b1112c77763e4266e8763447d2 | 02903a9ed31dc497b5d7be42527648161ee3f48b |
refs/heads/master | <file_sep>require 'test_helper'
class ColorsControllerTest < ActionController::TestCase
test "should get display" do
get :display
assert_response :success
end
test "should get score" do
post :score, {:original_color => '#fff',:players_color => '#fff'}
assert_response :success
end
test "score is appropriate (worst)" do
post :score, {:original_color => '#000',:players_color => '#fff'}
assert_in_delta(0, assigns(:score), 0.001)
end
test "score is appropriate (best)" do
post :score, {:original_color => '#000',:players_color => '#000'}
assert_in_delta(100, assigns(:score), 0.001)
end
end
<file_sep>class Color < ActiveRecord::Base
MAX = 15 * 3**0.5
def self.generate_colors(digits)
# btw make sure digits come in as strings
# initialize arrays; one for an array of one digit hex codes, e.g., ['0','5','a']
ones = []
# another for two digit hex codes, eg, ['00','05','0a','50',...]; and one for the final three digit codes
twos = []
rgbval_array = []
# just in case, sort digits (this will mainly be useful for the string that will later replace 'custom' with, eg. '05a')
digits.sort!
digits.each do |digit|
ones << digit
end
ones.each do |first_digit|
digits.each do |digit|
twos << first_digit + digit
end
end
twos.each do |first_two|
digits.each do |digit|
rgbval_array << first_two + digit
end
end
# rgbval_array = ['555','55a','5a5','aa5'] #initial static test array
rgbval_array.each do |rgbval|
# stop filling array with multiple copies of same color!
# modified this, as dont want to avoid creating of colors in custom set
# that also exist in other sets
unless Color.find_by(rgbvalue: rgbval, difficulty_level: "custom")
Color.create [{rgbvalue: rgbval, difficulty_level: "custom"}]
end
end
end
def color_difference(players_rgbvalue)
# magnitude of the vector difference a-b
# for 3-digit hex rgb strings thought of as vectors
total = 0.0
rgbvalue.length.times do |i|
total += (rgbvalue[i].to_i(16)-players_rgbvalue[i].to_i(16))**2
end
total = total ** 0.5
score = (MAX- total) * 100 /MAX
#puts score
# as bad as you can get -- 15 off on each color component --
# minus what you got, normalized to the maximum, times 100 to give percent
end
def is_dark?
# darkness -- green << red << blue so do a weighted average when deciding to go to white lettering
total = 0.0
color_weight = [2,3,1]
rgbvalue.length.times do |i|
total += rgbvalue[i].to_i(16) * color_weight[i]
end
total/color_weight.sum < 6
end
end
<file_sep>module ColorsHelper
def singularize_are(num)
return "are" if num > 1
return "is" if num == 1
end
end
<file_sep># Be sure to restart your server when you modify this file.
Hex::Application.config.session_store :cookie_store, key: '_hex_session'
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Color.create [{rgbvalue: '000', difficulty_level: 'easy'} ,
{rgbvalue: 'fff', difficulty_level: 'easy'},
{rgbvalue: 'f00', difficulty_level: 'easy'},
{rgbvalue: '00f', difficulty_level: 'easy'},
{rgbvalue: '0f0', difficulty_level: 'easy'},
{rgbvalue: '0ff', difficulty_level: 'easy'},
{rgbvalue: 'ff0', difficulty_level: 'easy'},
{rgbvalue: 'f0f', difficulty_level: 'easy'},
{rgbvalue: '007', difficulty_level: 'medium'},
{rgbvalue: '700', difficulty_level: 'medium'},
{rgbvalue: '070', difficulty_level: 'medium'},
{rgbvalue: '770', difficulty_level: 'medium'},
{rgbvalue: '077', difficulty_level: 'medium'},
{rgbvalue: '707', difficulty_level: 'medium'},
{rgbvalue: '777', difficulty_level: 'medium'},
{rgbvalue: 'ff7', difficulty_level: 'medium'},
{rgbvalue: '7ff', difficulty_level: 'medium'},
{rgbvalue: 'f7f', difficulty_level: 'medium'},
{rgbvalue: '77f', difficulty_level: 'medium'},
{rgbvalue: 'f77', difficulty_level: 'medium'},
{rgbvalue: '7f7', difficulty_level: 'medium'},
{rgbvalue: '0f7', difficulty_level: 'medium'},
{rgbvalue: 'f07', difficulty_level: 'medium'},
{rgbvalue: '7f0', difficulty_level: 'medium'},
{rgbvalue: '70f', difficulty_level: 'medium'},
{rgbvalue: 'f70', difficulty_level: 'medium'},
{rgbvalue: '07f', difficulty_level: 'medium'},
{rgbvalue: '004', difficulty_level: 'hard'},
{rgbvalue: '400', difficulty_level: 'hard'},
{rgbvalue: '040', difficulty_level: 'hard'},
{rgbvalue: '440', difficulty_level: 'hard'},
{rgbvalue: '044', difficulty_level: 'hard'},
{rgbvalue: '404', difficulty_level: 'hard'},
{rgbvalue: '444', difficulty_level: 'hard'},
{rgbvalue: 'ff4', difficulty_level: 'hard'},
{rgbvalue: '4ff', difficulty_level: 'hard'},
{rgbvalue: 'f4f', difficulty_level: 'hard'},
{rgbvalue: '44f', difficulty_level: 'hard'},
{rgbvalue: 'f44', difficulty_level: 'hard'},
{rgbvalue: '4f4', difficulty_level: 'hard'},
{rgbvalue: '0f4', difficulty_level: 'hard'},
{rgbvalue: 'f04', difficulty_level: 'hard'},
{rgbvalue: '4f0', difficulty_level: 'hard'},
{rgbvalue: '40f', difficulty_level: 'hard'},
{rgbvalue: 'f40', difficulty_level: 'hard'},
{rgbvalue: '04f', difficulty_level: 'hard'},
{rgbvalue: '009', difficulty_level: 'hard'},
{rgbvalue: '900', difficulty_level: 'hard'},
{rgbvalue: '090', difficulty_level: 'hard'},
{rgbvalue: '990', difficulty_level: 'hard'},
{rgbvalue: '099', difficulty_level: 'hard'},
{rgbvalue: '909', difficulty_level: 'hard'},
{rgbvalue: '999', difficulty_level: 'hard'},
{rgbvalue: 'ff9', difficulty_level: 'hard'},
{rgbvalue: '9ff', difficulty_level: 'hard'},
{rgbvalue: 'f9f', difficulty_level: 'hard'},
{rgbvalue: '99f', difficulty_level: 'hard'},
{rgbvalue: 'f99', difficulty_level: 'hard'},
{rgbvalue: '9f9', difficulty_level: 'hard'},
{rgbvalue: '0f9', difficulty_level: 'hard'},
{rgbvalue: 'f09', difficulty_level: 'hard'},
{rgbvalue: '9f0', difficulty_level: 'hard'},
{rgbvalue: '90f', difficulty_level: 'hard'},
{rgbvalue: 'f90', difficulty_level: 'hard'},
{rgbvalue: '09f', difficulty_level: 'hard'},
{rgbvalue: '049', difficulty_level: 'hard'},
{rgbvalue: '094', difficulty_level: 'hard'},
{rgbvalue: '490', difficulty_level: 'hard'},
{rgbvalue: '940', difficulty_level: 'hard'},
{rgbvalue: '409', difficulty_level: 'hard'},
{rgbvalue: '904', difficulty_level: 'hard'},
{rgbvalue: 'f49', difficulty_level: 'hard'},
{rgbvalue: 'f94', difficulty_level: 'hard'},
{rgbvalue: '49f', difficulty_level: 'hard'},
{rgbvalue: '94f', difficulty_level: 'hard'},
{rgbvalue: '4f9', difficulty_level: 'hard'},
{rgbvalue: '9f4', difficulty_level: 'hard'},
{rgbvalue: '449', difficulty_level: 'hard'},
{rgbvalue: '494', difficulty_level: 'hard'},
{rgbvalue: '944', difficulty_level: 'hard'},
{rgbvalue: '994', difficulty_level: 'hard'},
{rgbvalue: '949', difficulty_level: 'hard'},
{rgbvalue: '499', difficulty_level: 'hard'}
]
<file_sep>class AddDifficultyLevelToColors < ActiveRecord::Migration
def change
add_column :colors, :difficulty_level, :string
end
end
<file_sep>class ColorsController < ApplicationController
# MAX = 15 * 3**0.5
def display
@difficulty = params[:difficulty]
if @difficulty == "custom"
Color.generate_colors(['3','a'])
end
do_display_work
end
def timer_toggle
session[:timer] = !session[:timer]
@difficulty = session[:difficulty]
reset_redirect
end
def fresh
# start a fresh game
@difficulty = params[:difficulty] || "easy"
reset_redirect
end
def score
@computer_color = Color.find(params[:computer_color_id])
@players_rgbvalue = params[:players_rgbvalue].gsub(/[#]/, '')
#allow player to input colors with or without # in front
@score = @computer_color.color_difference(@players_rgbvalue)
session[:cumulative_score] += @score
session[:max_possible_score] += 100
@difficulty = session[:difficulty]
@colors_left = session[:num_colors]
if @difficulty == 'custom' && @colors_left == 0
# clear custom colors if a custom game is finished
Color.where({difficulty_level: 'custom'}).destroy_all
end
session[:elapsed_time] = Time.now - session[:start_time]
if session[:timer] && session[:elapsed_time] != 0
session[:time_bonus] = session[:time_bonus] + (10-session[:elapsed_time])*10
end
set_timer_and_score_instance_variables
respond_to do |format|
format.html { }
format.js { }
end
end
def help
# since layout uses a color object to set background color, pull up color 2 (white) for background of help page
@computer_color = Color.find(2)
end
# def custom
# # Color.create [{rgbvalue: 'c5c', difficulty_level: 'custom'}]
# # # need to set up a session_array of custom colors and then pick them one by one
# # # but first test with 1
# # @computer_color = Color.find_by(rgbvalue: 'c5c')
# Color.generate_colors
# @difficulty = "custom"
# do_display_work
# end
def visualize
# since we don't count on the user putting a #, strip it off if it is there and put it back on
@see_this_color = '#'+params[:see_this_color].gsub(/[#]/, '')
@computer_color = Color.find(2)
# not very dry, but have to keep this color defined
respond_to do |format|
format.html { }
format.js { }
end
end
private
def make_session_array_if_needed
# make it unless it already exists
unless session[:color_array]
# to maintain memory of color set within a minigame we create a shuffled array once and then reuse it till all the colors are gone
computer_color_array = Color.where({difficulty_level: @difficulty }).shuffle
# we create a color array to store in the session because the object array is too big
color_array = []
# for each color object, we push its rgbvalue into color array
computer_color_array.each do |color_obj|
color_array << color_obj.rgbvalue
end
session[:color_array] = color_array
# store the number of colors so we can deal with what happens when we run out of colors in a set
session[:num_colors] = color_array.length
# initialize the score variables
session[:cumulative_score] = 0
session[:max_possible_score] = 0
end
end
def set_timer_and_score_instance_variables
@timer = session[:timer]
@cumulative_score = session[:cumulative_score] if session[:cumulative_score]
@max_possible_score = session[:max_possible_score] if session[:max_possible_score]
@time_bonus = session[:time_bonus]
end
def reset_redirect
# clear the custom colors in case this wasn't done on game finish because game wasnt finished
Color.where({difficulty_level: 'custom'}).destroy_all
session[:color_array] = nil
session[:cumulative_score] = nil
session[:max_possible_score] = nil
session[:time_bonus] = 0
session[:elapsed_time] = 0
session[:start_time] = Time.now if session[:timer]
redirect_to color_path(@difficulty)
end
def do_display_work
session[:difficulty] = @difficulty
make_session_array_if_needed
@computer_color = Color.find_by(rgbvalue: session[:color_array].slice!(0))
# decrement number of colors left in session
session[:num_colors] -= 1
set_timer_and_score_instance_variables
session[:start_time] = Time.now if session[:timer]
respond_to do |format|
format.html { }
format.js { }
end
end
end
| 22f4c73d4e524b351238c3315322a032fb7ba883 | [
"Ruby"
] | 7 | Ruby | pjfranzini/hex | 2df65cd87eb7174e8a2d3c6be97d3ec0c0df5757 | a44fecc508af5a77859bed1d2576b089dbd58f2e |
refs/heads/master | <repo_name>dytlzl/ktube_django<file_sep>/vuefois/views.py
from django.shortcuts import render, get_object_or_404
from .models import Video
def ranking(request):
videos = Video.objects.all().order_by('-view_count')[:100]
return render(request, 'vuefois/ranking.html', {'videos': videos})
<file_sep>/vuefois/apps.py
from django.apps import AppConfig
class VuefoisConfig(AppConfig):
name = 'vuefois'
<file_sep>/vuefois/models.py
from django.db import models
class Video(models.Model):
video_id = models.CharField(max_length=100)
title = models.CharField(max_length=200)
channel_id = models.CharField(max_length=100)
channel_name = models.CharField(max_length=200)
view_count = models.IntegerField()
def __str__(self):
return self.title
<file_sep>/register.py
import sys
import os
import requests
import private
import django
sys.path.append("ktube")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ktube.settings")
django.setup()
class YouTube:
API_BASE_URI = 'https://www.googleapis.com/youtube/v3/'
API_KEY = private.API_KEY
RESOURCE = 'videos'
DEFAULT_PARAMS = {
'key': API_KEY,
'part': 'snippet',
'maxResults': 50
}
def __init__(self, params={}):
self.items = []
self.united_items = []
self.uri = self.API_BASE_URI+self.RESOURCE
self.params = dict(self.DEFAULT_PARAMS)
if params != {}:
self.params.update(params)
self.has_remaining_data = True
def fetch_data(self):
res = self.fetch_json()
remaining_data_count = res['pageInfo']['totalResults']-res['pageInfo']['resultsPerPage']
try:
self.params['pageToken'] = res['nextPageToken']
except KeyError:
pass
while remaining_data_count > 0:
additional_res = self.fetch_json()
res['items'] += additional_res['items']
remaining_data_count -= res['pageInfo']['resultsPerPage']
try:
self.params['pageToken'] = additional_res['nextPageToken']
except KeyError:
pass
return res['items']
def fetch_items(self):
res = self.fetch_json()
if len(res['items']) != 0:
self.items = res['items']
self.has_remaining_data = True if len(res['items']) == self.params['maxResults'] else False
if self.has_remaining_data:
try:
self.params['pageToken'] = res['nextPageToken']
except KeyError:
self.has_remaining_data = False
return True
else:
return False
def iterate_data(self):
while self.fetch_items():
for i in self.items:
yield i
if not self.has_remaining_data:
break
def fetch_json(self):
res = requests.get(self.uri, params=self.params)
return res.json()
class Videos(YouTube):
RESOURCE = 'videos'
def fetch_statistics(self, video_id):
params = {
'id': video_id,
'part': 'snippet,statistics',
'fields': 'items(snippet(channelId,channelTitle),statistics(viewCount,likeCount,dislikeCount,commentCount))'
}
self.params.update(params)
res = self.fetch_json()
return res['items'][0]
class Search(YouTube):
RESOURCE = 'search'
class Playlists(YouTube):
RESOURCE = 'playlists'
class PlaylistItems(YouTube):
RESOURCE = 'playlistItems'
class Main:
PLAYLISTS = private.PLAYLISTS
def __init__(self):
self.videos = []
def fetch_data(self):
for playlist in self.PLAYLISTS:
params = {
'playlistId': playlist,
'part': 'snippet',
'fields': 'pageInfo,nextPageToken,items(snippet(title,resourceId(videoId)))'
}
ytp = PlaylistItems(params)
pi = ytp.fetch_data()
for j in pi:
jt = j['snippet']['title']
if 'MV' in jt or 'M/V' in jt:
vi = j
ytv = Videos(params)
st = ytv.fetch_statistics(j['snippet']['resourceId']['videoId'])
vi['statistics'] = st['statistics']
vi['snippet'].update(st['snippet'])
self.videos.append(vi)
print('Fetched '+playlist)
def register_data(self):
from vuefois.models import Video
Video.objects.all().delete()
print('Deleted old data.')
for video in self.videos:
Video.objects.create(video_id=video['snippet']['resourceId']['videoId'],
title=video['snippet']['title'],
channel_id=video['snippet']['channelId'],
channel_name=video['snippet']['channelTitle'],
view_count=int(video['statistics']['viewCount']))
print('Registered new data.')
def main(self):
self.fetch_data()
self.register_data()
def main():
instance = Main()
instance.main()
if __name__ == '__main__':
main()
<file_sep>/vuefois/templates/vuefois/ranking.html
{% extends 'vuefois/base.html' %}
{% block content %}
<table class="table table-striped">
<thead><tr><th>#</th><th>Thumbnail</th><th>Title</th><th>Channel</th><th>View Count</th></tr></thead>
<tbody>
{% for video in videos %}
<tr>
<td>{{ forloop.counter }}</td>
<td><a href="https://www.youtube.com/watch?v={{ video.video_id }}"><img src="http://img.youtube.com/vi/{{ video.video_id }}/default.jpg" width="120" height="90" /></a></td>
<td><a href="https://www.youtube.com/watch?v={{ video.video_id }}">{{ video.title }}</a></td>
<td><a href="https://www.youtube.com/channel/{{ video.channel_id }}">{{ video.channel_name }}</a></td>
<td>{{ video.view_count }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %} | faf8891b6de309e19b1ffce9cb36afd295966b34 | [
"Python",
"HTML"
] | 5 | Python | dytlzl/ktube_django | 4b56cd65cb8f0597a3c3a0078579d083b7b5b3a3 | c310c866c1f5e22615d639e2527e514ef9170f37 |
refs/heads/main | <file_sep>
const games_Data= require("../datas/games.json");
module.exports.getGames= function(req, res) {
res.status(200).json(games_Data);
}
<file_sep>
const express= require("express");
const numsController= require("../controller/number.controller");
const router= express.Router();
router.route('/:num1').get(numsController.summingNumbers);
module.exports= router;
<file_sep># MWA--Day02<file_sep>
module.exports.summingNumbers= function(req, res){
const number1 = parseInt(req.params.num1);
const number2=parseInt(req.query.num2);
const sum = (number1+number2);
res.status(200).json({ Result: number1+number2 });
}
| 12d07be8171697b387d096e9bdbb68d736904594 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | nproscovia/MWA--Day02 | 2c716813debe6d073388c7822a4d155bfb113e25 | 37d945b0e4393e8e27e57ed5f336b41cedf186b1 |
refs/heads/main | <repo_name>ryoji-U/php-portfolio<file_sep>/loginYet/comment_detail_loginYet.php
<?php
/*これだけでもIDを表示可能
$id = $_GET['id'];
echo $id;
*/
/***********************************/
session_start();
require_once ('../child_classes/comment.php');
require_once ('../child_classes/instagram.php');
/*
//ログインされているか判断
$result = Comment::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
$login_user = $_SESSION['login_user'];
*/
/*********************************/
require_once ('../header_loginYet.php');
$comment = new Comment();
$result = $comment->getComments($_GET['id']);
//$login_user = $result['login_user'];
//$username = $login_user['username'];
/*************↓コメントフォームのphp**************/
$instagram = new instagram();
$post_result = $instagram->getById($_GET['id']);
$content = $post_result['content'];
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>udastagram</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
</head>
<body>
<section id="comment_detailphp">
<h2>コメントページ</h2>
<section class="spacer_50"></section>
<!--最新の投稿を一番上に表示するためのソート-->
<?php arsort($result);?>
<h3>本文:</h3>
<div class="comment-text"><p><?php echo nl2br($content);?></p></div>
<div class="spacer_50"></div>
<h3>コメント:</h3>
<?php if(!$result){echo ('コメントがありません。');}?>
<?php if($result):?><div class="comment-text"><?php endif;?>
<?php foreach($result as $details):?>
<!--コメント者名を設置-->
<?php $postUser = $comment->postUser($details['user_id'])?>
<!--投稿者名-->
<h3>
<?php if(isset($postUser[0]['username'])):?>
<?php echo $postUser[0]['username']?>
<?php else:?>
NoNAME
<?php endif;?>
</h3>
<p><?php echo nl2br($details['content']);?></p>
<!--コメントに対するリプライを表示-->
<?php $reply_all = $comment->getReply($details['id']);?>
<?php if($reply_all):?>
<?php foreach($reply_all as $reply):?>
<section class="spacer_10"></section>
<div class="reply-content">
<?php $replyUser = $comment->replyUser($reply['user_id']);?>
<h3>
<?php if(isset($replyUser[0]['username'])):?>
<?php echo $replyUser[0]['username']?>
<?php else:?>
NoNAME
<?php endif;?>
</h3>
<p><?php echo nl2br($reply['content']);?></p>
</div>
<?php endforeach;?>
<?php endif;?>
<section class="spacer_30"></section>
<?php endforeach;?>
<?php if($result):?></div><?php endif;?>
<section class="spacer_50"></section>
<div class="return-btn"><a href="./index_loginYet.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</body>
</html>
<file_sep>/child_classes/slide.php
<?php
require_once ('../dbc.php');
require_once ('instagram.php');
//extendsだと、その後のクラスの中身を引き継いだものとなる
class Slide extends Instagram{
protected $table_name = 'slide';
//スライダー制作メソッド
public function slideCreateMethod($instagrams,$userId){
//スライド1を制作
$this->slide0Create($instagrams['slides'],$instagrams['id'],$userId,$instagrams['images']);
//スライド1のIDを取得
$slide_id = $this->getSlideId($instagrams['id']);
//スライド2~8を制作
for($i=0;$i<8;$i++){
if(empty($instagrams['slides'][$i])){
$instagrams['slides'][$i] = null;
}
}
if($instagrams['slides'][0]){
$instagrams['slides'][0] = "../images/".$instagrams['slides'][0];
$this->slide1Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][1]){
$instagrams['slides'][1] = "../images/".$instagrams['slides'][1];
$this->slide1Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][2]){
$instagrams['slides'][2] = "../images/".$instagrams['slides'][2];
$this->slide2Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][3]){
$instagrams['slides'][3] = "../images/".$instagrams['slides'][3];
$this->slide3Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][4]){
$instagrams['slides'][4] = "../images/".$instagrams['slides'][4];
$this->slide4Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][5]){
$instagrams['slides'][5] = "../images/".$instagrams['slides'][5];
$this->slide5Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][6]){
$instagrams['slides'][6] = "../images/".$instagrams['slides'][6];
$this->slide6Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][7]){
$instagrams['slides'][7] = "../images/".$instagrams['slides'][7];
$this->slide7Create($instagrams['slides'],$slide_id['id']);
}
}
//スライダーが存在するかチェックする
public function checkSlide($postId){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM $this->table_name
WhERE post_id = :id";
//SQLの準備
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',(INT)$postId,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//結果を取得
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
}
public function slideUpdateMethod($instagrams,$userId){
if(count($instagrams['slides']) > 7){
echo " s<section class='return-btn-all'>
スライダーの画像を7枚以下にしてください。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
//どこのスライダーか判別
$slide_id = $this->getSlideId($instagrams['id']);
//スライド1~8をアップデート
for($i=0;$i<8;$i++){
if(empty($instagrams['slides'][$i])){
$instagrams['slides'][$i] = null;
}
}
$this->slide0Update($instagrams['slides'],$slide_id['id'],$instagrams['images']);
if($instagrams['slides'][0]){
$instagrams['slides'][0] = "../images/".$instagrams['slides'][0];
$this->slide1Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][1]){
$instagrams['slides'][1] = "../images/".$instagrams['slides'][1];
$this->slide2Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][2]){
$instagrams['slides'][2] = "../images/".$instagrams['slides'][2];
$this->slide3Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][3]){
$instagrams['slides'][3] = "../images/".$instagrams['slides'][3];
$this->slide4Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][4]){
$instagrams['slides'][4] = "../images/".$instagrams['slides'][4];
$this->slide5Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][5]){
$instagrams['slides'][5] = "../images/".$instagrams['slides'][5];
$this->slide6Create($instagrams['slides'],$slide_id['id']);
}
if($instagrams['slides'][6]){
$instagrams['slides'][6] = "../images/".$instagrams['slides'][6];
$this->slide7Create($instagrams['slides'],$slide_id['id']);
}
/*if($instagrams['slides'][7]){
$instagrams['slides'][7] = "../images/".$instagrams['slides'][7];
$this->slide7Create($instagrams['slides'],$slide_id['id']);
}*/
}
//投稿削除機能
public function slideDelete($instagrams){
if(count($instagrams['slides']) > 7){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
スライダーの画像を7枚以下にしてください。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$sql = "UPDATE $this->table_name SET
image_1 = null,image_2 = null,image_3 = null,image_4 = null,image_5 = null,image_6 = null,image_7 = null
WHERE
post_id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$instagrams['id'],PDO::PARAM_INT);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
public function slidePermanentlyDelete($instagrams){
$dbh = $this->dbConnect();
$sql = "DELETE
FROM $this->table_name
WHERE post_id = :id";
//SQLの準備
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',(INT)$instagrams['id'],PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//echo 'ブログを削除しました';
}
//スライダーの順番を変更
public function slideNumberEdit($slideNum,$post_id,$instagrams){
$dbh = $this->dbConnect();
//スライダーの情報を取得
$slide_id = $this->getSlideId($instagrams['id']);
if(empty($slideNum[0])){
}elseif($slideNum[0]){
//$slideNum[0] = "../images/".$slideNum[0];
$this->slide0NumUpdate($slideNum,$slide_id['id']);
}
if(empty($slideNum[1])){
}elseif($slideNum[1]){
//$slideNum[1] = "../images/".$slideNum[1];
$this->slide1NumUpdate($slideNum,$slide_id['id']);
}
if(empty($slideNum[2])){
}elseif($slideNum[2]){
//$slideNum[2] = "../images/".$slideNum[2];
$this->slide2NumUpdate($slideNum,$slide_id['id']);
}
if(empty($slideNum[3])){
}elseif($slideNum[3]){
//$slideNum[3] = "../images/".$slideNum[3];
$this->slide3NumUpdate($slideNum,$slide_id['id']);
}
if(empty($slideNum[4])){
}elseif($slideNum[4]){
//$slideNum[4] = "../images/".$slideNum[4];
$this->slide4NumUpdate($slideNum,$slide_id['id']);
}
if(empty($slideNum[5])){
}elseif($slideNum[5]){
//$slideNum[5] = "../images/".$slideNum[5];
$this->slide5NumUpdate($slideNum,$slide_id['id']);
}
if(empty($slideNum[6])){
}elseif($slideNum[6]){
//$slideNum[6] = "../images/".$slideNum[6];
$this->slide6NumUpdate($slideNum,$slide_id['id']);
}
if(empty($slideNum[7])){
}elseif($slideNum[7]){
//$slideNum[7] = "../images/".$slideNum[6];
$this->slide7NumUpdate($slideNum,$slide_id['id']);
}
}
//-----------------------------------------------------------------------
//スライド1
public function slide0Create($slides,$postId,$userId,$image){
if(count($slides) > 7){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
スライダーの画像を7枚以下にしてください。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$sql = "INSERT INTO
$this->table_name(post_id, user_id, image_0)
VALUES
(:postId, :userId, :slides0)";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':postId',$postId,PDO::PARAM_INT);
$stmt->bindValue(':userId',$userId,PDO::PARAM_INT);
$stmt->bindValue(':slides0',$image,PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライドIDを取得
public function getSlideId($postId){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM $this->table_name
WhERE post_id = :id";
//SQLの準備
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',(INT)$postId,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//結果を取得
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
}
public function slide0Update($slides,$id,$image){
$sql = "UPDATE $this->table_name SET
image_0 = :slides0
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides0',$image,PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド2
public function slide1Create($slides,$id){
$sql = "UPDATE $this->table_name SET
image_1 = :slides1
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides1',$slides[0],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド3
public function slide2Create($slides,$id){
$sql = "UPDATE $this->table_name SET
image_2 = :slides2
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides2',$slides[1],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド4
public function slide3Create($slides,$id){
$sql = "UPDATE $this->table_name SET
image_3 = :slides3
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides3',$slides[2],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド5
public function slide4Create($slides,$id){
$sql = "UPDATE $this->table_name SET
image_4 = :slides4
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides4',$slides[3],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド6
public function slide5Create($slides,$id){
$sql = "UPDATE $this->table_name SET
image_5 = :slides5
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides5',$slides[4],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド7
public function slide6Create($slides,$id){
$sql = "UPDATE $this->table_name SET
image_6 = :slides6
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides6',$slides[5],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド8
public function slide7Create($slides,$id){
$sql = "UPDATE $this->table_name SET
image_7 = :slides7
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides7',$slides[6],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//-----------------------------------------------------------------------
//スライド順番変更
//スライド1$this->slide0NumUpdate($slideNum,$post_id);
public function slide0NumUpdate($slides,$id){
$sql = "UPDATE $this->table_name SET
image_0 = :slides0
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides0',$slides[0],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド2
public function slide1NumUpdate($slides,$id){
$sql = "UPDATE $this->table_name SET
image_1 = :slides1
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides1',$slides[1],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド3
public function slide2NumUpdate($slides,$id){
$sql = "UPDATE $this->table_name SET
image_2 = :slides2
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides2',$slides[2],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド4
public function slide3NumUpdate($slides,$id){
$sql = "UPDATE $this->table_name SET
image_3 = :slides3
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides3',$slides[3],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド5
public function slide4NumUpdate($slides,$id){
$sql = "UPDATE $this->table_name SET
image_4 = :slides4
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides4',$slides[4],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド6
public function slide5NumUpdate($slides,$id){
$sql = "UPDATE $this->table_name SET
image_5 = :slides5
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides5',$slides[5],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド7
public function slide6NumUpdate($slides,$id){
$sql = "UPDATE $this->table_name SET
image_6 = :slides6
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides6',$slides[6],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//スライド8
public function slide7NumUpdate($slides,$id){
$sql = "UPDATE $this->table_name SET
image_7 = :slides7
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',$id,PDO::PARAM_INT);
$stmt->bindValue(':slides7',$slides[7],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
}
?><file_sep>/login/public/login.php
<?php
//require_once('../../header.php');
session_start();
require_once ('../../header.php');
require_once ('../classes/userLogic.php');
//
$err = [];
//バリデーション
if(!$email = filter_input(INPUT_POST,'email')){
$err['email'] = 'メールアドレスを入力してください。';
}
if(!$password = filter_input(INPUT_POST,'password')){
$err['password'] = 'パスワードを入力してください。';
}
//ログイン処理
if(count($err) > 0){
$_SESSION = $err;
header('Location: login_form.php');
return;
}
//else
$result = UserLogic::login($email,$password);
//ログイン失敗時の処理
if(!$result){
header('Location: login_form.php');
return;
}
$now_year = date('Y');
$now_month = date('m');
header("Location:../../public/index.php?year=$now_year&month=$now_month");
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>udastagram</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../..//css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
</head>
<body>
<section id="loginphp">
<section class="spacer_50"></section>
<h2>ようこそインスタグラムへ</h2>
<a href="../../public/index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>" class="selfinput send-btn">トップページ</a>
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/public/update_form.php
<?php
/***********************************/
session_start();
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
$login_user = $_SESSION['login_user'];
/*********************************/
require_once ('../header.php');
$instagram = new instagram();
$result = $instagram->getById($_GET['id']);
$id = $result['id'];
$title = $result['title'];
$slide0 = $result['slide0'];
$slide1 = $result['slide1'];
$slide2 = $result['slide2'];
$slide3 = $result['slide3'];
//$slide4 = $result['slide4'];
//$slide5 = $result['slide5'];
//$slide6 = $result['slide6'];
//$slide7 = $result['slide7'];
$movie = $result['movie'];
$content = $result['content'];
$category = (int)$result['category'];
$publish_status = (int)$result['publish_status'];
$post_address = $result['post_address'];
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="update_formphp">
<h2>更新フォーム</h2>
<section class="spacer_30"></section>
<form action="instagram_update.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?php echo $id?>">
<!--新しい画像を挿入する場合-->
<!--スライド ドラッグ&ドロップ-->
<h3>画像:</h3>
<div id="drag-drop-area">
<div class="drag-drop-inside">
<p class="drag-drop-info">ここにファイルをドロップ</p>
<p class="drag-drop-buttons">
<input id="fileSize" type="file" value="ファイルを選択" class="hidden" name="file[]" multiple="multiple">
</p>
<div id="previewArea"></div>
</div>
</div>
<!--スマホ版画像挿入方法-->
<div id="drag-drop-areaSP">
<input id="fileSizeSP" type="file" value="ファイルを選択" class="hidden" name="fileSP[]" multiple="multiple" accept="image/*;capture=camera">
<div id="previewAreaSP"></div>
</div>
<section class="spacer_30"></section>
<!--スライド ドラッグ&ドロップ-->
<h3>現在の画像:</h3>
<section id="updateArea">
<section>
<div class="update-slide-display"><img src="<?php echo $slide0?>"></div>
<input type="hidden" name="beforeSlide[]" value="<?php echo $slide0?>">
</section>
<section>
<?php if($slide1):?>
<div class="update-slide-display"><img src="<?php echo $slide1?>"></div>
<input type="hidden" name="beforeSlide[]" value="<?php echo $slide1?>">
<?php endif;?>
</section>
<section>
<?php if($slide2):?>
<div class="update-slide-display"><img src="<?php echo $slide2?>"></div>
<input type="hidden" name="beforeSlide[]" value="<?php echo $slide2?>">
<?php endif;?>
</section>
<section>
<?php if($slide3):?>
<div class="update-slide-display"><img src="<?php echo $slide3?>"></div>
<input type="hidden" name="beforeSlide[]" value="<?php echo $slide3?>">
<?php endif;?>
</section>
</section>
<section class="spacer_30"></section>
<!--動画 ドラッグ&ドロップ-->
<!--
<h3>動画:</h3>
<div id="drag-drop-area-movie">
<div class="drag-drop-inside">
<p class="drag-drop-info">ここにファイルをドロップ</p>
<p class="drag-drop-buttons">
<input id="fileSize_movie" type="file" value="ファイルを選択" class="hidden" name="video" accept="video/*;capture=camera">
</p>
<div id="previewArea_movie"></div>
</div>
</div>
-->
<?php if($movie):?>
<section>
<div class="update-movie-display"><video src="<?php echo $movie?>" controls></video></div>
<input type="hidden" name="beforeMovie" value="<?php echo $movie?>">
</section>
<div class="movie-delete">
動画を削除しますか?
<input type="radio" name="video_delete" value="0" class="selfinput" checked>いいえ
<input type="radio" name="video_delete" value="1" class="selfinput">はい
</div>
<?php endif;?>
<!--動画 ドラッグ&ドロップ-->
<h3>タイトル:</h3>
<input type="text" name="title" value="<?php echo $title?>" class="selfinput text">
<section class="spacer_30"></section>
<h3>本文:</h3>
<textarea name="content" id="content" class="selfinput text" cols="30" rows="10"><?php echo $content?></textarea>
<section class="spacer_30"></section>
<h3>カテゴリ:</h3>
<select name="category" class="selfinput selectbox">
<option value="1" class="selfinput selectbox" <?php if($category === 1)echo "selected"?>>グルメ</option>
<option value="2" class="selfinput selectbox" <?php if($category === 2)echo "selected"?>>観光</option>
<option value="3" class="selfinput selectbox" <?php if($category === 3)echo "selected"?>>アクティブ</option>
<option value="4" class="selfinput selectbox" <?php if($category === 4)echo "selected"?>>その他</option>
</select>
<section class="spacer_30"></section>
<h3>住所(任意)</h3>
<input type="text" name="post_address" class="selfinput text" placeholder="東京都世田谷区池尻3-1-3" value="<?php echo $post_address?>">
<section class="spacer_30"></section>
<input type="radio" name="publish_status" value="1" class="selfinput" <?php if($publish_status === 1)echo "checked"?>>公開
<input type="radio" name="publish_status" value="2" class="selfinput" <?php if($publish_status === 2)echo "checked"?>>下書き保存
<section class="spacer_30"></section>
<input type="submit" value="更新" class="selfinput send-btn">
</form>
<div class="spacer_30"></div>
<section class="spacer_50"></section>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</section>
<section class="spacer_50"></section>
</section>
<script src="../js/slide_add.js"></script>
<script src="../js/slide_addSP.js"></script>
<!--動画 ドラッグ&ドロップ-->
<!--
<script src="../js/movie_add.js"></script>
-->
<!--動画 ドラッグ&ドロップ-->
</body>
</html><file_sep>/child_classes/comment.php
<?php
require_once('../dbc.php');
//extends(継承)することで、protectedの関数を使えるようになる
class Comment extends Dbc{
protected $table_name = 'comment';
//コメントを生成する関数***********************************
public function commentCreate($comments){
$sql = "INSERT INTO
$this->table_name(content,user_id,post_id)
VALUES
(:content,:user_id,:post_id)";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue('content',$comments['content']);
$stmt->bindValue('user_id',$comments['user_id']);
$stmt->bindValue('post_id',$comments['post_id']);
$stmt->execute();
}catch(PDOException $e){
exit($e);
}
}
//コメントに対するリプライを生成する関数***********************************
public function commentReplyCreate($comments){
$table_name = 'comment_reply';
$sql = "INSERT INTO
$table_name(content,user_id,post_id,comment_id)
VALUES
(:content,:user_id,:post_id,:comment_id)";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue('content',$comments['content']);
$stmt->bindValue('user_id',$comments['user_id']);
$stmt->bindValue('post_id',$comments['post_id']);
$stmt->bindValue('comment_id',$comments['comment_id']);
$stmt->execute();
}catch(PDOException $e){
exit($e);
}
}
//コメントに対するリプライを表示する関数***********************************
public function getReply($comment_id){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM comment_reply
WHERE comment_id = $comment_id";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
}
//バリデーション関数***********************************
public function commentValidate($comments){
if($comments['content'] == null || $comments['content'] == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
コメントを入力してください。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
if($comments['post_id'] == null || $comments['post_id'] == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
もう一度入力し直してください。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
}
}
?><file_sep>/public/comment_reply.php
<?php
/*これだけでもIDを表示可能
$id = $_GET['id'];
echo $id;
*/
/***********************************/
session_start();
require_once ('../child_classes/comment.php');
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = Comment::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
$login_user = $_SESSION['login_user'];
/*********************************/
require_once ('../header.php');
$comment = new Comment();
$result = $comment->getCommentReply($_GET['comment_id']);
//$login_user = $result['login_user'];
//$username = $login_user['username'];
/*************↓コメントフォームのphp**************/
$instagram = new instagram();
$post_result = $instagram->getById($_GET['id']);
$content = $post_result['content'];
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>udastagram</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
</head>
<body>
<section id="comment_detailphp">
<h2>コメントページ</h2>
<section class="spacer_50"></section>
<h3>本文:</h3>
<div class="comment-text"><p><?php echo nl2br($content);?></p></div>
<div class="spacer_50"></div>
<h3>コメント:</h3>
<div class="comment-text">
<!--コメント者名を設置-->
<?php $postUser = $comment->postUser($result[0]['user_id'])?>
<!--投稿者名-->
<h3>
<?php if(isset($postUser[0]['username'])):?>
<?php echo $postUser[0]['username']?>
<?php else:?>
NoNAME
<?php endif;?>
</h3>
<p><?php echo nl2br($result[0]['content']);?></p>
<section class="spacer_30"></section>
</div>
<div class="spacer_50"></div>
<section id="comment_form">
<h3>コメントフォーム</h3>
<form action="comment_reply_create.php" method="POST">
<input type ="hidden" name="user_id" value="<?php echo $instagram->h($login_user['id'])?>">
<input type ="hidden" name="comment_id" value="<?php echo $_GET['comment_id'];?>">
<textarea name="content" id="content" cols="30" rows="10" class="selfinput text"></textarea>
<br>
<input type="hidden" name="post_id" value="<?php echo $_GET['id'];?>" readonly>
<br>
<input type="submit" value="送信" class="selfinput send-btn">
</form>
<section class="spacer_50"></section>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</section>
</body>
</html>
<file_sep>/loginYet/post_display_loginYet.php
<?php foreach($post as $column):?>
<!--投稿状況を確認-->
<?php if($instagram->h($column['publish_status']) == 1):?>
<section class="insta-list">
<div class="insta-content insta-title">
<!--トップ画像と投稿者名を設置-->
<?php $postUser = $instagram->postUser($column['user_id'])?>
<!--トップ画像-->
<div class="top_image">
<?php if(isset($postUser[0]['top_image'])) echo "<img src=".$postUser[0]['top_image'].">"?>
</div>
<!--投稿者名-->
<div class="post_user">
<?php if(isset($postUser[0]['username'])):?>
<?php echo $postUser[0]['username']?>
<?php else:?>
NoNAME
<?php endif;?>
</div>
<br>
</div>
<!--スライドテスト-->
<?php $postData = $instagram->getById($column['id']);?>
<?php
$slideCount = 0;
for($i=0;$i<8;$i++){
if($postData["slide$i"]){
$slideCount++;
}
}
if($column['movie']){
$slideCount++;
}
?>
<?php if($slideCount<=1):?>
<div class="insta-images">
<img src="<?php echo $instagram->h($column['slide0'])?>">
</div><br/>
<?php else:?>
<div class="insta-images slider-content">
<ul>
<?php for($i=0;$i<$slideCount;$i++):?>
<?php if($i == 0):?>
<li class="slide active"><img src="<?php echo $postData["slide$i"]?>"></li>
<?php else:?>
<li class="slide"><img src="<?php echo $postData["slide$i"]?>"></li>
<?php endif;?>
<?php endfor;?>
<?php if($column['movie']):?>
<li class="slide"><video src="<?php echo $column["movie"]?>" controls></video></li>
<?php endif;?>
</ul>
</div>
<section class="index-btn-all">
<?php for($i=0;$i<$slideCount;$i++):?>
<div class="index-btn" data-option="<?php echo $i?>"><img src="<?php echo $postData["slide$i"]?>"></div>
<?php endfor;?>
<?php if($column['movie']):?>
<div class="index-btn" data-option="<?php echo $i?>"><img src="../images/movie.jpg"></div>
<?php endif;?>
</section>
<?php endif;?>
<!--スライドテスト-->
<div class="insta-content">
<h3 class="post-title"><?php echo $instagram->h($column['title'])?><br/></h3>
<p><?php echo nl2br($instagram->h($column['content']))?><br/></p>
#<?php echo $instagram->h($instagram->setCategoryName($column['category']))?><br/>
<?php echo $instagram->h($column['post_at'])?><br/>
<section class="content-btton-all">
<!--いいねボタン-->
<div class="good-result">
<sectoin class="good-btn">
<div><i class="far fa-heart good-icon mit-user-good"></i></div>
</sectoin>
</div><!--result-->
<div class="mit-user-content">
<a class="comment-detail" href="./comment_detail_loginYet.php?id=<?php echo $column['id']?>"><i class="far fa-comments"></i></a><br/>
</div>
<?php if($column['post_address']):?>
<div class="address">
<a href="https://www.google.com/maps?q=<?php echo $column['post_address'];?>" target="blank">
<i class="fas fa-map-marker-alt"></i>
</a>
</div>
<?php endif;?>
</section>
</div>
</section>
<?php endif;?>
<?php endforeach;?><file_sep>/public/logout.php
<?php
/*******************************/
session_start();
setcookie($_COOKIE[session_name()], '', time()-1);
session_destroy();
//var_dump($_COOKIE);
/*******************************/
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="search_formphp">
<section class="spacer_50"></section>
<p>ログアウトしました。</p>
<div class="icon-btn login-btn">
<a href="../login/public/login_form.php"><i class="fas fa-sign-in-alt"></i>ログイン</a>
</div>
<section class="spacer_50"></section>
<a href="../login/public/signup_form.php" style="display:none">新規登録はこちら</a>
<a href="file_download.php?dl=images" style="display:none">ファイルをダウンロード</a>
</section>
</body>
</html><file_sep>/login/public/mypage.php
<?php
session_start();
require_once ('../../header.php');
require_once ('../classes/userLogic.php');
require_once ('../classes/functions.php');
//ログインされているか判断
$result = UserLogic::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: login_form.php');
return;
}
$login_user = $_SESSION['login_user'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>udastagram</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../..//css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
</head>
<body>
<section id="mypagephp">
<section class="spacer_50"></section>
<h2>マイページ</h2>
<p>ログインユーザー:<?php echo h($login_user['username'])?></p>
<p>メールアドレス:<?php echo h($login_user['email'])?></p>
<a href="./login.php" class="selfinput send-btn">ログアウト</a>
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/login/classes/userLogic.php
<?php
require_once ('../../dbc.php');
class UserLogic extends Dbc{
protected $table_name = 'users';
//ユーザー登録
//public static function createUser(
public function createUser($userData){
$result = false;
$sql = "INSERT INTO
$this->table_name(username,email,password)
VALUES
(?,?,?)";
//ユーザーデータを配列に入れる
$arr = [];
$arr[] = $userData['username'];
$arr[] = $userData['email'];
$arr[] = password_hash($userData['password'],PASSWORD_DEFAULT);
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$result = $stmt->execute($arr);
return $result;
}catch(\Exception $e){
echo $e->getMessage();
return $result;
}
}
public static function login($email,$password){
$result = false;
$user = self::getUserByEmail($email);
if(!$user){
$_SESSION['msg'] = 'メールアドレスが一致しません。';
return $result;
}
//パスワードの照会
if(password_verify($password,$user['password'])){
session_regenerate_id(true);//古いセッションIDを破棄して、セッションハイジャックを防ぐ
$_SESSION['login_user'] = $user;
$result = true;
return $result;
}
$_SESSION['msg']= 'パスワードが一致しません。';
return $result;
}
public static function getUserByEmail($email){
//上から取ってこれなかった
$table_name = 'users';
$sql = "SELECT * FROM $table_name
WHERE email = ?";
$arr = [];
$arr[] = $email;
//dbc.phpから取ってこれなかった-----------------------
function dbConnect(){
$host = DB_HOST;
$dbname = DB_NAME;
$user = DB_USER;
$pass = <PASSWORD>;
$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8";
//エラーを表示させる(接続テスト)
try{
$dbh = new PDO($dsn,$user,$pass,[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
//echo '接続成功';
}catch(PDOException $e){
echo '接続失敗'.$e->getMessage();
exit();
}
return $dbh;
}
//----------------------------------------------
try{
$stmt = dbConnect()->prepare($sql);
$stmt->execute($arr);
$user = $stmt->fetch();
return $user;
}catch(\Exception $e){
return false;
}
}
//ログインされているかチェック
public static function checkLogin(){
$result = false;
if(isset($_SESSION['login_user']) && $_SESSION['login_user']['id'] > 0){
return $result = true;
}
return $result;
}
}
?><file_sep>/public/slide_test.php
<?php
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="formphp">
<section class="spacer_50"></section>
<form action="slide_test_result.php" method="post" enctype="multipart/form-data">
<input type="file" value="ファイルを選択" name="file[]" accept="image/*;capture=camera" multiple>
<input type="submit" value="送信">
</form>
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/login/public/login_form.php
<?php
//require_once('../../header.php');
session_start();
$err = $_SESSION;
//更新したときにセッションを削除する
$_SESSION = array();
session_destroy();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>udastagram</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../..//css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
</head>
<body>
<section id="login_formphp">
<section class="spacer_50"></section>
<?php if(isset($err['login_err'])):?>
<p><?php echo $err['login_err'];?></p>
<?php endif;?>
<h2>ログインフォーム</h2>
<?php if(isset($err['msg'])):?>
<p><?php echo $err['msg'];?></p>
<?php endif;?>
<form action="login.php" method="POST">
<p>
<label for="text">メールアドレス</label>
<?php if(isset($err['email'])):?>
<p><?php echo $err['email'];?></p>
<?php endif;?>
<input type="text" name="email" class="text selfinput">
</p>
<p>
<label for="password">パスワード</label>
<?php if(isset($err['password'])):?>
<p><?php echo $err['password'];?></p>
<?php endif;?>
<input type="password" name="password" class="text selfinput">
</p>
<p><input type="submit" value="ログイン" class="selfinput send-btn"></p>
</form>
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/login/public/signup_form.php
<?php
//require_once('../../header.php');
session_start();
require_once('../classes/functions.php');
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../..//css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="signup_formphp">
<section class="spacer_50"></section>
<h2>ユーザー登録フォーム</h2>
<form action="register.php" method="POST">
<p>
<label for="username">ユーザー名:</label>
<input type="text" name="username" class="text selfinput">
</p>
<p>
<label for="email">メールアドレス:</label>
<input type="email" name="email" class="text selfinput">
</p>
<p>
<label for="password">パスワード:</label>
<input type="<PASSWORD>" name="password" class="text selfinput">
</p>
<p>
<label for="password_conf">パスワード確認:</label>
<input type="password" name="password_conf" class="text selfinput">
</p>
<!--setTokenをregister.phpに送る-->
<input type="hidden" name="csrf_token" value="<?php echo h(setToken());?>">
<p><input type="submit" value="新規登録" class="selfinput send-btn"></p>
</form>
<a href="./login_form.php">ログインページへ</a>
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/public/slide_edit.php
<?php
/*******************************/
session_start();
require_once ('../child_classes/instagram.php');
require_once ('../child_classes/slide.php');
//ログインされているか判断
$result = Instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
$login_user = $_SESSION['login_user'];
/*******************************/
require_once ('../header.php');
$instagram = new Instagram();
$slideClass = new Slide();
$result = $_POST;
$slides = $slideClass->getSlideId($result['post_id']);
$slideCount = 0;
for($i=0;$i<8;$i++){
if($slides["image_$i"]){
$slideCount++;
}
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="formphp">
<h2>スライダー編集フォーム</h2>
<!--ユーザーID-->
<div id="result1">ここに表示</div>
<section class="spacer_50"></section>
</section>
<!--<input type="file" id="text1" multiple="multiple" name="slides[]">-->
<?php for($i=0;$i<$slideCount;$i++):?>
<input type="text" id="text<?php echo $i?>" name="slide<?php echo $i?>" value="<?php echo $slides["image_$i"]?>"><br>
<?php endfor;?>
<input type="hidden" id="slide-count" value="<?php echo $slideCount;?>">
<!--
<input type="text" id="text0" name="slide0" value="../images/sample1.jpg"><br>
<input type="text" id="text1" name="slide1" value="../images/sample2.jpg"><br>
<input type="text" id="text2" name="slide2" value="../images/sample3.jpg"><br>
<input type="text" id="text3" name="slide3" value="../images/sample4.jpg"><br>
<input type="text" id="text4" name="slide4" value="../images/sample5.jpg"><br>
-->
<!--これを送信する-->
<input type="button" value="編集" id="send">
<script src="../js/slide_get.js"></script>
</body>
</html><file_sep>/js/good_btn.js
/* <div id="btn"></div>
var btn = document.getElementById('btn');
var count = 0;
btn.addEventListener('click',function(){
if(btn.style.background == 'red'){
btn.style.background = 'white';
btn.style.transition = '1s';
btn.style.width = '250px';
count = 0;
//btn.innerHTML = 'ボタン2';
console.log(count);
return;
}
btn.style.background = 'red';
btn.style.transition = '1s';
btn.style.width = '50px';
count = 1;
console.log(count);
return;
});*/
//ページ遷移無しでPHPを実行
jQuery('.AjaxForm').click(function(event){
//var good_btn_num = <?php echo $instagram->h($column['id'])?>;
//HTMLでの送信をキャンセル
event.preventDefault();
var $form = $(this);
var $button = $form.find('.submit');
var $result = $(this).parent().parent('.good-result');
var $good_btn = $(this).parent('.good-btn');
$.ajax({
url : $form.attr('action'),
type : $form.attr('method'),
data : $form.serialize(),
timeout : 10000,
//送信前
beforeSend : function(xhr,settings){
//ボタンを無効化し、二重送信を防止
$button.attr('desabled',true);
$result.html('');
$good_btn.html('');
//console.log(good_btn_num);
},
//応答後
complete: function(xhr,textStatus){
//ボタンを有効化し、再送信を許可
$button.attr('disaled',false);
},
//通信成功時の処理
success:function(result,textStatus,xhr){
//入力値を初期化
$form[0].reset();
$result.append(result);
},
//通信失敗時の処理
error:function(xhr,textStatus,error){
alert('エラー。暫く経ってからお試しください。');
}
});
});
<file_sep>/public/comment_create.php
<?php
/***********************************/
session_start();
require_once ('../child_classes/comment.php');
//ログインされているか判断
$result = Comment::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
/*********************************/
require_once ('../header.php');
$comments = $_POST;
$comments_id = $comments['post_id'];
$comment = new Comment();
$comment->commentValidate($comments);
$comment->commentCreate($comments);
header("Location:./comment_detail.php?id=$comments_id");
$now_year = date('Y');
$now_month = date('m');
//header("Location:./index.php?year=$now_year&month=$now_month");
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>udastagram</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
</head>
<body>
<section id="comment_createphp">
<p>コメントを送信しました</p>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
</section>
</body>
</html>
<file_sep>/SQL/udastagram.sql
-- phpMyAdmin SQL Dump
-- version 4.9.7
-- https://www.phpmyadmin.net/
--
-- ホスト: localhost:8889
-- 生成日時: 2021 年 6 月 16 日 01:28
-- サーバのバージョン: 5.7.32
-- PHP のバージョン: 7.4.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- データベース: `udastagram`
--
-- --------------------------------------------------------
--
-- テーブルの構造 `comment`
--
CREATE TABLE `comment` (
`id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`comment_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- テーブルの構造 `comment_reply`
--
CREATE TABLE `comment_reply` (
`id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`comment_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`comment_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- テーブルの構造 `good`
--
CREATE TABLE `good` (
`id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`click_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- テーブルのデータのダンプ `good`
--
INSERT INTO `good` (`id`, `post_id`, `user_id`, `click_at`) VALUES
(160, 58, 33, '2021-06-10 02:03:18');
-- --------------------------------------------------------
--
-- テーブルの構造 `post_data`
--
CREATE TABLE `post_data` (
`id` int(11) NOT NULL,
`title` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`slide0` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`slide1` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`slide2` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`slide3` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`slide4` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`slide5` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`slide6` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`slide7` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`movie` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`category` int(11) NOT NULL,
`post_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`publish_status` int(11) NOT NULL DEFAULT '1',
`user_id` int(11) NOT NULL,
`post_address` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- テーブルのデータのダンプ `post_data`
--
INSERT INTO `post_data` (`id`, `title`, `slide0`, `slide1`, `slide2`, `slide3`, `slide4`, `slide5`, `slide6`, `slide7`, `movie`, `content`, `category`, `post_at`, `publish_status`, `user_id`, `post_address`) VALUES
(58, 'test', '../images/202106100157230.jpg', '../images/202106100157231.jpg', '../images/202106100157232.jpg', NULL, NULL, NULL, NULL, NULL, NULL, 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest', 4, '2021-06-14 13:29:15', 1, 33, NULL);
-- --------------------------------------------------------
--
-- テーブルの構造 `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`top_image` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`post_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- テーブルのデータのダンプ `users`
--
INSERT INTO `users` (`id`, `username`, `top_image`, `email`, `password`, `post_id`) VALUES
(33, 'テスト太郎', '../images/20210610015325.jpg', '<EMAIL>', <PASSWORD>', NULL),
(34, 'test-jiro', '../images/20210610015325.jpg', '<EMAIL>', <PASSWORD>', NULL);
--
-- ダンプしたテーブルのインデックス
--
--
-- テーブルのインデックス `comment`
--
ALTER TABLE `comment`
ADD PRIMARY KEY (`id`);
--
-- テーブルのインデックス `comment_reply`
--
ALTER TABLE `comment_reply`
ADD PRIMARY KEY (`id`);
--
-- テーブルのインデックス `good`
--
ALTER TABLE `good`
ADD PRIMARY KEY (`id`);
--
-- テーブルのインデックス `post_data`
--
ALTER TABLE `post_data`
ADD PRIMARY KEY (`id`);
--
-- テーブルのインデックス `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- ダンプしたテーブルの AUTO_INCREMENT
--
--
-- テーブルの AUTO_INCREMENT `comment`
--
ALTER TABLE `comment`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
--
-- テーブルの AUTO_INCREMENT `comment_reply`
--
ALTER TABLE `comment_reply`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- テーブルの AUTO_INCREMENT `good`
--
ALTER TABLE `good`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=161;
--
-- テーブルの AUTO_INCREMENT `post_data`
--
ALTER TABLE `post_data`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=61;
--
-- テーブルの AUTO_INCREMENT `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=35;
<file_sep>/public/user_update.php
<?php
/*******************************/
session_start();
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = Instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
/*******************************/
require_once ('../header.php');
$userdata = $_POST;
$files = $_FILES;
//var_dump($files);
//echo "<br>";
//var_dump($userdata);
$login_user = $_SESSION['login_user'];
$instagram = new Instagram();
if(empty($userdata['top_image2'])){
}elseif($_FILES['top_file2']['name'] == ""){
if(empty($_FILES['top_fileSP2']['name'])){}else{
$_FILES['top_file2']['name'] = $_FILES['top_fileSP2']['name'];
$_FILES['top_file2']['type'] = $_FILES['top_fileSP2']['type'];
$_FILES['top_file2']['tmp_name'] = $_FILES['top_fileSP2']['tmp_name'];
$_FILES['top_file2']['error'] = $_FILES['top_fileSP2']['error'];
$_FILES['top_file2']['size'] = $_FILES['top_fileSP2']['size'];
}
$files = $_FILES;
}
//$userdata['top_image'] = $instagram->topImageChoice($userdata);
if(empty($userdata['top_image2'])){
}else{
$userdata = $instagram->fileSizeUser($userdata,$files);
$userdata['top_image'] = $userdata['top_image2'];
}
$instagram->userDataValidate($userdata);
if(empty($userdata['password'])){
//パスワードが無い場合のメソッド
$instagram->userDataUpdateNopass($userdata);
}else{
//パスワードがある場合のメソッド
$instagram->userDataUpdate($userdata);
}
//ユーザー情報を更新後、セッションの値を更新する。
$test = $instagram->userDataUpload($login_user['id']);
$_SESSION['login_user'] = $test[0];
//var_dump($_SESSION['login_user']);
//ここから下はregister.phpのもの
//↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//require_once ('../classes/userLogic.php');
//エラーメッセージ(エラーを溜める)
$err = [];
$token = filter_input(INPUT_POST,'csrf_token');
//トークンが無い、もしくは一致しない場合、処理を中止する。
//二重送信とURLを直接たたいてページに遷移されることを防ぐ。
if(!isset($_SESSION['csrf_token']) || $token !== $_SESSION['csrf_token']){
exit('不正なリクエスト');
}
unset($_SESSION['csrf_token']);
/*
//バリデーション
//ユーザー名
if(!$username = filter_input(INPUT_POST,'username')){
$err[] = 'ユーザー名を記入してください。';
}
//メールアドレス
if(!$email = filter_input(INPUT_POST,'email')){
$err[] = 'メールアドレスを記入してください。';
}
//パスワード(正規表現)
$password = filter_input(INPUT_POST,'password');
if(!preg_match("/\A[a-z\d]{8,100}+\z/i",$password)){
$err[] = 'パスワードは英数字8文字以上100文字以内にしてください。';
}
//パスワード確認
$password_conf = filter_input(INPUT_POST,'password_conf');
if($password_conf !== $password){
$err[] = '確認用パスワードと異なっています。';
}
*/
$now_year = date('Y');
$now_month = date('m');
header("Location:./index.php?year=$now_year&month=$now_month");
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="registerphp">
<section class="spacer_50"></section>
<?php if(count($err) > 0):?>
<?php foreach($err as $e):?>
<p><?php echo $e?></p>
<?php endforeach;?>
<?php else:?>
<p>ユーザー情報の更新が完了しました。</p>
<?php endif;?>
<a href="./index.php?year=<?php echo date("Y")?>" class="selfinput send-btn">トップへ戻る</a>
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/public/comment_form.php
<?php
/***********************************/
session_start();
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
/*********************************/
require_once ('../header.php');
//これでもエラーがでてしまう。
//if($_GET['id'] == null || $_GET['id'] == '')
$instagram = new instagram();
$result = $instagram->getById($_GET['id']);
$login_user = $_SESSION['login_user'];
$content = $result['content'];
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="comment_formphp">
<p><?php echo $content;?></p>
<div class="spacer_50"></div>
<h2>コメントフォーム</h2>
<form action="comment_create.php" method="POST">
<input type ="hidden" name="user_id" value="<?php echo $instagram->h($login_user['id'])?>">
<textarea name="content" id="content" cols="30" rows="10" class="selfinput text"></textarea>
<br>
<input type="hidden" name="post_id" value="<?php echo $_GET['id'];?>" readonly>
<br>
<input type="submit" value="送信" class="selfinput send-btn">
</form>
<section class="spacer_50"></section>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/js/slide_add.js
var fileArea = document.getElementById('drag-drop-area');
var fileSize = document.getElementById('fileSize');
fileArea.addEventListener('dragover', function(evt){
evt.preventDefault();
fileArea.classList.add('dragover');
//console.log('over');
});
fileArea.addEventListener('dragleave', function(evt){
evt.preventDefault();
fileArea.classList.remove('dragover');
//console.log('leave');
});
fileArea.addEventListener('drop', function(evt){
evt.preventDefault();
fileArea.classList.remove('dragenter');
var files = evt.dataTransfer.files;
//ファイルの大きさを確認する
const file_size = document.querySelector("#fileSize");
fileSize.files = files;
if(files.length > 4){
alert('画像の枚数を4枚以下にして下さい。');
}else{
if(!files[0].type.match(/image/)){
alert('ここには画像のみを挿入してください。');
}else if(!files[0].name.match(/jpg/) && !files[0].name.match(/jpeg/) && !files[0].name.match(/png/)){
alert('jpgまたはpng画像を挿入してください。');
}else{
photoPreview0('onChenge',files[0]);
}
if(files[1]){
if(!files[1].type.match(/image/)){
alert('ここには画像のみを挿入してください。');
}else if(!files[1].name.match(/jpg/) && !files[1].name.match(/jpeg/) && !files[1].name.match(/png/)){
alert('jpgまたはpng画像を挿入してください。');
}else{
photoPreview1('onChenge',files[1]);
}
}
if(files[2]){
if(!files[2].type.match(/image/)){
alert('ここには画像のみを挿入してください。');
}else if(!files[2].name.match(/jpg/) && !files[2].name.match(/jpeg/) && !files[2].name.match(/png/)){
alert('jpgまたはpng画像を挿入してください。');
}else{
photoPreview2('onChenge',files[2]);
}
}
if(files[3]){
if(!files[3].type.match(/image/)){
alert('ここには画像のみを挿入してください。');
}else if(!files[3].name.match(/jpg/) && !files[3].name.match(/jpeg/) && !files[3].name.match(/png/)){
alert('jpgまたはpng画像を挿入してください。');
}else{
photoPreview3('onChenge',files[3]);
}
}
//if(files[4])photoPreview4('onChenge',files[4]);
//if(files[5])photoPreview5('onChenge',files[5]);
//if(files[6])photoPreview6('onChenge',files[6]);
//if(files[7])photoPreview7('onChenge',files[7]);
}
});
jQuery(function() {
//ドラッグ&ドロップで順番を変えられるようにします。
jQuery('#previewArea').sortable();
//テキストの選択をできないようにする。(ドラッグ&ドロップをスムーズに)
jQuery('#previewArea').disableSelection();
});
jQuery(function() {
//ドラッグ&ドロップで順番を変えられるようにします。
jQuery('#updateArea').sortable();
//テキストの選択をできないようにする。(ドラッグ&ドロップをスムーズに)
jQuery('#updateArea').disableSelection();
});
//---------------------------------------
function photoPreview0(event, f = null) {
var file = f;
if(file === null){
file = event.target.files[1];
}
var reader = new FileReader();
var preview = document.getElementById("previewArea");
var previewImage = document.getElementById("previewImage");
var previewInput = document.getElementById("previewInput");
var classList = document.createElement("section");
classList.id = "elements0";
preview.appendChild(classList);
var classList0 = document.getElementById("elements0");
//プレビュー画像を削除
if(previewImage != null) {
classList0.removeChild(previewImage);
}
//inputタグ削除
if(previewInput != null) {
classList0.removeChild(previewInput);
}
reader.onload = function(event) {
var img = document.createElement("img");
img.setAttribute("src", reader.result);
img.setAttribute("id", "previewImage");
//img.innerHTML = '<div>おはよう</div>';
classList0.appendChild(img);
var slide1 = document.createElement("input");
slide1.type = "hidden";
slide1.id = "test";
slide1.name = "slide[]";
slide1.value = file.name;
slide1.setAttribute("id", "previewInput");
classList0.appendChild(slide1);
};
reader.readAsDataURL(file);
//console.log(file);
}
function photoPreview1(event, f = null) {
var file = f;
if(file === null){
file = event.target.files[1];
}
var reader = new FileReader();
var preview = document.getElementById("previewArea");
var previewImage = document.getElementById("previewImage");
var previewInput = document.getElementById("previewInput");
var classList = document.createElement("section");
classList.id = "elements1";
preview.appendChild(classList);
var classList1 = document.getElementById("elements1");
if(previewImage != null) {
classList1.removeChild(previewImage);
}
//inputタグ削除
if(previewInput != null) {
classList1.removeChild(previewInput);
}
reader.onload = function(event) {
var img = document.createElement("img");
img.setAttribute("src", reader.result);
img.setAttribute("id", "previewImage");
//img.innerHTML = '<div>おはよう</div>';
classList1.appendChild(img);
var slide1 = document.createElement("input");
slide1.type = "hidden";
slide1.id = "test";
slide1.name = "slide[]";
slide1.value = file.name;
slide1.setAttribute("id", "previewInput");
classList1.appendChild(slide1);
};
reader.readAsDataURL(file);
//console.log(file);
}
function photoPreview2(event, f = null) {
var file = f;
if(file === null){
file = event.target.files[1];
}
var reader = new FileReader();
var preview = document.getElementById("previewArea");
var previewImage = document.getElementById("previewImage");
var previewInput = document.getElementById("previewInput");
var classList = document.createElement("section");
classList.id = "elements2";
preview.appendChild(classList);
var classList2 = document.getElementById("elements2");
if(previewImage != null) {
classList2.removeChild(previewImage);
}
//inputタグ削除
if(previewInput != null) {
classList2.removeChild(previewInput);
}
reader.onload = function(event) {
var img = document.createElement("img");
img.setAttribute("src", reader.result);
img.setAttribute("id", "previewImage");
//img.innerHTML = '<div>おはよう</div>';
classList2.appendChild(img);
var slide1 = document.createElement("input");
slide1.type = "hidden";
slide1.id = "test";
slide1.name = "slide[]";
slide1.value = file.name;
slide1.setAttribute("id", "previewInput");
classList2.appendChild(slide1);
};
reader.readAsDataURL(file);
//console.log(file);
}
function photoPreview3(event, f = null) {
var file = f;
if(file === null){
file = event.target.files[1];
}
var reader = new FileReader();
var preview = document.getElementById("previewArea");
var previewImage = document.getElementById("previewImage");
var previewInput = document.getElementById("previewInput");
var classList = document.createElement("section");
classList.id = "elements3";
preview.appendChild(classList);
var classList3 = document.getElementById("elements3");
if(previewImage != null) {
classList3.removeChild(previewImage);
}
//inputタグ削除
if(previewInput != null) {
classList3.removeChild(previewInput);
}
reader.onload = function(event) {
var img = document.createElement("img");
img.setAttribute("src", reader.result);
img.setAttribute("id", "previewImage");
//img.innerHTML = '<div>おはよう</div>';
classList3.appendChild(img);
var slide1 = document.createElement("input");
slide1.type = "hidden";
slide1.id = "test";
slide1.name = "slide[]";
slide1.value = file.name;
slide1.setAttribute("id", "previewInput");
classList3.appendChild(slide1);
};
reader.readAsDataURL(file);
//console.log(file);
}
function photoPreview4(event, f = null) {
var file = f;
if(file === null){
file = event.target.files[1];
}
var reader = new FileReader();
var preview = document.getElementById("previewArea");
var previewImage = document.getElementById("previewImage");
var previewInput = document.getElementById("previewInput");
var classList = document.createElement("section");
classList.id = "elements4";
preview.appendChild(classList);
var classList4 = document.getElementById("elements4");
if(previewImage != null) {
classList4.removeChild(previewImage);
}
//inputタグ削除
if(previewInput != null) {
classList4.removeChild(previewInput);
}
reader.onload = function(event) {
var img = document.createElement("img");
img.setAttribute("src", reader.result);
img.setAttribute("id", "previewImage");
//img.innerHTML = '<div>おはよう</div>';
classList4.appendChild(img);
var slide1 = document.createElement("input");
slide1.type = "hidden";
slide1.id = "test";
slide1.name = "slide[]";
slide1.value = file.name;
slide1.setAttribute("id", "previewInput");
classList4.appendChild(slide1);
};
reader.readAsDataURL(file);
//console.log(file);
}
function photoPreview5(event, f = null) {
var file = f;
if(file === null){
file = event.target.files[1];
}
var reader = new FileReader();
var preview = document.getElementById("previewArea");
var previewImage = document.getElementById("previewImage");
var previewInput = document.getElementById("previewInput");
var classList = document.createElement("section");
classList.id = "elements5";
preview.appendChild(classList);
var classList5 = document.getElementById("elements5");
if(previewImage != null) {
classList5.removeChild(previewImage);
}
//inputタグ削除
if(previewInput != null) {
classList5.removeChild(previewInput);
}
reader.onload = function(event) {
var img = document.createElement("img");
img.setAttribute("src", reader.result);
img.setAttribute("id", "previewImage");
//img.innerHTML = '<div>おはよう</div>';
classList5.appendChild(img);
var slide1 = document.createElement("input");
slide1.type = "hidden";
slide1.id = "test";
slide1.name = "slide[]";
slide1.value = file.name;
slide1.setAttribute("id", "previewInput");
classList5.appendChild(slide1);
};
reader.readAsDataURL(file);
//console.log(file);
}
function photoPreview6(event, f = null) {
var file = f;
if(file === null){
file = event.target.files[1];
}
var reader = new FileReader();
var preview = document.getElementById("previewArea");
var previewImage = document.getElementById("previewImage");
var previewInput = document.getElementById("previewInput");
var classList = document.createElement("section");
classList.id = "elements6";
preview.appendChild(classList);
var classList6 = document.getElementById("elements6");
if(previewImage != null) {
classList6.removeChild(previewImage);
}
//inputタグ削除
if(previewInput != null) {
classList6.removeChild(previewInput);
}
reader.onload = function(event) {
var img = document.createElement("img");
img.setAttribute("src", reader.result);
img.setAttribute("id", "previewImage");
//img.innerHTML = '<div>おはよう</div>';
classList6.appendChild(img);
var slide1 = document.createElement("input");
slide1.type = "hidden";
slide1.id = "test";
slide1.name = "slide[]";
slide1.value = file.name;
slide1.setAttribute("id", "previewInput");
classList6.appendChild(slide1);
};
reader.readAsDataURL(file);
//console.log(file);
}
function photoPreview7(event, f = null) {
var file = f;
if(file === null){
file = event.target.files[1];
}
var reader = new FileReader();
var preview = document.getElementById("previewArea");
var previewImage = document.getElementById("previewImage");
var previewInput = document.getElementById("previewInput");
var classList = document.createElement("section");
classList.id = "elements7";
preview.appendChild(classList);
var classList7 = document.getElementById("elements7");
if(previewImage != null) {
classList7.removeChild(previewImage);
}
//inputタグ削除
if(previewInput != null) {
classList7.removeChild(previewInput);
}
reader.onload = function(event) {
var img = document.createElement("img");
img.setAttribute("src", reader.result);
img.setAttribute("id", "previewImage");
//img.innerHTML = '<div>おはよう</div>';
classList7.appendChild(img);
var slide1 = document.createElement("input");
slide1.type = "hidden";
slide1.id = "test";
slide1.name = "slide[]";
slide1.value = file.name;
slide1.setAttribute("id", "previewInput");
classList7.appendChild(slide1);
};
reader.readAsDataURL(file);
//console.log(file);
}<file_sep>/login/public/register.php
<?php
//require_once('../../header.php');
session_start();
require_once('../classes/userLogic.php');
//エラーメッセージ(エラーを溜める)
$err = [];
$token = filter_input(INPUT_POST,'csrf_token');
//トークンが無い、もしくは一致しない場合、処理を中止する。
//二重送信とURLを直接たたいてページに遷移されることを防ぐ。
if(!isset($_SESSION['csrf_token']) || $token !== $_SESSION['csrf_token']){
exit('不正なリクエスト');
}
unset($_SESSION['csrf_token']);
//バリデーション
//ユーザー名
if(!$username = filter_input(INPUT_POST,'username')){
$err[] = 'ユーザー名を記入してください。';
}
//メールアドレス
if(!$email = filter_input(INPUT_POST,'email')){
$err[] = 'メールアドレスを記入してください。';
}
//パスワード(正規表現)
$password = filter_input(INPUT_POST,'<PASSWORD>');
if(!preg_match("/\A[a-z\d]{8,100}+\z/i",$password)){
$err[] = 'パスワードは英数字8文字以上100文字以内にしてください。';
}
//パスワード確認
$password_conf = filter_input(INPUT_POST,'<PASSWORD>');
if($password_conf !== $password){
$err[] = '確認用パスワードと異なっています。';
}
$logic = new UserLogic();
//エラーがない場合、ユーザー登録の処理を行う
if(count($err) === 0){
$hasCreated = $logic->createUser($_POST);
if(!$hasCreated){
$err[] = '登録に失敗しました。';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>udastagram</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../..//css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
</head>
<body>
<section id="registerphp">
<section class="spacer_50"></section>
<?php if(count($err) > 0):?>
<?php foreach($err as $e):?>
<p><?php echo $e?></p>
<?php endforeach;?>
<?php else:?>
<p>登録が完了しました。</p>
<?php endif;?>
<a href="./signup_form.php" class="selfinput send-btn">新規登録画面へ戻る</a>
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/dbc.php
<?php
require_once('env.php');
class Dbc{
//namespace Insta\Dbc;
protected $table_name;
//1.データベースに接続する
protected function dbConnect(){
$host = DB_HOST;
$dbname = DB_NAME;
$user = DB_USER;
$pass = <PASSWORD>;
$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8";
//エラーを表示させる(接続テスト)
try{
$dbh = new PDO($dsn,$user,$pass,[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
//echo '接続成功';
}catch(PDOException $e){
echo '接続失敗'.$e->getMessage();
exit();
}
return $dbh;
}
//2.データを取得する
public function getAll(){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "
select *
from $this->table_name";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//post_dataを西暦ごとに取得
public function getByYearMonth($year,$month){
if($year == null || $year == '' || $month == null || $month == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
西暦、月が不正です。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
$sql = "SELECT *
FROM $this->table_name
WHERE DATE_FORMAT(post_at,'%Y%m')='$year$month'";
//SQLの準備
$stmt = $dbh->query($sql);
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
/*
if(!$result){
$presentYear = date("Y");
$presentMonth = date("m");
echo "<section class='return-btn-all'>
投稿がありません。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
//exit();
}
*/
return $result;
$dbh = null;
}
//引数:$id
//返り値:$result
public function getById($id){
if($id == null || $id == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
IDが不正です。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
$sql = "SELECT *
FROM $this->table_name
WHERE id = :id";
//SQLの準備
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',(INT)$id,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//結果を取得
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$result){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
投稿がありません。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
return $result;
}
//投稿削除機能
public function delete($id){
if($id == null || $id == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
IDが不正です。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
//SQLの準備
$stmt = $dbh->prepare("DELETE FROM $this->table_name WHERE id = :id");
$stmt->bindValue(':id',(INT)$id,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//echo 'ブログを削除しました';
}
//コメント削除機能(1つの記事に対するコメントを全て削除)
public function deletePostComment($id){
if($id == null || $id == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
IDが不正です。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
//SQLの準備
$stmt = $dbh->prepare("DELETE FROM comment WHERE post_id = :id");
$stmt->bindValue(':id',(INT)$id,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//echo 'ブログを削除しました';
}
//コメント削除機能
public function deleteComment($id){
if($id == null || $id == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
IDが不正です。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
//SQLの準備
$stmt = $dbh->prepare("DELETE FROM comment WHERE id = :id");
$stmt->bindValue(':id',(INT)$id,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//echo 'ブログを削除しました';
}
//コメント削除した場合、同時にリプライを削除する機能
public function deleteCommentDeleteReply($id){
if($id == null || $id == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
IDが不正です。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
//SQLの準備
$stmt = $dbh->prepare("DELETE FROM comment_reply WHERE comment_id = :id");
$stmt->bindValue(':id',(INT)$id,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//echo 'ブログを削除しました';
}
//コメントのリプライ削除機能
public function deleteReplyComment($id){
if($id == null || $id == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
IDが不正です。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
//SQLの準備
$stmt = $dbh->prepare("DELETE FROM comment_reply WHERE id = :id");
$stmt->bindValue(':id',(INT)$id,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//echo 'ブログを削除しました';
}
//いいね削除機能
public function deleteGood($id){
if($id == null || $id == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
IDが不正です。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
//SQLの準備
$stmt = $dbh->prepare("DELETE FROM good WHERE post_id = :id");
$stmt->bindValue(':id',(INT)$id,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//echo 'ブログを削除しました';
}
//投稿検索機能
public function getByCategory($category){
if($category == null || $category == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
カテゴリーを選択して下さい。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM $this->table_name
WHERE category = $category";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//コメント検索機能
public function getComments($id){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM $this->table_name
WHERE post_id = $id";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//リプライ用のコメント1つのみを取得
public function getCommentReply($comment_id){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM $this->table_name
WHERE id = $comment_id";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//タイトル検索機能
public function titleSearch($searchWord){
//検索ワードが入っていない場合
if($searchWord == null || $searchWord == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
検索ワードが入力されていません。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a onclick='history.back(-1)'>ページを一つ戻る</a></div>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM $this->table_name
WHERE title LIKE '%$searchWord%'";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//2.ユーザーデータを取得する
public function getUserAll(){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM users";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//2.IDからユーザーデータを取得する
public function getUserId($userId){
if($userId == null || $userId == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
ユーザーを選択して下さい。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM users
WHERE id = $userId";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//ユーザーIDから投稿を取得する
public function getUserById($id){
if($id == null || $id == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
IDが不正です。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
$sql = "SELECT *
FROM $this->table_name
WHERE user_id = :id";
//SQLの準備
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',(INT)$id,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//結果を取得
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
}
//ユーザーIDから投稿を取得する
public function getByIdUnpublish($id){
if($id == null || $id == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
IDが不正です。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
$sql = "SELECT *
FROM $this->table_name
WHERE user_id = :id";
//SQLの準備
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':id',(INT)$id,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//結果を取得
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
}
public function dataSearch($date){
//検索ワードが入っていない場合
if($date == null || $date == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
検索ワードが入力されていません。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a onclick='history.back(-1)'>ページを一つ戻る</a></div>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
$sql = "SELECT *
FROM $this->table_name
WHERE DATE_FORMAT(post_at,'%Y%m')='$date' ";
$stmt = $dbh->query($sql);
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//セキュリティ
public function h($S){
return htmlspecialchars($S,ENT_QUOTES,"UTF-8");
}
//セキュリティ
function setToken(){
$csrf_token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $csrf_token;
return $csrf_token;
}
//ログインチェック
public static function checkLogin(){
$result = false;
if(isset($_SESSION['login_user']) && $_SESSION['login_user']['id'] >= 0){
return $result = true;
}
return $result;
}
//トップ画像を付与
public function postUser($user_id){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM users
WHERE id = $user_id";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//リプライしたユーザーのIDからユーザー名を取得
public function replyUser($user_id){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM users
WHERE id = $user_id";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//コメントからユーザーを取得
public function commentUser($user_id){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM users
WHERE id = $user_id";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//中身が入っているかチェックする
public function getCheck($id){
if($id == null || $id == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
不正なアクセスです。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
}
//いいね削除ボタン
public function goodDelete($postId,$userId){
$dbh = $this->dbConnect();
//SQLの準備
$sql = "DELETE FROM good
WHERE post_id = :postId
AND user_id = :userId";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':postId',(INT)$postId,PDO::PARAM_INT);
$stmt->bindValue(':userId',(INT)$userId,PDO::PARAM_INT);
//SQLの実行
$stmt->execute();
//echo 'ブログを削除しました';
}
//いいねがついているかチェックする
public function ckeckGood($postId,$userId){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM good
WHERE post_id = :postId
AND user_id = :userId";
//2.SQLの実行
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':postId',(INT)$postId,PDO::PARAM_INT);
$stmt->bindValue(':userId',(INT)$userId,PDO::PARAM_INT);
$stmt->execute();
//3.SQLの結果を受け取る
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$result){
$result = true;
}else{
$result = false;
}
return $result;
$dbh = null;
}
//いいね検索機能
public function getByGood($userId){
if($userId == null || $userId == ''){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
IDがありません。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT post_id
FROM good
WHERE user_id = $userId";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
public function file_downdload($zipName){
$dist = $zipName.'.zip'; // 生成する圧縮ファイル名
$path = '../'.$zipName; // 圧縮するフォルダのパス
//DLするファイルのフォルダ構成を維持するか否か 0:しない/1:する
//維持する場合、ダウンロードしたファイルは $path の構成になります
$filePath = 0;
//DLファイルが1つの場合、フォルダに入れるか否か 0:いれない/1:いれる
$folderIn = 1;
$zip = new ZipArchive();
$zip->open($dist, ZipArchive::CREATE | ZipArchive::OVERWRITE);
if (is_dir($path)) {
$files = array_diff(scandir($path), ['.', '..']);
$filesNum = count($files);
foreach ($files as $file){
if($filePath >= 1){ //フォルダ構成を維持する
$zip->addFile($path.'/'.$file);
}else{ //維持しない
if(($folderIn >= 1) && ($filesNum <= 1)){ //ファイルが1つの時、フォルダに収める場合の処理
$localFile = $zipName.'/';
}else{
$localFile = '';
}
$zip->addFile($path.'/'.$file, $localFile.$file);
}
}
}
$zip->close();
// ストリームに出力
header('Content-Type: application/zip; name="' . $dist . '"');
header('Content-Disposition: attachment; filename="' . $dist . '"');
header('Content-Length: '.filesize($dist));
//echo file_get_contents($dist);
readfile($dist);
// 一時ファイルを削除しておく
unlink($dist);
exit;
}
}
?>
<file_sep>/README.md
# PHP-portfolio
PHPで作成したSNS
# Name
udastagram
# Features
写真の容量を最低限の容量にして格納することができる為、サーバーの容量の消費を抑えることができる。
# Requirement
* PHP 8.x
* MySQL 8.x
* Apache 2.4.x
# Note
1.DBのテーブルを作成してください。(『/SQL』にSQLファイルが格納されています。)
2.『/env.php』にDBの情報を入力してください。
# Author
* ryoji-U
<file_sep>/loginYet/search_form_loginYet.php
<?php
/*******************************/
session_start();
require_once ('../child_classes/instagram.php');
/*
//ログインされているか判断
$result = Instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
$login_user = $_SESSION['login_user'];
*/
/*******************************/
require_once ('../header_loginYet.php');
$instagram = new Instagram();
$userData = $instagram->getUserAll();
//var_dump($userData);
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="search_formphp">
<h2>検索ページ</h2>
<section class="spacer_50"></section>
<h3>タイトル検索</h3>
<form action="title_search_loginYet.php" method="POST">
<input type="text" name="searchWord" class="selfinput text">
<input type="submit" value="検索" class="search post-search">
</form>
<section class="spacer_50"></section>
<section class="date-search-all">
<h3>年月検索</h3>
<form action="date_search_loginYet.php" method="POST">
<input type='number' name='year' class='selfinput search-date' value='<?php echo date("Y")?>'>
<span>年</span>
<select name='month' class='selfinput search-date'>
<option value='01'>01</option>
<option value='02'>02</option>
<option value='03'>03</option>
<option value='04'>04</option>
<option value='05'>05</option>
<option value='06'>06</option>
<option value='07'>07</option>
<option value='08'>08</option>
<option value='09'>09</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
</select>
<span>月</span>
<br>
<input type="submit" value="検索" class="search post-search">
</form>
</section>
<section class="spacer_50"></section>
<h3>カテゴリー検索</h3>
<form action="category_search_loginYet.php" method="POST">
<select name="category" class="selfinput">
<option value='1'>グルメ</option>
<option value='2'>観光</option>
<option value='3'>アクティブ</option>
<option value='4'>その他</option>
</select>
<br>
<input type="submit" value="検索" class="search post-search">
</form>
<section class="spacer_50"></section>
<h3>ユーザー検索</h3>
<form action="user_search_loginYet.php" method="POST">
<select name="userId" class="selfinput">
<?php foreach($userData as $user):?>
<option value='<?php echo $user['id']?>'><?php echo $user['username']?></option>
<?php endforeach;?>
</select>
<br>
<input type="submit" value="検索" class="search post-search">
</form>
<section class="spacer_50"></section>
<div class="return-btn"><a href="./index_loginYet.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/public/index_top.php
<?php
/*******************************/
session_start();
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = Instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
$login_user = $_SESSION['login_user'];
/*******************************/
require_once ('../header.php');
$instagram = new Instagram();
//$instagram_data = $instagram->getByYear(date("Y"));
$instagram_data = $instagram->getByYearMonth($_GET['year'],$_GET['month']);
//最新の投稿を一番上に表示するためのソート
rsort($instagram_data);
$post = $instagram_data;
//一月前
$month0 = $_GET['month']-1;
$month0 = "0".$month0;
$instagram_data_prev = $instagram->getByYearMonth($_GET['year'],$month0);
//最新の投稿を一番上に表示するためのソート
rsort($instagram_data_prev);
$post_prev = $instagram_data_prev;
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>udastagram</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js" defer></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<section id="indexphp">
<section class="year-transition">
<div class="year <?php if($_GET['year'] == 2020)echo 'action-year'?>"><a href="./index.php?year=2020&month=<?php echo $_GET['month']?>">2020年</a></div>
<div class="year <?php if($_GET['year'] == 2021)echo 'action-year'?>"><a href="./index.php?year=2021&month=<?php echo $_GET['month']?>">2021年</a></div>
<div class="year <?php if($_GET['year'] == 2022)echo 'action-year'?>"><a href="./index.php?year=2022&month=<?php echo $_GET['month']?>">2022年</a></div>
</section>
<section class="year-transition">
<div class="year <?php if($_GET['month'] == 1)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=01">1月</a></div>
<div class="year <?php if($_GET['month'] == 2)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=02">2月</a></div>
<div class="year <?php if($_GET['month'] == 3)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=03">3月</a></div>
<div class="year <?php if($_GET['month'] == 4)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=04">4月</a></div>
<div class="year <?php if($_GET['month'] == 5)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=05">5月</a></div>
<div class="year <?php if($_GET['month'] == 6)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=06">6月</a></div>
<div class="year <?php if($_GET['month'] == 7)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=07">7月</a></div>
<div class="year <?php if($_GET['month'] == 8)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=08">8月</a></div>
<div class="year <?php if($_GET['month'] == 9)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=09">9月</a></div>
<div class="year <?php if($_GET['month'] == 10)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=10">10月</a></div>
<div class="year <?php if($_GET['month'] == 11)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=11">11月</a></div>
<div class="year <?php if($_GET['month'] == 12)echo 'action-year'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=12">12月</a></div>
</section>
<section class="insta-list-all">
<!--全ての投稿を表示-->
<?php require_once ('post_display.php');?>
</section>
<br>
<!--前の月の分-->
<p>前月投稿</p>
<section class="insta-list-all">
<?php foreach($post_prev as $column):?>
<!--投稿状況を確認-->
<?php if($instagram->h($column['publish_status']) == 1):?>
<section class="insta-list">
<div class="insta-content insta-title">
<!--トップ画像と投稿者名を設置-->
<?php $postUser = $instagram->postUser($column['user_id'])?>
<!--トップ画像-->
<div class="top_image">
<?php if(isset($postUser[0]['top_image'])) echo "<img src=".$postUser[0]['top_image'].">"?>
</div>
<!--投稿者名-->
<div class="post_user">
<?php if(isset($postUser[0]['username'])):?>
<?php echo $postUser[0]['username']?>
<?php else:?>
NoNAME
<?php endif;?>
</div>
<br>
</div>
<!--スライドテスト-->
<?php $postData = $instagram->getById($column['id']);?>
<?php
$slideCount = 0;
for($i=0;$i<8;$i++){
if($postData["slide$i"]){
$slideCount++;
}
}
if($column['movie']){
$slideCount++;
}
?>
<?php if($slideCount<=1):?>
<div class="insta-images">
<img src="<?php echo $instagram->h($column['slide0'])?>">
</div><br/>
<?php else:?>
<div class="insta-images slider-content">
<ul>
<?php for($i=0;$i<$slideCount;$i++):?>
<?php if($i == 0):?>
<li class="slide active"><img src="<?php echo $postData["slide$i"]?>"></li>
<?php else:?>
<li class="slide"><img src="<?php echo $postData["slide$i"]?>"></li>
<?php endif;?>
<?php endfor;?>
<?php if($column['movie']):?>
<li class="slide"><video src="<?php echo $column["movie"]?>" controls></video></li>
<?php endif;?>
</ul>
</div>
<section class="index-btn-all">
<?php for($i=0;$i<$slideCount;$i++):?>
<div class="index-btn" data-option="<?php echo $i?>"><img src="<?php echo $postData["slide$i"]?>"></div>
<?php endfor;?>
<?php if($column['movie']):?>
<div class="index-btn" data-option="<?php echo $i?>"><img src="../images/movie.jpg"></div>
<?php endif;?>
</section>
<?php endif;?>
<!--スライドテスト-->
<div class="insta-content">
<h3 class="post-title"><?php echo $instagram->h($column['title'])?><br/></h3>
<p><?php echo nl2br($instagram->h($column['content']))?><br/></p>
#<?php echo $instagram->h($instagram->setCategoryName($column['category']))?><br/>
<?php echo $instagram->h($column['post_at'])?><br/>
<section class="content-btton-all">
<!--いいねボタン-->
<div class="good-result">
<?php $goodResult = $instagram->ckeckGood($instagram->h($column['id']),$instagram->h($login_user['id']));?>
<?php if($goodResult == true):?>
<sectoin class="good-btn">
<form action="good_btn.php" method="post" class="AjaxForm">
<input type="hidden" value="<?php echo $instagram->h($login_user['id'])?>" name="user_id">
<input type="hidden" value="<?php echo $instagram->h($column['id'])?>" name="post_id">
<input type="submit" value="" class="submit good-icon">
</form>
</sectoin>
<?php else:?>
<sectoin class="good-btn">
<form action="good_delete.php" method="post" class="AjaxForm">
<input type="hidden" value="<?php echo $instagram->h($login_user['id'])?>" name="user_id">
<input type="hidden" value="<?php echo $instagram->h($column['id'])?>" name="post_id">
<input type="submit" value="" class="submit delete-icon">
</form>
</sectoin>
<?php endif;?>
</div><!--result-->
<a class="comment-detail" href="./comment_detail.php?id=<?php echo $column['id']?>"><i class="far fa-comments"></i></a><br/>
<!--編集・削除ボタンは自分の投稿にのみ表示される-->
<?php if($column['post_address']):?>
<div class="address">
<a href="https://www.google.com/maps?q=<?php echo $column['post_address'];?>" target="blank">
<i class="fas fa-map-marker-alt"></i>
</a>
</div>
<?php endif;?>
<?php if($instagram->h($login_user['id']) == $instagram->h($column['user_id'])):?>
<a class="updata post-updata" href="./update_form.php?id=<?php echo $column['id']?>"><i class="fas fa-pen"></i></a><br/>
<a class="delete post-delete" href="javascript:if(confirm('本当に削除しますか?')==true) document.location='./instagram_delete.php?id=<?php echo $column['id']?>'; else alert('キャンセルされました');"><i class="fas fa-trash-alt"></i></a>
<?php endif;?>
</section>
</div>
</section>
<?php endif;?>
<?php endforeach;?>
</section>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<!--いいねボタンテスト-->
<script src="../js/good_btn.js"></script>
<!--いいねボタンテスト-->
<!--スライドテスト-->
<script src="../js/slide.js"></script>
<!--スライドテスト-->
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/js/movie_add.js
var fileAreaMovie = document.getElementById('drag-drop-area-movie');
var fileSizeMovie = document.getElementById('fileSize_movie');
fileAreaMovie.addEventListener('dragover', function(evt){
evt.preventDefault();
fileAreaMovie.classList.add('dragover');
//console.log('overm');
});
fileAreaMovie.addEventListener('dragleave', function(evt){
evt.preventDefault();
fileAreaMovie.classList.remove('dragover');
//console.log('leave');
});
fileAreaMovie.addEventListener('drop', function(evt){
evt.preventDefault();
fileAreaMovie.classList.remove('dragenter');
var files = evt.dataTransfer.files;
//ファイルの大きさを確認する
const file_size = document.querySelector("#fileSize_movie");
fileSizeMovie.files = files;
console.log(files[0].type);
if(!files[0].type.match(/video/)){
alert('ここには動画を挿入してください。');
}else{
moviePreview0('onChenge',files[0]);
}
});
//---------------------------------------
function moviePreview0(event, f = null) {
var file = f;
if(file === null){
file = event.target.files[1];
}
var reader = new FileReader();
var preview = document.getElementById("previewArea_movie");
var previewMovie = document.getElementById("previewMovie");
var previewInputM = document.getElementById("previewInputM");
var classList = document.createElement("section");
classList.id = "movie";
preview.appendChild(classList);
var classList0 = document.getElementById("movie");
//プレビュー画像を削除
if(previewMovie != null) {
classList0.removeChild(previewMovie);
}
//inputタグ削除
if(previewInputM != null) {
classList0.removeChild(previewInputM);
}
reader.onload = function(event) {
var video = document.createElement("video");
video.setAttribute("src", reader.result);
video.setAttribute("id", "previewMovie");
video.setAttribute("controls","true");
//video.controls = boolean;
//video.innerHTML = '<div>おはよう</div>';
classList0.appendChild(video);
var movie1 = document.createElement("input");
movie1.type = "hidden";
movie1.id = "test";
movie1.name = "movie";
movie1.value = file.name;
movie1.setAttribute("id", "previewInputM");
classList0.appendChild(movie1);
};
reader.readAsDataURL(file);
//console.log(file);
}
<file_sep>/public/slide_test_result.php
<?php
$result = $_POST;
$files = $_FILES;
var_dump($files);
echo "<br>";
echo $files["file"]["tmp_name"][0];
echo "<br>";
/*ここから */
$before_file = $files["file"]["tmp_name"][0];
$original_image = @imagecreatefromjpeg($before_file);
$canvas = @imagecreatetruecolor(450,300);
@imagecopyresampled($canvas,$original_image,0,0,0,0,450,300,450,300);
@imageresolution($canvas,72);
@imagejpeg($canvas,"../images/dpi.jpg");
//echo '<img src="'.$canvas.'">';
//qiita
/*ここから*//*
$before_file = $files["file"]["tmp_name"][0];
List($original_w,$original_h,$type) = @getimagesize($before_file);
print_r(getimagesize($before_file));
$rate = ($original_w / 450);
if($rate > 1){
$w = floor((1 / $rate) * $original_w);
$h = floor((1 / $rate) * $original_h);
echo "小さくしました";
echo '高さ:'.$h;
}else{
$w = $original_w;
$h = $original_h;
echo "そのままでも大丈夫です";
}
switch($type){
case IMAGETYPE_JPEG:
$original_image = @imagecreatefromjpeg($before_file);
break;
case IMAGETYPE_PNG:
$original_image = @imagecreatefrompng($before_file);
break;
default:
throw new RuntimeException('対応していないファイル形式です。',$type);
}
$canvas = @imagecreatetruecolor($w,$h);
@imagecopyresampled($canvas,$original_image,0,0,0,0,$w,$h,$original_w,$original_h);
$path = '../images/';
$resize_path = $path."after.jpg";
switch($type){
case IMAGETYPE_JPEG:
@imagejpeg($canvas,$resize_path);
break;
case IMAGETYPE_PNG:
@imagepng($canvas,$resize_path,9);
break;
}
@imagedestroy($original_image);
@imagedestroy($canvas);
*/
?>
<html>
<head>
</head>
<body>
</body>
</html><file_sep>/header.php
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="header-all">
<section id="header">
<section class="global-all">
<section class="global">
<section class="left-btn">
<div class="top-btn">
<a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">
<img src="../logo/logo.png"></a>
</div>
<div class="right-btn-js">
<i class="fas fa-bars bar-btn-js"></i>
</div>
</section>
<section class="right-btn">
<div class="search-btn user-button js_btn" id="js_search_btn">
<a href="./search_form.php"><i class="fas fa-search"></i><br>
<div class="header-text">検索</div></a>
</div>
<div class="post-btn user-button">
<a href="./form.php"><i class="fas fa-edit"></i><br>
<div class="header-text">投稿</div></a>
</div>
<div class="admin-btn user-button">
<a href="./user.php"><i class="fas fa-user-alt"></i><br>
<div class="header-text">ユーザー</div></a>
</div>
<div class="logout-btn user-button js_btn" id="js_search_btn">
<a href="javascript:if(confirm('本当にログアウトしますか?')==true) document.location='./logout.php'; else alert('キャンセルされました');"><i class="fas fa-sign-out-alt"></i><br>
<div class="header-text">ログアウト</div></a>
</div>
</section>
</section>
<!--カテゴリー検索のプルダウンメニュー
<section class="post-search-btn-all-2 js_btn" id="js_serach_btn2">
<a class="search2 post-search2" href="/instagram/new/category_search.php?category=1">グルメ</a><br/>
<a class="search2 post-search2" href="/instagram/new/category_search.php?category=2">観光</a><br/>
<a class="search2 post-search2" href="/instagram/new/category_search.php?category=3">アクティブ</a><br/>
<a class="search2 post-search2" href="/instagram/new/category_search.php?category=4">その他</a><br/>
</section>-->
</section>
</section>
</section>
<script src="../js/header.js"></script>
</body>
</html><file_sep>/public/user_form.php
<?php
/***********************************/
session_start();
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
/*********************************/
require_once ('../header.php');
$login_user = $_SESSION['login_user'];
$instagram = new instagram();
//$result = $instagram->getById($_GET['id']);
$id = $login_user['id'];
$username = $login_user['username'];
$email = $login_user['email'];
$top_image = $login_user['top_image'];
//$instagram->userDataUpload();
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="user_formphp">
<h2>ユーザー情報編集フォーム</h2>
<section class="spacer_30"></section>
<h3>現在のトップ画像:</h3>
<span class="top_image"><img src="<?php echo $top_image?>"></span>
<form action="user_update.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?php echo $id?>">
<p>
<input type="hidden" name="top_image" class="text selfinput" value="<?php echo $top_image?>" readonly>
<div class="spacer_30"></div>
<!--新しい画像を挿入する場合-->
<h3>トップ画像を編集する場合は入力してください。</h3>
<div id="drag-drop-area">
<div class="drag-drop-inside">
<p class="drag-drop-info">ここにファイルをドロップ</p>
<p class="drag-drop-buttons">
<input id="fileSize" type="file" value="ファイルを選択" class="hidden" name="top_file2" accept="image/*;capture=camera">
</p>
<div id="previewArea"></div>
</div>
</div>
<section class="spacer_30"></section>
<!--スマホ版画像挿入方法-->
<div id="drag-drop-areaSP">
<input id="fileSizeSP" type="file" value="ファイルを選択" class="hidden" name="top_fileSP2" multiple="multiple" accept="image/*;capture=camera">
<div id="previewAreaSP"></div>
</div>
</p>
<section class="spacer_30"></section>
<p>
<h3><label for="username">ユーザー名:</label></h3>
<input type="text" name="username" class="text selfinput" value="<?php echo $username?>">
</p>
<section class="spacer_30"></section>
<p>
<h3><label for="email">メールアドレス:</label></h3>
<input type="email" name="email" class="text selfinput" value="<?php echo $email?>">
</p>
<section class="spacer_30"></section>
<p>
<h3><label for="password">パスワード:</label></h3>
<input type="<PASSWORD>" name="password" class="text selfinput">
</p>
<section class="spacer_30"></section>
<p>
<h3><label for="password_conf">パスワード確認用:</label></h3>
<input type="password" name="password_conf" class="text selfinput">
</p>
<section class="spacer_30"></section>
<!--setTokenをregister.phpに送る-->
<input type="hidden" name="csrf_token" value="<?php echo $instagram->h($instagram->setToken());?>">
<p><input type="submit" value="更新" class="selfinput send-btn"></p>
</form>
<section class="spacer_50"></section>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</section>
<script src="../js/user_topImage.js"></script>
<script src="../js/user_topImageSP.js"></script>
</body>
</html><file_sep>/public/comment_detail.php
<?php
/*これだけでもIDを表示可能
$id = $_GET['id'];
echo $id;
*/
/***********************************/
session_start();
require_once ('../child_classes/comment.php');
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = Comment::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
$login_user = $_SESSION['login_user'];
/*********************************/
require_once ('../header.php');
$comment = new Comment();
$result = $comment->getComments($_GET['id']);
//$login_user = $result['login_user'];
//$username = $login_user['username'];
/*************↓コメントフォームのphp**************/
$instagram = new instagram();
$post_result = $instagram->getById($_GET['id']);
$content = $post_result['content'];
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>udastagram</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
</head>
<body>
<section id="comment_detailphp">
<h2>コメントページ</h2>
<section class="spacer_50"></section>
<h3>本文:</h3>
<div class="comment-text"><p><?php echo nl2br($content);?></p></div>
<div class="spacer_50"></div>
<h3>コメント:</h3>
<?php if(!$result){echo ('コメントがありません。');}?>
<?php if($result):?><div class="comment-text"><?php endif;?>
<?php foreach($result as $details):?>
<!--コメント者名を設置-->
<?php $postUser = $comment->postUser($details['user_id']);?>
<!--コメント者名-->
<h3>
<?php if(isset($postUser[0]['username'])):?>
<?php echo $postUser[0]['username']?>
<?php else:?>
NoNAME
<?php endif;?>
</h3>
<p><?php echo nl2br($details['content']);?></p>
<a class="reply-button" href="./comment_reply.php?id=<?php echo $_GET['id']?>&comment_id=<?php echo $details['id']?>">返信</a>
<?php if($postUser[0]['username'] == $login_user['username']):?>
<a class="delete comment-delete" href="javascript:if(confirm('本当に削除しますか?')==true) document.location='./comment_delete.php?id=<?php echo $details['id']?>&postId=<?php echo $_GET['id']?>'; else alert('キャンセルされました');">削除</a>
<?php endif;?>
<!--コメントに対するリプライを表示-->
<?php $reply_all = $comment->getReply($details['id']);?>
<?php if($reply_all):?>
<?php foreach($reply_all as $reply):?>
<section class="spacer_10"></section>
<div class="reply-content">
<?php $replyUser = $comment->replyUser($reply['user_id']);?>
<h3>
<?php if(isset($replyUser[0]['username'])):?>
<?php echo $replyUser[0]['username']?>
<?php else:?>
NoNAME
<?php endif;?>
</h3>
<p><?php echo nl2br($reply['content']);?></p>
<?php if($replyUser[0]['username'] == $login_user['username']):?>
<a class="delete comment-delete" href="javascript:if(confirm('本当に削除しますか?')==true) document.location='./comment_reply_delete.php?id=<?php echo $reply['id']?>&postId=<?php echo $_GET['id']?>'; else alert('キャンセルされました');">削除</a>
<?php endif;?>
</div>
<?php endforeach;?>
<?php endif;?>
<section class="spacer_30"></section>
<?php endforeach;?>
<?php if($result):?></div><?php endif;?>
<div class="spacer_50"></div>
<section id="comment_form">
<h3>コメントフォーム</h3>
<form action="comment_create.php" method="POST">
<input type ="hidden" name="user_id" value="<?php echo $instagram->h($login_user['id'])?>">
<textarea name="content" id="content" cols="30" rows="10" class="selfinput text"></textarea>
<br>
<input type="hidden" name="post_id" value="<?php echo $_GET['id'];?>" readonly>
<br>
<input type="submit" value="送信" class="selfinput send-btn">
</form>
<section class="spacer_50"></section>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</section>
</body>
</html>
<file_sep>/public/form.php
<?php
session_start();
require_once ('../header.php');
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = Instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
$instagram = new Instagram();
$login_user = $_SESSION['login_user'];
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="formphp">
<h2>投稿フォーム</h2>
<section class="spacer_30"></section>
<form action="instagram_create.php" method="POST" enctype="multipart/form-data">
<!--ユーザーID-->
<input type ="hidden" name="userid" value="<?php echo $instagram->h($login_user['id'])?>">
<!--スライド ドラッグ&ドロップ-->
<h3>画像:</h3>
<div id="drag-drop-area">
<div class="drag-drop-inside">
<p class="drag-drop-info">ここにファイルをドロップ</p>
<p class="drag-drop-buttons">
<input id="fileSize" type="file" value="ファイルを選択" class="hidden" name="file[]" multiple="multiple" accept="image/*;capture=camera">
</p>
<div id="previewArea"></div>
</div>
</div>
<div id="drag-drop-areaSP">
<input id="fileSizeSP" type="file" value="ファイルを選択" class="hidden" name="fileSP[]" multiple="multiple" accept="image/*;capture=camera">
<div id="previewAreaSP"></div>
</div>
<section class="spacer_30"></section>
<!--スライド ドラッグ&ドロップ-->
<!--動画 ドラッグ&ドロップ-->
<!--
<h3>動画:</h3>
<div id="drag-drop-area-movie">
<div class="drag-drop-inside">
<p class="drag-drop-info">ここにファイルをドロップ</p>
<p class="drag-drop-buttons">
<input id="fileSize_movie" type="file" value="ファイルを選択" class="hidden" name="video" accept="video/*;capture=camera">
</p>
<div id="previewArea_movie"></div>
</div>
</div>
-->
<!--動画 ドラッグ&ドロップ-->
<h3>タイトル:</h3>
<input type="text" name="title" class="selfinput text">
<section class="spacer_30"></section>
<h3>本文:</h3>
<textarea name="content" id="content" class="selfinput text" cols="30" rows="10"></textarea>
<section class="spacer_30"></section>
<h3>カテゴリ:</h3>
<select name="category" class="selfinput selectbox">
<option value="1" class="selfinput selectbox">グルメ</option>
<option value="2" class="selfinput selectbox">観光</option>
<option value="3" class="selfinput selectbox">アクティブ</option>
<option value="4" class="selfinput selectbox">その他</option>
</select>
<section class="spacer_30"></section>
<h3>住所(任意)</h3>
<input type="text" name="post_address" class="selfinput text" placeholder="〇〇県□□市△△1-1-1">
<section class="spacer_30"></section>
<section class="spacer_30"></section>
<input type="radio" name="publish_status" value="1" checked class="selfinput">公開
<input type="radio" name="publish_status" value="2" class="selfinput">下書き保存
<section class="spacer_30"></section>
<!--<input type="file" value="ファイルを選択" name="image">-->
<input type="submit" value="投稿" class="selfinput send-btn">
</form>
<section class="spacer_50"></section>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</section>
<script src="../js/slide_add.js"></script>
<script src="../js/slide_addSP.js"></script>
<!--動画 ドラッグ&ドロップ-->
<!--
<script src="../js/movie_add.js"></script>
-->
<!--動画 ドラッグ&ドロップ-->
<script>
</script>
</body>
</html><file_sep>/env.php
<?php
//ローカルxamppのDB情報
define('DB_HOST',''); //ホスト名
define('DB_NAME',''); //データベース名
define('DB_USER',''); //ユーザー名
define('DB_PASS',''); //パスワード
?><file_sep>/js/slide.js
window.onload = function(){
$('.index-btn').click(function(){
var clickedIndex = $(this).attr('data-option');
//thisの親要素のactiveのみremove
var $remove = $(this).parent().prev().children().children('.active');
$remove.removeClass('active');
//thisの親要素のslideにactiveをaddClass
var $addClass = $(this).parent().prev().children().children('.slide');
$addClass.eq(clickedIndex).addClass('active');
});
};
//var $result = $(this).parent().parent('.result');
//var $good_btn = $(this).parent('.good-btn');<file_sep>/public/instagram_update.php
<?php
/*******************************/
session_start();
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = Instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
$login_user = $_SESSION['login_user'];
/*******************************/
require_once ('../header.php');
$instagrams = $_POST;
$files = $_FILES;
//var_dump($instagrams);
//echo "<br>";
//var_dump($files);
$instagram = new Instagram();
if($_FILES['file']['name'][0] == ""){
for($i=0;$i<8;$i++){
if(empty($_FILES['fileSP']['name'][$i])){}else{
$_FILES['file']['name'][$i] = $_FILES['fileSP']['name'][$i];
$_FILES['file']['type'][$i] = $_FILES['fileSP']['type'][$i];
$_FILES['file']['tmp_name'][$i] = $_FILES['fileSP']['tmp_name'][$i];
$_FILES['file']['error'][$i] = $_FILES['fileSP']['error'][$i];
$_FILES['file']['size'][$i] = $_FILES['fileSP']['size'][$i];
}
if(empty($instagrams['slideSP'][$i])){}else{
$instagrams['slide'][$i] = $instagrams['slideSP'][$i];
}
}
$files = $_FILES;
}
//新しい画像が挿入されていなければ前の画像を挿入
if(empty($instagrams['slide'])){
$instagrams['slide'] = $instagrams['beforeSlide'];
}else{
//画像の容量とファイル名を確認
$instagrams = $instagram->fileSize($instagrams,$files);
}
//画像が入っていない配列にはnullを入れる
for($i=7;$i>0;$i--){
if(empty($instagrams['slide'][$i])){
$instagrams['slide'][$i] = null;
}
}
//画像が入っていない配列にはnullを入れる
if(empty($instagrams['post_address'])){
$instagrams['post_address'] = null;
}
//新しい動画が挿入されていなければ前の動画を挿入
if(empty($instagrams['movie'])){
if(empty($instagrams['beforeMovie'])){
$instagrams['movie'] = null;
}elseif($instagrams['beforeMovie']){
$instagrams['movie'] = $instagrams['beforeMovie'];
}
}else{
//画像の容量とファイル名を確認
$instagrams = $instagram->movieSize($instagrams,$files);
//動画削除ボタン
if($instagrams['video_delete'] == 1)$instagrams['movie'] = null;
}
$instagram->instagramValidate($instagrams);
//記事を生成,スライドが何枚あるかでメソッドが決まる。
$instagram->instagramUpdate($instagrams);
$now_year = date('Y');
$now_month = date('m');
header("Location:./index.php?year=$now_year&month=$now_month");
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="instagram_deletephp">
<p>投稿を更新しました。<br/>確認してください。</P>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</body>
</html><file_sep>/public/file_download.php
<?php
//ヘッダーを表示
require_once ('../header.php');
require_once ('../child_classes/instagram.php');
//クラスを使う
$instagram = new instagram();
// 圧縮するフォルダ名
$zipName = $_GET['dl'];
//画像ディレクトリをダウンロード
$instagram->file_downdload($zipName);
//記事を生成する。
$now_year = date('Y');
$now_month = date('m');
header("Location:./index.php?year=$now_year&month=$now_month");
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="instagram_createphp">
<p>投稿しました。<br/>確認してください。</P>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/public/good_delete.php
<?php
/*******************************/
session_start();
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = Instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
/*******************************/
$instagram = new instagram();
$postId = $_POST['post_id'];
$userId = $_POST['user_id'];
$instagram->goodDelete($postId,$userId);
//$instagram->ckeckGood($postId,$userId);
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<title>udastagram</title>
</head>
<body>
<sectoin class="good-btn">
<form action="good_btn.php" method="post" class="AjaxForm">
<input type="hidden" value="<?php echo $instagram->h($userId)?>" name="user_id">
<input type="hidden" value="<?php echo $instagram->h($postId)?>" name="post_id">
<input type="submit" value="" class="submit good-icon">
</form>
</sectoin>
<script src="../js/good_btn.js"></script>
</body>
</html><file_sep>/public/index.php
<?php
/*******************************/
session_start();
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = Instagram::checkLogin();
if(!$result){
//$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
$presentYear = date("Y");
$presentMonth = date("m");
header("Location: ../loginYet/index_loginYet.php?year=$presentYear&month=$presentMonth");
return;
}
$login_user = $_SESSION['login_user'];
/*******************************/
require_once ('../header.php');
$instagram = new Instagram();
//$instagram_data = $instagram->getByYear(date("Y"));
$instagram_data = $instagram->getByYearMonth($_GET['year'],$_GET['month']);
//最新の投稿を一番上に表示するためのソート
rsort($instagram_data);
$post = $instagram_data;
//PHPバージョン確認
//phpinfo();
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>udastagram</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js" defer></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<section id="indexphp">
<!--<a href="http://localhost/instagram/new/public/index_top.php?year=2020&month=08">新トップページ</a>-->
<section class="year-transition">
<div class="year <?php if($_GET['year'] == 2020)echo 'action-date action-year action-white'?>"><a href="./index.php?year=2020&month=<?php echo $_GET['month']?>"><span>2020年</span><?php if($_GET['year'] == 2020)echo "<div class='white-ball'></div>"?></a></div>
<div class="year <?php if($_GET['year'] == 2021)echo 'action-date action-year action-white'?>"><a href="./index.php?year=2021&month=<?php echo $_GET['month']?>"><span>2021年</span><?php if($_GET['year'] == 2021)echo "<div class='white-ball'></div>"?></a></div>
<div class="year <?php if($_GET['year'] == 2022)echo 'action-date action-year action-white'?>"><a href="./index.php?year=2022&month=<?php echo $_GET['month']?>"><span>2022年</span><?php if($_GET['year'] == 2022)echo "<div class='white-ball'></div>"?></a></div>
</section>
<section class="year-transition">
<div class="year <?php if($_GET['month'] == 1)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=01">1月</a></div>
<div class="year <?php if($_GET['month'] == 2)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=02">2月</a></div>
<div class="year <?php if($_GET['month'] == 3)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=03">3月</a></div>
<div class="year <?php if($_GET['month'] == 4)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=04">4月</a></div>
<div class="year <?php if($_GET['month'] == 5)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=05">5月</a></div>
<div class="year <?php if($_GET['month'] == 6)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=06">6月</a></div>
<div class="year <?php if($_GET['month'] == 7)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=07">7月</a></div>
<div class="year <?php if($_GET['month'] == 8)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=08">8月</a></div>
<div class="year <?php if($_GET['month'] == 9)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=09">9月</a></div>
<div class="year <?php if($_GET['month'] == 10)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=10">10月</a></div>
<div class="year <?php if($_GET['month'] == 11)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=11">11月</a></div>
<div class="year <?php if($_GET['month'] == 12)echo 'action-date action-month'?>"><a href="./index.php?year=<?php echo $_GET['year']?>&month=12">12月</a></div>
</section>
<section class="insta-list-all">
<?php require_once ('post_display.php');?>
</section>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<!--いいねボタンテスト-->
<script src="../js/good_btn.js"></script>
<!--いいねボタンテスト-->
<!--スライドテスト-->
<script src="../js/slide.js"></script>
<!--スライドテスト-->
<section class="spacer_50"></section>
</section>
</body>
</html><file_sep>/child_classes/instagram.php
<?php
require_once('../dbc.php');
//extendsだと、その後のクラスの中身を引き継いだものとなる
class Instagram extends Dbc{
protected $table_name = 'post_data';
//3.カテゴリー名を文字にする
public function setCategoryName($category){
if($category === '1'){
return 'グルメ';
}elseif($category === '2'){
return '観光';
}elseif($category === '3'){
return 'アクティブ';
}else{
return 'その他';
}
}
//記事を生成する
public function instagramCreate($instagrams){
$sql = "INSERT INTO
$this->table_name(title,slide0,slide1,slide2,slide3,slide4,slide5,slide6,slide7,movie,content,category,publish_status,user_id,post_address)
VALUES
(:title,:slide0,:slide1,:slide2,:slide3,:slide4,:slide5,:slide6,:slide7,:movie,:content,:category,:publish_status,:userid,:post_address)";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':title',$instagrams['title'],PDO::PARAM_STR);
$stmt->bindValue(':slide0',$instagrams['slide'][0],PDO::PARAM_STR);
$stmt->bindValue(':slide1',$instagrams['slide'][1],PDO::PARAM_STR);
$stmt->bindValue(':slide2',$instagrams['slide'][2],PDO::PARAM_STR);
$stmt->bindValue(':slide3',$instagrams['slide'][3],PDO::PARAM_STR);
$stmt->bindValue(':slide4',$instagrams['slide'][4],PDO::PARAM_STR);
$stmt->bindValue(':slide5',$instagrams['slide'][5],PDO::PARAM_STR);
$stmt->bindValue(':slide6',$instagrams['slide'][6],PDO::PARAM_STR);
$stmt->bindValue(':slide7',$instagrams['slide'][7],PDO::PARAM_STR);
$stmt->bindValue(':movie',$instagrams['movie'],PDO::PARAM_STR);
$stmt->bindValue(':content',$instagrams['content'],PDO::PARAM_STR);
$stmt->bindValue(':category',$instagrams['category'],PDO::PARAM_INT);
$stmt->bindValue(':publish_status',$instagrams['publish_status'],PDO::PARAM_INT);
$stmt->bindValue(':userid',$instagrams['userid'],PDO::PARAM_INT);
$stmt->bindValue(':post_address',$instagrams['post_address'],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
//記事をアップデート
public function instagramUpdate($instagrams){
$sql = "UPDATE $this->table_name SET
title = :title,slide0 = :slide0,slide1 = :slide1,slide2 = :slide2,slide3 = :slide3,slide4 = :slide4,slide5 = :slide5,slide6 = :slide6,slide7 = :slide7,movie = :movie,content = :content,category = :category,publish_status = :publish_status,post_address = :post_address
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':title',$instagrams['title'],PDO::PARAM_STR);
$stmt->bindValue(':slide0',$instagrams['slide'][0],PDO::PARAM_STR);
$stmt->bindValue(':slide1',$instagrams['slide'][1],PDO::PARAM_STR);
$stmt->bindValue(':slide2',$instagrams['slide'][2],PDO::PARAM_STR);
$stmt->bindValue(':slide3',$instagrams['slide'][3],PDO::PARAM_STR);
$stmt->bindValue(':slide4',$instagrams['slide'][4],PDO::PARAM_STR);
$stmt->bindValue(':slide5',$instagrams['slide'][5],PDO::PARAM_STR);
$stmt->bindValue(':slide6',$instagrams['slide'][6],PDO::PARAM_STR);
$stmt->bindValue(':slide7',$instagrams['slide'][7],PDO::PARAM_STR);
$stmt->bindValue(':movie',$instagrams['movie'],PDO::PARAM_STR);
$stmt->bindValue(':content',$instagrams['content'],PDO::PARAM_STR);
$stmt->bindValue(':category',$instagrams['category'],PDO::PARAM_INT);
$stmt->bindValue(':publish_status',$instagrams['publish_status'],PDO::PARAM_INT);
$stmt->bindValue(':id',$instagrams['id'],PDO::PARAM_INT);
$stmt->bindValue(':post_address',$instagrams['post_address'],PDO::PARAM_STR);
$stmt->execute();
//echo "投稿を更新しました";
}catch(PDOException $e){
exit($e);
}
}
//投稿のバリデーション(入力されているか確認する)
public function instagramValidate($instagrams){
$error = true;
if($instagrams['title'] == null || $instagrams['title'] == ''){
echo " <section class='return-btn-all'>
タイトルを入力してください。<br></section>";
$error = false;
}
if(mb_strlen($instagrams['title']) > 191){
echo " <section class='return-btn-all'>
タイトルを191文字以下にして下さい。<br></section>";
$error = false;
}
if(empty($instagrams['slide'][0])){
echo " <section class='return-btn-all'>
1枚以上画像を挿入して下さい。<br></section>";
$error = false;
}
if($instagrams['content'] == null || $instagrams['content'] == ''){
echo " <section class='return-btn-all'>
本文を入力して下さい。<br></section>";
$error = false;
}
if($instagrams['category'] == null || $instagrams['category'] == ''){
echo " <section class='return-btn-all'>
カテゴリーを入力して下さい。<br></section>";
$error = false;
}
if($instagrams['publish_status'] == null || $instagrams['publish_status'] == ''){
echo " <section class='return-btn-all'>
公開状況を入力してください。<br></section>";
$error = false;
}
//パスワード正規化
if(empty($userdata['password'])){}else{
$userdata['password'] = filter_input(INPUT_POST,'password');
if(!preg_match("/\A[a-z\d]{8,100}+\z/i",$userdata['password'])){
$err[] = 'パスワードは英数字8文字以上100文字以内にしてください。';
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
パスワードは英数字8文字以上100文字以内にしてください。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
//パスワード確認
$userdata['password_conf'] = filter_input(INPUT_POST,'password_conf');
if($userdata['password_conf'] !== $userdata['password']){
$err[] = '確認用パスワードと異なっています。';
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
確認用パスワードと異なっています。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
}
if($error == false){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
<div class='spacer_50'></div>
<div class='return-btn'><a onclick='history.back(-1)'>ページを一つ戻る</a></div>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
}
//ユーザー情報更新メソッド
public function userDataUpdateNoPass($userdata){
$sql = "UPDATE users SET
username = :username,top_image = :top_image,email = :email
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username',$userdata['username'],PDO::PARAM_STR);
$stmt->bindValue(':top_image',$userdata['top_image'],PDO::PARAM_STR);
$stmt->bindValue(':email',$userdata['email'],PDO::PARAM_STR);
$stmt->bindValue(':id',$userdata['id'],PDO::PARAM_INT);
$stmt->execute();
//echo "ユーザー情報を更新しました";
}catch(PDOException $e){
exit($e);
}
}
//ユーザー情報更新メソッド
public function userDataUpdate($userdata){
$sql = "UPDATE users SET
username = :username,top_image = :top_image,email = :email,password = :password
WHERE
id = :id";
$dbh = $this->dbConnect();
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username',$userdata['username'],PDO::PARAM_STR);
$stmt->bindValue(':top_image',$userdata['top_image'],PDO::PARAM_STR);
$stmt->bindValue(':email',$userdata['email'],PDO::PARAM_STR);
$stmt->bindValue(':password',password_hash($userdata['password'],PASSWORD_DEFAULT));
$stmt->bindValue(':id',$userdata['id'],PDO::PARAM_INT);
$stmt->execute();
//echo "ユーザー情報を更新しました";
}catch(PDOException $e){
exit($e);
}
}
public function fileSizeUser($userdata,$files){
$path = '../images/';
$before_file = $files["top_file2"]["tmp_name"];
List($original_w,$original_h,$type) = @getimagesize($before_file);
$rate = ($original_w / 200);
if($rate > 1){
$w = floor((1 / $rate) * $original_w);
$h = floor((1 / $rate) * $original_h);
echo "小さくしました";
echo '高さ:'.$h;
}else{
$w = $original_w;
$h = $original_h;
//echo "そのままでも大丈夫です";
}
switch($type){
case IMAGETYPE_JPEG:
$original_image = @imagecreatefromjpeg($before_file);
break;
case IMAGETYPE_PNG:
$original_image = @imagecreatefrompng($before_file);
break;
default:
throw new RuntimeException('対応していないファイル形式です。',$type);
}
$canvas = @imagecreatetruecolor($w,$h);
@imagecopyresampled($canvas,$original_image,0,0,0,0,$w,$h,$original_w,$original_h);
$dateformat = date("Ymdhis");
$resize_path = "$path$dateformat".".jpg";
$userdata['top_image2'] = $resize_path;
@imagejpeg($canvas,$resize_path);
/*
switch($type){
case IMAGETYPE_JPEG:
@imagejpeg($canvas,$resize_path);
break;
case IMAGETYPE_PNG:
@imagepng($canvas,$resize_path,9);
break;
}*/
@imagedestroy($original_image);
@imagedestroy($canvas);
return $userdata;
}
//ユーザー情報のバリデーション
public function userDataValidate($userdata){
$error = true;
if($userdata['username'] == null || $userdata['username'] == ''){
echo " <section class='return-btn-all'>
ユーザー名を入力して下さい。<br></section>";
$error = false;
}
if(mb_strlen($userdata['username']) > 64){
echo " <section class='return-btn-all'>
ユーザー名を64文字以下にして下さい。<br></section>";
$error = false;
}
if($userdata['top_image'] == null || $userdata['top_image'] == ''){
echo " <section class='return-btn-all'>
画像URLを入力して下さい。<br></section>";
$error = false;
}
if($userdata['email'] == null || $userdata['email'] == ''){
echo " <section class='return-btn-all'>
メールアドレスを入力して下さい。<br></section>";
$error = false;
}
if(empty($userdata['password'])){}else{
//パスワード(正規表現)
$password = $userdata['<PASSWORD>'];
if(!preg_match("/\A[a-z\d]{8,100}+\z/i",$password)){
echo " <section class='return-btn-all'>
パスワードは英数字8文字以上100文字以内にしてください。<br></section>";
$error = false;
}
//パスワード確認
if($userdata['password'] !== $userdata['<PASSWORD>']){
echo " <section class='return-btn-all'>
確認用パスワードと異なっています。<br></section>";
$error = false;
}
}
if($error == false){
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
<div class='spacer_50'></div>
<div class='return-btn'><a onclick='history.back(-1)'>ページを一つ戻る</a></div><br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
}
//ユーザー情報更新後、セッションをリセットする。
public function userdataUpload($userId){
$dbh = $this->dbConnect();
//1.SQLの準備
$sql = "SELECT *
FROM users
WHERE id = $userId";
//2.SQLの実行
$stmt = $dbh->query($sql);
//3.SQLの結果を受け取る
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
return $result;
$dbh = null;
}
//いいね追加ボタン
public function goodbtn($postId,$userId){
$dbh = $this->dbConnect();
$sql = "INSERT INTO good(post_id, user_id)
VALUE(:postId, :userId)";
try{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':postId',$postId,PDO::PARAM_INT);
$stmt->bindValue(':userId',$userId,PDO::PARAM_INT);
$stmt->execute();
//echo "投稿しました";
}catch(PDOException $e){
exit($e);
}
}
public function fileSize($instagrams,$files){
$path = '../images/';
for($i=0;$i<8;$i++){
if(empty($_FILES['file']['name'][$i])){
//echo "ファイルがありません。";
$i=8;
}else{
for($ii=0;$ii<8;$ii++){
if(empty($_FILES['file']['name'][$ii]) || empty($instagrams['slide'][$i])){
$ii = 8;
}elseif($instagrams['slide'][$i] == $_FILES['file']['name'][$ii]){
$before_file = $files["file"]["tmp_name"][$ii];
//$imagick = new \Imagick(realpath($before_file));
//$before_file = $imagick->setImageResolution(72,72);
//$before_file = Imagick::setImageResolution(72,72);
List($original_w,$original_h,$type) = @getimagesize($before_file);
$rate_w = ($original_w / 460);
if($rate_w > 1){
$w = floor((1 / $rate_w) * $original_w);
$h = floor((1 / $rate_w) * $original_h);
echo "小さくしました";
echo '高さ:'.$h;
}else{
echo "そのままでも大丈夫です";
}
$rate_h = ($original_h / 350);
if($rate_h > 1){
$w = floor((1 / $rate_h) * $original_w);
$h = floor((1 / $rate_h) * $original_h);
echo "小さくしました";
echo '高さ:'.$h;
}else{
$w = $original_w;
$h = $original_h;
//echo "そのままでも大丈夫です";
}
switch($type){
case IMAGETYPE_JPEG:
$original_image = @imagecreatefromjpeg($before_file);
break;
case IMAGETYPE_PNG:
$original_image = @imagecreatefrompng($before_file);
break;
default:
throw new RuntimeException('対応していないファイル形式です。',$type);
}
$canvas = @imagecreatetruecolor($w,$h);
@imagecopyresampled($canvas,$original_image,0,0,0,0,$w,$h,$original_w,$original_h);
//dpiの変更
//@imageresolution($canvas,9);
$dateformat = date("Ymdhis");
$resize_path = "$path$dateformat$i".".jpg";
$instagrams['slide'][$i] = $resize_path;
$ii = 8;
@imagejpeg($canvas,$resize_path);
/*下記コードだとpng画像はpng画像として保存されてしまう。
switch($type){
case IMAGETYPE_JPEG:
@imagejpeg($canvas,$resize_path);
break;
case IMAGETYPE_PNG:
@imagepng($canvas,$resize_path,9);
break;
}*/
}
}
@imagedestroy($original_image);
@imagedestroy($canvas);
}
}
return $instagrams;
}
//画像の大きさを判定とファイル名を日付の数字羅列に変更
public function movieSize($instagrams,$files){
$path = '../images/';
if($_FILES['video']['size'] < 500000000){
//サイズが大丈夫な場合、フォルダにアップロードする
//順番を入れ替えた状態でファイル名を日付の数字羅列に
list($file_name,$file_type) = explode(".",$_FILES['video']['name']);
$dateformat = date("Ymdhis");
$uploadfile = "$path$dateformat.$file_type";//$uploadfileには、日付でファイル名が格納されている
move_uploaded_file($_FILES['video']['tmp_name'],$uploadfile);
$instagrams['movie'] = $uploadfile;
}else{
$presentYear = date("Y");
$presentMonth = date("m");
echo " <section class='return-btn-all'>
ファイルのサイズが大きいため、アップロードできません。<br>
<div class='spacer_50'></div>
<div class='return-btn'><a href='../public/index.php?year=$presentYear&month=$presentMonth'>トップへ戻る</a></div></section>";
exit();
}
return $instagrams;
}
}
?><file_sep>/public/user_search.php
<?php
/*******************************/
session_start();
require_once ('../child_classes/instagram.php');
//ログインされているか判断
$result = Instagram::checkLogin();
if(!$result){
$_SESSION['login_err'] = 'ユーザー登録をして、ログインをして下さい。';
header('Location: ../login/public/login_form.php');
return;
}
$login_user = $_SESSION['login_user'];
/*******************************/
//ヘッダーを表示
require_once ('../header.php');
//送信された値を受け取る
$userId = $_POST;
//クラスを使う
$instagram = new Instagram();
//検索
//検索したユーザーのデータ(名前等)を取得
$userData = $instagram->getUserId($userId['userId']);
//検索したユーザーのIDから、投稿データを取得
$post = $instagram->getUserById($userId['userId']);
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/9f2e7499ce.js"></script>
<title>udastagram</title>
</head>
<body>
<section id="title_searchphp">
<h2 class="search-word">検索ユーザー:<?php echo $userData[0]['username']?>さん</h2>
<!--投稿があるか確認する-->
<?php
$post_all = [];
foreach($post as $publish){
if($publish['publish_status'] == 1){
$post_all[] = $publish;
}
}
?>
<?php if(empty($post_all)):?>
<div class="spacer_50"></div>
<p>検索されたユーザーの投稿はありません。</p>
<?php endif;?>
<!--最新の投稿を一番上に表示するためのソート-->
<?php arsort($post);?>
<section class="insta-list-all">
<!--全ての投稿を表示-->
<?php require_once ('post_display.php');?>
</section>
<!--いいねボタンテスト-->
<script src="../js/good_btn.js"></script>
<!--いいねボタンテスト-->
<!--スライドテスト-->
<script src="../js/slide.js"></script>
<!--スライドテスト-->
<section class="spacer_50"></section>
<div class="return-btn"><a href="./index.php?year=<?php echo date("Y")?>&month=<?php echo date("m")?>">トップへ戻る</a></div>
<section class="spacer_50"></section>
</section>
</body>
</html> | 72c01b47d37a0a34cc327d68883395ebd779fe2a | [
"JavaScript",
"SQL",
"Markdown",
"PHP"
] | 39 | PHP | ryoji-U/php-portfolio | b7aa46e96c01047f9842cd023d0f7eb7e33b4979 | 02e93296e8d10325a2f7a48928efafa7f2ddf3a5 |
refs/heads/master | <repo_name>pepetox/rails-mpv-seed<file_sep>/app/views/things/index.json.jbuilder
json.array!(@things) do |thing|
json.extract! thing, :id, :name, :private, :user_id
json.url thing_url(thing, format: :json)
end
<file_sep>/Gemfile
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails'
#--------DATABASE------
# Use mysql as the database for Active Record
#gem 'mysql2'
# Use postgresql as the database for Active Record
#gem 'pg'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring', group: :development
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
##Server
# Use unicorn as the app server, p for port, E for enviroment and -D for daemon
# unicorn -p 8080 -E production -D
gem 'unicorn'
#gem 'puma'
##For styles
#gem 'pure-css-rails'
gem 'materialize-sass'
#if need geocoding and maps
# gem 'geocoder'
# gem 'underscore-rails'
# gem 'gmaps4rails'
#For charts
# gem 'chartkick'
# gem 'groupdate'
#searching
# gem "ransack"
# gem 'sunspot_rails'
# gem 'sunspot_solr' # optional pre-packaged Solr distribution for use in development
#pagination
#gem 'kaminari'
#Autentification and authoritation
gem 'devise'
gem 'cancan'
gem 'tzinfo', '~> 1.2.2'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
gem 'nokogiri'
#gem 'dalli'
#gem 'htmltoword'
#gem 'rubyzip'
#gem 'zip-zip'
#gem 'execjs'
#gem 'carrierwave'
#gem 'ckeditor'
#gem 'mini_magick'
#gem 'jquery-fileupload-rails'
gem 'therubyracer', :platforms => :ruby
#gem 'wkhtmltopdf-binary'
#gem "pdfkit"
# kgem 'best_in_place', github: 'aaronchi/best_in_place' #para la edición en el sitio en con doble click
#gem "breadcrumbs_on_rails"
#gem 'rmagick', :require => 'RMagick'
#gem 'sidekiq'
group :development do
gem 'guard'
gem 'guard-minitest'
gem 'guard-cucumber'
gem 'guard-rspec'
gem 'bullet'
gem 'ruby-growl'
end
group :production, :staging do
gem 'rails_12factor'
end
group :development, :test do
gem 'progress_bar'
#gem "minitest"
gem "spork-rails"
gem 'capybara'
gem 'rspec-rails'
gem 'rspec-activemodel-mocks'
gem 'cucumber-rails', :require => false
gem 'database_cleaner'
gem 'selenium-webdriver'
gem 'factory_girl_rails'
gem 'launchy'
gem 'poltergeist'
#gem 'debugger'
gem 'pdf-reader'
#test de rendimiento
gem 'rails-perftest'
gem 'ruby-prof'
end
<file_sep>/app/controllers/things_controller.rb
class ThingsController < ApplicationController
before_action :set_thing, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
respond_to :html
def index
@things = Thing.all
respond_with(@things)
end
def show
respond_with(@thing)
end
def new
@thing = Thing.new
respond_with(@thing)
end
def edit
end
def create
@thing = Thing.new(thing_params)
@thing.save
respond_with(@thing)
end
def update
@thing.update(thing_params)
respond_with(@thing)
end
def destroy
@thing.destroy
respond_with(@thing)
end
private
def set_thing
@thing = Thing.find(params[:id])
end
def thing_params
params.require(:thing).permit(:name, :private, :user_id)
end
end
<file_sep>/spec/factories/things.rb
FactoryGirl.define do
factory :thing do
name "MyString"
private false
user nil
end
end
<file_sep>/features/step_definitions/my_steps.rb
Given(/^A signed in (.+)$/) do |user_type|
@user = create(user_type)
login_as(@user, :scope => :user)
end
Given(/^A unsigned in user$/) do
logout
end
Given(/^I am on (.+)$/) do |page_name|
visit path_to(page_name)
end
Given(/^There is a (.+)$/) do |thing_name|
@thing_name = create(thing_name.to_s)
end
When(/^I go to (.+)$/) do |page_name|
visit path_to(page_name)
end
When (/^(?:|I )press "([^"]*)"$/) do |button|
click_button(button)
end
When (/^(?:|I )click in "([^"]*)"$/) do |link|
click_link(link)
end
When(/^I click in the icon "(.*?)"$/) do |icon|
puts page.find(".#{icon}")
end
Then (/^(?:|I )should be on (.+)$/) do |page_name|
current_path = URI.parse(current_url).path
if current_path.respond_to? :should
current_path.should == path_to(page_name)
else
assert_equal path_to(page_name), current_path
end
end
Then(/^I should go to (.*?) page$/) do |arg1|
if(arg1 == "my customer")
visit customer_path(@cliente)
end
end
Then(/^I should see field "(.*?)" of "(.*?)"$/) do |arg2, arg1|
if page.respond_to? :should
page.should have_content(@arg1.send(arg2).to_s)
else
assert page.has_content?(@arg1.send(arg2).to_s)
end
end
Then(/^I should see user email$/) do
if page.respond_to? :should
page.should have_content(@user.email.to_s)
else
assert page.has_content?(@user.email.to_s)
end
end
Then (/^(?:|I )should see "([^"]*)"$/) do |text|
if page.respond_to? :should
page.should have_content(text)
else
assert page.has_content?(text)
end
end
Then (/^show me the page$/) do
save_and_open_page
end
Then (/^(?:|I )should not see "([^"]*)"$/) do |text|
if page.respond_to? :should
page.should have_no_content(text)
else
assert page.has_no_content?(text)
end
end
When(/^I choose "(.*?)" in "(.*?)"$/) do |arg1, arg2|
page.select(arg1, :from => arg2)
end
Then(/^I should see icon "(.*?)"$/) do |arg1|
page.find('span.mostrar').should be_present
end
Then /^"([^"]*)" should be selected for "([^"]*)"(?: within "([^\"]*)")?$/ do |value, field, selector|
with_scope(selector) do
field_labeled(field).find(:xpath, ".//option[@selected = 'selected'][text() = '#{value}']").should be_present
end
end
Then /^I should get a download with the filename "([^\"]*)"$/ do |filename|
page.driver.response.headers['Content-Disposition'].should eq ("filename=\"#{filename}\"")
end
<file_sep>/app/views/things/show.json.jbuilder
json.extract! @thing, :id, :name, :private, :user_id, :created_at, :updated_at
<file_sep>/README.md
rails-mpv-seed
==============
A good start for a mpv with rails and angular, with cucumber ready to use, devise, can can and more
<file_sep>/features/support/warden.rb
Warden.test_mode!
World Warden::Test::Helpers
World(FactoryGirl::Syntax::Methods)
After { Warden.test_reset! } | f5c1550372c210b721c022d9ddc9d059ef3155b7 | [
"Markdown",
"Ruby"
] | 8 | Ruby | pepetox/rails-mpv-seed | cd3f1c599c3934de0559cad715b64e1b3c13be9d | f6844b089fbe3fcd21a20fb2d361369d074d19fa |
refs/heads/master | <repo_name>jiachaofeng/codetest<file_sep>/README.md
# codetest
Please execute MainApp.main()
Sample output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
Fizz
14
FizzBuzz
16
... etc up to 100<file_sep>/src/main/java/com/github/codetest/util/MathUtil.java
package com.github.codetest.util;
public class MathUtil {
public static boolean isDivisibleByNumber(Integer inVal, Integer number){
if(inVal == null || number == null || number == 0){
return false;
}
if(inVal % number == 0){
return true;
}else {
return false;
}
}
public static boolean isContainsNumber(Integer inVal, Integer number){
if(inVal == null || number == null){
return false;
}
String sVal = inVal.toString();
String sNumber = number.toString();
if(sVal.contains(sNumber)){
return true;
}else {
return false;
}
}
}
| e1f86e1639776f7df3ccddbe85644f9207e50c9d | [
"Markdown",
"Java"
] | 2 | Markdown | jiachaofeng/codetest | dacd9f439ea1d252eab3867078c061a6b95c9805 | 1e4051f4b85599aeb06de986a500f67819178fde |
refs/heads/master | <repo_name>vdixit-fordham/FeatureSelection<file_sep>/README.md
# FeatureSelection
This project is to implement feature selection techniques using filter and wrapper method
For this project, we will be extending our KNN classifier to include automated feature selection. Feature selection is used to remove irrelevant or correlated features in order to improve classification performance. We will be performing feature selection on a variant of the UCI vehicle dataset in the file veh-prime.arff. We will be comparing 2 different feature selection methods: <br />
Filter method which doesn't make use of cross-validation performance and the Wrapper method which does. <br />
<br />
Fix the KNN parameter to be k = 7 for all runs of LOOCV in both task. <br />
<br />
Filter Method <br />
Make the class labels numeric (set \noncar"=0 and \car"=1) and calculate the Pearson Correlation Coeficient (PCC) of each feature with the numeric class label. The PCCvalue is commonly referred to as r. For a simple method to calculate the PCC that is both computationally eficient and numerically stable, see the pseudo code in the pearson.html file.<br />
(a) Fine the features from highest |r| (the absolute value of r) to lowest, along with their |r| values. <br />
(b) Select the features that have the highest m values of |r|, and run LOOCV on the dataset restricted to only those m features. Which value of m gives the highest LOOCV classification accuracy, and what is the value of this optimal accuracy?<br />
<br />
Wrapper Method<br />
Starting with the empty set of features, use a greedy approach to add the single feature that improves performance by the largest amount when added to the feature set. This is Sequential Forward Selection. Define performance as the LOOCV classification accuracy of the KNN classifier using only the features in the selection set (including the ?candidate? feature). Stop adding features only when there is no candidate that when added to the selection set increases the LOOCV accuracy. <br />
(a) Show the set of selected features at each step, as it grows from size zero to its final size (increasing in size by exactly one feature at each step). <br />
(b) What is the LOOCV accuracy over the final set of selected features?
<file_sep>/Question-4.py
from __future__ import division
from scipy.io import arff
import numpy as np
import pandas as pd
from pandas import DataFrame as df
import time
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
def normalizeDF(dataFrame):
dfNormalized = dataFrame.copy()
colList = list(dataFrame.columns)
#print(cols)
for col in range(len(colList)):
colMean = dataFrame[colList[col]].mean()
colStd = dataFrame[colList[col]].std()
#print(col,'= ', colMean)
#print(col,'= ', colStd)
dfNormalized[colList[col]] = (dataFrame[colList[col]] - colMean)/colStd
return dfNormalized
def getPredictedClassUsingKNN(trainDF , testRow, trainLableDF):
kValue = 7
#print(trainDF)
#print(testRow)
#print("trainLableDF =", len(trainLableDF))
#This DF will have the distance sorted (ascending)
distanceDF = calculateEculidDist(trainDF , testRow)
#print(distanceDF)
kRows = distanceDF.iloc[:kValue]
#print("kRows ------ > ", kRows)
#print("kRows ------ > ", kRows.index)
#print(trainLableDF.iloc[kRows.index.tolist()]['CLASS'].values)
#print("Index =", kRows.index.tolist())
tmp = trainLableDF.iloc[kRows.index.tolist()]['CLASS'].value_counts()
#print(tmp)
#print(tmp.idxmax())
return tmp.idxmax()
def calculateEculidDist(trainDF , testRow):
#np.sqrt(np.sum(np.square((trainArray - testArray))))
tmp = (((trainDF.sub( testRow, axis=1))**2).sum(axis=1))**0.5
tmp.sort_values(axis=0, ascending=True, inplace=True)
#print(type(tmp))
return tmp
startTime = time.clock()
data = arff.loadarff("veh-prime.arff")
trainDF = pd.DataFrame(data[0])
trainLableDF = trainDF[['CLASS']].copy()
trainDF.drop('CLASS' , axis=1, inplace=True)
# Updating noncar as 0 and car as 1.
trainLableDF['CLASS'] = np.where(trainLableDF['CLASS'] == b'noncar', 0, 1)
print(trainLableDF)
# Z score normalization
trainDFNormalized = normalizeDF(trainDF)
#print(trainDFNormalized)
featureList = trainDF.columns.tolist()
remainingFeatureList = trainDF.columns.tolist()
print(featureList)
selectedFeatureList = []
accuracyAttain = 0
#tmp = [1,5,8000,10,1000]
#print(max(tmp))
#print(tmp.index(max(tmp)))
iteration = 1
print("********* Starting feature selection using wrapper method (with empty set of feature) **********")
while (len(remainingFeatureList) > 0):
print("Iteration = ", iteration)
iteration += 1
tmpAccuracyList = []
for counter in range(len(remainingFeatureList)):
tmpFeatureList = selectedFeatureList + [remainingFeatureList[counter]]
#print(tmpFeatureList)
tmptrainDF = trainDFNormalized[tmpFeatureList]
#print(tmptrainDF.columns)
index = 0
accuracyCount = 0
predictedClassList = []
for row in tmptrainDF.itertuples(index=False):
tmpDF = tmptrainDF.drop(index)
#tmpTrainLableDF = trainLableDF.drop(index)
#print(len(tmpTrainLableDF))
predictedClass = getPredictedClassUsingKNN(tmpDF, row, trainLableDF)
#print("predictedClass---- ", predictedClass, " class ---- ", trainLableDF.iloc[index]['CLASS'])
#if(predictedClass == trainLableDF.iloc[index]['CLASS']):
#accuracyCount += 1
#index += 1
predictedClassList.append(predictedClass)
predictedTestLabelDF = pd.DataFrame({"CLASS" : predictedClassList})
#print(predictedTestLabelDF)
differenceLabel = trainLableDF.sub(predictedTestLabelDF , axis=1)
#print(differenceLabel)
accuracyCount = len(differenceLabel[ differenceLabel['CLASS'] ==0 ])
tmpAccuracyList.append(round(((accuracyCount/len(trainDFNormalized))*100),2))
print("Features = ",remainingFeatureList )
print("Accuracies = ",tmpAccuracyList )
maxAccuracy = max(tmpAccuracyList)
maxAccuracyIndex = tmpAccuracyList.index(max(tmpAccuracyList))
maxAccuracyFeature = remainingFeatureList[maxAccuracyIndex]
print("Maximum Accuracy achieved is ",maxAccuracy, "%, with feature ",maxAccuracyFeature)
if(maxAccuracy >= accuracyAttain):
selectedFeatureList.append(maxAccuracyFeature)
remainingFeatureList.remove(maxAccuracyFeature)
accuracyAttain = maxAccuracy
print("New Selected feature subset is ",selectedFeatureList)
else:
print("Accuracy is not increased from the previous feature set, Breaking the iteration")
break
print("Final Selected Feature set is ,", selectedFeatureList)
print("Final Accuracy with above feature set is ", accuracyAttain)
print('Total Time taken is ', (time.clock() - startTime))
#featureList.remove('f4')
#print(featureList)
<file_sep>/Question-3B.py
from __future__ import division
from scipy.io import arff
import numpy as np
import pandas as pd
from pandas import DataFrame as df
def normalizeDF(dataFrame):
dfNormalized = dataFrame.copy()
colList = list(dataFrame.columns)
#print(cols)
for col in range(len(colList)):
colMean = dataFrame[colList[col]].mean()
colStd = dataFrame[colList[col]].std()
#print(col,'= ', colMean)
#print(col,'= ', colStd)
dfNormalized[colList[col]] = (dataFrame[colList[col]] - colMean)/colStd
return dfNormalized
def calculatePCC(xDF , yDF, ySumSqurd, yMean):
xSumSqurd = np.sum(np.square(xDF))
#ySumSqurd = np.sum(np.square(yDF))
sumCoProduct = np.sum( xDF * yDF )
xMean = np.mean(xDF)
xPopSD = np.sqrt( (xSumSqurd / float(len(xDF))) - (xMean**2) )
yPopSD = np.sqrt( (ySumSqurd / float(len(yDF))) - (yMean**2) )
xyCov = ( (sumCoProduct / float(len(yDF))) - (xMean * yMean) )
correlation = ( xyCov / (xPopSD * yPopSD) )
#print(correlation)
return correlation
def getPredictedClassUsingKNN(trainDF , testRow, trainLableDF):
kValue = 7
#print(trainDF)
#print(testRow)
#print(trainLableDF)
#This DF will have the distance sorted (ascending)
distanceDF = calculateEculidDist(trainDF , testRow)
#print(distanceDF)
kRows = distanceDF.iloc[:kValue]
#print("kRows ------ > ", kRows)
#print("kRows ------ > ", kRows.index)
#print(trainLableDF.iloc[kRows.index.tolist()]['CLASS'].values)
tmp = trainLableDF.iloc[kRows.index.tolist()]['CLASS'].value_counts()
#print(tmp)
return tmp.idxmax()
def calculateEculidDist(trainDF , testRow):
#np.sqrt(np.sum(np.square((trainArray - testArray))))
tmp = (((trainDF.sub( testRow, axis=1))**2).sum(axis=1))**0.5
tmp.sort_values(axis=0, ascending=True, inplace=True)
#print(type(tmp))
return tmp
data = arff.loadarff("veh-prime.arff")
trainDF = pd.DataFrame(data[0])
trainLableDF = trainDF[['CLASS']].copy()
trainDF.drop('CLASS' , axis=1, inplace=True)
# Updating noncar as 0 and car as 1.
trainLableDF['CLASS'] = np.where(trainLableDF['CLASS'] == b'noncar', 0, 1)
# Z score normalization
trainDFNormalized = normalizeDF(trainDF)
#print(trainDF)
# Calculating Sum Squared Y (For class lebel)
ySumSqurd = np.sum(np.square(trainLableDF['CLASS']))
yMean = np.mean(trainLableDF['CLASS'])
#print(ySumSqurd)
#print(yMean)
pccList = []
abspccList = []
featureList = []
for counter in range(len(trainDF.columns)):
#print(trainDF.columns[counter])
featureList.append(trainDF.columns[counter])
pcc = calculatePCC(trainDF[trainDF.columns[counter]], trainLableDF['CLASS'], ySumSqurd, yMean)
pccList.append( pcc )
abspccList.append( np.abs(pcc) )
#print(featureList)
tmpDict = {'feature' : featureList , 'pcc' : pccList, 'abspcc' : abspccList}
pccDF = pd.DataFrame(tmpDict)
pccDF.sort_values(['abspcc'] , ascending=0 , inplace=True)
#print(pccDF)
rankedFeatureList = pccDF['feature'].tolist()
#rankedFeatureList = ['f4']
#print(rankedFeatureList)
for counter in range(len(rankedFeatureList)):
print("Selected Feature set -- ", rankedFeatureList[:counter+1])
#tmptrainDF = trainDF[rankedFeatureList[:counter+1]]
tmptrainDF = trainDFNormalized[rankedFeatureList[:counter+1]]
#print(tmptrainDF)
index = 0
accuracyCount = 0
for row in tmptrainDF.itertuples(index=False):
#print("For row --- ", index)
#if(index > 2):
#break
tmpDF = tmptrainDF.drop(index)
predictedClass = getPredictedClassUsingKNN(tmpDF, row, trainLableDF)
#print("predictedClass---- ", predictedClass, " class ---- ", trainLableDF.iloc[index]['CLASS'])
if(predictedClass == trainLableDF.iloc[index]['CLASS']):
accuracyCount += 1
index += 1
print("Accuracy Count = ", accuracyCount)
print("Accuracy Percentage = ", round((accuracyCount / len(trainDFNormalized))*100, 2))
print("\n")
#print(trainDF[['f0', 'f1']])
<file_sep>/Question-3A.py
from scipy.io import arff
import numpy as np
import pandas as pd
from pandas import DataFrame as df
def calculatePCC(xDF , yDF, ySumSqurd, yMean):
xSumSqurd = np.sum(np.square(xDF))
#ySumSqurd = np.sum(np.square(yDF))
sumCoProduct = np.sum( xDF * yDF )
xMean = np.mean(xDF)
xPopSD = np.sqrt( (xSumSqurd / float(len(xDF))) - (xMean**2) )
#print((ySumSqurd / len(yDF)) - (yMean**2))
yPopSD = np.sqrt( (ySumSqurd / float(len(yDF))) - (yMean**2) )
xyCov = ( (sumCoProduct / len(yDF)) - (xMean * yMean) )
correlation = ( xyCov / (xPopSD * yPopSD) )
#print(correlation)
return correlation
data = arff.loadarff("veh-prime.arff")
trainDF = pd.DataFrame(data[0])
# Updating noncar as 0 and car as 1.
trainDF['CLASS'] = np.where(trainDF['CLASS'] == b'noncar', 0, 1)
#print(trainDF)
# Calculating Sum Squared Y (For class lebel)
ySumSqurd = np.sum(np.square(trainDF['CLASS']))
yMean = np.mean(trainDF['CLASS'])
#print(ySumSqurd)
#print(yMean)
pccList = []
abspccList = []
featureList = []
for counter in range(len(trainDF.columns) - 1):
#print(trainDF.columns[counter])
featureList.append(trainDF.columns[counter])
pcc = calculatePCC(trainDF[trainDF.columns[counter]], trainDF['CLASS'], ySumSqurd, yMean)
pccList.append( pcc )
abspccList.append( np.abs(pcc) )
tmpDict = {'feature' : featureList , 'pcc' : pccList, '|pcc|' : abspccList}
#print(len(pccList))
#print(len(columnList))
pccDF = pd.DataFrame(tmpDict)
print(pccDF.sort_values(['|pcc|'] , ascending=0))
| 9652ddf01156b1528de8ef5bbf6796edbf28558c | [
"Markdown",
"Python"
] | 4 | Markdown | vdixit-fordham/FeatureSelection | c695c20bf10477ccd6cf4c831dd1936c5b23cffc | c1ada9d294a46d2dfed4954973658a1bd440505b |
refs/heads/master | <file_sep>package roiattia.com.imagessearch.data.domain_model
import roiattia.com.imagessearch.data.mapper.Mapper
import roiattia.com.imagessearch.data.web_dto.ImageResponse
data class Image(
val previewURL: String,
val largeImageUrl: String
) {
companion object {
val NetworkMapper by lazy {
object : Mapper<ImageResponse, Image> {
override fun map(source: ImageResponse): Image {
source.apply {
return Image(
previewURL, largeImageUrl
)
}
}
}
}
}
}
<file_sep>package roiattia.com.imagessearch.di
import android.content.Context
import android.content.SharedPreferences
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import roiattia.com.imagessearch.utils.Constants.SharedPreferences.FILE_NAME
import roiattia.com.imagessearch.data.repositories.ImageRepositoryImpl
import roiattia.com.imagessearch.data.repositories.ImagesRepository
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
abstract class AppModule {
@Binds
abstract fun provideImagesRepository(repository: ImageRepositoryImpl): ImagesRepository
companion object {
@Singleton
@JvmStatic
@Provides
fun providePreferences(@ApplicationContext appContext: Context): SharedPreferences =
appContext.getSharedPreferences(
FILE_NAME,
Context.MODE_PRIVATE
)
}
}<file_sep>rootProject.name = "ImagesSearch"
include ':app'
<file_sep>package roiattia.com.imagessearch.network
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
import roiattia.com.imagessearch.utils.Constants.Network.SEARCH_IMAGES
import roiattia.com.imagessearch.data.web_dto.ImagesListResponse
interface PixabayWebApi {
@GET(SEARCH_IMAGES)
suspend fun searchImages(
@Query("q") query: String,
@Query("page") page: Int,
@Query("key") apiKey: String
): Response<ImagesListResponse>
}<file_sep>package roiattia.com.imagessearch.utils
object Constants {
object Network {
const val API_KEY = ""
const val BASE_URL = "https://pixabay.com/"
const val SEARCH_IMAGES = "api/"
}
object SharedPreferences {
const val FILE_NAME = "images_search_preferences"
const val SEARCH_IMAGES_QUERY = "query"
}
}<file_sep>package roiattia.com.imagessearch.data.mapper
// Non-nullable to Non-nullable
interface ListMapper<I, O> : Mapper<List<I>, List<O>>
class ListMapperImpl<I, O>(
private val mapper: Mapper<I, O>
) : ListMapper<I, O> {
override fun map(source: List<I>): List<O> {
return source.map { mapper.map(it) }
}
}
<file_sep>package roiattia.com.imagessearch.utils
import android.content.SharedPreferences
import javax.inject.Inject
class PreferencesManager @Inject constructor(
private val prefs: SharedPreferences
) {
fun putString(key: String, value: String) {
prefs.edit().putString(key, value).apply()
}
fun getString(key: String, defValue: String): String? {
return prefs.getString(key, defValue)
}
}<file_sep>package roiattia.com.imagessearch.data.mapper
interface Mapper<T, R> {
fun map(source: T): R
}<file_sep>package roiattia.com.imagessearch.ui.search_images
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.list_item_image.view.*
import roiattia.com.imagessearch.R
import roiattia.com.imagessearch.data.domain_model.Image
class ImagesAdapter(
private var images: List<Image>
) : RecyclerView.Adapter<ImagesAdapter.CriteriaViewHolder>() {
fun setData(images: List<Image>) {
this.images = images
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CriteriaViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.list_item_image, parent, false)
return CriteriaViewHolder(view)
}
override fun onBindViewHolder(holder: CriteriaViewHolder, position: Int) {
val image = images[position]
holder.bindImage(image)
}
override fun getItemCount(): Int = images.size
class CriteriaViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
fun bindImage(image: Image) {
Glide.with(view)
.load(image.largeImageUrl)
.into(view.imageView)
}
}
}<file_sep>package roiattia.com.imagessearch.ui.search_images
import androidx.lifecycle.*
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import roiattia.com.imagessearch.utils.Constants.SharedPreferences.SEARCH_IMAGES_QUERY
import roiattia.com.imagessearch.utils.PreferencesManager
import roiattia.com.imagessearch.data.domain_model.Image
import roiattia.com.imagessearch.data.domain_model.Image.Companion.NetworkMapper
import roiattia.com.imagessearch.data.mapper.ListMapperImpl
import roiattia.com.imagessearch.data.repositories.ImagesRepository
import roiattia.com.imagessearch.data.repositories.SearchState
import roiattia.com.imagessearch.data.web_dto.ImageResponse
import timber.log.Timber
import javax.inject.Inject
@HiltViewModel
class SearchImagesViewModel @Inject constructor(
private val repository: ImagesRepository,
private val prefsManager: PreferencesManager
) : ViewModel(), LifecycleObserver {
var query = prefsManager.getString(SEARCH_IMAGES_QUERY, "") ?: ""
private var page = 1
private var imagesList = ArrayList<Image>()
private val _showProgressBar = MutableLiveData<Boolean>()
val showProgressBar: LiveData<Boolean> = _showProgressBar
private val _command = MutableLiveData<Command>()
val command: LiveData<Command> = _command
sealed class Command {
data class UpdateImages(val images: List<Image>) : Command()
}
fun onGoClicked() {
page = 1
searchImages(query, page)
prefsManager.putString(SEARCH_IMAGES_QUERY, query)
}
fun loadNextPage() {
page += 1
searchImages(query, page)
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
private fun initView() {
observeSearchState()
searchImages(query, page)
}
private fun observeSearchState() {
viewModelScope.launch {
repository.searchState.collect { searchProgress ->
when (searchProgress) {
is SearchState.Success -> {
if(searchProgress.images.isNotEmpty()){
handleImages(searchProgress.images)
} else{
//TODO: handle no search results
}
}
is SearchState.Failed -> {
_showProgressBar.value = false
Timber.d(searchProgress.errorMessage)
}
is SearchState.InProgress -> {
_showProgressBar.value = true
}
is SearchState.NotStarted -> {
}
}
}
}
}
private fun handleImages(responseImages: List<ImageResponse>) {
val images = ListMapperImpl(NetworkMapper).map(responseImages)
//TODO: handle case where loaded last page
if (page > 1) {
imagesList.addAll(images)
} else {
imagesList = images as ArrayList<Image>
}
_command.value = Command.UpdateImages(imagesList)
_showProgressBar.value = false
}
private fun searchImages(query: String, page: Int){
viewModelScope.launch {
repository.searchImages(query, page)
}
}
}<file_sep>package roiattia.com.imagessearch.ui.search_images
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_search_images.*
import roiattia.com.imagessearch.R
import roiattia.com.imagessearch.data.domain_model.Image
import roiattia.com.imagessearch.databinding.FragmentSearchImagesBinding
@AndroidEntryPoint
class SearchImagesFragment : Fragment() {
private val viewModel: SearchImagesViewModel by viewModels()
lateinit var adapter: ImagesAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycle.addObserver(viewModel)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return DataBindingUtil.inflate<FragmentSearchImagesBinding>(
inflater, R.layout.fragment_search_images, container, false
).also {
it.viewModel = this@SearchImagesFragment.viewModel
it.lifecycleOwner = this
}.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initRecyclerView()
subscribeViewModelCommand()
}
private fun initRecyclerView() {
adapter = ImagesAdapter(emptyList())
rvImages.adapter = adapter
rvImages.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
val isBottomReached = !recyclerView.canScrollVertically(1)
if (isBottomReached) {
viewModel.loadNextPage()
}
}
})
}
private fun subscribeViewModelCommand() {
viewModel.command.observe(viewLifecycleOwner, {
when (it) {
is SearchImagesViewModel.Command.UpdateImages -> updateImages(it.images)
}
})
}
private fun updateImages(images: List<Image>) {
adapter.setData(images)
}
}<file_sep>package roiattia.com.imagessearch.data.web_dto
import com.google.gson.annotations.SerializedName
data class ImagesListResponse(
@SerializedName("total") val total: Int,
@SerializedName("totalHits") val totalHits: Int,
@SerializedName("hits") val hits: List<ImageResponse>
)
data class ImageResponse(
@SerializedName("id") val id: Int,
@SerializedName("pageURL") val pageURL: String,
@SerializedName("photo") val photo: String,
@SerializedName("tags") val tags: String,
@SerializedName("previewURL") val previewURL: String,
@SerializedName("previewWidth") val previewWidth: Int,
@SerializedName("previewHeight") val previewHeight: Int,
@SerializedName("webformatURL") val webFormatUrl: String,
@SerializedName("webformatWidth") val webFormatWidth: Int,
@SerializedName("webformatHeight") val webFormatHeight: Int,
@SerializedName("largeImageURL") val largeImageUrl: String,
@SerializedName("fullHDURL") val fullHdUrl: String,
@SerializedName("imageURL") val imageUrl: String,
@SerializedName("imageWidth") val imageWidth: Int,
@SerializedName("imageHeight") val imageHeight: Int,
@SerializedName("imageSize") val imageSize: Int,
@SerializedName("views") val views: Int,
@SerializedName("downloads") val downloads: Int,
@SerializedName("favorites") val favorites: Int,
@SerializedName("likes") val likes: Int,
@SerializedName("comments") val comments: Int,
@SerializedName("user_id") val userId: Int,
@SerializedName("user") val user: String,
@SerializedName("userImageURL") val userImageUrl: String,
)
<file_sep>package roiattia.com.imagessearch.di
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import roiattia.com.imagessearch.utils.Constants.Network.BASE_URL
import roiattia.com.imagessearch.network.PixabayWebApi
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
object NetworkModule {
@JvmStatic
@Singleton
@Provides
fun provideRetrofitBuilder(converterFactory: Converter.Factory): Retrofit =
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(converterFactory)
.build()
@JvmStatic
@Singleton
@Provides
fun provideGson(): Gson = GsonBuilder().serializeNulls().setLenient().create()
@JvmStatic
@Singleton
@Provides
fun provideConverterFactory(gson: Gson): Converter.Factory = GsonConverterFactory.create(gson)
@JvmStatic
@Singleton
@Provides
fun providePixabayWebApi(retrofit: Retrofit): PixabayWebApi =
retrofit.create(PixabayWebApi::class.java)
}<file_sep>package roiattia.com.imagessearch.data.repositories
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
import roiattia.com.imagessearch.utils.Constants.Network.API_KEY
import roiattia.com.imagessearch.data.web_dto.ImageResponse
import roiattia.com.imagessearch.network.PixabayWebApi
import timber.log.Timber
import javax.inject.Inject
interface ImagesRepository {
val searchState: StateFlow<SearchState>
suspend fun searchImages(query: String, page: Int)
}
sealed class SearchState {
object NotStarted : SearchState()
object InProgress: SearchState()
data class Success(val images: List<ImageResponse>) : SearchState()
data class Failed(val errorMessage: String) : SearchState()
}
class ImageRepositoryImpl @Inject constructor(
private val webApi: PixabayWebApi
) : ImagesRepository {
private val _searchState = MutableStateFlow<SearchState>(SearchState.NotStarted)
override val searchState: StateFlow<SearchState>
get() = _searchState
override suspend fun searchImages(query: String, page: Int) = withContext(Dispatchers.IO) {
Timber.d("searchImages query = $query page = $page")
_searchState.value = SearchState.InProgress
try {
val response = webApi.searchImages(query, page, API_KEY)
if (response.isSuccessful) {
response.body()?.let {
_searchState.value = SearchState.Success(it.hits)
}
}
} catch (e: Exception) {
_searchState.value = SearchState.Failed("Exception ${e.message}")
}
}
} | e66d51cf1921a0375d8067f0d7145eb02e5f5b3f | [
"Kotlin",
"Gradle"
] | 14 | Kotlin | roiAttia/ImagesSearch | 26fff0d38061daee1a98630f75319b60e9d9cbe8 | af4c37ff36d317c4949953c76e1636f22f828ea5 |
refs/heads/master | <file_sep>import { Link } from "react-router-dom";
function NavBarRoute(){
return(
<ul className="d-flex list-unstyled justify-content-center">
<li className="mx-2"><Link to="/" className="p-2">Home</Link></li>
<li className="mx-2"><Link to="/counterContent" className="p-2">Counter</Link></li>
<li className="mx-2"><Link to="/shop" className="p-2">Shop</Link></li>
</ul>
)
}
export default NavBarRoute;<file_sep>import "./Counter.css";
function Counter(props){
return(
<>
<h1>{props.myCount}</h1>
<h2>increment app</h2>
</>
)
}
export default Counter;<file_sep>import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
function ShopSelectedItem({ match }) {
const [singleProduct, setSingleProduct] = useState({})
//useEffect function
useEffect(() => {
fetchProduct();
}, [])
const fetchProduct = () => {
return (
fetch(`https://fakestoreapi.com/products/${match.params.id}`)
.then(res => res.json())
.then(json => setSingleProduct(json))
)
}
console.log(singleProduct);
return (
<div>
{
singleProduct
?
(
<div className="container shop-list">
<h2>product number {singleProduct.id}</h2>
<hr />
<div className="singleItem row">
<figure className="col-sm-4"><img className="w-50" src={singleProduct.image} alt="" /></figure>
<div className="col-sm-8">
<p>{singleProduct.title}</p>
<p>price: {singleProduct.price} $</p>
</div>
</div>
</div>
)
:
(<div>loading</div>)
}
<Link to="/shop">
<button className="btn btn-danger">back to shop page</button>
</Link>
</div>
)
}
export default ShopSelectedItem;<file_sep>import './CounterLogic.css';
function CounterLogic(props){
return(
<div className="btnContainer">
<button className="increment btn btn-primary mx-2" onClick={props.incre}>Increment</button>
<button className="decrement btn btn-danger mx-2" onClick={props.decre}>decrement</button>
<button className="reset btn btn-warning mx-2" onClick={props.reset}>reset</button>
</div>
)
}
export default CounterLogic; | cd23d464e515ffb7b90266b772d4785058f1462c | [
"JavaScript"
] | 4 | JavaScript | Abdelrahman-Mehrat/React-test-project | c513f2c62b84f1f9b0c33ff63f7c8401a04dcc06 | 763acb8ff87d18501275a6f3a6b69df52a423087 |
refs/heads/master | <repo_name>souz9/grpc-balancing-test<file_sep>/README.md
# grpc-balancing-test
Example of gRPC load balancing
<file_sep>/server/server.go
package main
import (
"github.com/souz9/grpc-balancing-test/service"
"log"
"os"
)
func main() {
bind := os.Args[1]
id := os.Args[2]
s := service.Service{ID: id}
log.Fatal(s.Listen(bind))
}
<file_sep>/client/client.go
package main
import (
"github.com/souz9/grpc-balancing-test/service"
"context"
"log"
"os"
"time"
)
func main() {
addrs := os.Args[1:]
client, err := service.NewClient(addrs)
if err != nil {
log.Fatal(err)
}
for {
time.Sleep(time.Second)
res, err := client.Ping(context.Background(), &service.Request{})
if err != nil {
log.Print(err)
continue
}
log.Printf("%v: %v", res.Id, res.N)
}
}
<file_sep>/service/resolver.go
package service
import (
"google.golang.org/grpc/resolver"
"strings"
)
const scheme = "test"
func init() {
resolver.Register(&Resolver{})
}
type Resolver struct{}
func (_ *Resolver) Scheme() string { return scheme }
func (_ *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
var addrs []resolver.Address
for _, addr := range strings.Split(target.Endpoint, ",") {
addrs = append(addrs, resolver.Address{Addr: addr})
}
cc.UpdateState(resolver.State{Addresses: addrs})
return &Resolver{}, nil
}
func (_ *Resolver) ResolveNow(opts resolver.ResolveNowOptions) {}
func (_ *Resolver) Close() {}
<file_sep>/service/service.go
//go:generate protoc --go_out=plugins=grpc:. service.proto
package service
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/balancer/roundrobin"
"net"
"strings"
"sync/atomic"
)
type Service struct {
ID string
n int32
}
func NewClient(addrs []string) (ServiceClient, error) {
target := scheme + ":///" + strings.Join(addrs, ",")
conn, err := grpc.Dial(target,
grpc.WithInsecure(),
grpc.WithBalancerName(roundrobin.Name))
if err != nil {
return nil, err
}
return NewServiceClient(conn), nil
}
func (s *Service) Listen(addr string) error {
lis, err := net.Listen("tcp", addr)
if err != nil {
return err
}
srv := grpc.NewServer()
RegisterServiceServer(srv, s)
return srv.Serve(lis)
}
func (s *Service) Ping(context.Context, *Request) (*Response, error) {
n := atomic.AddInt32(&s.n, 1)
return &Response{Id: s.ID, N: n}, nil
}
var _ ServiceServer = &Service{}
<file_sep>/Makefile
BUILD_PREFIX ?= /tmp
build:
go build -o ${BUILD_PREFIX}/server ./server
go build -o ${BUILD_PREFIX}/client ./client
generate: install-tools
find | grep .pb.go | xargs -r rm -v
go generate ./...
install-tools:
go get github.com/golang/protobuf/protoc-gen-go
.PHONY: build generate install-tools
| c8cb4b4c98b9b3d71201014677ee32579aa08427 | [
"Markdown",
"Go",
"Makefile"
] | 6 | Markdown | souz9/grpc-balancing-test | 4070d2a2bbb989d436c20856996aba700e3dec91 | 5530af3da63096f13bc88f7b2af424f852a0cf08 |
refs/heads/master | <file_sep>def roll_call_dwarves(array)
array.each.with_index(1) do |dwarves, index|
puts "#{index} #{dwarves}"
end
end
def summon_captain_planet(calls)
calls.map {|element| element.capitalize + "!"}
end
def long_planeteer_calls(calls)
calls.any? {|letters| letters.length > 4}
end
def find_the_cheese(array)
array.detect {|cheese| cheese.include?("cheddar" || "gouda" || "camembert")}
end
| c439674329279bd6921aab0107409e6c3536b720 | [
"Ruby"
] | 1 | Ruby | B2carlso/cartoon-collections-v-000 | 2a0e1e0df1b96f53b6d4bf63c70c1fa0819ab0d0 | 37b756dda4a5e993899e5fb6ff3270629bb83069 |
refs/heads/master | <file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Row from '../Row';
import './Board.css';
export default function Board({ matrix }) {
return (
<table className="Board">
<tbody>
{ /* eslint-disable react/no-array-index-key */ }
{
matrix.map((row, idx) => (
<Row row={row} key={idx} />
))
}
</tbody>
</table>
);
}
Board.propTypes = {
matrix: PropTypes.arrayOf(PropTypes.array).isRequired,
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import './cell.css';
export default function Cell({ value }) {
const color = `color-${value}`;
return (
<td>
<div className={`cell ${color}`}>
<div className="number">
{ value || null }
</div>
</div>
</td>
);
}
Cell.propTypes = {
value: PropTypes.number.isRequired,
};
<file_sep>import { createStore } from 'redux';
import rootReducer from './reducers';
/* eslint-disable no-underscore-dangle */
const store = createStore(rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__());
let preBoard = null;
store.subscribe(() => {
const { board } = store.getState();
if (JSON.stringify(preBoard) !== JSON.stringify(board)) {
localStorage.setItem('board', JSON.stringify(board));
preBoard = board;
}
});
export default store;
<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import './App.css';
import Board from '../../components/Board';
import {
initMatrix,
moveUp,
moveDown,
moveLeft,
moveRight,
placeRandom,
reset,
} from '../../reducers/board';
class App extends Component {
static propTypes = {
onInit: PropTypes.func.isRequired,
onMoveUp: PropTypes.func.isRequired,
onMoveDown: PropTypes.func.isRequired,
onMoveLeft: PropTypes.func.isRequired,
onMoveRight: PropTypes.func.isRequired,
onPlaceRandom: PropTypes.func.isRequired,
onReset: PropTypes.func.isRequired,
matrix: PropTypes.arrayOf(PropTypes.array).isRequired,
score: PropTypes.number.isRequired,
gameOver: PropTypes.bool.isRequired,
};
componentWillMount() {
const board = JSON.parse(localStorage.getItem('board')) || null;
if (board && !board.gameOver) {
this.props.onInit(board);
} else {
this.props.onInit();
}
const { body } = document;
body.addEventListener('keyup',
this.handleKeyDown.bind(this));
}
handleKeyDown(e) {
const up = 38;
const right = 39;
const down = 40;
const left = 37;
const n = 78;
switch (e.keyCode) {
case up:
this.props.onMoveUp();
this.props.onPlaceRandom();
break;
case down:
this.props.onMoveDown();
this.props.onPlaceRandom();
break;
case left:
this.props.onMoveLeft();
this.props.onPlaceRandom();
break;
case right:
this.props.onMoveRight();
this.props.onPlaceRandom();
break;
case n:
this.props.onReset();
break;
default:
break;
}
}
render() {
const { matrix, score, gameOver } = this.props;
return (
<div className="App">
Welcome to React-2048-Game
<p>Your score is: { score }</p>
<p className="App-game-over">{ gameOver ? 'Game Over!' : '' }</p>
<Board matrix={matrix} />
</div>
);
}
}
const mapStateToProps = state => ({
matrix: state.board.matrix,
score: state.board.score,
gameOver: state.board.gameOver,
});
const matDispatchToProps = dispatch => ({
onInit(board) {
dispatch(initMatrix(board));
},
onPlaceRandom() {
dispatch(placeRandom());
},
onMoveUp() {
dispatch(moveUp());
},
onMoveDown() {
dispatch(moveDown());
},
onMoveLeft() {
dispatch(moveLeft());
},
onMoveRight() {
dispatch(moveRight());
},
onReset() {
dispatch(reset());
},
});
export default connect(mapStateToProps, matDispatchToProps)(App);
| 7169b505f76758ea2193e12b936af25cc10e4567 | [
"JavaScript"
] | 4 | JavaScript | cycbot/2048-react | f82aef2f1437c80aedc51e76f62854c1ac247c9c | 792be28f7a2921953bf8c97523f67063b154160c |
refs/heads/master | <repo_name>larkin2296/OC<file_sep>/app/Repositories/Models/DrugLibrary.php
<?php
namespace App\Repositories\Models;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
/**
* Class DrugLibrary.
*
* @package namespace App\Repositories\Models;
*/
class DrugLibrary extends Model implements Transformable
{
use TransformableTrait, ModelTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'company_id',
'type',
'common_en_name',
'common_zh_name',
'common_standard_name',
'active_ingredients',
'drug_class',
'manufacturer',
'approval_number',
'product_en_name',
'product_zh_name',
'specification',
'dosage',
'indications',
'reg_approval_date',
'first_sale_date',
'replacement_date',
'replacement_date',
'medication_way',
'treatment_person',
'pinyin',
'chemical_name',
'molecular_formula',
'molecular_weight',
'trait',
'approval_end_date',
'country',
'production_batch',
'production_quantity',
'sales',
'sales_zone',
'recall_num',
'real_recall_num',
'adverse_reactions',
'base_drug',
'medical_insurance_drug',
'non_prescription_drug',
'chinese_medicine_protection_varieties',
'reg_date',
'international_birth_day',
'first_reg_date',
'drug_testing_deadline',
'first_reg_date_again',
'status',
];
protected $primaryKey = 'drug_id';
protected $table = 'drug';
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('drug', $this->drug_id);
}
# region Scope
public function scopeType(Builder $builder, $type)
{
return $builder->where('type', $type);
}
public function ScopeStatus(Builder $builder, $status, $not_in = false)
{
if (is_array($status)) {
if ($not_in) {
return $builder->whereNotIn('status', $status);
}
return $builder->whereIn('status', $status);
} else {
if ($not_in) {
return $builder->where('status', '<>', $status);
}
return $builder->where('status', $status);
}
}
#endregion
}
<file_sep>/resources/lang/en/code/menu.php
<?php
return [
'store' => [
'fail' => '菜单创建失败',
'success' => '菜单创建成功',
],
'update' => [
'fail' => '菜单修改失败',
'success' => '菜单修改成功',
],
'destroy' => [
'fail' => '菜单删除失败',
'success' => '菜单删除成功',
],
'sort' => [
'fail' => '菜单排序失败',
'success' => '菜单排序成功',
],
];<file_sep>/app/Listeners/SetCompanyListener.php
<?php
namespace App\Listeners;
use App\Events\SetCompany;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repositories\Interfaces\CompanyRepository;
class SetCompanyListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param SetCompany $event
* @return void
*/
public function handle(SetCompany $event)
{
$model = $event->model;
$companyId = $event->companyId;
$bool = $event->bool;
if($bool) {
$company = app(CompanyRepository::class)->find($companyId);
$model->company_name = $company->name;
}
$model->company_id = $companyId;
$model->save();
}
}
<file_sep>/app/Http/Controllers/Back/Report/ValueController.php
<?php
namespace App\Http\Controllers\Back\Report;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use App\Services\Report\ValueService as Service;
use Illuminate\Validation\Rule;
class ValueController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back.report.value';
protected $routePrefix = 'admin.report';
protected $encryptConnection = 'report';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index($reportId)
{
$results = $this->service->index($reportId);
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
/**
* 获取 报告的tab数据
* @param [type] $reportId [description]
* @param [type] $reportTabId [description]
* @return [type] [description]
*/
public function reportTabHtml($reportId, $reportTabId)
{
$results = $this->service->reportTabHtml($reportId, $reportTabId);
return view(getThemeTemplate($this->folder . '.components.' . $results['reportTabId']))->with($results);
}
/**
* 报告数据保存
* @return [type] [description]
*/
public function save($reportId, $reportTabId)
{
$results = $this->service->save($reportId, $reportTabId);
return response()->json($results);
}
}
<file_sep>/app/Repositories/Models/Regulation.php
<?php
namespace App\Repositories\Models;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
/**
* Class Regulation.
*
* @package namespace App\Repositories\Models;
*/
class Regulation extends Model implements Transformable
{
use TransformableTrait,ModelTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'company_id',
'title',
'severity',
'priority',
'finished_date',
'data_insert',
'data_qc',
'medical_exam',
'medical_exam_qc',
'report_submit',
'status',
'unit',
];
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('regulation', $this->id);
}
public function ScopeStatus(Builder $builder, $status, $not_in = false)
{
if (is_array($status)) {
if ($not_in) {
return $builder->whereNotIn('status', $status);
}
return $builder->whereIn('status', $status);
} else {
if ($not_in) {
return $builder->where('status', '<>', $status);
}
return $builder->where('status', $status);
}
}
public function ScopeCompanyId(Builder $builder,$company_id){
return $builder->where('company_id',$company_id);
}
public function ScopeSeverity(Builder $builder,$severity){
return $builder->where('severity',$severity);
}
}
<file_sep>/app/Traits/QueueTrait.php
<?php
/*队列执行*/
namespace App\Traits;
use Exception;
Trait QueueTrait
{
/**
* 运行规则事件
* @return [type] [description]
*/
public function runRugulationUpdate($regulation)
{
event(new \App\Events\Regulation\Update($regulation));
}
/**
* 设置报告任务的冗余数据
* @return [type] [description]
*/
public function runSetReportTaskRedundanceData($companyId, $reportId, $data)
{
event(new \App\Events\Report\Task\SetRedundanceData($companyId, $reportId, $data));
}
/**
* 设置报告主页面的冗余数据
* @param [type] $companyId [description]
* @param [type] $reportId [description]
* @param [type] $data [description]
* @return [type] [description]
*/
public function runSetReportRedundanceData($companyId, $reportId, $data)
{
event(new \App\Events\Report\Task\SetReportMainData($companyId, $reportId, $data));
}
}<file_sep>/routes/routes/systems/workflow.php
<?php
$router->group(['namespace' => 'Workflow'], function($router) {
/*工作流配置*/
$router->group(['prefix' => 'workflow', 'as' => 'workflow.'], function($router){
/*工作流配置*/
$router->get('setting/{id}', [
'uses' => 'WorkflowController@setting',
'as' => 'setting',
]);
/*启用工作流*/
$router->post('{id}/open', [
'uses' => 'WorkflowController@open',
'as' => 'open',
]);
/*工作流节点配置*/
$router->resource('node', 'WorkflowNodeController');
});
$router->resource('workflow', 'WorkflowController');
});<file_sep>/.env.example
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=10.0.1.40
DB_PORT=3306
DB_DATABASE=pv
DB_USERNAME=zhouwen
DB_PASSWORD=<PASSWORD>
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=<PASSWORD>
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
<file_sep>/app/Traits/ControllerTrait.php
<?php
namespace App\Traits;
use Illuminate\Http\Request;
use Validator;
Trait ControllerTrait
{
public $storeReturn;
public $updateReturn;
public function setStoreReturnRoute()
{
$this->storeReturn = route($this->routePrefix() . '.index');
}
public function getStoreReturnRoute()
{
return $this->storeReturn;
}
public function setUpdateReturnRoute()
{
$this->updateReturn = route($this->routePrefix() . '.index');
}
public function getUpdateReturnRoute()
{
return $this->updateReturn;
}
/*获取路由前缀*/
public function routeHighLightPrefix()
{
$this->routeHighLightPrefix = isset($this->routeHighLightPrefix) && $this->routeHighLightPrefix ? $this->routeHighLightPrefix : $this->routePrefix;
return isset($this->routeHighLightPrefix) && $this->routeHighLightPrefix ? $this->routeHighLightPrefix : '';
}
/*获取路由前缀*/
public function routePrefix()
{
return isset($this->routePrefix) && $this->routePrefix ? $this->routePrefix : '';
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$results = $this->service->create();
return view(getThemeTemplate($this->folder . '.create'))->with($results);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->requestValidate($request);
$this->setStoreReturnRoute();
$results = $this->service->store();
if($request->ajax()) {
return response()->json($results);
} else {
if($results['result']) {
return redirect($this->getStoreReturnRoute());
} else {
return redirect()->back()->withInput()->withErrors($results['message']);
}
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$results = $this->service->show($id);
return view(getThemeTemplate($this->folder . '.show'))->with($results);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$results = $this->service->edit($id);
return view(getThemeTemplate($this->folder . '.edit'))->with($results);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->requestValidate($request);
$this->setUpdateReturnRoute();
$results = $this->service->update($id);
if($request->ajax()) {
return response()->json($results);
} else {
if($results['result']) {
return redirect($this->getUpdateReturnRoute());
} else {
return redirect()->back()->withInput()->withErrors($results['message']);
}
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$results = $this->service->destroy($id);
return response()->json($results);
}
public function requestValidate($request) {
$rules = $this->checkRules();
$messages = $this->messages();
$this->validate($request, $rules, $messages);
}
public function checkRules()
{
$curRoute = isset(request()->route()->action['as']) && request()->route()->action['as'] ? request()->route()->action['as'] : '';
$rules = $this->rules();
if($curRoute) {
$action = trim(str_replace($this->routePrefix, '', $curRoute), '.');
$method = $action . 'Rules';
if( method_exists(self::class, $method) ) {
$rules = $this->{$method}();
}
}
return $rules;
}
public function rules()
{
return [];
}
public function messages()
{
return [];
}
}<file_sep>/resources/lang/en/code/supervision.php
<?php
/**
* Created by PhpStorm.
* User: lvxinxin
* Date: 2018/02/01
* Email: <EMAIL>
*/
return [
'store' => [
'fail' => '原始资料创建失败',
'success' => '原始资料创建成功',
],
'update' => [
'fail' => '原始资料修改失败',
'success' => '原始资料修改成功',
],
'destroy' => [
'fail' => '原始资料删除失败',
'success' => '原始资料删除成功',
],
'sort' => [
'fail' => '原始资料排序失败',
'success' => '原始资料排序成功',
],
'recycling' => [
'fail' => '原始资料回收失败',
'success' => '原始资料回收成功',
],
'noNeed' => [
'fail' => '操作成功',
'success' => '操作失败',
],
'download' => [
'fail' => '原始资料下载失败',
'success' => '原始资料下载成功',
],
'issueCreate' => [
'source_no_exists' => '原始资料数据不存在',
'success' => '原始资料下载成功',
],
];<file_sep>/routes/routes/dash.php
<?php
$router->group(['namespace' => 'Back'], function($router) {
$router->resource('dash', 'DashController');
});<file_sep>/readme.md
# readme
## 配置文件
后台通用配置路径 ```config/back/global.php```
后台缓存配置路径 ```config/back/cache.php```
系统加密配置路径 ```config/back/encrypt.php```
菜单种子文件配置路径 ```config/seeder/menu.php```
## helper
存储路径 ```app/helpers/```
获取cache的缓存值 ```app/helpers/cache.php```
通用的方法 ```app/helpers/common.php```
加密的方法 ```app/helpers/encrypt.php```
global配置的方法 ```app/helpers/global.php```
## 目录结构
Trait => app/Traits
Repositories => app/Repositories 仓库
## 主题
view/themes/metronic
## 报告详情--保存数据格式
```
tab : {
// 标签id
id : 5,
"values" : [
{
// 列id,可以为空
"col_id" : '',
// 列名称
"col_name" : '',
// 数据
"data" : {
"key" : "value",
// 表格
"tables" : [
// {} 代表一个表格
{
"table_id" : 1,
"values" : [
{
"key" : "value"
}
]
}
]
}
}
]
}
```
<file_sep>/routes/routes/report/task.php
<?php
$router->group(['prefix' => 'report', 'as' => 'report.', 'middleware' => 'ishaschoice.company'], function($router) {
$router->group(['prefix' => 'task', 'as' => "task."], function($router){
$router->group(['prefix' => '{id}', 'namespace' => 'Task'], function($router){
/*报告任务重新分发*/
$router->resource('reassign', 'ReassignController');
/*报告任务-新建版本*/
$router->resource('newversion', 'NewVersionController');
/*报告任务-关联*/
$router->resource('relevance', 'RelevanceController');
});
});
$router->resource('task', 'TaskController');
});<file_sep>/app/Http/Controllers/Back/Report/LogisticsController.php
<?php
namespace App\Http\Controllers\Back\Report;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\Report\LogisticsService as Service;
/**
* Class LogisticsController.
*
* @package namespace App\Http\Controllers;
*/
class LogisticsController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.report.logistics';
protected $routePrefix = 'admin.logistics';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function lists($id){
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
<file_sep>/app/Subscribes/UserEventSubscribe.php
<?php
namespace App\Subscribes;
use App\Repositories\Interfaces\RoleRepository;
use App\Repositories\Interfaces\CompanyRepository;
use App\Repositories\Interfaces\UserRepository;
class UserEventSubscribe
{
/**
* 绑定用户角色
* @param [type] $event [description]
* @return [type] [description]
*/
public function onBindRole($event)
{
$user = $event->user;
$roleIds = $event->roleIds;
$companyId = $event->companyId;
$roles = app(RoleRepository::class)->findWhereIn('id', $roleIds);
$company = app(CompanyRepository::class)->find($companyId);
$bindRoleIds = $roles->keyBy('id')->keys()->toArray();
$user->syncRoles($bindRoleIds, $company);
}
/**
* 设置用户密码
* @return [type] [description]
*/
public function onSetPassword($event)
{
$user = $event->user;
/*默认密码<PASSWORD>*/
$password = request('password', '<PASSWORD>');
$user->password = <PASSWORD>($password);
$user->save();
}
/**
* 锁定用户
* @param [type] $event [description]
* @return [type] [description]
*/
public function onLock($event)
{
$user = $event->user;
$user->status = getCommonCheckValue(false);
if(!$user->save()) {
throw new Exception(trans('code/user.lock.fail'), 2);
}
}
/**
* 锁定用户
* @param [type] $event [description]
* @return [type] [description]
*/
public function onUnlock($event)
{
$user = $event->user;
$user->status = getCommonCheckValue(true);
if(!$user->save()) {
throw new Exception(trans('code/user.unlock.fail'), 2);
}
}
/**
* 通过企业id, 批量修改用户的企业名称
* @param [type] $event [description]
* @return [type] [description]
*/
public function onSetCompanyName($event)
{
$company = $event->company;
$userRepo = app(UserRepository::class);
$data = [
'company_name' => $company->name,
];
$where = [
'company_id' => $company->id,
];
$userRepo->updateWhere($data, $where);
}
public function subscribe($events)
{
/*绑定角色*/
$events->listen(
'App\Events\User\BindRole',
'App\Subscribes\UserEventSubscribe@onBindRole'
);
/*设置密码*/
$events->listen(
'App\Events\User\SetPassword',
'App\Subscribes\UserEventSubscribe@onSetPassword'
);
/*锁定用户*/
$events->listen(
'App\Events\User\Lock',
'App\Subscribes\UserEventSubscribe@onLock'
);
/*解锁用户*/
$events->listen(
'App\Events\User\Unlock',
'App\Subscribes\UserEventSubscribe@onUnlock'
);
/*修改用户的企业名称*/
$events->listen(
'App\Events\User\SetCompanyName',
'App\Subscribes\UserEventSubscribe@onSetCompanyName'
);
}
}
<file_sep>/routes/routes/systems/user.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'user', 'as' => 'user.'], function($router){
/*重置密码*/
$router->put('resetpass/{id}', [
'uses' => 'UserController@resetPass',
'as' => 'pass.reset'
]);
/*锁定用户*/
$router->put('lock/{id}', [
'uses' => 'UserController@lock',
'as' => 'lock'
]);
/*解锁用户*/
$router->put('unlock/{id}', [
'uses' => 'UserController@unlock',
'as' => 'unlock'
]);
});
$router->resource('user', 'UserController');
});<file_sep>/database/migrations/2018_04_02_212237_create_platform_config_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePlatformConfigTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('platform_config', function (Blueprint $table) {
$table->increments('id');
$table->string('platform_code',255)->nullable()->comment('平台代码');
$table->string('platform_name',255)->nullable()->comment('平台名字');
$table->integer('status')->default('0')->comment('0为启用,1为禁用');
$table->string('regular',255)->nullable()->comment('平台卡密规则');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('platform_config');
}
}
<file_sep>/app/Traits/Services/Menu/MenuTrait.php
<?php
namespace App\Traits\Services\Menu;
use App\Repositories\Criterias\OrderBySortCriteria;
use App\Repositories\Criterias\SearchLikeByFieldCriteria;
use Cache;
Trait MenuTrait
{
/**
* 获取缓存菜单
* @return [type] [description]
*/
private function cachedAllMenu()
{
$key = getCacheAllMenu();
return Cache::rememberForever($key, function() {
$this->menuRepo->pushCriteria(new OrderBySortCriteria('asc', 'sort'));
$menus = $this->menuRepo->with(['sonMenus', 'parentMenu'])->get();
$this->menuRepo->resetCriteria();
return $menus;
});
}
/**
* 获取缓存的用户菜单
* @return [type] [description]
*/
private function cachedUserMenu()
{
$key = getCacheUserMenu(getUserId());
return Cache::rememberForever($key, function() {
$user = getUser();
$permissions = $user->allPermissions()->keyBy('name')->keys()->toArray();
$this->menuRepo->pushCriteria(new OrderBySortCriteria('asc', 'sort'));
$menus = $this->menuRepo->with(['sonMenus', 'parentMenu'])->findWhereIn('permission', $permissions);
$this->menuRepo->resetCriteria();
return $menus;
});
}
/**
* 菜单列表
* @param array $permissions [description]
* @return [type] [description]
*/
public function menuList($isUser = false)
{
/*获取菜单*/
if($isUser) {
$menus = $this->cachedUserMenu();
} else {
$menus = $this->cachedAllMenu();
}
return $menus->filter(function($item, $key) {
if( $item->parentMenu->isNotEmpty() ) {
return false;
}
return true;
});
}
/**
* 高亮菜单
*/
public function highLightMenu($route, $routePrefix)
{
/*菜单*/
$menuMaps = $this->cachedAllMenu()->keyBy('id');
$menus = $this->menuRepo->findByField('route', $route);
if($menus->isEmpty()) {
$where = [
'route_prefix' => $routePrefix
];
$menus = $this->menuRepo->findWhere($where);
}
return $this->getHighLightMenuIds($menus, $menuMaps);
}
private function getHighLightMenuIds($menus, $menuMaps)
{
$results = [];
foreach($menus as $menu) {
$results[] = $menu->id;
if(isset($menuMaps[$menu->id]->parentMenu) && $menuMaps[$menu->id]->parentMenu->isNotEmpty()) {
$results = array_merge($results, $this->getHighLightMenuIds($menuMaps[$menu->id]->parentMenu, $menuMaps));
}
}
return $results;
}
}<file_sep>/routes/routes/registered/route.php
<?php
$router->group(['namespace' => 'Back\Home\Registered'], function($router) {
/*用户注册*/
require(__DIR__ . '/login.php');
});<file_sep>/app/Repositories/Eloquents/RoleRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\RoleRepository;
use App\Role;
use App\Repositories\Validators\RoleValidator;
use App\Traits\EncryptTrait;
use Illuminate\Container\Container as Application;
/**
* Class RoleRepositoryEloquent
* @package namespace App\Repositories\Eloquents;
*/
class RoleRepositoryEloquent extends BaseRepository implements RoleRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('role');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Role::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return RoleValidator::class;
}
/**
* 获取组织结构的角色
* @return [type] [description]
*/
public function organizeRoles($organizeRoleId)
{
$this->applyCriteria();
$this->applyScope();
$results = $this->model->where('organize_role_id', $organizeRoleId)->get();
$this->resetModel();
return $results;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/app/Repositories/Presenters/LogisticsPresenter.php
<?php
namespace App\Repositories\Presenters;
use App\Repositories\Transformers\LogisticsTransformer;
use Prettus\Repository\Presenter\FractalPresenter;
/**
* Class LogisticsPresenter.
*
* @package namespace App\Repositories\Presenters;
*/
class LogisticsPresenter extends FractalPresenter
{
/**
* Transformer
*
* @return \League\Fractal\TransformerAbstract
*/
public function getTransformer()
{
return new LogisticsTransformer();
}
}
<file_sep>/app/Http/Controllers/Back/System/RegulationsController.php
<?php
namespace App\Http\Controllers\Back\System;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\RegulationService as Service;
/**
* Class RegulationsController.
*
* @package namespace App\Http\Controllers;
*/
class RegulationsController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.system.regulation';
protected $routePrefix = 'admin.rule';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* 规则列表
* @return [type] [description]
*/
public function index()
{
if (request()->ajax()) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
}
<file_sep>/app/Services/DictionariesService.php
<?php
namespace App\Services;
use App\Repositories\Models\Subdictionaries;
use App\Services\Service as BasicService;
use Illuminate\Http\Request;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use Yajra\DataTables\DataTables;
use Exception;
use DB;
use App\Repositories\Models\Dictionaries;
Class DictionariesService extends BasicService{
//ResultTrait返回字段 ExceptionTrait 例外 ServiceTrait 限制
use ResultTrait , ExceptionTrait , ServiceTrait;
//使用Builder插件
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function builder()
{
$info = $this->questionRepo->all();
return $info;
}
/*ajax请求*/
public function datatables()
{
$data = $this->dictionariesRepo->all();
return DataTables::of($data)
->addColumn('action', getThemeTemplate('back.system.dictionaries.datatable'))
->make();
}
public function index()
{
$html = $this->builder->columns([
['data' => 'serial', 'name' => 'serial', 'title' => '序号'],
['data' => 'chinese', 'name' => 'chinese', 'title' => '中文'],
['data' => 'forpage', 'name' => 'forpage', 'title' => '所属页面'],
['data' => 'structure', 'name' => 'structure', 'title' => '系统构件'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false]
])
->ajax([
'url' => route('admin.dictionaries.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
/*编辑*/
public function edit($id)
{
try {
/*获取字典信息*/
$subdictionaries_info = $this->subdictionariesRepo->find($id);
return [
'subdictionaries'=> $subdictionaries_info,
];
} catch (Exception $e) {
abort(404);
}
}
/*修改*/
public function update($id)
{
try {
$exception = DB::transaction(function() use ($id) {
if( $info = $this->subdictionariesRepo->update(request()->all(), $id) ) {
} else {
throw new Exception(trans('code/subdictionaries.update.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/subdictionaries.update.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/subdictionaries.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
/*删除*/
public function destroy($id)
{
try {
$exception = DB::transaction(function() use ($id) {
if( $info = $this->subdictionariesRepo->delete($id) ){
event(new \App\Events\Dictionaries\dele($id));
} else {
throw new Exception(trans('code/dictionaries.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/dictionaries.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/dictionaries.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
/*所属页面*/
public function search($page,$keyword)
{
try {
if($page==0&&$keyword=='null'){$datas = $this->dictionariesRepo->all();}
else{
if($page!=0&&$keyword=='null'){$datas = $this->dictionariesRepo->findWhere(['forpage'=>$page])->all();}else{
if($page==0&&$keyword!='null'){$datas = $this->dictionariesRepo->findWhere([['chinese','like',"%{$keyword}%"]])->all();}else{
$datas = $this->dictionariesRepo->findWhere(['forpage' => $page, ['chinese', 'like', "%{$keyword}%"]])->all();
}
}
}
$results = array_merge($this->results, [
'result' => true,
'data' => $datas,
'message' => trans('code/dictionaries.search.success'),
]);
} catch (Exception $e) {
$results = array_merge($this->results, [
'result' => false,
'data' => $this->handler($e, trans('code/dictionaries.search.fail')),
]);
}
return array_merge($this->results, $results);
}
/*新增*/
public function create()
{
try {
$exception = DB::transaction(function() {
if( $info = $this->subdictionariesRepo->create(request()->all())){
} else {
throw new Exception(trans('code/subdictionaries.create.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/subdictionaries.create.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/subdictionaries.create.fail')),
]);
}
return array_merge($this->results, $exception);
}
/*字段编辑*/
public function show($id)
{
try {
$exception = DB::transaction(function() use ($id){
$datas = $this->subdictionariesRepo->findWhereIn('dict_id',[$id])->map(function($item, $key){
$item->delete = route('admin.dictionaries.destroy', $item->id);
$item->edit = route('admin.dictionaries.edit', $item->id);
return $item;
});
return array_merge($this->results, [
'result' => true,
'data'=>$datas,
'message' => trans('code/subdictionaries.field.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/subdictionaries.field.fail')),
]);
}
return array_merge($this->results, $exception);
}
/*字典全局接口*/
public function hasmanydictionaries()
{
try {
$exception = DB::transaction(function(){
// $results = ['chinese'=>'国家','chinese'=>'企业报告类型'];
// $results = [
// ['chinese'=>'国家'],
// ['chinese'=>'企业报告类型'],
// ];
// $results = ['chinese' => [
// '0' => '国家',
// '1' => '企业报告类型'
// ]];
// array(1) { ["chinese"]=> array(2) { [0]=> string(6) "国家" [1]=> string(18) "企业报告类型" } }
$results = request()->all();
if (is_array($results)) {
$dictionaries = new Dictionaries();
$newData = array();
foreach($results['chinese'] as $k=>$item) {
$data = $dictionaries::where('chinese',$item)->select('id')->get();
foreach($data as $key=>$val){
$newData[$item] = $this->subdictionariesRepo->findWhere(['dict_id'=>$val['id']])->all();
}
}
/*闭包*/
// $data = $data->each(function ($item,$key) {
// $item->data;
// })->toArray();
}
else
{
return false;
}
return array_merge($this->results, [
'result' => true,
'data' => $newData,
'message' => trans('code/hasmanydictionaries.field.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/hasmanydictionaries.field.fail')),
]);
}
return array_merge($this->results, $exception);
}
}
?><file_sep>/routes/routes/systems/role.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'role', 'as' => 'role.'], function($router) {
/*角色用户*/
$router->get('{id}/user/show', [
'uses' => 'RoleController@userShow',
'as' => 'user.show'
]);
/*修改角色权限*/
$router->get('{id}/permission/edit', [
'uses' => 'RoleController@permissionEdit',
'as' => 'permission.edit'
]);
/*角色权限保存修改*/
$router->put('{id}/permission', [
'uses' => 'RoleController@permissionUpdate',
'as' => 'permission.update'
]);
/*角色权限保存修改*/
$router->get('organize/{organize_role_id}', [
'uses' => 'RoleController@organize',
'as' => 'organize'
]);
});
$router->resource('role', 'RoleController');
});<file_sep>/app/helpers/checkRole.php
<?php
/**
* 验证角色是否有组织结构
*/
if ( !function_exists('checkRoleHasOrganizeRoleId') ) {
function checkRoleHasOrganizeRoleId($roles, $organizeRoleId)
{
$allowedOrganizeRoleIds = $roles->keyBy('organize_role_id')->keys()->toArray();
return in_array($organizeRoleId, $allowedOrganizeRoleIds);
}
}
/**
* 企业管理员
*/
if ( !function_exists('isCompanyManager') ) {
function isCompanyManager($roles)
{
$organizeRoleId = getRoleOrganizeValue('company_manager');
return checkRoleHasOrganizeRoleId($roles, $organizeRoleId);
}
}
/**
* 企业资料管理员
*/
if ( !function_exists('isSourceManager') ) {
function isSourceManager($roles)
{
$organizeRoleId = getRoleOrganizeValue('source_manager');
return checkRoleHasOrganizeRoleId($roles, $organizeRoleId);
}
}
/**
* 企业数据录入员
*/
if ( !function_exists('isDataInsert') ) {
function isDataInsert($roles)
{
$organizeRoleId = getRoleOrganizeValue('data_insert');
return checkRoleHasOrganizeRoleId($roles, $organizeRoleId);
}
}
/**
* 企业数据质控QC
*/
if ( !function_exists('isDataQc') ) {
function isDataQc($roles)
{
$organizeRoleId = getRoleOrganizeValue('data_qc');
return checkRoleHasOrganizeRoleId($roles, $organizeRoleId);
}
}
/**
* 企业医学审评
*/
if ( !function_exists('isMedicalExam') ) {
function isMedicalExam($roles)
{
$organizeRoleId = getRoleOrganizeValue('medical_exam');
return checkRoleHasOrganizeRoleId($roles, $organizeRoleId);
}
}
/**
* 企业医学审评QC
*/
if ( !function_exists('isCompanyManagerQc') ) {
function isCompanyManagerQc($roles)
{
$organizeRoleId = getRoleOrganizeValue('medical_exam_qc');
return checkRoleHasOrganizeRoleId($roles, $organizeRoleId);
}
}
/**
* 企业报告递交
*/
if ( !function_exists('isReportSubmit') ) {
function isReportSubmit($roles)
{
$organizeRoleId = getRoleOrganizeValue('report_submit');
return checkRoleHasOrganizeRoleId($roles, $organizeRoleId);
}
}<file_sep>/app/Http/Controllers/Back/System/Workflow/WorkflowController.php
<?php
namespace App\Http\Controllers\Back\System\Workflow;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\WorkflowService as Service;
class WorkflowController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.system.workflow';
protected $routePrefix = 'admin.workflow';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* 用户列表
* @return [type] [description]
*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
/**
* 工作流配置
* @return [type] [description]
*/
public function setting($id)
{
$results = $this->service->setting($id);
return view(getThemeTemplate($this->folder . '.setting'))->with($results);
}
/**
* 启用工作流
* @param [type] $id [description]
* @return [type] [description]
*/
public function open($id)
{
$results = $this->service->open($id);
return response()->json($results);
}
}
<file_sep>/routes/oc_routes/supplier/supplierlist.php
<?php
$router->group(['namespace'=>'Card\Supplier'], function($router) {
$router->group(['prefix' => 's_list', 'as' => 's_list.'], function($router) {
//订单查询
$router->get('index', [
'uses' => 'SupplierListController@index',
'as' => 'index'
]);
//用户信息页面
$router->get('show', [
'uses' => 'SupplierListController@show',
'as' => 'show'
]);
//修改用户信息
$router->get('store', [
'uses' => 'SupplierListController@store',
'as' => 'store'
]);
//卡密订单页面
$router->get('cardencry', [
'uses' => 'SupplierListController@cardencry',
'as' => 'cardencry'
]);
//卡密订单上传
$router->post('create', [
'uses' => 'SupplierListController@create',
'as' => 'create'
]);
});
});<file_sep>/app/Events/Report/Task/Assign.php
<?php
//原始资料分发录入员
namespace App\Events\Report\Task;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class Assign
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public $taskUserId;
public $source;
public $regulation;
public function __construct($taskUserId, $source, $regulation)
{
/*任务处理人*/
$this->taskUserId = $taskUserId;
/*原始资料*/
$this->source = $source;
/*报告规则*/
$this->regulation = $regulation;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
<file_sep>/routes/oc_routes/purchasing/list.php
<?php
$router->group(['namespace'=>'Card\Purchasing'], function($router) {
$router->group(['prefix' => 'list', 'as' => 'list.'], function($router) {
$router->get('index', [
'uses' => 'ListController@index',
'as' => 'index'
]);
});
$router->get('message', [
'uses' => 'MessageController@index',
'as' => 'index'
]);
});<file_sep>/app/Http/Controllers/Back/DashController.php
<?php
namespace App\Http\Controllers\Back;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
class DashController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.dash';
/**/
protected $routePrefix = 'admin.dash';
public function index()
{
return view(getThemeTemplate($this->folder . '.index'));
}
}
<file_sep>/app/Repositories/Interfaces/CompanyRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface CompanyRepository
* @package namespace App\Repositories\Interfaces;
*/
interface CompanyRepository extends RepositoryInterface
{
//
}
<file_sep>/app/Repositories/Models/Category.php
<?php
namespace App\Repositories\Models;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
/**
* Class Category.
*
* @package namespace App\Repositories\Models;
*/
class Category extends Model implements Transformable
{
use TransformableTrait,ModelTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'pid',
'company_id',
'module',
'sort',
'status',
];
protected $table = 'category';
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('category', $this->id);
}
public function ScopeStatus(Builder $builder, $status, $not_in = false)
{
if (is_array($status)) {
if ($not_in) {
return $builder->whereNotIn('status', $status);
}
return $builder->whereIn('status', $status);
} else {
if ($not_in) {
return $builder->where('status', '<>', $status);
}
return $builder->where('status', $status);
}
}
}
<file_sep>/app/Services/CompanyService.php
<?php
namespace App\Services;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use App\Traits\Services\Permission\PermissionTrait;
use DataTables;
use Exception;
use DB;
class CompanyService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait, PermissionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
}<file_sep>/app/Services/PermissionService.php
<?php
namespace App\Services;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DataTables;
use Exception;
use DB;
class PermissionService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
/**
* 列表
* @return [type] [description]
*/
public function index()
{
$html = $this->builder->columns([
// ['data' => 'id', 'name' => 'id', 'title' => 'Id'],
['data' => 'name', 'name' => 'name', 'title' => '权限名'],
['data' => 'display_name', 'name' => 'display_name', 'title' => '权限展示名'],
['data' => 'description', 'name' => 'description', 'title' => '描述'],
['data' => 'created_at', 'name' => 'created_at', 'title' => '创建时间'],
['data' => 'updated_at', 'name' => 'updated_at', 'title' => '修改时间'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false],
])
->ajax([
'url' => route('admin.permission.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
/**
* 列表数据
* @return [type] [description]
*/
public function datatables()
{
$data = $this->permissionRepo->all();
return DataTables::of($data)
->editColumn('id', '{{ $id_hash }}')
->addColumn('action', getThemeTemplate('back.system.permission.datatable'))
->make();
}
/**
* 权限保存
* @return [type] [description]
*/
public function store()
{
try {
$exception = DB::transaction(function() {
$data = request()->all();
if( $permission = $this->permissionRepo->create($data) ) {
} else {
throw new Exception(trans('code/permission.store.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/permission.store.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/permission.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 权限修改
* @param [type] $id [权限id]
* @return [type] [description]
*/
public function edit($id)
{
try {
/*获取权限信息*/
$id = $this->permissionRepo->decodeId($id);
$permission = $this->permissionRepo->find($id);
return [
'permission' => $permission,
];
} catch (Exception $e) {
abort(404);
}
}
/**
* 权限修改保存
* @param [type] $id [description]
* @return [type] [description]
*/
public function update($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$data = request()->all();
$id = $this->permissionRepo->decodeId($id);
if($this->permissionRepo->update($data, $id)) {
} else {
throw new Exception(trans('code/permission.update.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/permission.update.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/permission.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 删除权限
* @param [type] $id [description]
* @return [type] [description]
*/
public function destroy($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->permissionRepo->decodeId($id);
if($this->permissionRepo->delete($id)) {
} else {
throw new Exception(trans('code/permission.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/permission.destroy.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/permission.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/app/Traits/Services/Question/QuestionTrait.php
<?php
namespace App\Traits\Services\Question;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;
use App\Repositories\Models\Question;
use Mail;
use HskyZhou\NineOrange\NineOrange;
Trait QuestionTrait
{
/**
* 质疑条件选择
* @return [type] [description]
*/
public function searchWhere($data)
{
$query = new Question();
$results = $query->where(function($query)use($data){
$data['question_num'] && $query->where('question_num', 'like', '%' . $data['question_num'] . '%');
$data['report_num'] && $query->where('report_num', 'like', '%' . $data['report_num'].'%');
$data['status'] && $query->where('status',$data['status']);
$data['operation_name'] && $query->where('operation_name','like','%'.$data['operation_name'].'%');
})->get();
return $results;
}
/**发送质疑**/
public function send($question_id,$end_date,$content,$id,$status)
{
/*同步主表数据*/
$data = $this->questionRepo->update(['end_date'=>$end_date,'content'=>$content,'status'=>2],$question_id);
/*成功 增加发送次数*/
$structure = DB::table('question')->where('id',$question_id)->increment('sending');
/*更新次数*/
$str = $this->questionRepo->find($question_id);
$sending = $str->sending;
$info = $this->questioningRepo->update(['sending'=>$sending],$id);
/*区分邮件发送请求*/
if($status !=1 ){
if($structure&&$info&&$data){
return $info;
}else{
return false;
}
}else{
#TODO 验证公司id(companies) 2.查询公司下所注册的邮箱(mail) 3.将当前需要发送的数据取出(send_information)
/*内容 标题 发件人名称 账号*/
/*虚拟数据*/
$company_id = 1;
dd($company_id);
$info = $this->checkMail($company_id,$id);
if($structure&&$info&&$data){
return $info;
}else{
return false;
}
}
/*业务*/
}
protected function checkMail($company_id,$id)
{
$company_info = $this->mailRepo->findWhereIn('company_id',[$company_id])->all();
#TODO 将数据发送到服务器邮箱 :
$results = $this->questioningRepo->find($id);
$email = $results->email;
$account = explode(';',$email);//得到要发送邮件的数组
$email_theme = $results->email_theme;//邮件主题
$company_name = $company_info->mail_account;//己方公司的账户
#todo 发送邮件接口
}
}<file_sep>/routes/routes/systems/company.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'company', 'as' => 'company.'], function($router){
/*切换公司*/
$router->get('{company}/exchange', [
'middleware' => 'exchange.company',
'uses' => 'CompanyController@exchange',
'as' => 'exchange',
]);
});
$router->resource('company', 'CompanyController');
});<file_sep>/app/Services/Report/SourceService.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/23
* Time: 下午8:24
*/
namespace App\Services\Report;
use App\Traits\DictionariesTrait;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\Services\Workflow\WorkflowTrait;
use App\Traits\ServiceTrait;
use Exception;
use Yajra\DataTables\Html\Builder;
use Yajra\DataTables\DataTables;
use DB;
use App\Services\Service;
class SourceService extends Service
{
use ServiceTrait,ResultTrait,ExceptionTrait,WorkflowTrait,DictionariesTrait;
protected $builder;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function store()
{
$data = request()->all();
$data['company_id'] = getCompanyId() ;
#TODO::研究方案编号 即当前的项目编号
#$data['solution_number'] = '';
try {
$exception = DB::transaction(function () use ($data) {
if ($cate = $this->sourceRepo->create($data)) {
if(isset($data['attach_ids']) && !empty($data['attach_ids'])){
$attach_id = $this->attachmentRepo->decodeId($data['attach_ids']);
$cate->attachments()->attach($attach_id);
}
else{
throw new Exception(trans('code/source.attach.attach_no_exists'), 2);
}
} else {
throw new Exception(trans('code/source.store.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/source.store.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/source.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function datatables()
{
$model = $this->sourceRepo->makeModel();
$model = $model->whereHas('attachments',function($query)use($model){
return $query->where('attachment_model_type',get_class($model));
});
$model = $model->with('attachments');
$model = $model->status(1);
return DataTables::of($model)
->editColumn('id', '{{ $id_hash }}')
->addColumn('action', getThemeTemplate('back.report.source.datatable'))
->make();
}
public function index()
{
$html = $this->builder->columns([
['data' => 'attachments.name', 'name' => 'attachments.name', 'title' => '文件名'],
['data' => 'report_number', 'name' => 'report_number', 'title' => '报告编号'],
['data' => 'accept_report_date', 'name' => 'accept_report_date', 'title' => '接受报告时间'],
['data' => 'solution_number', 'name' => 'solution_number', 'title' => '研究方案编号'],
['data' => 'created_at', 'name' => 'created_at', 'title' => '创建时间'],
['data' => 'creator_name', 'name' => 'creator_name', 'title' => '创建人'],
['data' => 'action', 'name' => 'action', 'title' => '操作'],
])
->ajax([
'url' => route('admin.source.index'),
'type' => 'GET',
]);
return [
'html' => $html,
'drug_class'=>[] #左侧树型分类
];
}
public function create()
{
#原始资料-添加-文件类型
$fileClass = $this->hasManyDictionaries(['文件类型']);
#原始资料-添加-文件来源
$fileSource = $this->hasManyDictionaries(['文件来源']);
#树型分类
$drug_class = [];
return [
'file_class' => $fileClass,
'file_source' => $fileSource,
'drug_class' => $drug_class
];
}
public function edit($id)
{
try {
#获取某个分类
$id = $this->sourceRepo->decodeId($id);
$source = $this->sourceRepo->find($id);
#原始资料-添加-文件类型
$fileClass = get_file_class();
#原始资料-添加-文件来源
$fileSource = get_file_source();
#树型分类
$drug_class = [];
return [
'source' => $source,
'file_class' => $fileClass,
'file_source' => $fileSource,
'drug_class' => $drug_class
];
} catch (Exception $e) {
abort(404);
}
}
public function show($id)
{
try {
#获取某个分类
$id = $this->sourceRepo->decodeId($id);
$source = $this->sourceRepo->find($id);
#原始资料-添加-文件类型
$fileClass = get_file_class();
#原始资料-添加-文件来源
$fileSource = get_file_source();
return [
'source' => $source,
'file_class' => $fileClass,
'file_source' => $fileSource,
];
} catch (Exception $e) {
abort(404);
}
}
public function update($id)
{
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->sourceRepo->decodeId($id);
$data = request()->all();
if ($source = $this->sourceRepo->update($data, $id)) {
#TODO:: exec other logic
} else {
throw new Exception(trans('code/source.update.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/source.update.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/source.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function destroy($id)
{
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->sourceRepo->decodeId($id);
#删除
if ($source = $this->sourceRepo->update(['status' => 2], $id)) {
#TODO:: other logic
} else {
throw new Exception(trans('code/source.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/source.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/source.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* @desc 回收
* @param $id
* @return array
*/
public function recycling($id){
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->sourceRepo->decodeId($id);
# 回收分发,即把状态改为1,未分发状态
if ($source = $this->sourceRepo->update(['issue' => 1], $id)) {
#TODO:: other logic
event(new \App\Events\Report\Task\Delete($source->id));
} else {
throw new Exception(trans('code/source.recycling.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/source.recycling.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/source.recycling.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* @desc 分发
* @param $id
* @return array
*/
public function issue($id){
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->sourceRepo->decodeId($id);
# 分发,即把状态改为2,已分发状态
if ($source = $this->sourceRepo->update(['issue' => 2], $id)) {
$data = request()->all();
$taskUserId = $this->userRepo->decodeId($data['uid']);
$regulation = $this->regulaRepo->getRegulationsBySeverity(getCompanyId(),$data['severity']);
#TODO::事件触发
event(new \App\Events\Report\Task\Assign($taskUserId, $source, $regulation));
} else {
throw new Exception(trans('code/source.issue.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/source.issue.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/source.issue.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function issueCreate($id)
{
try {
$id = $this->sourceRepo->decodeId($id);
$source = $this->sourceRepo->find($id);
if(empty($source)) throw new Exception(trans('code/source.issueCreate.source_no_exists'));
#严重性
$severity = $this->hasManyDictionaries(['报告严重性']);
#录入人员
$organize_value = getRoleOrganizeValue('source_manager');
$data_insert_users = $this->nextNodeUsers($organize_value);
return [
'id' => $id,
'severity' => $severity,
'data_insert_users' => $data_insert_users,
];
} catch (Exception $e) {
abort(404);
}
}
/**
* @desc 下载
* @param $id
* @return array
*/
public function download($id){
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->sourceRepo->decodeId($id);
if ($source = $this->sourceRepo->update(['issue' => 2], $id)) {
#TODO:: other logic
} else {
throw new Exception(trans('code/source.download.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/source.download.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/source.download.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/database/migrations/2018_02_14_171431_create_purchase_tables.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePurchaseTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('purchase', function(Blueprint $table) {
$table->increments('id');
$table->string('purchase_number')->nullable()->comment('卡密');
$table->string('denomination')->nullable()->comment('面额');
$table->string('number')->nullable()->comment('数量');
$table->string('commodity')->nullable()->comment('商品名称');
$table->string('price')->nullable()->comment('价格');
$table->string('total_price')->nullable()->comment('价格总计');
$table->tinyInteger('status')->nullable()->default(1)->comment('1-正常,2-关闭');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/routes/routes/management/route.php
<?php
$router->group(['namespace' => 'Back\Home\Management'], function($router) {
//油卡管理
require(__DIR__.'/management.php');
//卡密采购
require(__DIR__.'/purchase.php');
});
<file_sep>/database/migrations/2018_04_02_213105_create_order_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrderTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('order', function (Blueprint $table) {
$table->increments('id');
$table->string('name_of_card_supply')->nullable()->comment('供卡名称');
$table->string('supply_status')->nullable()->comment('供卡状态');
$table->string('denomination')->nullable()->comment('面额');
$table->string('order_type')->nullable()->comment('订单类型');
$table->string('supply_time')->nullable()->comment('供货时间');
$table->string('order_time')->nullable()->comment('订单时间');
$table->string('order_number')->nullable()->comment('订单号');
$table->string('discount')->nullable()->comment('油卡折扣');
$table->string('pin_denomination_card')->nullable()->comment('实际销卡面额');
$table->string('content')->nullable()->comment('备注');
$table->string('user_id')->nullable()->comment('用户id');
$table->tinyInteger('status')->nullable()->default(1)->comment('1-正常,2-关闭');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('order');
}
}
<file_sep>/resources/lang/en/field/permission.php
<?php
return [
'name' => [
'label' => '权限名称',
'name' => 'name',
'placeholder' => '权限名称',
'rules' => [
'required' => '权限名称不能为空',
]
],
'display_name' => [
'label' => '权限显示名称',
'name' => 'display_name',
'placeholder' => '权限显示名称',
'rules' => [
'required' => '权限显示名称不能为空',
]
],
'description' => [
'label' => '权限描述',
'name' => 'description',
'placeholder' => '权限描述',
'rules' => [
'required' => '权限描述不能为空',
]
]
];<file_sep>/app/Repositories/Eloquents/ReportMainpageRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\ReportMainpageRepository;
use App\Repositories\Models\ReportMainpage;
use App\Repositories\Validators\ReportMainpageValidator;
use App\Traits\EncryptTrait;
use Illuminate\Container\Container as Application;
/**
* Class ReportMainpageRepositoryEloquent
* @package namespace App\Repositories\Eloquents;
*/
class ReportMainpageRepositoryEloquent extends BaseRepository implements ReportMainpageRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('reportmainpage');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return ReportMainpage::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/resources/lang/en/code/role.php
<?php
return [
'store' => [
'fail' => '角色创建失败',
'success' => '角色创建成功',
],
'update' => [
'fail' => '角色修改失败',
'success' => '角色修改成功',
],
'destroy' => [
'fail' => '角色删除失败',
'success' => '角色删除成功',
],
'user' => [
'show' => [
'fail' => '获取角色用户失败',
'success' => '获取角色用户成功',
],
],
'permission' => [
'edit' => [
'fail' => '获取角色修改权限失败',
'success' => '获取角色修改权限成功',
],
'update' => [
'fail' => '角色权限修改失败',
'success' => '角色权限修改成功',
],
],
'organize' => [
'fail' => '获取角色组织结构失败',
'success' => '获取角色组织结构成功',
],
];<file_sep>/app/Services/MenuService.php
<?php
namespace App\Services;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use App\Traits\Services\Menu\MenuTrait;
use Exception;
use DB;
class MenuService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait, MenuTrait;
public function __construct()
{
parent::__construct();
}
public function index(){
try {
$menus = $this->menuList();
$menuMaps = $this->cachedAllMenu()->keyBy('id');
return [
'menus' => $menus,
'menuMaps' => $menuMaps,
];
} catch (Exception $e) {
abort(404);
}
}
public function create(){
try {
$id = request('id', 0);
$id = $this->menuRepo->decodeId($id);
/*菜单位置*/
$positions = getMenuPosition();
$parentMenu = $id ? $this->menuRepo->find($id) : [];
$parentMenu = $this->parentMenu($parentMenu);
} catch (Exception $e) {
}
return [
'parentMenu' => $parentMenu,
'positions' => $positions,
];
}
public function store(){
try {
$exception = DB::transaction(function(){
$data = request()->all();
if( $menu = $this->menuRepo->create($data) ){
/*执行绑定父级菜单*/
$parentMenuId = request('parent_id');
$parentMenuId = $this->menuRepo->decodeId($parentMenuId);
event(new \App\Events\Menu\BindParentMenu($menu, $parentMenuId));
/*清除菜单缓存*/
event(new \App\Events\FlushCache());
} else {
throw new Exception(trans('code/menu.store.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/menu.store.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/menu.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function edit($id){
try {
/*修改的菜单*/
$id = $this->menuRepo->decodeId($id);
$menu = $this->menuRepo->find($id);
/*父级菜单*/
$parentMenu = $this->parentMenu($menu->parentMenu->first());
/*菜单位置*/
$positions = getMenuPosition();
return [
'menu' => $menu,
'parentMenu' => $parentMenu,
'positions' => $positions,
];
} catch (Exception $e) {
abort(404);
}
}
private function parentMenu($parentMenu)
{
$defaultParentMenu = [
'id_hash' => 0,
'id' => 0,
'name' => '顶级菜单'
];
return $parentMenu ? $parentMenu->toArray() : $defaultParentMenu;
}
public function update($id){
try {
$exception = DB::transaction(function() use ($id){
$id = $this->menuRepo->decodeId($id);
$data = request()->all();
if( $menu = $this->menuRepo->update($data, $id) ){
/*执行绑定父级菜单*/
$parentMenuId = request('parent_id');
$parentMenuId = $this->menuRepo->decodeId($parentMenuId);
event(new \App\Events\Menu\BindParentMenu($menu, $parentMenuId));
/*清除菜单缓存*/
event(new \App\Events\FlushCache());
} else {
throw new Exception(trans('code/menu.update.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/menu.update.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/menu.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 删除菜单
* @param [type] $id [菜单id]
* @return [type] [description]
*/
public function destroy($id){
try {
$exception = DB::transaction(function() use ($id){
/*获取菜单*/
$id = $this->menuRepo->decodeId($id);
$menu = $this->menuRepo->find($id);
if($this->menuRepo->delete($id) ){
/*执行取消菜单关系*/
event(new \App\Events\Menu\DetachMenuRelation($menu));
/*清除菜单缓存*/
event(new \App\Events\FlushCache());
} else {
throw new Exception(trans('code/menu.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/menu.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/menu.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 菜单排序
* @return [type] [description]
*/
public function sort(){
try {
$exception = DB::transaction(function() {
/*解析json数据*/
$menuIds = json_decode(request('data'), 'true');
/*排序菜单*/
$parentMenu = Null;
$this->sortMenu($menuIds, $parentMenu);
/*清除菜单缓存*/
event(new \App\Events\FlushCache());
return array_merge($this->results, [
'result' => true,
'message' => trans('code/menu.sort.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/menu.sort.fail')),
]);
}
return array_merge($this->results, $exception);
}
private function sortMenu($menuIds, $parentMenu)
{
if($menuIds) {
foreach($menuIds as $key => $val){
/*获取菜单*/
$menuId = $val['id'];
$menuId = $this->menuRepo->decodeId($menuId);
$menu = $this->menuRepo->find($menuId);
event(new \App\Events\Menu\SortCurrentMenu($menu, $key, $parentMenu));
/*存在子菜单需要排序*/
if(isset($val['children']) && $val['children']) {
$this->sortMenu($val['children'], $menu);
}
}
}
}
}<file_sep>/app/Http/Controllers/Back/System/MenuController.php
<?php
namespace App\Http\Controllers\Back\System;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\MenuService as Service;
use Illuminate\Validation\Rule;
class MenuController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.system.menu';
protected $routePrefix = 'admin.menu';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* 排序
* @return [type] [description]
*/
public function sort()
{
$results = $this->service->sort();
return response()->json($results);
}
}
<file_sep>/app/Traits/Services/Workflow/WorkflowTrait.php
<?php
namespace App\Traits\Services\Workflow;
use App\Repositories\Interfaces\WorkflowRepository;
Trait WorkflowTrait
{
/**
* 获取下一个工作流节点的用户
* @return [type] [description]
*/
public function nextNodeUsers($organizeRoleId = '', $companyId = '')
{
$companyId = getCompanyId($companyId);
/*获取工作流*/
$workflow = $this->getWorkflow($companyId);
/*所有的工作流节点*/
$workflowNodes = $workflow->nodes->keyBy('organize_role_id');
/*当前工作流节点*/
$curWorkflowNode = $workflowNodes[$organizeRoleId];
/*获取当前工作流节点的下一个节点*/
$nextWorkflowNode = $workflow->nodes->where('sort', '>', $curWorkflowNode->sort)->first();
/*返回节点的用户*/
return $this->nodeUsers($nextWorkflowNode, $companyId);
}
/**
* 获取当前节点的用户
* @return [type] [description]
*/
public function curNodeUsers($organizeRoleId = '', $companyId = '')
{
$companyId = getCompanyId($companyId);
/*获取工作流*/
$workflow = $this->getWorkflow($companyId);
/*所有的工作流节点*/
$workflowNodes = $workflow->nodes->keyBy('organize_role_id');
/*当前工作流节点*/
$curWorkflowNode = $workflowNodes[$organizeRoleId];
/*返回节点的用户*/
return $this->nodeUsers($curWorkflowNode, $companyId);
}
private function nodeUsers($workflowNode, $companyId)
{
// 返回节点的用户
return $workflowNode->role->users($companyId)->get();
}
private function getWorkflow($companyId)
{
/*获取工作流*/
$workflowWhere = [
'company_id' => $companyId,
'status' => getCommonCheckValue(true),
'is_use' => getCommonCheckValue(true),
];
return $this->workflowRepo->with('nodes')->findWhere($workflowWhere)->first();
}
}<file_sep>/app/Repositories/Interfaces/SourceRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface SourceRepository.
*
* @package namespace App\Repositories\Interfaces;
*/
interface SourceRepository extends RepositoryInterface
{
//
}
<file_sep>/app/Repositories/Eloquents/AttachmentModelRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\AttachmentModelRepository;
use App\Repositories\Models\AttachmentModel;
use App\Repositories\Validators\AttachmentModelValidator;
/**
* Class AttachmentModelRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class AttachmentModelRepositoryEloquent extends BaseRepository implements AttachmentModelRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return AttachmentModel::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return AttachmentModelValidator::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/routes/routes/systems/permission.php
<?php
$router->group([], function($router) {
$router->resource('permission', 'PermissionController');
});<file_sep>/app/Repositories/Eloquents/QuestioningRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\questioningRepository;
use App\Repositories\Models\Questioning;
use App\Repositories\Validators\QuestioningValidator;
/**
* Class QuestioningRepositoryEloquent
* @package namespace App\Repositories\Eloquents;
*/
class QuestioningRepositoryEloquent extends BaseRepository implements QuestioningRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Questioning::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/app/Events/Report/Main/PushReportEvent.php
<?php
namespace App\Events\Report\Main;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PushReportEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public $report_identifier;
public $report_first_received_date;
public $report_drug_safety_date;
public $create_version_cause;
public $sourceId;
public $companyId;
public function __construct($report_identifier,$report_first_received_date,$report_drug_safety_date,$create_version_cause, $sourceId, $companyId)
{
//报告编号
$this->report_identifier = $report_identifier;
//接受报告时间
$this->report_first_received_date = $report_first_received_date;
//PV部门获知时间
$this->report_drug_safety_date = $report_drug_safety_date;
//创建新版本的原因
$this->create_version_cause = $create_version_cause;
$this->sourceId = $sourceId;
$this->companyId = $companyId;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
<file_sep>/app/Repositories/Interfaces/RegulationRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface RegulationRepository.
*
* @package namespace App\Repositories\Interfaces;
*/
interface RegulationRepository extends RepositoryInterface
{
public function getRegulationsBySeverity($companyId,$severity);
}
<file_sep>/app/Http/Controllers/Back/System/MailController.php
<?php
namespace App\Http\Controllers\Back\System;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use App\Services\MailService as Service;
use Illuminate\Validation\Rule;
class MailController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back.system.mail';
/*路由*/
protected $routePrefix = 'admin.mail';
protected $encryptConnection = 'mail';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
$this->setEncryptConnection($this->encryptConnection);
}
/*添加页面*/
public function index()
{
if(request()->ajax())
{
return view(getThemeTemplate($this->folder . '.index'));
}
}
/*添加数据*/
public function create()
{
$results = $this->service->create();
return response()->json($results);
}
}<file_sep>/routes/routes/quality/datatrace.php
<?php
/**
* 稽查管理
*/
$router->group([], function($router) {
$router->resource('datatrace', 'DataTraceController');
});<file_sep>/resources/lang/en/code/workflow.php
<?php
return [
'store' => [
'fail' => '工作流节点创建失败',
'success' => '工作流节点创建成功',
],
'update' => [
'fail' => '工作流节点修改失败',
'success' => '工作流节点修改成功',
],
'destroy' => [
'fail' => '工作流节点删除失败',
'success' => '工作流节点删除成功',
],
'open' => [
'fail' => '工作流开启失败',
'success' => '工作流开启成功',
],
];<file_sep>/app/Http/Controllers/Back/Report/SupervisionsController.php
<?php
namespace App\Http\Controllers\Back\Report;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\Report\SupervisionsService as Service;
/**
* Class SourcesController.
*
* @package namespace App\Http\Controllers;
*/
class SupervisionsController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.report.supervision';
protected $routePrefix = 'admin.supervision';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index()
{
if (request()->ajax()) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
public function immediately($id){
if (request()->ajax()) {
return $this->service->immediately($id);
}
abort(404);
}
public function other(){
dd(__LINE__);
}
public function noNeed(){
}
}
<file_sep>/app/Services/RoleService.php
<?php
namespace App\Services;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use App\Traits\Services\Permission\PermissionTrait;
use DataTables;
use Exception;
use DB;
class RoleService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait, PermissionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function index()
{
$html = $this->builder->columns([
// ['data' => 'id', 'name' => 'id', 'title' => '角色ID', 'class' => 'text-center'],
['data' => 'name', 'name' => 'name', 'title' => '角色名'],
['data' => 'display_name', 'name' => 'display_name', 'title' => '展示名'],
['data' => 'description', 'name' => 'description', 'title' => '描述'],
['data' => 'created_at', 'name' => 'created_at', 'title' => '创建时间'],
['data' => 'updated_at', 'name' => 'updated_at', 'title' => '修改时间'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false],
])
->ajax([
'url' => route('admin.role.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
public function datatables()
{
$data = $this->roleRepo->all();
return DataTables::of($data)
->editColumn('id', '{{ $id_hash }}')
->addColumn('action', getThemeTemplate('back.system.role.datatable'))
->make();
}
public function create()
{
try {
/*组织结构的值*/
$roleOrganizes = getRoleOrganize();
return [
'roleOrganizes' => $roleOrganizes,
];
} catch (Exception $e) {
abort(404);
}
}
public function edit($id)
{
try {
/*获取用户信息*/
$id = $this->roleRepo->decodeId($id);
$role = $this->roleRepo->find($id);
/*组织结构的值*/
$roleOrganizes = getRoleOrganize();
return [
'roleOrganizes' => $roleOrganizes,
'role' => $role,
];
} catch (Exception $e) {
abort(404);
}
}
/**
* 保存
* @return [type] [description]
*/
public function store()
{
try {
$exception = DB::transaction(function() {
if($role = $this->roleRepo->create(request()->all())) {
} else {
throw new Exception(trans('code/role.store.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/role.store.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/role.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 修改保存
* @param [type] $id [description]
* @return [type] [description]
*/
public function update($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->roleRepo->decodeId($id);
if( $role = $this->roleRepo->update(request()->all(), $id) ) {
} else {
throw new Exception(trans('code/role.update.fail'), 2);
}
/*清除菜单缓存*/
event(new \App\Events\FlushCache());
return array_merge($this->results, [
'result' => true,
'message' => trans('code/role.update.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/role.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 删除角色
* @param [type] $id [description]
* @return [type] [description]
*/
public function destroy($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->roleRepo->decodeId($id);
if( $role = $this->roleRepo->delete($id) ){
} else {
throw new Exception(trans('code/role.destroy.fail'), 2);
}
/*清除菜单缓存*/
event(new \App\Events\FlushCache());
return array_merge($this->results, [
'result' => true,
'message' => trans('code/role.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/role.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 角色用户
* @return [type] [description]
*/
public function userShow($id)
{
$results = [];
try {
/*获取用户信息*/
$id = $this->roleRepo->decodeId($id);
$role = $this->roleRepo->find($id);
$users = $role->users->map(function($item, $key) {
return [
'name' => $item->name,
'company_name' => $item->company_name,
];
});
$results = [
'role' => $role,
'data' => $users,
];
} catch (Exception $e) {
$results = [
'role' => $role,
'data' => []
];
}
return $results;
}
/**
* 角色权限列表
* @param [type] $id [description]
* @return [type] [description]
*/
public function permissionEdit($id)
{
try {
/*角色权限*/
$id = $this->roleRepo->decodeId($id);
$role = $this->roleRepo->find($id);
$rolePermissions = $role->permissions->keyBy('name')->keys()->toArray();
/*获取所有权限并且表明已选择的*/
$permissionSelected = $this->permissionSelect($rolePermissions);
$results = [
'role' => $role,
'data' => $permissionSelected
];
} catch (Exception $e) {
$results = [
'role' => $role,
'data' => []
];
}
return $results;
}
/**
* 角色权限保存
* @return [type] [description]
*/
public function permissionUpdate($id)
{
try {
$exception = DB::transaction(function() use ($id) {
/*获取角色信息*/
$id = $this->roleRepo->decodeId($id);
$role = $this->roleRepo->find($id);
/*角色绑定权限*/
$permissionIds = $this->checkParam('permission', [], false);
event(new \App\Events\Role\BindPermission($role, $permissionIds));
return array_merge($this->results, [
'result' => true,
'message' => trans('code/role.permission.update.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/role.permission.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 组织结构角色
* @return [type] [description]
*/
public function organize($organizeRoleId)
{
$results = [];
try {
/*获取组织结构对应的角色*/
$roles = $this->roleRepo->organizeRoles($organizeRoleId)->map(function($item, $key) {
return [
'id' => $item->id_hash,
'name' => $item->name,
];
});
$results = array_merge($this->results, [
'result' => true,
'data' => $roles,
'message' => trans('code/role.organize.success'),
]);
} catch (Exception $e) {
$results = array_merge($this->results, [
'result' => false,
'data' => $this->handler($e, trans('code/role.organize.fail')),
]);
}
return array_merge($this->results, $results);
}
}<file_sep>/app/Repositories/Interfaces/DrugLibraryRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface DrugLibraryRepository.
*
* @package namespace App\Repositories\Interfaces;
*/
interface DrugLibraryRepository extends RepositoryInterface
{
//
}
<file_sep>/app/Repositories/Models/Question.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
class Question extends Model implements Transformable
{
protected $table = 'question';
use TransformableTrait;
public $timestamps = false;
protected $fillable = ['question_num','report_num','operation_name','operation_id','status','operation_date','content','end_date','sending'];
}
<file_sep>/routes/routes/drug-library/pre-drug.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/16
* Time: 上午11:31
*/
$router->group([], function($router) {
$router->group(['prefix' => 'predrug', 'as' => 'predrug.'], function($router) {
//上市前
//列表页
$router->get('index', [
'uses' => 'PreDrugController@preIndex',
'as' => "index"
]);
// 添加
$router->get('add',[
'uses' => 'PreDrugController@preCreate',
'as' => "add"
]);
// 修改
$router->get('{id}/edit', [
'uses' => 'PreDrugController@preEdit',
'as' => "edit"
]);
//删除
$router->delete('{id}/remove',[
'uses' => 'PreDrugController@remove',
'as' => "remove"
]);
});
});<file_sep>/app/Repositories/Eloquents/LogisticsRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use App\Traits\EncryptTrait;
use Illuminate\Container\Container as Application;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\LogisticsRepository;
use App\Repositories\Models\Logistics;
use App\Repositories\Validators\LogisticsValidator;
/**
* Class LogisticsRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class LogisticsRepositoryEloquent extends BaseRepository implements LogisticsRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('logistics');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Logistics::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return LogisticsValidator::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
public function getList($report_identifier)
{
$companyId = getCompanyId();
return $this->model->companyId($companyId)->reportIdentifier($report_identifier)->get();
}
}
<file_sep>/app/Repositories/Eloquents/CategoryRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use App\Traits\EncryptTrait;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\CategoryRepository;
use App\Repositories\Models\Category;
use App\Repositories\Validators\CategoryValidator;
use Illuminate\Container\Container as Application;
/**
* Class CategoryRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class CategoryRepositoryEloquent extends BaseRepository implements CategoryRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('category');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Category::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return CategoryValidator::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/app/Http/Controllers/Back/System/UserController.php
<?php
namespace App\Http\Controllers\Back\System;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use App\Services\UserService as Service;
use Illuminate\Validation\Rule;
class UserController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back.system.user';
protected $routePrefix = 'admin.user';
protected $encryptConnection = 'user';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
$this->setEncryptConnection($this->encryptConnection);
}
/**
* 用户列表
* @return [type] [description]
*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
/**
* 重置密码
* @return [type] [description]
*/
public function resetPass($id)
{
$results = $this->service->resetPass($id);
return response()->json($results);
}
/**
* 锁定用户
* @param [type] $id [description]
* @return [type] [description]
*/
public function lock($id)
{
$results = $this->service->lock($id);
return response()->json($results);
}
/**
* 解锁用户
* @param [type] $id [description]
* @return [type] [description]
*/
public function unlock($id)
{
$results = $this->service->unlock($id);
return response()->json($results);
}
private function storeRules()
{
return [
'name' => [
'required',
Rule::unique('users')->where(function($query) {
return $query->whereNull('deleted_at');
}),
],
'truename' => 'required',
'password' => '<PASSWORD>',
'role' => 'required',
'mobile' => 'required',
'email' => 'required',
'company' => 'required',
'is_check_email' => 'required',
];
}
private function updateRules()
{
return [
'name' => [
'required',
Rule::unique('users')->where(function($query) {
return $query->whereNull('deleted_at');
})->ignore($this->decodeId(getRouteParam('user')), 'id'),
],
'truename' => 'required',
'role' => 'required',
'mobile' => 'required',
'email' => 'required',
'company' => 'required',
'is_check_email' => 'required',
];
}
private function messages()
{
return [
'name.required' => '账号不能为空',
'name.unique' => '账号已经存在',
'truename.required' => '真实姓名不能为空',
'password.required' => '<PASSWORD>',
'role.required' => '角色不能为空',
'mobile.required' => '手机号不能为空',
'email.required' => '邮箱不能为空',
'company.required' => '公司不能为空',
'is_check_email.required' => '是否验证邮箱不能为空',
];
}
}
<file_sep>/config/back/redundance.php
<?php
/**
* 冗余数据
*/
return [
/*报告冗余字段*/
'report' => [
/*||| first 代表第一条数据, normal 按照正常格式 ||||*/
/*基本信息*/
'basic' => [
//pv获悉时间
'report_drug_safety_date' => 'normal',
// 事件发生国家
'ae_country' => 'normal',
// 企业报告类型
'received_from_id' => 'normal',
// 项目编号
'research_id' => 'normal',
// 中心编号
'center_number' => 'normal',
// 迟到原因
'delayed_reason' => 'normal',
/*报告者信息中--判断是否是首要报告*/
// 报告者姓名
'reporter_name' => 'table_first',
// 单位名称
'reporter_organisation' => 'table_first',
// 部门
'reporter_department' => 'table_first',
// 国家
'reporter_country' => 'table_first',
// 省
'reporter_staeor_province' => 'table_first',
// 市
'reporter_city' => 'table_first',
// 邮编
'reporter_post' => 'table_first',
// 电话
'reporter_telephone_number' => 'table_first',
/*文献信息*/
// 文献发表年
'literature_published_year' => 'normal',
// 文献作者
'literature_author' => 'normal',
// 期刊名
'literature_published_journals' => 'normal',
// 文献标题
'literature_title' => 'normal',
],
/*药物*/
'drug' => [
// 商品名称
'brand_name' => 'normal',
// 首要商品名称
'first_brand_name' => 'first',
// 药品名称
'drug_name' => 'normal',
// 首要药品名称
'first_drug_name' => 'first',
// 通用名称
'generic_name' => 'normal',
// 首要通用名称
'first_generic_name' => 'first',
],
/*不良事件*/
'event' => [
// 不良事件
'event_term' => 'normal' ,
// 首要不良事件
'first_event_term' => 'first' ,
// // 是否严重 --- 删除
// 'seriousness' => 'first' ,
/*不良事件发生时间*/
'event_of_onset' => 'first' ,
],
/*患者信息*/
'patient' => [
// 姓名
'patient_name' => 'normal',
// 患者编号
'subject_number' => 'normal',
// 出生日期
'date_of_birth' => 'normal',
// 年龄
'age' => 'normal',
// 年龄单位
'age_at_time_of_onset_unit' => 'normal',
// 性别
'sex' => 'normal',
// 电话
'patient_contact_infomation' => 'normal',
],
],
/*报告任务冗余字段*/
'report_task' => [
'basic' => [
// 企业报告类型
'received_from_id' => 'normal',
],
'drug' => [
// 药品名称
'drug_name' => 'normal',
// 首要药品名称
'first_drug_name' => 'first',
],
'event' => [
// 不良事件
'event_term' => 'normal',
// 首要不良事件
'first_event_term' => 'first',
/*首要不良事件是否是严重*/
// 严重性
'seriousness' => 'first',
// 严重性标准
'standard_of_seriousness' => 'first',
],
'appraise' => [
// 因果关系
'case_causality' => 'normal',
],
],
/*报告详情冗余字段*/
'report_value' => [
'basic' => [
/*事件发生国家*/
'ae_country' => 'normal',
/*企业报告类型*/
'received_from_id' => 'normal',
/*首次接受时间*/
'report_first_received_date' => 'normal',
/*报告者信息中--判断是否是首要报告*/
// 报告者姓名
'reporter_name' => 'table_first',
// 单位名称
'reporter_organisation' => 'table_first',
// 部门
'reporter_department' => 'table_first',
// 国家
'reporter_country' => 'table_first',
// 报告者类型
'reporter_type' => 'table_first',
// 电话
'reporter_telephone_number' => 'table_first',
// 报告者职位
'reporter_occupation' => 'table_first',
],
'drug' => [
// 商品名称
'brand_name' => 'first',
// 怀疑用药
'drug_type' => 'first',
/*通用名称*/
'generic_name' => 'first',
/*生产厂家*/
'manu_facture' => 'first',
],
'patient' => [
// 姓名
'patient_name' => 'normal',
// 出生日期
'date_of_birth' => 'normal',
// 年龄
'age' => 'normal',
// 年龄单位
'age_at_time_of_onset_unit' => 'normal',
// 性别
'sex' => 'normal',
// 是否妊娠
'pregnancy_report' => 'normal',
],
'event' => [
/*不良事件名称*/
'event_term' => 'first',
/*不良事件发生事件*/
'event_of_onset' => 'first' ,
/*不良事件的结局*/
'event_out_come' => 'first'
],
],
];<file_sep>/config/seeder/report.php
<?php
return [
'tab' => [
['name' => '概览'],
['name' => '基本信息'],
['name' => '患者信息'],
['name' => '药物信息'],
['name' => '不良事件'],
['name' => '报告评价'],
['name' => '事件描述'],
['name' => '问卷'],
['name' => '附件信息'],
],
];<file_sep>/app/Repositories/Criterias/OrderBySortCriteria.php
<?php
namespace App\Repositories\Criterias;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Class OrderBySortCriteria
* @package namespace App\Repositories\Criterias;
*/
class OrderBySortCriteria implements CriteriaInterface
{
protected $order;
protected $field;
public function __construct($order = 'desc', $field = 'sort')
{
$this->order = $order;
$this->field = $field;
}
/**
* Apply criteria in query repository
*
* @param $model
* @param RepositoryInterface $repository
*
* @return mixed
*/
public function apply($model, RepositoryInterface $repository)
{
return $model->orderBy($this->field, $this->order);
}
}
<file_sep>/app/Repositories/Models/PlatformConfig.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
/**
* Class PlatformConfig.
*
* @package namespace App\Repositories\Models;
*/
class PlatformConfig extends Model implements Transformable
{
use TransformableTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $table = 'platform_config';
protected $fillable = ['platform_code','platform_name','status','regular','created_at','updated_at'];
}
<file_sep>/routes/oc_routes/purchasing/c_recharge.php
<?php
$router->group(['namespace'=>'Card\Purchasing'], function($router) {
$router->group(['prefix' => 'c_recharge', 'as' => 'c_recharge.'], function($router) {
$router->get('index', [
'uses' => 'CamiloRechargeController@index',
'as' => 'index'
]);
});
});<file_sep>/database/seeds/MenuSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Repositories\Models\Menu;
use App\Repositories\Models\RecursiveRelation;
use Illuminate\Support\Facades\Artisan;
class MenuSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->command->info('Truncating Menu, RecursiveRelation tables');
$this->truncateTables();
$config = config('seeder.menu.structure');
$maps = config('seeder.menu.maps');
$parentMenu = Null;
$this->createMenus($config, $parentMenu, $maps);
}
private function createMenus($config, $parentMenu, $maps)
{
foreach($config as $key => $modules) {
if ( isset($modules['next'])) {
$menu = Menu::create([
'name' => $maps[$key],
'route' => '#',
'icon' => $modules['icon'],
'permission' => $modules['permission'],
'route_prefix' => $modules['route_prefix'],
]);
$this->createMenus($modules['next'], $menu, $maps);
} else {
/*进行保存*/
$menu = Menu::create([
'name' => $maps[$key],
'route' => $modules['route'],
'icon' => $modules['icon'],
'permission' => $modules['permission'],
'route_prefix' => $modules['route_prefix'],
]);
}
if($parentMenu) {
$menu->parentMenu()->attach($parentMenu);
}
}
Artisan::call('cache:clear');
}
private function truncateTables()
{
Schema::disableForeignKeyConstraints();
DB::table('recursive_relations')->truncate();
Menu::truncate();
Schema::enableForeignKeyConstraints();
}
}
<file_sep>/app/Http/Controllers/Card/Purchasing/MessageController.php
<?php
namespace App\Http\Controllers\Card\Purchasing;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class MessageController extends Controller
{
public function index(){
return view('themes.metronic.ocback.backstage.purchasing.message');
}
}
<file_sep>/app/Services/Report/MainpageService.php
<?php
namespace App\Services\Report;
use Yajra\DataTables\Html\Builder;
use App\Services\Service;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use App\Traits\DictionariesTrait;
use App\Traits\Services\Report\MainTrait;
use App\Events\Report\Main;
use Exception;
use DB;
use DataTables;
class MainpageService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait,DictionariesTrait,MainTrait;
protected $builder;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function datatables($source_id)
{
$field = ['id','report_first_received_date','report_drug_safety_date','aecountry_id','aecountrys_id','aecountry','received_fromid_id','received_fromids_id','received_from_id','research_id','center_number','delayedreason','brand_name','generic_name','event_term','seriousness','event_of_onset','report_identifier','report_type','reporter_name','reporter_organisation','reporter_department','reporter_country','reporter_country_id','reporter_countries_id','reporter_stateor_province','reporter_city','reporter_post','reporter_telephone_number','patient_name','subject_number','date_of_birth','age','age_at_timeofonsetunit','sex','patient_contact_information','literature_publishedyear','literature_author','literature_published_journals','status_type','literature_title','time_begin','time_end','severity'];
$searchFields = [
'report_first_received_date' => 'like',
'report_drug_safety_date' => 'like',
'aecountry_id' => '=',
'received_fromid_id' => '=',
'research_id' => 'like',
'center_number' => 'like',
'delayed_reason' => 'like',
'severity'=> '=',
'brand_name' => 'like',
'generic_name' => 'like',
'event_term' => 'like',
'first_brand_name'=>'like',
'seriousness' => '=',
'event_of_onset' => '=',
'reporter_name' => 'like',
'reporter_organisation' => 'like',
'reporter_department' => 'like',
'reporter_country_id' => '=',
'reporter_stateor_province' => 'like',
'reporter_city' => 'like',
'reporter_post' => 'like',
'reporter_telephone_number' => 'like',
'patient_name' => 'like',
'subject_number' => 'like',
'date_of_birth' => '=',
'age' => '=',
'age_at_timeofonsetunit' => '=',
'sex' => '=',
'role_organize_status'=> '=',
'patient_contact_information' => '=',
'literature_published_year' => 'like',
'literature_author' => 'like',
'literature_published_journals' => 'like',
'literature_title' => 'like',
];
$user = getUser();
$userNowId = $user->id;
/*当前用户的权限 如果包含数据录入员( 2 )显示新建 按钮*/
$organizeRoleIds = $user->roles->keyBy('organize_role_id')->keys()->toArray();
/*获取查询条件*/
$where = $this->searchArray($searchFields);
$allData = $this->reportMainpageRepo->findWhere($where)->all();
return DataTables::of($allData)
->addColumn('organizeRoleIds', $organizeRoleIds)
->addColumn('source_id', $source_id)
->addColumn('action', getThemeTemplate('back.report.mainpage.datatables'))
->addColumn('role_organize_status', getThemeTemplate('back.report.mainpage.status'))
->removeColumn('organizeRoleIds')
->removeColumn('source_id')
->make();
}
public function index()
{
$html = $this->builder->columns([
['data' => 'report_first_received_date', 'name' => 'report_first_received_date', 'title' => '首次获悉的时间'],
['data' => 'report_drug_safety_date', 'name' => 'report_drug_safety_date', 'title' => 'pv获悉的时间'],
['data' => 'research_id', 'name' => 'research_id', 'title' => '项目编号'],
['data' => 'center_number', 'name' => 'center_number', 'title' => '中心编号'],
['data' => 'event_term', 'name' => 'event_term', 'title' => '不良事件'],
['data' => 'first_drug_name', 'name' => 'first_drug_name', 'title' => '药品名称'],
['data' => 'report_identifier', 'name' => 'report_identifier', 'title' => '报告编号'],
['data' => 'received_from_id', 'name' => 'received_from_id', 'title' => '报告类型'],
['data' => 'patient_name', 'name' => 'patient_name', 'title' => '患者姓名'],
['data' => 'subject_number', 'name' => 'subject_number', 'title' => '患者编号'],
['data' => 'role_organize_status', 'name' => 'role_organize_status', 'title' => '当前的状态 与角色权限所关联 2:数据录入3:数据质控qc4:医学评审5:医学审评QC6:已完成'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false],
])
->ajax([
'url' => route('admin.report.mainpage.index'),
'type' => 'GET',
]);
return [
'html' => $html
];
}
/*新建报告*/
public function create()
{
try {
$exception = DB::transaction(function(){
/*获取原始资料id*/
$sourceId = request('source_id', '');
//获取当前登录用户id
$user = getUser();
$user_id = $user->id;
$company = $user->company;
//判断当前报告是否首次商品名称
$companyName = $company->name;
$companyId = $company->id;
$companyId = getCompanyId();
$report_identifier = $this->getReportNumber($companyName,$companyId);
$infoResults = request()->all();
$report_identifier = $this->getReportNumber($companyName,$companyId);
if($this->reportMainpageRepo->findWhere(['company_id'=>$companyId])){$infoResults['is_first_report']=1;};
$infoResults['report_identifier'] = $report_identifier;
$infoResults['company_id'] = $companyId;
$infoResults['source_id']= $sourceId;
$infoResults['user_id']=$user_id;
$infoResults['drug_name'] = $infoResults['brand_name'].'/'.$infoResults['generic_name'];
//获取规则 找到当前规则id
$severity=request()->severity;
$regulationInfo=$this->regulaRepo->getRegulationsBySeverity($companyId, $severity);
$regulation_id = $regulationInfo->id;
$infoResults['regulation_id']=$regulation_id;
$Information = $this->reportMainpageRepo->create($infoResults);
if($Information) {
$id = $Information->id;
$report = $this->reportMainpageRepo->find($id);
// //数据推送到Tab数据表
event(new \App\Events\Report\Task\Create($report,$companyId,$regulationInfo,$user_id));
// //数据推送
if($sourceId) {
//设置报告任务数据
event(new \App\Events\Report\Task\Update($report, $companyId,$regulationInfo, $sourceId));
} else {
//创建报告任务
event(new \App\Events\Report\Task\Create($report,$companyId,$regulationInfo,$user_id));
}
//数据推送
event(new \App\Events\Report\Value\Create($report));
} else {
throw new Exception(trans('code/mainpage.create.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'data'=>$Information,
'message' => trans('code/mainpage.create.success'),
]);
});
} catch (Exception $e) {
dd($e);
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/mainpage.create.fail')),
]);
}
return array_merge($this->results, $exception);
}
/*复制*/
public function copyData($id)
{
try {
$exception = DB::transaction(function() use ($id){
//获取当前登录用户id
$user = getUser();
$user_id = $user->id;
$company = $user->company;
$companyName = $company->name;
$companyId = $company->id;
$report_identifier = $this->getReportNumber($companyName,$companyId);
$infoResults = $this->reportMainpageRepo->find($id)->toArray();
$infoResults['report_identifier'] = $report_identifier;$infoResults['is_first_report']=1;
$infoResults['company_id'] = $companyId;
$infoResults['user_id'] = $user_id;
$regulation_id = $infoResults['regulation_id'];
if($Information = $this->reportMainpageRepo->create($infoResults)) {
$id = $Information->id;
$report = $this->reportMainpageRepo->find($id);
//数据推送到Tab数据表
event(new \App\Events\Report\Task\Create($report,$companyId,$regulation_id,$user_id));
//数据推送
event(new \App\Events\Report\Value\Create($report));
} else {
throw new Exception(trans('code/mainpage.copydata.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'data'=>$Information,
'message' => trans('code/mainpage.copydata.success'),
]);
});
} catch (Exception $e) {
dd($e);
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/mainpage.copydata.fail')),
]);
}
return array_merge($this->results, $exception);
}
/*隐藏 *删除*/
public function edit($id)
{
// event(new \App\Events\Report\Main\PushReportEvent(null,null,null,null));
// dd(__LINE__);
$exception = DB::transaction(function() use ($id) {
$user = getUser();
$user_id = $user->id;
if(1) {
$report_identifier = '2018MSYX000001';
$report_first_received_date='2018/2/5';
$report_drug_safety_date='2018/2/5';
$create_version_cause='1';
// event(new \App\Events\Report\Value\SetRedundanceData(null, null, null));
event(new \App\Events\Report\Main\PushReportEvent($report_identifier, $report_first_received_date, $report_drug_safety_date, $create_version_cause));
// dd(__LINE__);
} else {
throw new Exception(trans('code/mainpage.delete.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/mainpage.delete.success'),
]);
});
// $report_identifier = '2018MSYX000001';
// $report_first_received_date='2018/2/5';
// $report_drug_safety_date='2018/2/5';
// $create_version_cause='1';
// event(new \App\Events\Report\Main\PushReportEvent($report_identifier,$report_first_received_date,$report_drug_safety_date,$create_version_cause));
// dd(__LINE__);
try {
$exception = DB::transaction(function() use ($id) {
$user = getUser();
$user_id = $user->id;
if(1) {
// $report_identifier = '2018MSYX000001';
// $report_first_received_date='2018/2/5';
// $report_drug_safety_date='2018/2/5';
// $create_version_cause='1';
// event(new \App\Events\Report\Value\SetRedundanceData(null, null, null));
// event(new \App\Events\Report\Main\PushReportEvent(null,null,null,null));
// dd(__LINE__);
} else {
throw new Exception(trans('code/mainpage.delete.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/mainpage.delete.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/mainpage.delete.fail')),
]);
}
return array_merge($this->results, $exception);
}
/*新建版本*/
public function newReport($data)
{
try{
$exception = DB::transaction(function() use ($data){
//获取当前登录用户id
$user = getUser();
$user_id = $user->id;
$company = $user->company;
if(is_array($data)){
$company_id = $this->reportMainpageRepo->findWhere(['report_identifier'=>$data['report_identifier']])->pluck('company_id');
$report = $this->getReport($company,$user_id,$company_id);
$report['create_version_cause'] = $data['create_version_cause'];
$report['report_first_received_date'] = $data['report_first_received_date'];
$report['report_drug_safety_date'] = $data['report_drug_safety_date'];
$information = $this->reportMainpageRepo->create($report);
// /*复制报告任务*/
// event(new \App\Events\Report\Task\Copy($reportId, $taskUserId, $regulation, $reportFirstReceivedData, $newReport));
// event(new \App\Events\Report\Value\Copy($reportId, $newReport));
}else {
$report_identifier = $this->reportMainpageRepo->findWhere(['id'=>$data])->pluck('report_identifier');
$company_id = $this->reportMainpageRepo->findWhere(['report_identifier'=>$report_identifier])->pluck('company_id');
$report = $this->getReport($company,$user_id,$company_id);
$information = $this->reportMainpageRepo->create($report);
}
if($information){
} else{
throw new Exception(trans('code/mainpage.newreport.fail'),2);
}
return array_merge($this->results, [
'result' => true,
'data'=>$information,
'message' => trans('code/mainpage.newreport.success'),
]);
});
} catch(Exception $e){
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/mainpage.newreport.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function getReport($company,$user_id,$company_id)
{
//当前所有的编号
$reportSome = $this->reportMainpageRepo->findWhere(['company_id'=>$company_id])->pluck('report_identifier');
foreach($reportSome as $key=>$item){
if(substr($item,0,strrpos($item,'-'))){
$id = $this->reportMainpageRepo->findWhere(['report_identifier'=>$item])->pluck('id');
}
}
$company_now_id = $company->id;
$report = $this->reportMainpageRepo->find($id)->toArray();$report = $report[0];
$report['user_id'] = $user_id;$report_identifier = $report['report_identifier'];
$versionName = $this->getEdition($report_identifier,$company_now_id);
$report['report_identifier'] = $versionName;$report['report_identifier_status']=1;
return $report;
}
/*关联*/
public function relation()
{
#TODO 通过报告编号获取最新一条报告 并 关联到当前的数据上 关联事件
try {
$exception = DB::transaction(function(){
if(1) {
// $report_identifier = '2018MSYX000001';
// $report_first_received_date='2018/2/5';
// $report_drug_safety_date='2018/2/5';
// $create_version_cause='1';
// event(new \App\Events\Report\Main\PushReportEvent($report_identifier,$report_first_received_date,$report_drug_safety_date,$create_version_cause));
$sourceId = '';
event(new \App\Events\Report\Task\Delete($sourceId));
} else {
throw new Exception(trans('code/mainpage.delete.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/mainpage.delete.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/mainpage.delete.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/app/Traits/Services/Report/MainTrait.php
<?php
namespace App\Traits\Services\Report;
use App\Repositories\Interfaces\ReportMainpageRepository;
Trait MainTrait{
/*生成编号规则*/
public function getReportNumber($companyName,$companyId)
{
$language = app('pinyin');
$companies = strtoupper(pinyin_abbr($companyName));
$times = date('Y',time());
$information = $this->getNumber($companies,$times,$companyId);
return $information;
}
protected function getNumber($company,$times,$companyId)
{
$num = '000001';
$device_name = $times.$company;
$initial = $device_name.$num;
// ReportMainpageRepository::class
if ($report_num = app(ReportMainpageRepository::class)->findWhere(['company_id'=>$companyId,'report_identifier_status'=>0])->pluck('report_identifier')->all()) {
$report_identifier = app(ReportMainpageRepository::class)->findWhere(['company_id'=>$companyId,'report_identifier_status'=>0])->count()+1;
$report_identifier_len = strlen($report_identifier);
$new_report_identifier = substr($initial,0,-$report_identifier_len);
$report_num = $new_report_identifier.$report_identifier;
return $report_num;
}else {
return $initial;
}
}
/*新建版本号*/
protected function getEdition($report_identifier,$company_id)
{
$num = '-001';
$initial = $report_identifier.$num;
if($report_num = app(ReportMainpageRepository::class)->findWhere(['company_id'=>$company_id,'report_identifier_status'=>1])->pluck('report_identifier')->all()) {
$report_version= app(ReportMainpageRepository::class)->findWhere(['company_id'=>$company_id,'report_identifier_status'=>1])->count()+1;
$report_identifier_len = strlen($report_version);
$new_report_identifier = substr($initial,0,-$report_identifier_len);
$new_report_identifier = explode('-',$new_report_identifier);
unset($new_report_identifier[2]);
$report_num=implode('-',$new_report_identifier);
$new_report_identifier = substr($report_num,0,-$report_identifier_len);
// if($new_report_identifier)
// $report_num = strrpos($new_report_identifier,'-');
$report_num = $new_report_identifier.$report_version;
return $report_num;
}else {
return $initial;
}
}
}<file_sep>/database/migrations/2018_04_06_174135_create_attachement_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAttachementTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('attachement', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable()->default('')->comment('加密文件名');
$table->string('origin_name')->nullable()->default('')->comment('上传文件名');
$table->integer('file_size')->nullable()->default(0)->comment('文件大小');
$table->string('path')->nullable()->default('')->comment('文件相对路径');
$table->string('file_ext', 10)->nullable()->default('')->comment('文件扩展名');
$table->string('ext_info')->nullable()->default('')->comment('文件扩展信息');
$table->integer('user_id')->nullable()->default(0)->comment('上传用户者id');
$table->string('user_name')->nullable()->default(0)->comment('用户创建者id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('attachement');
}
}
<file_sep>/app/Providers/RepositoryServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind(\App\Repositories\Interfaces\UserRepository::class, \App\Repositories\Eloquents\UserRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\RoleRepository::class, \App\Repositories\Eloquents\RoleRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\PermissionRepository::class, \App\Repositories\Eloquents\PermissionRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\MenuRepository::class, \App\Repositories\Eloquents\MenuRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\CompanyRepository::class, \App\Repositories\Eloquents\CompanyRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\DictionariesRepository::class, \App\Repositories\Eloquents\DictionariesRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\RecursiveRelationRepository::class, \App\Repositories\Eloquents\RecursiveRelationRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\MailRepository::class, \App\Repositories\Eloquents\MailRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\SubdictionariesRepository::class, \App\Repositories\Eloquents\SubdictionariesRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\DrugLibraryRepository::class, \App\Repositories\Eloquents\DrugLibraryRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\WorkflowRepository::class, \App\Repositories\Eloquents\WorkflowRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\WorkflowNodeRepository::class, \App\Repositories\Eloquents\WorkflowNodeRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\WorkflowNodeDetailRepository::class, \App\Repositories\Eloquents\WorkflowNodeDetailRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\RegulationRepository::class, \App\Repositories\Eloquents\RegulationRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\ReportValuesRepository::class, \App\Repositories\Eloquents\ReportValuesRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\QuestionRepository::class, \App\Repositories\Eloquents\QuestionRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\QuestioningRepository::class, \App\Repositories\Eloquents\QuestioningRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\SourceRepository::class, \App\Repositories\Eloquents\SourceRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\CategoryRepository::class, \App\Repositories\Eloquents\CategoryRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\ReportTabRepository::class, \App\Repositories\Eloquents\ReportTabRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\ReportTaskRepository::class, \App\Repositories\Eloquents\ReportTaskRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\DataTraceRepository::class, \App\Repositories\Eloquents\DataTraceRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\ReportMainpageRepository::class, \App\Repositories\Eloquents\ReportMainpageRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\SupervisionRepository::class, \App\Repositories\Eloquents\SupervisionRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\AttachmentRepository::class, \App\Repositories\Eloquents\AttachmentRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\LogisticsRepository::class, \App\Repositories\Eloquents\LogisticsRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\AttachmentModelRepository::class, \App\Repositories\Eloquents\AttachmentModelRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\EnterpriseRepository::class, \App\Repositories\Eloquents\EnterpriseRepositoryEloquent::class);
//:end-bindings:
/*OC*/
$this->app->bind(\App\Repositories\Interfaces\OcloginRepository::class, \App\Repositories\Eloquents\OcloginRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\ManagementRepository::class, \App\Repositories\Eloquents\ManagementRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\PurchaseRepository::class, \App\Repositories\Eloquents\PurchaseRepositoryEloquent::class);
//$this->app->bind(\App\Repositories\Interfaces\PurchaseRepository::class, \App\Repositories\Eloquents\PurchaseRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\OilCardRepository::class, \App\Repositories\Eloquents\OilCardRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\SupplierRepository::class, \App\Repositories\Eloquents\SupplierRepositoryEloquent::class);
$this->app->bind(\App\Repositories\Interfaces\PlatformConfigRepository::class, \App\Repositories\Eloquents\PlatformConfigRepositoryEloquent::class);
}
}
<file_sep>/app/Http/Controllers/Back/System/RoleController.php
<?php
namespace App\Http\Controllers\Back\System;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\RoleService as Service;
use Illuminate\Validation\Rule;
use App\Traits\EncryptTrait;
class RoleController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back.system.role';
protected $routePrefix = 'admin.role';
protected $encryptConnection = 'role';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
$this->setEncryptConnection($this->encryptConnection);
}
/**
* 角色列表
* @return [type] [description]
*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
/**
* 角色用户--拥有此角色的用户列表
* @return [type] [description]
*/
//TODO: 这里需要返回的是 datatables 表头包含:序号,登陆账号,真实姓名
public function userShow($id)
{
$results = $this->service->userShow($id);
dd($results);
return view(getThemeTemplate($this->folder . '.user'))->with($results);
}
/**
* 修改角色权限
* @param [type] $id [角色id]
* @return [type] [description]
*/
public function permissionEdit($id)
{
$results = $this->service->permissionEdit($id);
return view(getThemeTemplate($this->folder . '.permission'))->with($results);
}
/**
* 角色权限保存
* @param [type] $id [角色id]
* @return [type] [description]
*/
//TODO:这里是返回页面
public function permissionUpdate($id)
{
$results = $this->service->permissionUpdate($id);
if($results['result']) {
return redirect()->route($this->routePrefix . '.index');
} else {
return redirect()->back()->withErrors($results['message']);
}
}
/**
* 组织结构的角色列表
* @return [type] [description]
*/
public function organize($organizeRoleId)
{
$results = $this->service->organize($organizeRoleId);
return response()->json($results);
}
private function storeRules()
{
return [
'name' => [
'required',
Rule::unique('roles'),
],
'display_name' => 'required',
'description' => 'required',
];
}
private function updateRules()
{
return [
'name' => [
'required',
Rule::unique('roles')->ignore($this->decodeId(getRouteParam('role')), 'id'),
],
'display_name' => 'required',
'description' => 'required',
];
}
private function messages()
{
return [
'name.required' => '角色名称不能为空',
'name.unique' => '角色名称已经存在',
'display_name.required' => '角色显示名称不能为空',
'description.required' => '角色描述不能为空',
];
}
}
<file_sep>/routes/routes/quality/question.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'question', 'as' => 'question.'], function($router){
/*质疑管理*/
/*查看tab详情页面*/
$router->put('{id}/show',[
'uses' => 'QuestionController@show',
'as' => 'show'
]);
});
/*资源路由*/
$router->resource('question', 'QuestionController');
});<file_sep>/app/Services/PurchaseService.php
<?php
namespace App\Services;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DataTables;
use Exception;
use DB;
Class PurchaseService extends Service{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
/*多条件查询*/
public function datatables()
{
$searchFields = [
'purchase_number' => 'like',
'denomination' => 'like',
'number' => '=',
];
/*获取查询条件*/
$where = $this->searchArray($searchFields);
/*获取数据*/
$data = $this->managementRepo->findWhere($where);
return DataTables::of($data)
->addColumn('action', getThemeTemplate('back.quality.question.datatable'))
->addColumn('status', getThemeTemplate('back.homepage.questioning.status'))
->make();
}
}<file_sep>/config/oc/field.php
<?php
return [
/*订单类型
key_word是关键字
chinese是中文
value是值
*/
'order_type'=>[
'0'=>[
'key_word'=>'no_pay',
'chinese'=>'未付款',
'value'=>'0',
],
'1'=>[
'key_word'=>'no_finished',
'chinese'=>'未完成',
'value'=>'1',
],
'2'=>[
'key_word'=>'finished',
'chinese'=>'已完成',
'value'=>'2',
],
'3'=>[
'key_word'=>'misstake',
'chinese'=>'问题订单',
'value'=>'3',
],
],
//省份
'province'=>[
'0'=>[
'key_word'=>'beijing',
'chinese'=>'北京',
'value'=>'1',
],
],
//卡密状态
'status'=>[
'0'=>[
'key_word'=>'normal',
'chinese'=>'正常',
'value'=>'0',
],
'1'=>[
'key_word'=>'no_normal',
'chinese'=>'不正常',
'value'=>'1',
],
],
//面额
'denomination'=>[
'0'=>[
'key_word'=>'fifty',
'chinese'=>'50',
'value'=>'50',
],
'1'=>[
'key_word'=>'hundred',
'chinese'=>'100',
'value'=>'100',
],
],
//采购方式
'procurement_type'=>[
],
//折扣
'discount'=>[
],
//油卡选择
'oil_card'=>[
],
//城市
'city'=>[
],
'commodity'=>[
],
//供卡名称
'platform_type'=>[
],
//供卡状态
's_status'=>[
],
//面额
'price'=>[
],
];<file_sep>/routes/routes/report/route.php
<?php
$router->group(['namespace' => 'Back\Report'], function($router) {
/*报告详情*/
require(__DIR__ . '/value.php');
#原始数据
require(__DIR__ . '/source.php');
/*报告任务*/
require(__DIR__ . '/task.php');
/*报告主页面*/
require(__DIR__.'/mainpage.php');
#上报监管
require(__DIR__.'/supervision.php');
#物流信息
require(__DIR__.'/logistics.php');
});<file_sep>/routes/routes/registered/login.php
<?php
$router->group(['prefix' => 'registered', 'as' => 'registered.'], function($router) {
$router->group(['prefix' => 'login', 'as' => 'login.'], function ($router) {
/*列表*/
$router->get('index',[
'uses'=>'LoginController@index',
'as'=>'index',
]);
});
$router->resource('login','LoginController');
});<file_sep>/app/Repositories/Interfaces/LogisticsRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface LogisticsRepository.
*
* @package namespace App\Repositories\Interfaces;
*/
interface LogisticsRepository extends RepositoryInterface
{
//
public function getList($report_identifier);
}
<file_sep>/app/Repositories/Eloquents/ReportTaskRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\ReportTaskRepository;
use App\Repositories\Models\ReportTask;
use App\Repositories\Validators\ReportTaskValidator;
use App\Traits\EncryptTrait;
use App\Traits\RepositoryTrait;
use Illuminate\Container\Container as Application;
/**
* Class ReportTaskRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class ReportTaskRepositoryEloquent extends BaseRepository implements ReportTaskRepository
{
use EncryptTrait, RepositoryTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('reporttask');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return ReportTask::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return ReportTaskValidator::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
// $this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/app/Http/Controllers/Card/Purchasing/UserMessageController.php
<?php
namespace App\Http\Controllers\Card\Purchasing;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\UserService as Service;
class UserMessageController extends Controller
{
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index(){
$results=$this->service->get_config_blade(config('oc.default.usermessage'));
//dd($results);
return view('themes.metronic.ocback.backstage.purchasing.usermessage')->with($results);
}
}
<file_sep>/app/Http/Controllers/Card/Index/SupplierMeauController.php
<?php
namespace App\Http\Controllers\Card\Index;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class SupplierMeauController extends Controller
{
public function index(){
return view('themes.metronic.ocback.backstage.supplier.supplier_meau');
}
}
<file_sep>/app/Services/OcService/AttachmentService.php
<?php
namespace App\Services\OcService;
use App\Services\Service;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use Exception;
use DB;
use Storage;
class AttachmentService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
protected $disk = 'local';
/**
* 上传附件
* @return [type] [description]
*/
public function upload()
{
try {
$exception = DB::transaction(function() {
/*判断是否有文件*/
if ( !request()->hasFile('file') ) {
throw new Exception(trans('code/attachment.upload.selectfile'), 2);
}
$file = request()->file('file');
/*上传文件路径*/
$path = $file->store('attachments', $this->disk);
/*上传者信息*/
$user = getUser();
$userId = $user->id;
$userName = $user->name;
/*文件信息*/
$name = $file->hashName();
$data = [
'name' => $name,
'origin_name' => $file->getClientOriginalName(),
'file_size' => $file->getClientSize(),
'path' => $path,
'file_ext' => $file->getClientOriginalExtension(),
'ext_info' => '',
'user_id' => $userId,
'user_name' => $userName,
];
/*新增附件信息*/
if( $attachment = $this->attachmentRepo->create($data) ) {
$this->results = array_merge($this->results, [
'data' => [
'id_hash' => $attachment->id_hash,
'name' => str_replace('.' . $attachment->file_ext, '', $attachment->origin_name),
'file_ext' => $attachment->file_ext,
'file_size' => calcFileSize($attachment->file_size),
'url' => route('admin.attachment.show', [$attachment->id_hash]),
],
]);
} else {
throw new Exception(trans('code/attachment.upload.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/attachment.upload.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/attachment.upload.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 获取上传文件访问路径
* @return [type] [description]
*/
public function show($id)
{
try {
/*解密*/
$id = $this->attachmentRepo->decodeId($id);
/*获取附件信息*/
$attachment = $this->attachmentRepo->find($id);
/*验证文件是否存在*/
if( Storage::disk($this->disk)->exists($attachment->path) ) {
/*获取文件*/
return Storage::disk($this->disk)->path($attachment->path);
} else {
abort(404, '文件不存在');
}
} catch (Exception $e) {
abort(404, '文件不存在');
}
}
}<file_sep>/routes/oc_routes/purchasing/route.php
<?php
$router->group(['namespace'=>'Card\Purchasing'], function($router) {
//采购商
require(__DIR__.'/purchasing.php');
});
//$router->group(['namespace' => 'Back\System'], function($router) {
// /*用户*/
// require(__DIR__ . '/user.php');
// /*角色*/
// require(__DIR__ . '/role.php');
// /*权限*/
// require(__DIR__ . '/permission.php');
// /*菜单*/
// require(__DIR__ . '/menu.php');
// /*字典管理*/
// require(__DIR__ . '/dictionaries.php');
// /*工作流*/
// require(__DIR__ . '/workflow.php');
// /*公司*/
// require(__DIR__ . '/company.php');
//
// /*邮箱管理*/
// require(__DIR__.'/mail.php');
// #报告规则
// require(__DIR__ . '/regulations.php');
// #通用分类
// require(__DIR__ . '/category.php');
//
//});<file_sep>/app/Repositories/Interfaces/ReportTaskRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface ReportTaskRepository.
*
* @package namespace App\Repositories\Interfaces;
*/
interface ReportTaskRepository extends RepositoryInterface
{
//
}
<file_sep>/app/helpers/redundance.php
<?php
/**
* 获取redundance的配置
*/
if ( !function_exists('getRedundanceConfig') )
{
function getRedundanceConfig($key)
{
return config('back.redundance.' . $key);
}
}
/**
* 获取报告冗余字段
*/
if (!function_exists('getReportRedundanceField')) {
function getReportRedundanceField($key = '')
{
$key = $key ? '.' . $key : '';
return getRedundanceConfig('report' . $key);
}
}
/**
* 获取报告任务冗余字段
*/
if (!function_exists('getReportTaskRedundanceField')) {
function getReportTaskRedundanceField($key = '')
{
$key = $key ? '.' . $key : '';
return getRedundanceConfig('report_task' . $key);
}
}
/**
* 获取报告详情冗余字段
*/
if (!function_exists('getReportValueRedundanceField')) {
function getReportValueRedundanceField($key = '')
{
$key = $key ? '.' . $key : '';
return getRedundanceConfig('report_value' . $key);
}
}<file_sep>/routes/routes/attachment.php
<?php
$router->group(['namespace' => 'Back'], function($router) {
$router->group(['prefix' => "attachment", 'as' => 'attachment.'], function($router) {
/*附件上传*/
$router->post('upload', [
'as' => 'upload',
'uses' => 'AttachmentController@upload',
]);
/*查看附件*/
$router->get('show/{id}', [
'as' => 'show',
'uses' => 'AttachmentController@show',
]);
});
});<file_sep>/resources/lang/en/code/drug.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/16
* Time: 上午11:48
*/
return [
'store' => [
'fail' => '药品创建失败',
'success' => '药品创建成功',
],
'update' => [
'fail' => '药品修改失败',
'success' => '药品修改成功',
],
'destroy' => [
'fail' => '药品删除失败',
'success' => '药品删除成功',
],
'sort' => [
'fail' => '药品排序失败',
'success' => '药品排序成功',
],
];<file_sep>/app/Repositories/Interfaces/DictionariesRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface DictionariesRepository
* @package namespace App\Repositories\Interfaces;
*/
interface DictionariesRepository extends RepositoryInterface
{
}
<file_sep>/app/Subscribes/ReportTaskEventSubscribe.php
<?php
namespace App\Subscribes;
use App\Repositories\Interfaces\UserRepository;
use App\Repositories\Interfaces\ReportTaskRepository;
use App\Traits\Services\Report\TaskTrait;
use Carbon\Carbon;
class ReportTaskEventSubscribe
{
use TaskTrait;
/**
* 设置报告任务的执行者
* @param [type] $event [description]
* @return [type] [description]
*/
public function onReassign($event)
{
$taskUserId = $event->taskUserId;
$reportTask = $event->reportTask;
/*获取报告任务执行者信息*/
$taskUser = app(UserRepository::class)->find($taskUserId);
/*保存*/
$this->setReportTaskUserInReportTask($taskUser, $reportTask);
}
/**
* 设置任务执行者信息
* @param [type] $taskUserId [description]
* @param [type] $reportTask [description]
*/
private function setReportTaskUserInReportTask($taskUser, $reportTask)
{
/*保存*/
$reportTask->task_user_id = $taskUser->id;
$reportTask->task_user_name = $taskUser->name;
$reportTask->save();
}
/**
* 设置组织结构角色
* @param [type] $taskUserId [description]
* @param [type] $reportTask [description]
*/
private function initOrganizeRoleInReportTask($reportTask)
{
/*保存*/
$organizeRoleId = getRoleOrganizeValue('data_insert');
$organizes = getRoleOrganize();
$reportTask->organize_role_id = $organizeRoleId;
$reportTask->organize_role_name = $organizes[$organizeRoleId];
$reportTask->save();
}
/**
* 原始资料分发给录入员
* @param [type] $event [description]
* @return [type] [description]
*/
public function onAssign($event)
{
/*任务处理人*/
$taskUserId = $event->taskUserId;
/*原始资料*/
$source = $event->source;
/*报告规则*/
$regulation = $event->regulation;
$reportTaskRepo = app(ReportTaskRepository::class);
/*创建报告任务*/
$reportTaskData = [
'report_first_received_date' => $source->accept_report_date,
'assigned_at' => new \Carbon\Carbon(),
'source_id' => $source->id,
'regulation_id' => $regulation->id,
];
$reportTask = $this->createReportTask($reportTaskData);
/*获取报告任务执行者信息*/
$taskUser = app(UserRepository::class)->find($taskUserId);
/*设置报告任务的其他数据*/
$this->setReportTaskData($reportTask, $taskUser, $regulation);
}
/**
* 创建报告任务
* @param [type] $data [description]
* @return [type] [description]
*/
private function createReportTask($data)
{
return app(ReportTaskRepository::class)->create($data);
}
/**
* 创建报告任务
* @param [type] $event [description]
* @return [type] [description]
*/
public function onCreate($event)
{
$report = $event->report;
$companyId = $report->companyId;
$regulation = $event->regulation;
$taskUserId = $event->taskUserId;
$data = [
'company_id' => $companyId,
'report_id' => $report->id,
'report_identify' => $report->report_identifier,
'report_first_received_date' => $report->report_first_received_date,
'assigned_at' => new \Carbon\Carbon(),
'drug_name' => $report->drug_name,
'first_drug_name' => $report->first_drug_name,
'event_term' => $report->event_term,
'first_event_term' => $report->first_event_term,
'seriousness' => $report->seriousness,
'report_cate' => getCommonCheckValue(true),
'received_from_id' => $report->received_from_id,
'status' => getCommonCheckValue(false),
'regulation_id' => $regulation->id,
];
/*创建报告任务*/
$reportTask = $this->createReportTask($data);
/*获取报告任务执行者信息*/
$taskUser = app(UserRepository::class)->find($taskUserId);
/*设置报告任务的其他数据*/
$this->setReportTaskData($reportTask, $taskUser, $regulation);
return $reportTask;
}
/**
* 修改报告任务
* @param [type] $event [description]
* @return [type] [description]
*/
public function onUpdate($event)
{
$report = $event->report;
$companyId = $report->companyId;
$regulation = $event->regulation;
$sourceId = $event->sourceId;
$data = [
'report_id' => $report->id,
'report_identify' => $report->report_identifier,
'report_first_receive_date' => $report->report_first_receive_date,
'drug_name' => $report->drug_name,
'first_drug_name' => $report->first_drug_name,
'event_term' => $report->event_term,
'first_event_term' => $report->first_event_term,
'seriousness' => $report->seriousness,
'report_cate' => getCommonCheckValue(true),
'received_from_id' => $report->received_from_id,
'status' => getCommonCheckValue(false),
'regulation_id' => $regulation->id,
];
$reportTask = $this->updateTaskData($data, $event->sourceId);
/*设置报告规则的条件*/
$where = [
'id' => $reportTask->id,
];
$this->setRegulationBak($regulation, $where);
/*设置任务和报告倒计时*/
$organizeMaps = array_flip(getRoleOrganizeMap());
$this->setCountdown($reportTask, $organizeMaps);
}
/**
* 修改报告任务数据
* @param [type] $event [description]
* @return [type] [description]
*/
public function onUpdateData($event)
{
$report = $event->report;
$data = [
'report_id' => $report->id,
'report_identify' => $report->report_identifier,
'report_first_receive_date' => $report->report_first_receive_date,
'drug_name' => $report->drug_name,
'first_drug_name' => $report->first_drug_name,
'event_term' => $report->event_term,
'first_event_term' => $report->first_event_term,
'seriousness' => $report->seriousness,
'report_cate' => getCommonCheckValue(true),
'received_from_id' => $report->received_from_id,
'status' => getCommonCheckValue(false),
];
$this->updateTaskData($data, $event->sourceId);
}
private function updateTaskData($data, $sourceId)
{
/*查找报告任务*/
$reportTask = app(ReportTaskRepository::class)->findByField('source_id', $sourceId)->first();
/*修改报告任务*/
return app(ReportTaskRepository::class)->update($data, $reportTask->id);
}
/**
* 删除报告任务
* @param [type] $event [description]
* @return [type] [description]
*/
public function onDelete($event)
{
$sourceId = $event->sourceId;
$where = [
'source_id' => $sourceId,
];
app(ReportTaskRepository::class)->deleteWhere($where);
}
/**
* 复制报告任务
* @param [type] $event [description]
* @return [type] [description]
*/
public function onCopy($event)
{
/*报告id*/
$reportId = $event->reportId;
/*报告任务执行者*/
$taskUserId = $event->taskUserId;
/*报告规则*/
$regulation = $event->regulation;
/*报告首次接受日期*/
$reportFirstReceivedData = $event->reportFirstReceivedData;
/*新报告*/
$newReport = $event->newReport;
$reportTaskClone = app(ReportTaskRepository::class)->findByField('report_id', $reportId)->first()->replicate([]);
$data = $reportTaskClone->toArray();
/*报告id*/
$data['report_id'] = $newReport->id;
/*报告编号*/
$data['report_identify'] = $newReport->report_identifier;
/*设置任务分发时间*/
$data['assigned_at'] = (new Carbon())->now();
/*设置任务获悉时间*/
$data['report_first_received_date'] = $reportFirstReceivedData;
/*首次报告还是随访报告*/
$data['report_cate'] = getCommonCheckValue(false);
/*创建报告*/
$reportTask = $this->createReportTask($data);
/*获取报告任务执行者信息*/
$taskUser = app(UserRepository::class)->find($taskUserId);
/*设置报告任务的其他数据*/
$this->setReportTaskData($reportTask, $taskUser, $regulation);
}
/**
* 设置报告任务的其他数据
* @param [type] $reportTask [description]
* @param [type] $taskUser [description]
* @param [type] $regulation [description]
*/
private function setReportTaskData($reportTask, $taskUser, $regulation)
{
/*设置报告任务的处理者*/
$this->setReportTaskUserInReportTask($taskUser, $reportTask);
/*设置报告任务的组织结构*/
$this->initOrganizeRoleInReportTask($reportTask);
/*设置报告规则的条件*/
$where = [
'id' => $reportTask->id,
];
$this->setRegulationBak($regulation, $where);
/*设置任务和报告倒计时*/
$organizeMaps = array_flip(getRoleOrganizeMap());
$this->setCountdown($reportTask, $organizeMaps);
}
public function subscribe($events)
{
/*设置报告任务的执行者*/
$events->listen(
'App\Events\Report\Task\Reassign',
'App\Subscribes\ReportTaskEventSubscribe@onReassign'
);
/*原始资料分发给录入员*/
$events->listen(
'App\Events\Report\Task\Assign',
'App\Subscribes\ReportTaskEventSubscribe@onAssign'
);
/*创建报告任务*/
$events->listen(
'App\Events\Report\Task\Create',
'App\Subscribes\ReportTaskEventSubscribe@onCreate'
);
/*修改报告任务*/
$events->listen(
'App\Events\Report\Task\Update',
'App\Subscribes\ReportTaskEventSubscribe@onUpdate'
);
/*修改报告任务数据*/
$events->listen(
'App\Events\Report\Task\UpdateData',
'App\Subscribes\ReportTaskEventSubscribe@onUpdateData'
);
/*删除报告任务*/
$events->listen(
'App\Events\Report\Task\Delete',
'App\Subscribes\ReportTaskEventSubscribe@onDelete'
);
/*复制报告任务*/
$events->listen(
'App\Events\Report\Task\Copy',
'App\Subscribes\ReportTaskEventSubscribe@onCopy'
);
}
}
<file_sep>/app/Http/Controllers/Card/Supplier/SupplierListController.php
<?php
namespace App\Http\Controllers\Card\Supplier;
use App\Traits\ControllerTrait;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\OcService\SupplierListService as Service;
class SupplierListController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'ocback.backstage.supplier';
protected $routePrefix = 'admin.logistics';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* 订单列表
* @return [type] [description]
*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.supplierlist'))->with($results);
}
}
/**
* 信息管理
* @return [type] [description]
*/
public function show()
{
$results = $this->service->showUserInfo();
return response()->json($results);
}
/**
* 信息修改
* @return [type] [description]
*/
public function store($id)
{
$results = $this->service->store($id);
return response()->json($results);
}
/**
* 卡密供货页面
* @return [type] [description]
*/
public function cardencry()
{
$results = $this->service->cardIndex();
return view(getThemeTemplate($this->folder.'.suppliercamilo'))->with($results);
}
/**
* 卡密添加
* @return [type] [description]
*/
public function create()
{
$results = $this->service->cardPassEncryption();
return response()->json($results);
}
}
<file_sep>/app/Repositories/Models/RecursiveRelation.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
class RecursiveRelation extends Model implements Transformable
{
use TransformableTrait;
protected $fillable = [];
public function recursive()
{
return $this->morphTo();
}
}
<file_sep>/app/Http/Controllers/Back/Home/Registered/LoginController.php
<?php
namespace App\Http\Controllers\Back\Home\Registered;
use Illuminate\Http\Request;
use App\Traits\EncryptTrait;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\LoginService as Service;
class LoginController extends Controller{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'ocback.user';
/*路由*/
protected $routePrefix = 'admin.registered';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/*展示注册页面*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
/*注册用户*/
public function login()
{
$results = $this->service->create();
return response()->json($results);
}
}<file_sep>/app/Repositories/Criterias/FilterByFieldCriteria.php
<?php
namespace App\Repositories\Criterias;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Class FilterCompanyIdCriteria
* @package namespace App\Repositories\Criterias;
*/
class FilterByFieldCriteria implements CriteriaInterface
{
protected $key;
protected $value;
public function __construct($key, $value)
{
$this->key = $key;
$this->value = $value;
}
/**
* Apply criteria in query repository
*
* @param $model
* @param RepositoryInterface $repository
*
* @return mixed
*/
public function apply($model, RepositoryInterface $repository)
{
return $model->where($this->key, $this->value);
}
}
<file_sep>/app/Services/LoginService.php
<?php
namespace App\Services;
use App\Services\Service as BasicService;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DataTables;
use Exception;
use DB;
class LoginService extends BasicService
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function datatables()
{
//页面信息
dd(123);
}
public function index()
{
//页面信息
}
/*注册*/
public function create()
{
try{
$exception = DB::transaction(function() {
if( $info = $this->ocloginRepo->create(request()->all())){
} else {
throw new Exception(trans('code/login.create.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/login.create.success'),
]);
});
} catch(Exception $e){
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/login.create.fail')),
]);
}
}
/*登录*/
}<file_sep>/resources/lang/en/field/workflownode.php
<?php
return [
'name' => [
'label' => '流程名称',
'name' => 'name',
'placeholder' => '请输入流程名称',
'rules' => [
'required' => '流程名称不能为空',
]
],
'en_name' => [
'label' => '流程名称(英文)',
'name' => 'en_name',
'placeholder' => '请输入流程名称(英文)',
'rules' => [
'required' => '流程名称(英文)不能为空',
]
],
'is_message_notice' => [
'label' => '是否启用短信通知',
'name' => 'is_message_notice',
],
'is_email_notice' => [
'label' => '是否启用Email通知',
'name' => 'is_email_notice',
],
'organize_role_id' => [
'label' => '组织结构角色',
'name' => 'organize_role_id',
'rules' => [
'required' => '组织结构角色不能为空',
]
],
'role_id' => [
'label' => '角色',
'name' => 'role_id',
'rules' => [
'required' => '角色不能为空',
]
],
'rule' => [
'label' => '规则',
'name' => 'rule',
'placeholder' => '请输入规则',
],
'description' => [
'label' => '描述',
'name' => 'description',
'placeholder' => '请输入描述',
],
];<file_sep>/app/Repositories/Models/Mail.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
class Mail extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'mail';
protected $fillable = ['service_type','mail_account','mail_password','company_id','server','port','ssl_crypt','status'];
}
<file_sep>/app/Events/Report/Value/SetRedundanceData.php
<?php
namespace App\Events\Report\Value;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class SetRedundanceData
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
// 单位id
public $companyId;
// 报告id
public $reportId;
// 数据
public $data;
public function __construct($companyId, $reportId, $data)
{
$this->companyId = $companyId;
$this->reportId = $reportId;
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
<file_sep>/app/Http/Controllers/Card/Supplier/SupplierCamiloController.php
<?php
namespace App\Http\Controllers\Card\Supplier;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\OcService\SupplierCamiloService as Service;
class SupplierCamiloController extends Controller
{
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function get_platform(){
return $this->service->platform_search(array('status'=>'0'));
}
public function index(){
$results['arr'] = $this->get_platform();
return view('themes.metronic.ocback.backstage.supplier.suppliercamilo')->with($results);
}
public function search(){
$results=$this->service->search();
return response()->json($results);
}
}
<file_sep>/routes/routes/systems/mail.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'mail', 'as' => 'mail.'], function($router){
/*新增邮箱*/
$router->post('create',[
'uses'=>'MailController@create',
'as'=>'create.',
]);
});
$router->resource('mail', 'MailController');
});<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/*
* ============ API ============
* 周文
* https://documenter.getpostman.com/view/159564/pvhsky/7LuaenB
*
* 刘通
* https://documenter.getpostman.com/view/3528973/pv-/7TKgsPx
*
* 吕新新
* https://documenter.getpostman.com/view/3537275/medsci-pv-/7TRdqGn
*
* 原型
* https://qtx480.axshare.com/
* ============ END ============
*/
/*网站中间键*/
$router->group(['middleware' => "web"], function($router) {
/*设置语言*/
$router->get('language/{language}', [
'uses' => "LanguageController@set",
'as' => 'language'
]);
Auth::routes();
$router->group(['middleware' => ['auth']], function ($router) {
/*默认首页*/
$router->get('/',[
'uses' => 'Card\DashController@index',
'as' => 'index',
]);
$router->get('home',[
'uses' => 'Card\DashController@index',
'as' => 'index',
])->name('home');
$router->group(['prefix' => 'admin', 'as' => 'admin.',], function ($router) {
/*默认首页*/
require(__DIR__ . '/oc_routes/dash.php');
/*后台首页*/
require(__DIR__ . '/oc_routes/backstage/route.php');
/*采购商*/
require(__DIR__ . '/oc_routes/backstage.php');
/*文件上传*/
require(__DIR__ . '/oc_routes/attachment.php');
});
});
});
<file_sep>/app/Http/Controllers/Card/Purchasing/DirectlyRechargeController.php
<?php
namespace App\Http\Controllers\Card\Purchasing;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use Illuminate\Validation\Rule;
use App\Services\OcService\DirectlyRechargeService as Service;
class DirectlyRechargeController extends Controller
{
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index(){
$results=$this->service->get_config_blade(config('oc.default.directlyrecharge'));
//dd($results);
return view('themes.metronic.ocback.backstage.purchasing.directlyrecharge')->with($results);
}
}
<file_sep>/resources/lang/en/field/menu.php
<?php
return [
'name' => [
'label' => '菜单名称',
'name' => 'name',
'placeholder' => '请输入菜单名称',
'rules' => [
'required' => '菜单名称不能为空',
]
],
'route' => [
'label' => '菜单路由',
'name' => 'route',
'placeholder' => '请输入菜单路由',
'rules' => [
'required' => '菜单路由不能为空',
]
],
'icon' => [
'label' => '菜单图标',
'name' => 'icon',
'placeholder' => '请输入菜单图标',
'rules' => [
'required' => '菜单图标不能为空',
]
],
'permission' => [
'label' => '菜单权限',
'name' => 'permission',
'placeholder' => '请输入菜单权限',
'rules' => [
'required' => '菜单权限不能为空',
]
],
'description' => [
'label' => '菜单描述',
'name' => 'description',
'placeholder' => '请输入菜单描述',
'rules' => [
'required' => '菜单描述不能为空',
]
]
];<file_sep>/resources/lang/en/code/global.php
<?php
return [
'param' => [
'loss' => '参数丢失'
],
'model_not_found' => '数据不存在',
'encrypt_fail' => '数据不存在',
'HY000' => "数据库设置值异常",
];<file_sep>/app/Http/Controllers/Back/Home/Management/PurchaseController.php
<?php
namespace App\Http\Controllers\Back\Home\Management;
//use App\Events\Questioning\questioning;
use Illuminate\Http\Request;
use App\Traits\EncryptTrait;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\PurchaseService as Service;
Class PurchaseController extends Controller{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back..card';
/*路由*/
protected $routePrefix = 'admin.managements';
protected $encryptConnection = 'management';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
$this->setEncryptConnection($this->encryptConnection);
}
/*卡密列表*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
}<file_sep>/app/Http/Controllers/Card/Purchasing/CamiloRechargeController.php
<?php
namespace App\Http\Controllers\Card\Purchasing;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use Illuminate\Validation\Rule;
use App\Services\OcService\CamiloRechargeService as Service;
class CamiloRechargeController extends Controller
{
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index(){
$result['goods_type'] = $this->service->search(array('status'=>'0'));
return view('themes.metronic.ocback.backstage.purchasing.camilorecharge')->with($result);
}
}
<file_sep>/config/laratrust_seeder.php
<?php
return [
'role_structure' => [
'superadministrator' => [
'system' => 'm',
'user' => 'c,r,u,d,m',
'role' => 'c,r,u,d,m',
'permission' => 'c,r,u,d,m',
'menu' => 'c,r,u,d,s,m',
],
'admin' => [
'system' => 'm',
'user' => 'c,r,u,d,m',
'role' => 'c,r,u,d,m',
'permission' => 'c,r,u,d,m',
'menu' => 'c,r,u,d,s,m',
],
'user' => [
'system' => 'm',
'user' => 'c,r,u,d,m',
'role' => 'c,r,u,d,m',
'permission' => 'c,r,u,d,m',
'menu' => 'c,r,u,d,s,m',
],
],
'permissions_map' => [
'c' => 'create',
'r' => 'read',
'u' => 'update',
'd' => 'delete',
's' => 'sort',
'm' => 'manage',
]
];
<file_sep>/routes/oc_routes/backstage/route.php
<?php
$router->group(['namespace'=>'Card\Index'], function($router) {
/*采购商首页*/
require(__DIR__.'/p_index.php');
/*供应商首页*/
require(__DIR__.'/s_index.php');
});<file_sep>/app/Repositories/Models/Supplier.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
/**
* Class Supplier.
*
* @package namespace App\Repositories\Models;
*/
class Supplier extends Model implements Transformable
{
use TransformableTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $tables = 'order';
protected $fillable = ['name_of_card_supply','supply_status','denomination','order_type','supply_time','order_time','order_number','discount','pin_denomination_card','content','user_id','order_status'];
}
<file_sep>/app/Http/Controllers/Back/System/PermissionController.php
<?php
namespace App\Http\Controllers\Back\System;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\PermissionService as Service;
use Illuminate\Validation\Rule;
use App\Traits\EncryptTrait;
class PermissionController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back.system.permission';
protected $routePrefix = 'admin.permission';
protected $encryptConnection = 'permission';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
$this->setEncryptConnection($this->encryptConnection);
}
/**
* 角色列表
* @return [type] [description]
*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
/**
* 保存规则
* @return [type] [description]
*/
private function storeRules()
{
return [
'name' => [
'required',
Rule::unique('permissions'),
],
'display_name' => 'required',
'description' => 'required',
];
}
/**
* 修改规则
* @return [type] [description]
*/
private function updateRules()
{
return [
'name' => [
'required',
Rule::unique('permissions')->ignore($this->decodeId(getRouteParam('permission')), 'id'),
],
'display_name' => 'required',
'description' => 'required',
];
}
private function messages()
{
return [
'name.required' => '权限名称不能为空',
'name.unique' => '权限名称已经存在',
'display_name.required' => '权限显示名称不能为空',
'description.required' => '权限描述不能为空',
];
}
}
<file_sep>/app/Repositories/Models/Logistics.php
<?php
namespace App\Repositories\Models;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
/**
* Class Logistics.
*
* @package namespace App\Repositories\Models;
*/
class Logistics extends Model implements Transformable
{
use TransformableTrait,ModelTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'company_id',
'report_identifier',
'waybill_number',
'department',
'reported_way',
'logistics_info',
'reported_date',
'remark',
'logistics_status',
'status',
];
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('regulation', $this->id);
}
public function ScopeStatus(Builder $builder, $status, $not_in = false)
{
if (is_array($status)) {
if ($not_in) {
return $builder->whereNotIn('status', $status);
}
return $builder->whereIn('status', $status);
} else {
if ($not_in) {
return $builder->where('status', '<>', $status);
}
return $builder->where('status', $status);
}
}
public function ScopeCompanyId(Builder $builder,$company_id){
return $builder->where('company_id',$company_id);
}
public function ScopeReportIdentifier(Builder $builder,$report_identifier){
return $builder->where('report_identifier',$report_identifier);
}
}
<file_sep>/app/Http/Controllers/Card/Supplier/SupplierDirectlyController.php
<?php
namespace App\Http\Controllers\Card\Supplier;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\OcService\SupplierDirectlyService as Service;
class SupplierDirectlyController extends Controller
{
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index(){
$results=$this->service->get_config_blade(config('oc.supplier.supplierdirectly'));
$results['data'] = '';
return view('themes.metronic.ocback.backstage.supplier.supplierdirectly')->with($results);
}
public function search(){
$results=$this->service->search();
return response()->json($results);
}
}
<file_sep>/app/helpers/drug.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/16
* Time: 下午2:26
*/
#获取药品分类
if(!function_exists('getDrugClass'))
{
function getDrugClass(){
#TODO::从字典里读取
return [];
}
}
#是否是进口或国产
if(!function_exists('drugImport'))
{
function drugImport(){
#TODO::从字典里读取
return [];
}
}
#剂型
if(!function_exists('formulation'))
{
function formulation(){
#TODO::从字典里读取
return [];
}
}
#给药途径
if(!function_exists('medicationWay'))
{
function medicationWay(){
#TODO::从字典里读取
return [];
}
}
<file_sep>/app/Http/Controllers/Card/Purchasing/CamiloController.php
<?php
namespace App\Http\Controllers\Card\Purchasing;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use Illuminate\Validation\Rule;
use App\Services\OcService\CamiloService as Service;
class CamiloController extends Controller
{
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index(){
$results=$this->service->get_config_blade(config('oc.default.camilo'));
//dd($results);
return view('themes.metronic.ocback.backstage.purchasing.camilo')->with($results);
}
}
<file_sep>/app/Traits/RepositoryTrait.php
<?php
namespace App\Traits;
use Hashids;
Trait RepositoryTrait
{
/**
* 按照条件修改数据
* @param [type] $data [description]
* @param array $where [description]
* @return [type] [description]
*/
public function updateWhere($data, array $where)
{
$this->applyScope();
$temporarySkipPresenter = $this->skipPresenter;
$this->skipPresenter(true);
$this->applyConditions($where);
$updated = $this->model->update($data);
event(new \Prettus\Repository\Events\RepositoryEntityUpdated($this, $this->model->getModel()));
$this->skipPresenter($temporarySkipPresenter);
$this->resetModel();
return $updated;
}
/**
* Delete multiple entities by given criteria.
*
* @param array $where
*
* @return int
*/
public function forceDeleteWhere(array $where)
{
$this->applyScope();
$temporarySkipPresenter = $this->skipPresenter;
$this->skipPresenter(true);
$this->applyConditions($where);
$deleted = $this->model->forceDelete();
event(new \Prettus\Repository\Events\RepositoryEntityDeleted($this, $this->model->getModel()));
$this->skipPresenter($temporarySkipPresenter);
$this->resetModel();
return $deleted;
}
}<file_sep>/app/Http/Controllers/Back/DrugLibrary/DrugController.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/16
* Time: 上午11:06
*/
namespace App\Http\Controllers\Back\DrugLibrary;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\DrugLibraryService as Service;
class DrugController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.drug-library';
protected $routePrefix = 'admin.drug';
protected $routeHighLightPrefix = 'admin.predrug';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
private function storeRules(){
$type = \request('type');
#上市前
if ($type == 1) {
return [
'common_zh_name' => 'required',
'common_en_name' => 'required',
'common_standard_name' => 'required',
'active_ingredients' => 'required',
'drug_class' => 'required',
'manufacturer' => 'required',
'formulation' => 'required',
];
}
#上市后
if ($type == 2) {
# TODO:: 原型上没有具体标,暂不处理
return [
'approval_number' => 'required',
'product_en_name' => 'required',
'product_zh_name' => 'required',
'common_zh_name' => 'required',
'common_en_name' => 'required',
'common_standard_name' => 'required',
'active_ingredients' => 'required',
'drug_class' => 'required',
'manufacturer' => 'required',
'formulation' => 'required',
];
}
}
private function updateRules()
{
$type = \request('type');
#上市前
if ($type == 1) {
return [
'common_zh_name' => 'required',
'common_en_name' => 'required',
'common_standard_name' => 'required',
'active_ingredients' => 'required',
'drug_class' => 'required',
'manufacturer' => 'required',
'formulation' => 'required',
];
}
#上市后
if ($type == 2) {
# TODO:: 原型上没有具体标,暂不处理
return [
'approval_number' => 'required',
'product_en_name' => 'required',
'product_zh_name' => 'required',
'common_zh_name' => 'required',
'common_en_name' => 'required',
'common_standard_name' => 'required',
'active_ingredients' => 'required',
'drug_class' => 'required',
'manufacturer' => 'required',
'formulation' => 'required',
];
}
}
private function messages()
{
return [
'common_zh_name.required' => '通用中文名称不能为空',
'common_en_name.required' => '通用英文名称不能为空',
'common_standard_name.required' => '标准通用名称不能为空',
'active_ingredients.required' => '活性成份不能为空',
'drug_class.required' => '药品分类不能为空',
'manufacturer.required' => '生产厂家不能为空',
'formulation.required' => '剂型不能为空',
];
}
}<file_sep>/app/Http/Controllers/Back/Report/TaskController.php
<?php
namespace App\Http\Controllers\Back\Report;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use App\Services\Report\TaskService as Service;
class TaskController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back.report.task';
protected $routePrefix = 'admin.report.task';
protected $encryptConnection = 'reporttask';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* 用户列表
* @return [type] [description]
*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
/**
* 报告任务重新分发
* @param [type] $id [description]
* @return [type] [description]
*/
public function reassignCreate($id)
{
$results = $this->service->reassignCreate($id);
return view(getThemeTemplate($this->folder . '.reassign'))->with($results);
}
}
<file_sep>/app/Http/Controllers/Back/Report/SourcesController.php
<?php
namespace App\Http\Controllers\Back\Report;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\Report\SourceService as Service;
/**
* Class SourcesController.
*
* @package namespace App\Http\Controllers;
*/
class SourcesController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.report.source';
protected $routePrefix = 'admin.source';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index()
{
if (request()->ajax()) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
public function recycling($id){
if (request()->ajax()) {
return $this->service->recycling($id);
}
else
{
abort(404);
}
}
public function issue($id){
if(request()->method() == 'POST'){
if (request()->ajax()) {
return $this->service->issue($id);
}
abort(404);
}
else
{
$results = $this->service->issueCreate($id);
return view(getThemeTemplate($this->folder . '.issue'))->with($results);
}
}
public function download($id){
if (request()->ajax()) {
return $this->service->download($id);
}
else
{
abort(404);
}
}
}
<file_sep>/routes/routes/management/purchase.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'purchase', 'as' => 'purchase.'], function ($router) {
/*卡密采购管理*/
$router->get('index', [
'uses' => 'ManagementController@index',
'as' => 'index'
]);
});
});<file_sep>/resources/lang/en/code/permission.php
<?php
return [
'store' => [
'fail' => '权限创建失败',
'success' => '权限创建成功',
],
'update' => [
'fail' => '权限修改失败',
'success' => '权限修改成功',
],
'destroy' => [
'fail' => '权限删除失败',
'success' => '权限删除成功',
],
];<file_sep>/app/Repositories/Criterias/SearchLikeByFieldCriteria.php
<?php
namespace App\Repositories\Criterias;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Class SearchLikeByFieldCriteria
* @package namespace App\Repositories\Criterias;
*/
class SearchLikeByFieldCriteria implements CriteriaInterface
{
protected $field;
protected $value;
protected $way;
public function __construct($field, $value, $way = 'left')
{
$this->field = $field;
$this->value = $value;
$this->way = $way;
}
/**
* Apply criteria in query repository
*
* @param $model
* @param RepositoryInterface $repository
*
* @return mixed
*/
public function apply($model, RepositoryInterface $repository)
{
$likeValue = $this->value;
switch($this->way) {
case 'left' :
$likeValue = '%' . $likeValue;
break;
case 'right' :
$likeValue = $likeValue . '%';
break;
case 'both' :
$likeValue = '%' . $likeValue . '%';
break;
}
return $model->where($this->field, 'like', $likeValue);
}
}
<file_sep>/resources/lang/en/code/report.php
<?php
return [
'value' => [
'save' => [
'fail' => "报告详情保存失败",
'success' => "报告详情保存成功",
'nopermission' => '没有保存权限',
],
],
/*报告任务*/
'task' => [
'reassign' => [
'store' => [
'fail' => "报告任务重新分发失败",
'success' => "报告任务重新分发成功",
],
],
'newversion' => [
'store' => [
'fail' => "新建版本失败",
'success' => "新建版本成功",
],
],
],
];<file_sep>/app/Listeners/Report/Value/SetReportMainDataListener.php
<?php
namespace App\Listeners\Report\Value;
use App\Events\Report\Value\SetReportMainData;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SetReportMainDataListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param SetReportMainData $event
* @return void
*/
public function handle(SetReportMainData $event)
{
//
}
}
<file_sep>/app/Subscribes/WorkflowNodeEventSubscribe.php
<?php
namespace App\Subscribes;
use App\Repositories\Interfaces\WorkflowNodeRepository;
class WorkflowNodeEventSubscribe
{
/**
* 设置工作流id
* @param [type] $event [description]
* @return [type] [description]
*/
public function onSetWorkflowId($event)
{
$workflowNode = $event->workflowNode;
$workflowId = $event->workflowId;
$workflowNode->workflow_id = $workflowId;
$workflowNode->save();
}
/**
* 工作流节点排序
* @param [type] $event [description]
* @return [type] [description]
*/
public function onSort($event)
{
$prevNodeId = $event->prevNodeId;
$curNode = $event->curNode;
$workflowId = $curNode->workflow_id;
$preNodeSort = 0;
if($prevNodeId) {
/*被插入的节点*/
$prevNode = app(WorkflowNodeRepository::class)->find($prevNodeId);
/*被插入节点的排序*/
$preNodeSort = $prevNode->sort;
}
/*自动递增被插入节点之后的sort,其值+1*/
app(WorkflowNodeRepository::class)->incrementLargerSort($workflowId, $preNodeSort);
/*设置当前节点为被插入点之后*/
$curNode->sort = $preNodeSort + 1;
$curNode->save();
// dd($curNode);
}
public function subscribe($events)
{
/*设置workflowId*/
$events->listen(
'App\Events\WorkflowNode\SetWorkflowId',
'App\Subscribes\WorkflowNodeEventSubscribe@onSetWorkflowId'
);
/*设置workflowId*/
$events->listen(
'App\Events\WorkflowNode\Sort',
'App\Subscribes\WorkflowNodeEventSubscribe@onSort'
);
}
}
<file_sep>/app/Subscribes/ReportValueEventSubscribe.php
<?php
namespace App\Subscribes;
use App\Repositories\Interfaces\ReportValuesRepository;
class ReportValueEventSubscribe
{
/*清除表格数据*/
public function onClearTableData($event)
{
$companyId = $event->companyId;
$reportId = $event->reportId;
$reportTabId = $event->reportTabId;
// app(ReportValuesRepository::class)->clearTableData($reportId, $reportTabId);
$where = [
'company_id' => $companyId,
'report_id' => $reportId,
'report_tab_id' => $reportTabId,
];
app(ReportValuesRepository::class)->forceDeleteWhere($where);
}
/**
* 创建报告详情的数据
* @param [type] $event [description]
* @return [type] [description]
*/
public function onCreate($event)
{
/*报告数据*/
$report = $event->report;
/*设置报告详情数据除了概览页面*/
$tabFields = getReportRedundanceField();
$this->setReportValueData($tabFields, $report);
/*设置报告详情概览界面*/
$reportValueFields = getReportValueRedundanceField();
$this->setReportValueData($reportValueFields, $report);
/*设置报告概览基本信息*/
$this->setInitReportValueIn($report, 'report_identify', $report->report_identifier);
$this->setInitReportValueIn($report, 'report_cate', $report->is_first_report);
$this->setInitReportValueIn($report, 'created_at', $report->created_at);
}
/*设置报告详情数据*/
private function setReportValueData($tabFields, $report)
{
/*获取报告的冗余字段*/
if( $tabFields ) {
/*遍历*/
foreach($tabFields as $tabIdentify => $tabField) {
$reportTabId = getReportTabValue($tabIdentify);
if( is_array($tabFields) ) {
/*药物信息*/
$drug = getReportTabValue('drug');
/*不良*/
$event = getReportTabValue('event');
/*基础信息*/
$basic = getReportTabValue('basic');
/*属性*/
$attributes = [
'company_id' => $report->company_id,
'report_id' => $report->id,
'report_tab_id' => $reportTabId,
'col' => 0,
'col_name' => '',
'is_table' => getCommonCheckValue(false),
'table_alias' => 0,
'table_row_id' => 0,
];
switch($tabIdentify) {
/*药物*/
case $drug :
$attributes = array_merge($attributes, [
'col' => 1,
'col_name' => $report->brand_name,
]);
break;
/*事件*/
case $event :
$attributes = array_merge($attributes, [
'col' => 1,
'col_name' => $report->event_term,
]);
break;
}
foreach($tabField as $field => $position) {
/*重置关于table的数据*/
$attributes = array_merge($attributes, [
'is_table' => getCommonCheckValue(false),
'table_alias' => 0,
'table_row_id' => 0,
]);
if( $position == 'table_first' ) {
$attributes = array_merge($attributes, [
'is_table' => getCommonCheckValue(true),
'table_alias' => 1,
'table_row_id' => 1,
]);
}
/*存在回写数据,并且数据存在*/
if( isset($report->{$field}) && $value = $report->{$field} ) {
$data = array_merge($attributes, [
'name' => $field,
'value' => $value,
]);
app(ReportValuesRepository::class)->create($data);
}
}
}
}
}
}
/**
* 设置报告详情初始化数据
* @param [type] $report [description]
* @param [type] $field [description]
* @param [type] $value [description]
*/
private function setInitReportValueIn($report, $field, $value)
{
$attributes = [
'company_id' => $report->company_id,
'report_id' => $report->id,
'report_tab_id' => getReportTabValue('overview'),
'col' => 0,
'col_name' => '',
'is_table' => getCommonCheckValue(false),
'table_alias' => 0,
'table_row_id' => 0,
'name' => $field,
];
$data = [
'value' => $value,
];
app(ReportValuesRepository::class)->updateOrCreate($attributes, $data);
}
/**
* 复制报告详情数据
* @param [type] $event [description]
* @return [type] [description]
*/
public function onCopy($event)
{
$reportId = $event->reportId;
$newReport = $event->newReport;
$reportValues = app(ReportValuesRepository::class)->findByField('report_id', $reportId);
if( $reportValues->isNotEmpty() ) {
foreach( $reportValues as $reportValue ) {
$data = $reportValue->replicate()->toArray();
$data['report_id'] = $newReport->id;
app(ReportValuesRepository::class)->create($data);
}
}
/*设置报告概览基本信息*/
$this->setInitReportValueIn($newReport, 'report_identify', $newReport->report_identifier);
}
public function subscribe($events)
{
/*清除报告详情中-table数据*/
$events->listen(
'App\Events\Report\Value\ClearTableData',
'App\Subscribes\ReportValueEventSubscribe@onClearTableData'
);
/*创建数据*/
$events->listen(
'App\Events\Report\Value\Create',
'App\Subscribes\ReportValueEventSubscribe@onCreate'
);
/*复制数据*/
$events->listen(
'App\Events\Report\Value\Copy',
'App\Subscribes\ReportValueEventSubscribe@onCopy'
);
}
}
<file_sep>/app/helpers/global.php
<?php
/**
* 获取global的配置
*/
if ( !function_exists('getGlobalConfig') )
{
function getGlobalConfig($key)
{
return config('back.global.' . $key);
}
}
/**
* 获取主题文件
*/
if( !function_exists('getThemeFolder')) {
function getThemeFolder()
{
return getGlobalConfig('theme.folder');
}
}
/**
* 获取主题名称
*/
if( !function_exists('getThemeName')) {
function getThemeName()
{
return getGlobalConfig('theme.name');
}
}
/**
* 获取主题
*/
if (!function_exists('getTheme')) {
function getTheme()
{
return getThemeFolder() . '.' . getThemeName();
}
}
if (!function_exists('getThemeTemplate')) {
function getThemeTemplate($template)
{
return getTheme() . '.' . $template;
}
}
/**
* 获取redis前缀
*/
if( !function_exists('getRedisPrefix')) {
function getRedisPrefix($key = '')
{
return getGlobalConfig('redis.prefix') . $key;
}
}
/**
* 获取cache前缀
*/
if( !function_exists('getCachePrefix')) {
function getCachePrefix($key = '')
{
return getGlobalConfig('cache.prefix') . $key;
}
}
/**
* 获取性别
*/
if( !function_exists('getSex') ) {
function getSex()
{
return getGlobalConfig('sex.value');
}
}
/**
* 获取通用的true false
*/
if( !function_exists('getCommonCheck') ) {
function getCommonCheck()
{
return getGlobalConfig('commoncheck.value');
}
}
/**
* 获取通用的验证的值
*/
if( !function_exists('getCommonCheckValue') ) {
function getCommonCheckValue($bool = true)
{
return $bool ? getGlobalConfig('commoncheck.map.true') : getGlobalConfig('commoncheck.map.false');
}
}
/**
* 获取通用验证显示的值
*/
if ( !function_exists('getCommonCheckShowValue') ) {
function getCommonCheckShowValue($value, $trueVale='是', $falseValue='否')
{
if ( getCommonCheckValue(true) == $value) {
return $trueVale;
} else {
return $falseValue;
}
}
}
/**
* 获取组织结构的值
*/
if ( !function_exists('getRoleOrganize') )
{
function getRoleOrganize()
{
return getGlobalConfig('role_organize.value');
}
}
if ( !function_exists('getRoleOrganizeMap') )
{
function getRoleOrganizeMap()
{
return getGlobalConfig('role_organize.map');
}
}
if ( !function_exists('getRoleOrganizeValue') )
{
function getRoleOrganizeValue($key)
{
return getGlobalConfig('role_organize.map.' . $key);
}
}
/**
* 获取菜单位置
*/
if ( !function_exists('getMenuPosition') )
{
function getMenuPosition()
{
return getGlobalConfig('menu_position.value');
}
}
if ( !function_exists('getMenuPositionValue') )
{
function getMenuPositionValue($key)
{
return getGlobalConfig('menu_position.map.' . $key);
}
}
/**
* 获取 报告详情 tab数据
*/
if ( !function_exists('getReportTab') )
{
function getReportTab($type = 'value')
{
return getGlobalConfig('report.tab.' . $type);
}
}
if ( !function_exists('getReportTabValue') )
{
function getReportTabValue($key)
{
return getGlobalConfig('report.tab.map.' . $key);
}
}
/**
* 报告规则 - 严重性
*/
if(!function_exists('severity'))
{
function severity()
{
return [];
}
}
/**
* 系统模块
*/
if(!function_exists('module'))
{
function module()
{
return [];
}
}
/**
* 原始资料-添加-文件类型
*/
if(!function_exists('get_file_class'))
{
function get_file_class()
{
return [];
}
}
/*字典*/
if(!function_exists('getDictionaries'))
{
function getDictionaries()
{
return [];
}
}
/**
* 原始资料-添加-文件来源
*/
if(!function_exists('get_file_source'))
{
function get_file_source()
{
return [];
}
}
/**
* 原始资料-添加-文件来源
*/
if(!function_exists('get_severity'))
{
function get_severity()
{
return [];
}
}
<file_sep>/routes/routes/drug-library/post-drug.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/16
* Time: 上午11:31
*/
$router->group([], function($router) {
$router->group(['prefix' => 'postdrug', 'as' => 'postdrug.'], function($router) {
/*菜单排序*/
$router->post('sort', [
'uses' => 'PostDrugController@sort',
'as' => "sort"
]);
//上市后
$router->get('index', [
'uses' => 'PostDrugController@postIndex',
'as' => "index"
]);
// 添加
$router->get('add',[
'uses' => 'PostDrugController@postCreate',
'as' => "add"
]);
// 修改
$router->get('{id}/edit', [
'uses' => 'PostDrugController@postEdit',
'as' => "edit"
]);
//删除
$router->delete('{id}/remove',[
'uses' => 'PostDrugController@remove',
'as' => "remove"
]);
});
});<file_sep>/resources/lang/en/field/drug.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/17
* Time: 下午2:54
*/
return [
'common_zh_name' => [
'label' => '通用名称(中文)',
'name' => 'common_zh_name',
'placeholder' => '请输入通用名称(中文)',
'rules' => [
'required' => '通用名称(中文)不能为空',
]
],
'common_en_name' => [
'label' => '通用名称(英文)',
'name' => 'common_en_name',
'placeholder' => '通用名称(英文)',
'rules' => [
'required' => '通用名称(英文)不能为空',
]
],
'common_standard_name' => [
'label' => '标准通用名称',
'name' => 'common_standard_name',
'placeholder' => '标准通用名称',
'rules' => [
'required' => '标准通用名称不能为空',
]
],
'active_ingredients' => [
'label' => '活性成份',
'name' => 'active_ingredients',
'placeholder' => '活性成份',
'rules' => [
'required' => '活性成份不能为空',
]
],
'drug_class' => [
'label' => '药品分类',
'name' => 'drug_class',
'placeholder' => '药品分类',
'rules' => [
'required' => '药品分类不能为空',
]
],
'manufacturer' => [
'label' => '生产厂家',
'name' => 'manufacturer',
'placeholder' => '生产厂家',
'rules' => [
'required' => '生产厂家不能为空',
]
],
];<file_sep>/resources/lang/en/field/user.php
<?php
return [
'name' => [
'label' => '账号',
'name' => 'name',
'placeholder' => '请输入账号',
'rules' => [
'required' => '账号不能为空',
]
],
'truename' => [
'label' => '真实姓名',
'name' => 'truename',
'placeholder' => '请输入真实姓名',
'rules' => [
'required' => '真实姓名不能为空',
]
],
'mobile' => [
'label' => '手机号',
'name' => 'mobile',
'placeholder' => '请输入手机号',
'rules' => [
'required' => '手机号不能为空',
]
],
'company' => [
'label' => '公司',
'name' => 'company',
'placeholder' => '请输入公司',
'rules' => [
'required' => '公司不能为空',
]
],
'is_check_email' => [
'label' => '是否验证邮箱',
'name' => 'is_check_email',
'placeholder' => '是否验证邮箱',
'rules' => [
'required' => '是否验证邮箱不能为空',
]
],
'notes' => [
'label' => '备注',
'name' => 'notes',
'placeholder' => '请输入备注',
],
'email' => [
'label' => '邮箱',
'placeholder' => '请输入邮箱',
'rules' => [
'required' => '邮箱不能为空',
'email' => '邮箱格式不正确',
'unique' => '邮箱已存在',
],
],
'password' => [
'label' => '密码',
'name' => 'password',
'placeholder' => '请输入密码',
'rules' => [
'required' => '密码不能为空',
'minlength' => '密码不能小于{0}位',
]
],
'password_confirmation' => [
'label' => '确认密码',
'placeholder' => '请输入确认密码',
'rules' => [
'required' => '确认密码不能为空',
'minlength' => '确认密码不能小于{0}位',
'equalto' => '确认密码和密码不一致'
],
],
'role' => [
'label' => '角色',
'placeholder' => '选择角色'
],
];<file_sep>/app/Services/Report/LogisticsService.php
<?php
/**
* Created by PhpStorm.
* User: lvxinxin
* Date: 2018/02/05
* Email: <EMAIL>
*/
namespace App\Services\Report;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use Exception;
use Yajra\DataTables\Html\Builder;
use Yajra\DataTables\DataTables;
use DB;
use App\Services\Service;
class LogisticsService extends Service{
use ServiceTrait,ResultTrait,ExceptionTrait;
protected $builder;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function lists($report_identifier){
try{
if (!$report_identifier) throw new Exception('参数为空');
return $this->logisticsRepo->getLists($report_identifier);
}
catch (Exception $e){
\Log::error(__METHOD__,[$e->getMessage()]);
return false;
}
}
public function create()
{
#上报监管-添加-物流公司
$logistics_company = [];
return [
'logistics_company' => $logistics_company,
];
}
public function store()
{
$data = request()->all();
$data['company_id'] = getCompanyId() ;
#TODO::研究方案编号 即当前的项目编号
#$data['solution_number'] = '';
try {
$exception = DB::transaction(function () use ($data) {
if ($logistics = $this->logisticsRepo->create($data)) {
# TODO:: exec other logic
} else {
throw new Exception(trans('code/logistics.store.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/logistics.store.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/logistics.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function destroy($id)
{
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->logisticsRepo->decodeId($id);
#删除
if ($source = $this->logisticsRepo->update(['status' => 2], $id)) {
#TODO:: other logic
} else {
throw new Exception(trans('code/logistics.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/logistics.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/logistics.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/app/Services/QuestioningService.php
<?php
namespace App\Services;
use App\Services\Service as BasicService;
use Illuminate\Http\Request;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use App\Traits\Services\Question\QuestionTrait;
use Yajra\DataTables\DataTables;
use Exception;
use Illuminate\Support\Facades\DB;
Class QuestioningService extends BasicService
{
use ResultTrait, ExceptionTrait, ServiceTrait, QuestionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function datatables()
{
$data = $this->questionRepo->findWhereNotIn('status', ['1'])->all();
return DataTables::of($data)
->addColumn('action', getThemeTemplate('back.homepage.questioning.datatable'))
->addColumn('status', getThemeTemplate('back.homepage.questioning.status'))
->make();
}
/*发送页面*/
public function show($id)
{
try {
/*发送质疑的数据*/
$data = $info = $this->questionRepo->find($id, ['id', 'end_date', 'content']);
return [
'data' => $data,
];
} catch (Exception $e) {
abort(404);
}
}
/*发送质疑*/
public function create()
{
try {
$exception = DB::transaction(function (){
if ($send = $this->questioningRepo->create(request()->all())) {
/*获取关联数据*/
//['question_id'=>3,'end_data'=>'2018/1/23','content'=>'服务信息14.12','status'=>1]
$question_id = $send->question_id;
$end_date = $send->end_date;
$content = $send->content;
$status = $send->status;
$id = $send->id;
$info = $this->send($question_id,$end_date,$content,$id,$status);
} else {
throw new Exception(trans('code/questioning.create.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'data'=>$send,
'message' => trans('code/questioning.create.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/questioning.create.fail')),
]);
}
return array_merge($this->results, $exception);
}
/*关闭质疑状态*/
public function end($id)
{
try {
$exception = DB::transaction(function() use ($id) {
//关闭质疑状态
if( $status = $this->questionRepo->update(['status'=>1],$id) ) {
} else {
throw new Exception(trans('code/questioning.end.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/questioning.end.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/questioning.end.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function index()
{
$html = $this->builder->columns([
// ['data' => 'id', 'name' => 'id', 'title' => 'Id'],
['data' => 'question_num', 'name' => 'question_num', 'title' => '质疑编号', 'class' => 'text-center'],
['data' => 'report_num', 'name' => 'report_num', 'title' => '报告编号', 'class' => 'text-center'],
['data' => 'operation_name', 'name' => 'operation_name', 'title' => '操作人', 'class' => 'text-center'],
// ['data' => 'operation_id', 'name' => 'operation_id', 'title' => 'operation_id'],
['data' => 'status', 'name' => 'status', 'title' => '状态', 'class' => 'text-center'],
['data' => 'operation_date', 'name' => 'operation_date', 'title' => '操作日期', 'class' => 'text-center'],
['data' => 'content', 'name' => 'content', 'title' => '内容'],
['data' => 'end_date', 'name' => 'end_date', 'title' => '截止日期', 'class' => 'text-center'],
['data' => 'sending', 'name' => 'sending', 'title' => '发送次数', 'class' => 'text-center'],
// ['data' => 'created_at', 'name' => 'created_at', 'title' => 'Created At'],
// ['data' => 'updated_at', 'name' => 'updated_at', 'title' => 'Updated At'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false]
])
->ajax([
'url' => route('admin.questioning.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
}
<file_sep>/app/Role.php
<?php
namespace App;
use Laratrust\Models\LaratrustRole;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use App\Traits\ModelTrait;
class Role extends LaratrustRole implements Transformable
{
use TransformableTrait;
use ModelTrait;
protected $fillable = [
'name', 'display_name', 'description', 'organize_role_id',
];
protected $appends = [
'id_hash'
];
/**
* 获取角色的用户
* @return [type] [description]
*/
public function users($companyId = '')
{
$users = $this->belongsToMany(
config('laratrust.user_models.users'),
config('laratrust.tables.role_user'),
config('laratrust.foreign_keys.role'),
config('laratrust.foreign_keys.user')
)->wherePivot('user_type', config('laratrust.user_models.users'));
if (config('laratrust.use_teams')) {
$users->withPivot(config('laratrust.foreign_keys.team'));
}
if($companyId) {
$users->where('users.company_id', $companyId);
}
return $users;
}
public function getIdHashAttribute()
{
return $this->encodeId('role', $this->id);
}
}
<file_sep>/resources/lang/en/module/regulation.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/23
* Time: 下午2:01
*/
return [
'create' => [
'title' => '规则添加',
'submit' => '添加',
'reset' => '重置',
],
'edit' => [
'title' => '规则修改',
'submit' => '修改',
'reset' => '重置',
],
'index' => [
'create' => '添加',
'destroy' => [
'confirm' => '确定要删除吗?',
'fail' => '删除失败',
]
],
];<file_sep>/app/Repositories/Eloquents/PlatformConfigRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\PlatformConfigRepository;
use App\Repositories\Models\PlatformConfig;
use App\Repositories\Validators\PlatformConfigValidator;
/**
* Class PlatformConfigRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class PlatformConfigRepositoryEloquent extends BaseRepository implements PlatformConfigRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return PlatformConfig::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/public/backend/js/common.js
(function($, win){
if(typeof $ == "undefined") return false;
//动态Modal 隐藏后设空
var layerIndex = 0;
$('#php-ajax-modal,#php-ajax-modal-small').on('hidden.bs.modal',function(){
$(this).find('.modal-content').html("");
}).on('show.bs.modal',function(){
layerIndex = layer.load();
}).on('shown.bs.modal', function(){
layer.close(layerIndex);
});
//静态Modal 重置form
$('#local-modal').on('hidden.bs.modal',function(){
$(this).find('form').trigger('reset');
});
// 系统配置
var config = {
dictURL: '/admin/dictionaries/hasmanydictionaries' //获取字典下拉数据
, fileUploadURL: '/admin/attachment/upload' //文件上传接口
, fileSWFURL: '/vendor/webuploader-0.1.5/Uploader.swf' // 上传插件需要的 swf 文件
};
// 数据缓存
var cache = {
};
// 系统方法
var pv = {
/**
* 初始化系统全局方法
* @return {[type]} [description]
*/
init: function(){
pv.rendre.renderDict();
},
/**
* 公共的 ajax 请求
* @param {[type]} opts ajax 请求配置参数
* @param {[type]} loading 是否请求显示 loading 状态,默认为 true
* @return {[type]} [description]
*/
ajax: function(opts,loading){
var loading = loading || true;
var index = null;
var opts_def = {};
var def = {
headers: {
'X-CSRF-TOKEN': $('meta[name=_token]').attr('content')
}
}
if(loading) (typeof layer != "undefined") && (index = layer.load());
opts_def = $.extend({},def, opts,true);
$.ajax(opts_def).always(function(){
if(index != null) layer && layer.close(index);
});
},
/**
* 页面 dom 常用公共事件监听
* @type {Object}
*/
events: {
},
/**
* 页面dom常用渲染库
* @type {Object}
*/
rendre: {
/**
* 通用 select option 渲染
* @param {[type]} el [description]
* @param {[type]} data [description]
* @param {[type]} opts [description]
* @return {[type]} [description]
*/
optionFn: function(el, data, opts){
if(el == undefined || el.length <= 0) return;
var def_cfg = {
name: 'name',
value: 'value'
}
var buff = '';
var opt = $.extend({}, def_cfg, opts, true);
for(var i = 0; i < data.length; i++){
var d = data[i];
buff += '<option value="'+d[opt.name]+'">'+d[opt.value]+'</option>'
}
el.html(buff);
},
/**
* 渲染需要使用字典库的 select
* @param {[type]} el [description]
* @return {[type]} [description]
*/
renderDict: function(el){
var params = [];
var el = el || $(document);
el.find('select[data-dict]').each(function(){
params.push($(this).attr("data-dict"));
});
pv.getDict(params, el);
}
},
/**
* 获取字典库数据
* @param {[type]} arrParams [description]
* @param {[type]} el [description]
* @return {[type]} [description]
*/
getDict: function(arrParams, el){
if(arrParams == undefined || arrParams.length <=0) return false;
var el = el || $(document);
var renderSelectFn = function(data){
for(var i in data){
var ele = $('select[data-dict="'+i+'"]',el);
var val = ele.attr("data-value");
var option = '';
for(var j = 0; j < data[i].length; j++){
var d = data[i][j];
var selected = d.id == val ? 'selected' : '';
option += '<option value="'+d.id+'" ' + selected + ' >'+d.sub_chinese+'</option>';
}
ele.html(option);
}
}
pv.ajax({
url: config.dictURL,
type: 'GET',
data: {
chinese : arrParams
},
success: function(resp){
if(resp.result){
renderSelectFn(resp.data);
}
}
})
},
/**
* 文件上传功能
* @param {[type]} el [description]
* @param {[type]} opts [description]
* @param {Object} callbackOpts [description]
* @return {[type]} [description]
*/
uploadFile: function(el,opts,callbackOpts){
if(typeof WebUploader == "undefined") return ;
var selectInput = $('#file-upload-element');
if(selectInput.length >0){
selectInput.hide();
}else{
selectInput = $('<div id="file-upload-element"></div>').appendTo($('body')).hide();
}
// 上传成功后的配置
var callback_cfg = {
callback:{},
// 上传成功回调写入 dom 的数据点
opts:{
"file": 'input[type=file]', // 选中文件的input
"value": 'input[name=file_id]', // 回调写入文件id的隐藏input
// "other":[{ //需要存储的其他文件信息格式为
// ele: "", //页面 dom sel
// key: "" //文件返回的数据字段
// }]
}
}
//上传插件配置
var cfg = {
server: config.fileUploadURL,
swf: config.fileSWFURL,
method: 'POST',
chunked: false ,// 分片上传关闭
paste: document.body,
formData: {
_token: $('meta[name=_token]').attr('content')
},
accept:{
extensions: '',//允许的文件后缀
mimeTypes: '*',//允许的文件类型
},
pick: {
id: '#file-upload-element',
label: '点击选择图片'
}
}
var opt = $.extend({}, cfg, opts || {}, true);
var cOpt = $.extend({}, callback_cfg, callbackOpts || {}, true);
var callback = cOpt.callback;
var cOption = cOpt.opts;
var uploader = WebUploader.create(opt);
//上传进度
uploader.onUploadProgress = function(){
console.log(arguments);
}
// 开始上传
uploader.onStartUpload = function(){
if(callback && callback.startUpload){
callback.startUpload.apply(this,arguments);
}else{
layer.msg("开始上传文件!");
}
};
//上传暂停
uploader.onStopUpload = function(){
if(callback && callback.stopUpload){
callback.stopUpload.apply(this,arguments);
}else{
layer.msg("文件上传暂停!");
}
};
//上传进度
uploader.onUploadProgress = function(file, percentage){
if(callback && callback.uploadProgress){
callback.uploadProgress.apply(this,arguments);
}else{
console.log(percentage);
}
};
//上传结束
uploader.onUploadFinished = function(){
if(callback && callback.uploadFinished){
callback.uploadFinished.apply(this,arguments);
}
};
// 上传成功
uploader.onUploadSuccess = function(file, resp){
if(callback && callback.uploadSuccess){
callback.uploadSuccess.apply(this,arguments);
}else{
layer.msg("文件上传成功!");
console.log(resp);
}
}
return {
uploader: uploader,
upload: function(callback, file){
if(typeof file !== "undefined"){
uploader.addFile(file);
}else{
var file = $(cOption.file,el);
if(file.length >0){
uploader.reset();
uploader.addFile(file[0].files);
uploader.upload();
if(callback){
// 上传成功
uploader.onUploadSuccess = function(file, resp){
callback.apply(this,arguments);
}
}
}else{
console.log("未找到对应的file标签!");
}
}
}
};
},
/**
* 原始资料分类
* @param {[type]} el [description]
* @param {[type]} url [description]
* @return {[type]} [description]
*/
jsTree: function(el, url){
if(el.length <= 0) return false;
return el.jstree({
"core" : {
"multiple": false,
"themes" : {
"responsive": false
},
'data' : [
{
"text" : "上市前药品相关资料", "id": "1","state" : {"opened" : true }, "children" : [
{ "text" : "通用名A", "id": "1-1", "children": [
{ "text": "临床一期", "id": "1-1-1"},
{ "text": "临床二期", "id": "1-1-2"},
{ "text": "临床三期", "id": "1-1-3"},
]},
{ "text" : "通用名B", "id": "1-2", "children": [
{ "text": "临床一期", "id": "1-2-1"},
{ "text": "临床二期", "id": "1-2-2"},
{ "text": "临床三期", "id": "1-2-3"},
]},
]
},{
"text" : "上市后药品相关资料", "id": "2","state" : {"opened" : true }, "children" : [
{ "text" : "通用名A", "id": "2-1", "children": [
{ "text": "临床一期", "id": "2-1-1"},
{ "text": "临床二期", "id": "2-1-2"},
{ "text": "临床三期", "id": "2-1-3"},
]},
{ "text" : "通用名B", "id": "2-2", "children": [
{ "text": "临床一期", "id": "2-2-1"},
{ "text": "临床二期", "id": "2-2-2"},
{ "text": "临床三期", "id": "2-2-3"},
]},
]
}
]
},
"types" : {
"default" : {
"icon" : "fa fa-folder icon-state-warning icon-lg"
},
"file" : {
"icon" : "fa fa-file icon-state-warning icon-lg"
}
},
"plugins": ["types"]
});
},
/**
* datatable 公共 js 实现方法
* @param {Element} el datatable el
* @param {[type]} opts [description]
* @param {[type]} form [description]
* @return {[type]} [description]
* table class => table table-striped table-bordered table-hover dataTable no-footer white-space-nowrap
*
*/
datatable: function(el, opts,form){
var cfg = {
processing: true,
serverSide: true,
pagingType: "bootstrap_extended",
autoWidth: false,
dom: "<'table-responsive't><'row'<'col-md-12 col-sm-12'il<'table-group-actions pull-right'p>>>",
language: {
url: '/vendor/datatables/lang/zh_CN.json'
},
bStateSave: true,
drawCallback: function(){
PVJs.tableInit.apply(this,arguments);
}
}
var options = $.extend({},cfg,opts,true);
var table = el.DataTable(options);
if(form){
form.find('.pv-search-event').click(function(){
table.ajax.reload();
});
}
return table;
},
/**
* datatable action init
* @return {[type]} [description]
*/
tableInit: function(){
var el = $(this);
pv.tooltip(el);
pv.tableAction(el);
pv.modal(el);
},
/**
* 激活 tooltip 插件
* @param {[type]} el 需要激活的 tooltip 范围
* @return {[type]} [description]
*/
tooltip: function(el){
var el = el || $(document);
$('[data-toggle*="tooltip"]',el).tooltip({container:'body'});
},
/**
* 激活 modal 插件
* @param {[type]} el el 需要激活的 modal 范围
* @return {[type]} [description]
*/
modal: function(el){
var el = el || $(document);
$('[data-toggle*="modal"]',el).each(function(){
var that = $(this);
var target = that.attr('data-target');
var url = that.attr("href");
if(target.indexOf('php-ajax-modal') > 0){
var modalEl = $(target);
that.click(function(e){
e.stopPropagation();
e.preventDefault();
console.log(1);
var m = modalEl.modal({
remote: url,
show: true
});
// $.get(url,function(resp){
// modalEl.find('.modal-content').html(resp);
// m.modal('show');
// });
})
}
})
},
/**
* datatable 内按钮操作
* @param {Element} el 元素范围
* @param {Function} callback 操作结束后的回调方法
* @return {[type]} [description]
*/
tableAction: function(el, callback){
el.find('[data-method="delete"],[data-method="post"],[data-method="get"],[data-method="put"]').each(function(){
var that = $(this);
var method = that.attr('data-method');
var url = that.attr('data-url');
var type = that.attr('data-type');
var confirm = that.attr('data-confirm');
var reload = that.attr('data-reload');
var title = that.attr('title') || that.attr('data-original-title');
var loading = that.attr('data-loading');
var elCallback = that.attr('data-callback');// callback 的规则为 page.function
var ajax = function(){
pv.ajax({
url: url,
type: method,
dataType: type,
success: function(resp){
if(resp.result){
layer.msg(resp.message);
if(reload){
window.location.reload();
}
callback && callback.apply(that,[resp,that]);
if(elCallback){
var arr_callback = elCallback.split('.');
window[arr_callback[0]][arr_callback[1]](that,arguments);
}
}
}
},loading);
}
that.click(function(){
$('[data-toggle*="tooltip"]').tooltip('hide');
if(confirm == undefined){
ajax();
}else{
if(confirm.length >0){
layer.confirm(confirm,{
btn:["确定", "取消"]
},ajax);
}else{
layer.confirm("您确定执行 [ " + title + " ] 操作!",{
btn:["确定", "取消"]
},ajax);
}
}
});
});
},
/**
* 轻轻等待loading
* @param {String} el Element select
* @return {[type]} [description]
*/
backUI: function(el){
App.blockUI({
target: el,
animate: true
});
},
/**
* 清除请求等待 如果没有 el 则清楚全部的
* @param {String} el Element Select
* @return {[type]} [description]
*/
clearBackUI: function(el){
if(el){
App.unblockUI(el);
}else{
$.unblockUI();
}
},
/**
* 公共的默认激活事件
* @return {[type]} [description]
*/
commonEventInit: function(){
$('button[type="submit"]').click(function(){
pv.backUI($(this).parents('.form-fit'));
})
}
};
win.PVJs = pv;
PVJs.init(); // 初始化系统全局方法
})(jQuery,window);<file_sep>/app/Listeners/Report/Value/SetRedundanceDataListener.php
<?php
namespace App\Listeners\Report\Value;
use App\Events\Report\Value\SetRedundanceData;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repositories\Interfaces\ReportValuesRepository;
class SetRedundanceDataListener
{
/**
* Create the event listener.
*
* @return void
*/
protected $reportValueRepo;
public function __construct(
ReportValuesRepository $reportValueRepo
)
{
$this->reportValueRepo = $reportValueRepo;
}
/**
* Handle the event.
*
* @param SetRedundanceData $event
* @return void
*/
public function handle(SetRedundanceData $event)
{
$companyId = $event->companyId;
$reportId = $event->reportId;
$data = $event->data;
if( $data ) {
foreach( $data as $field => $value ) {
$attributes = [
'company_id' => $companyId,
'report_id' => $reportId,
'report_tab_id' => getReportTabValue('overview'),
'col' => 0,
'col_name' => '',
'is_table' => getCommonCheckValue(false),
'table_alias' => 0,
'table_row_id' => 0,
'name' => $field,
];
$values = [
'value' => $value,
];
$this->reportValueRepo->updateOrCreate($attributes, $values);
}
}
}
}
<file_sep>/resources/lang/en/module/quality.php
<?php
return [
'datatrace' => [
'index' => [
'title' => '稽查管理',
],
],
];<file_sep>/app/Services/ManagementService.php
<?php
namespace App\Services;
use App\Repositories\Models\Source;
use App\Services\Service as BasicService;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DataTables;
use Exception;
use DB;
use TCPDF;
use Excel;
Class ManagementService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function datatables()
{
$searchFields = [
'oc_number' => 'like',
'order_type' => '=',
'province' => '=',
'name' => 'like',
'status' => '=',
'card_number' => 'like',
'number' => 'like',
];
/*获取查询条件*/
$where = $this->searchArray($searchFields);
/*获取数据*/
$data = $this->managementRepo->findWhere($where);
return DataTables::of($data)
->addColumn('action', getThemeTemplate('ocback.managements.datatable'))
->addColumn('status', getThemeTemplate('back.homepage.questioning.status'))
->make();
}
public function index()
{
$html = $this->builder->columns([
['data' => 'number', 'name' => 'number', 'title' => '订单号', 'class' => 'text-center'],
['data' => 'oc_number', 'name' => 'oc_number', 'title' => '油卡编号', 'class' => 'text-center'],
['data' => 'oc_name', 'name' => 'oc_name', 'title' => '油卡信息', 'class' => 'text-center'],
['data' => 'number_uptime', 'name' => 'number_uptime', 'title' => '订单修改时间', 'class' => 'text-center'],
['data' => 'card_number', 'name' => 'card_number', 'title' => '油卡号', 'class' => 'text-center'],
['data' => 'name', 'name' => 'name', 'title' => '用户名', 'class' => 'text-center'],
['data' => 'number_status', 'name' => 'number_status', 'title' => '订单状态', 'class' => 'text-center'],
['data' => 'img_id', 'name' => 'img_id', 'title' => '图片id', 'class' => 'text-center'],
])
->ajax([
'url' => route('admin.management.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
/*添加*/
public function create()
{
try {
$exception = DB::transaction(function () {
//订单编号
//
if ($info = $this->managementRepo->create(request()->all())) {
} else {
throw new Exception(trans('code/management.create.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/management.create.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/management.create.fail')),
]);
}
return array_merge($this->results, $exception);
}
/*油卡删除*/
public function destroy($id)
{
try {
$exception = DB::transaction(function() use ($id) {
if( $info = $this->managementRepo->delete($id) ){
/*删除油卡关联事件*/
} else {
throw new Exception(trans('code/management.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/management.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/management.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
/*油卡状态更改*/
public function update($id)
{
try {
$exception = DB::transaction(function() use ($id) {
if( $info = $this->managementRepo->find($id)) {
if($info->status == 1)
{
$info = $this->managementRepo->update(['status'=>0],$id);
} else{
$info = $this->managementRepo->update(['status'=>1],$id);
}
} else {
throw new Exception(trans('code/management.update.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/management.update.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/management.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function show()
{
dd(123);
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// 设置文档信息
$pdf->SetCreator('Hello world');
$pdf->SetAuthor('dyk');
$pdf->SetTitle('TCPDF示例');
$pdf->SetSubject('TCPDF示例');
$pdf->SetKeywords('TCPDF, PDF, PHP');
// 设置页眉和页脚信息
$pdf->SetHeaderData('tcpdf_logo.jpg', 30, 'www.marchsoft.cn', '三月软件!', [0, 64, 255], [0, 64, 128]);
$pdf->setFooterData([0, 64, 0], [0, 64, 128]);
// 设置页眉和页脚字体
$pdf->setHeaderFont(['stsongstdlight', '', '10']);
$pdf->setFooterFont(['helvetica', '', '8']);
// 设置默认等宽字体
$pdf->SetDefaultMonospacedFont('courier');
// 设置间距
$pdf->SetMargins(15, 15, 15);//页面间隔
$pdf->SetHeaderMargin(5);//页眉top间隔
$pdf->SetFooterMargin(10);//页脚bottom间隔
// 设置分页
$pdf->SetAutoPageBreak(true, 25);
// 设置自动换页
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// 设置图像比例因子
$pdf->setImageScale(1.25);
// 设置默认字体构造子集模式
$pdf->setFontSubsetting(true);
// 设置字体 stsongstdlight支持中文
$pdf->SetFont('stsongstdlight', '', 14);
// 添加一页
$pdf->AddPage();
$pdf->Ln(5);//换行符
$html = '
<table width="400" border="1">
<tr>
<th align="left">消费项目</th>
<th align="right">一月</th>
<th align="right">二月</th>
</tr>
<tr>
<td align="left">衣服</td>
<td align="right">$241.10</td>
<td align="right">$50.20</td>
</tr>
<tr>
<td align="left">化妆品</td>
<td align="right">$30.00</td>
<td align="right">$44.45</td>
</tr>
<tr>
<td align="left">食物</td>
<td align="right">$730.40</td>
<td align="right">$650.00</td>
</tr>
<tr>
<th align="left">总计</th>
<th align="right">$1001.50</th>
<th align="right">$744.65</th>
</tr>
</table>
';
$pdf->writeHTML($html, true, false, true, false, '');
//输出PDF
$pdf->Output('t.pdf', 'I');//I输出、D下载
}
public function excel()
{
dd(123);
}
}<file_sep>/routes/routes/report/mainpage.php
<?php
$router->group(['prefix' => 'report', 'as' => 'report.'], function($router) {
$router->group(['prefix' => 'mainpage', 'as' => 'mainpage.'], function ($router) {
/*列表*/
$router->any('index',[
'uses'=>'MainpageController@index',
'as'=>'index',
]);
/*新建*/
$router->post('create',[
'uses'=>'MainpageController@create',
'as'=>'create',
]);
/*复制*/
$router->get('{id}/copy',[
'uses'=>'MainpageController@copy',
'as'=>'copy',
]);
/*删除*/
$router->get('{id}/edit',[
'uses'=>'MainpageController@edit',
'as'=>'edit',
]);
/*导出*/
$router->get('{id}/export',[
'uses'=>'MainpageController@export',
'as'=>'export',
]);
/*新建版本*/
$router->get('{id}/build',[
'uses'=>'MainpageController@build',
'as'=>'build',
]);
/*查看详情*/
$router->get('{id}/show',[
'uses'=>'MainpageController@show',
'as'=>'show',
]);
/*查看详情*/
$router->get('{id}/newreport',[
'uses'=>'MainpageController@newreport',
'as'=>'newreport',
]);
});
$router->resource('mainpage','MainpageController');
});<file_sep>/routes/routes/basic/route.php
<?php
$router->group(['namespace' => 'Back\Basic'], function($router) {
/*企业信息*/
require(__DIR__ . '/enterprise.php');
});<file_sep>/database/migrations/2018_02_14_155017_create_managements_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
/**
* Class CreateManagementsTable.
*/
class CreateManagementsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('managements', function(Blueprint $table) {
$table->increments('id');
$table->string('oc_number')->nullable()->comment('油卡编号');
$table->string('name')->nullable()->comment('真实姓名');
$table->string('card_number')->nullable()->comment('油卡号');
$table->string('order_type')->nullable()->comment('订单类型');
$table->string('province')->nullable()->comment('省份');
$table->string('province_id')->nullable()->comment('省份id');
$table->string('number')->nullable()->comment('编号');
$table->string('user_id')->nullable()->comment('用户id');
$table->tinyInteger('status')->nullable()->default(1)->comment('1-正常,2-关闭');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('managements');
}
}
<file_sep>/app/Traits/Services/Report/TaskTrait.php
<?php
namespace App\Traits\Services\Report;
use App\Repositories\Interfaces\ReportTaskRepository;
Trait TaskTrait
{
/**
* 设置任务和报告倒计时
* @param [type] $reportTask [description]
* @param [type] $organizeMaps [description]
*/
public function setCountdown($reportTask, $organizeMaps)
{
/*重新获取报告任务*/
$reportTask = app(ReportTaskRepository::class)->find($reportTask->id);
$organizeRoleId = $reportTask->organize_role_id;
$taskCompleteCountdownKey = $organizeMaps[$organizeRoleId] . '_countdown';
$taskCompleteCountdown = $reportTask->{$taskCompleteCountdownKey};
/*报告完成的时间*/
$reportCompleteCountdown = $reportTask->report_complete_countdown;
$assignedAt = $reportTask->assigned_at;
$knowdedAt = $reportTask->report_first_received_date;
switch( $reportTask->countdown_unit ) {
case 'd' :
/*任务倒计时*/
$taskCountdown = $assignedAt->addDays($taskCompleteCountdown);
/*报告倒计时*/
$reportCountdown = $knowdedAt->addDays($reportCompleteCountdown);
break;
case 'h' :
/*任务倒计时*/
$taskCountdown = $assignedAt->addHours($taskCompleteCountdown);
/*报告倒计时*/
$reportCountdown = $knowdedAt->addHours($reportCompleteCountdown);
break;
default :
/*任务倒计时*/
$taskCountdown = $assignedAt;
/*报告倒计时*/
$reportCountdown = $knowdedAt;
}
$reportTask->task_countdown = $taskCountdown;
$reportTask->report_countdown = $reportCountdown;
$reportTask->save();
}
/**
* 设置报告规则的冗余数据
*/
public function setRegulationBak($regulation, $where = [])
{
/*
修改报告中的报告规则的倒计时时间
*/
$data = [
'data_insert_countdown' => $regulation->data_insert,
'data_qc_countdown' => $regulation->data_qc,
'medical_exam_countdown' => $regulation->medical_exam,
'medical_exam_qc_countdown' => $regulation->medical_exam_qc,
'report_submit_countdown' => $regulation->report_submit,
//报告完成倒计时
'report_complete_countdown' => $regulation->finished_date,
/*报告规则倒计时单位*/
'countdown_unit' => $regulation->unit,
];
$where = array_merge($where, [
'regulation_id' => $regulation->id,
]);
app(ReportTaskRepository::class)->updateWhere($data, $where);
}
}<file_sep>/app/Http/Controllers/Back/System/DictionariesController.php
<?php
namespace App\Http\Controllers\Back\System;
use App\Events\Dictionaries\Dictionaries;
use App\Traits\EncryptTrait;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\DictionariesService as Service;
//use App\Repositories\Models\Dictionaries;
Class DictionariesController extends Controller
{
use EncryptTrait;
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.system.Dictionaries';
/*定义路由*/
protected $routePrefix = 'admin.Diction';
protected $encryptConnection = 'dictionaries';
/*service*/
protected $service;
/*构造函数*/
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* 字典列表
* @return [type] [description]
*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
/**
* 新增字典
* @return [type]data id [description]
*/
public function create()
{
$result = $this->service->create();
return response()->json($result);
}
/**
* 子列表
* @return [type] id [description]
*/
public function show($id)
{
$results = $this->service->show($id);
return response()->json($results);
}
/**
* 编辑子列表
* @return [type] id [description]
*/
public function edit($id)
{
$results = $this->service->edit($id);
return view(getThemeTemplate($this->folder . '.edit'))->with($results);
}
/**
* 删除子列表
* @return [type] id [description]
*/
public function destroy($id)
{
$results = $this->service->destroy($id);
return response()->json($results);
}
/**
* 修改子列表数据
* @return [type]data id [description]
*/
public function update($id)
{
$results = $this->service->update($id);
return response()->json($results);
}
/**
* 查询所属页面 关键字
* @return [type]page keyword [description]
*/
public function search($page=0,$keyWord='null')
{
$results = $this->service->search($page,$keyWord);
return response()->json($results);
}
private function storeRules()
{
return [
'name' => [
'required',
Rule::unique('dictionaries')->where(function($query) {
return $query->whereNull('deleted_at');
}),
],
'sub_chinese' => 'required',
'sub_english' => 'required',
'e_name' => 'required',
'e_formate' => 'required',
];
}
private function updateRules()
{
return [
'name' => [
'required',
Rule::unique('dictionaries')->where(function($query) {
return $query->whereNull('deleted_at');
})->ignore($this->decodeId(getRouteParam('dictionaries')), 'id'),
],
'sub_chinese' => 'required',
'sub_english' => 'required',
'e_name' => 'required',
'email' => 'required',
'e_formate' => 'required',
];
}
private function messages()
{
return [
];
}
/**
* 字典查询 durg_name b_n/g_n
* @param [type] $array [description]
* @param [type] [description]
* @return [type] [description]
*/
public function hasmanydictionaries()
{
$results = $this->service->hasmanydictionaries();
return response()->json($results);
}
}<file_sep>/app/Services/Service.php
<?php
namespace App\Services;
use App\Repositories\Interfaces\CategoryRepository;
use App\Repositories\Interfaces\DrugLibraryRepository;
use App\Repositories\Interfaces\LogisticsRepository;
use App\Repositories\Interfaces\RegulationRepository;
use App\Repositories\Interfaces\QuestionRepository;
use App\Repositories\Interfaces\SourceRepository;
//use App\Repositories\Interfaces\SupplierRepository;
use App\Repositories\Interfaces\UserRepository;
use App\Repositories\Interfaces\RoleRepository;
use App\Repositories\Interfaces\PermissionRepository;
use App\Repositories\Interfaces\MenuRepository;
use App\Repositories\Interfaces\CompanyRepository;
use App\Repositories\Interfaces\DictionariesRepository;
use App\Repositories\Interfaces\SubdictionariesRepository;
use App\Repositories\Interfaces\RecursiveRelationRepository;
use App\Repositories\Interfaces\WorkflowRepository;
use App\Repositories\Interfaces\WorkflowNodeRepository;
use App\Repositories\Interfaces\QuestioningRepository;
use App\Repositories\Interfaces\MailRepository;
use App\Repositories\Interfaces\ReportTabRepository;
use App\Repositories\Interfaces\ReportValuesRepository;
use App\Repositories\Interfaces\ReportTaskRepository;
use App\Repositories\Interfaces\ReportMainpageRepository;
use App\Repositories\Interfaces\DataTraceRepository;
use App\Repositories\Interfaces\EnterpriseRepository;
/*OC*/
use App\Repositories\Interfaces\OcloginRepository;
use App\Repositories\Interfaces\ManagementRepository;
use App\Repositories\Interfaces\PurchaseRepository;
use App\Repositories\Interfaces\PurchasingRepository;
use App\Repositories\Interfaces\OilCardRepository;
use App\Repositories\Interfaces\AttachmentRepository;
use App\Repositories\Interfaces\SupplierRepository;
use App\Repositories\Interfaces\PlatformConfigRepository;
class Service
{
public $userRepo;
public $roleRepo;
public $permissionRepo;
public $menuRepo;
public $companyRepo;
public $dictionariesRepo;
public $subdictionariesRepo;
public $recursiveRelationRepo;
public $drugRepo;
public $workflowRepo;
public $workflowNodeRepo;
public $regulaRepo;
public $questionRepo;
public $questioningRepo;
public $mailRepo;
public $cateRepo;
public $reportTabRepo;
public $reportValueRepo;
public $sourceRepo;
public $reportTaskRepo;
public $reportMainpageRepo;
public $attachmentRepo;
public $logisticsRepo;
public $dataTraceRepo;
public $enterpriseRepo;
/*OC*/
public $ocloginRepo;
public $managementRepo;
public $purchaseRepo;
public $oilcardbindingRepo;
public $supplierRepo;
public $platformRepo;
public function __construct()
{
$this->userRepo = app(UserRepository::class);
$this->roleRepo = app(RoleRepository::class);
$this->permissionRepo = app(PermissionRepository::class);
$this->menuRepo = app(MenuRepository::class);
$this->companyRepo = app(CompanyRepository::class);
$this->dictionariesRepo = app(DictionariesRepository::class);
$this->recursiveRelationRepo = app(RecursiveRelationRepository::class);
$this->subdictionariesRepo = app(SubdictionariesRepository::class);
$this->drugRepo = app(DrugLibraryRepository::class);
$this->workflowRepo = app(WorkflowRepository::class);
$this->workflowNodeRepo = app(WorkflowNodeRepository::class);
$this->regulaRepo = app(RegulationRepository::class);
$this->questionRepo = app(QuestionRepository::class);
$this->questioningRepo = app(QuestioningRepository::class);
$this->mailRepo = app(MailRepository::class);
$this->cateRepo = app(CategoryRepository::class);
$this->reportTabRepo = app(ReportTabRepository::class);
$this->reportValueRepo = app(ReportValuesRepository::class);
$this->sourceRepo = app(SourceRepository::class);
$this->reportTaskRepo = app(ReportTaskRepository::class);
$this->reportMainpageRepo = app(ReportMainpageRepository::class);
$this->attachmentRepo = app(AttachmentRepository::class);
$this->logisticsRepo = app(LogisticsRepository::class);
$this->dataTraceRepo = app(DataTraceRepository::class);
$this->enterpriseRepo = app(EnterpriseRepository::class);
/*OC*/
$this->ocloginRepo = app(OcloginRepository::class);
$this->managementRepo = app(ManagementRepository::class);
$this->purchaseRepo = app(PurchaseRepository::class);
$this->oilcardbindingRepo = app(OilCardRepository::class);
$this->supplierRepo = app(SupplierRepository::class);
$this->platformRepo = app(PlatformConfigRepository::class);
}
}<file_sep>/routes/oc_routes/dash.php
<?php
$router->group(['namespace' => 'Card'], function($router) {
$router->resource('dash', 'DashController');
});<file_sep>/app/User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laratrust\Traits\LaratrustUserTrait;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\ModelTrait;
class User extends Authenticatable implements Transformable
{
use LaratrustUserTrait;
use Notifiable;
use TransformableTrait;
use SoftDeletes;
use ModelTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'truename', 'sex', 'mobile', 'company_id', 'compnay_name', 'is_check_email', 'notes', 'email', 'password'
];
protected $dates = ['deleted_at'];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'remember_token',
];
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('user', $this->id);
}
//公司id
public function company()
{
return $this->hasOne(Company::class, 'id', 'company_id');
}
}
<file_sep>/app/Http/Controllers/Card/Purchasing/OilCardBindingController.php
<?php
namespace App\Http\Controllers\Card\Purchasing;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\OcService\OilCardBindingService as Service;
class OilCardBindingController extends Controller
{
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index(){
$this->get_data();
return $this->view();
}
//创建油卡
public function create(Request $request){
$this->service->create();
//重定向到index路由
return redirect('/admin/backstage/oil_binding/index');
}
//获取视图
public function view(){
//获取config的配置
$results=$this->service->get_config_blade(config('oc.default.oilcardbinding'));
//获取表格数据
$results['data'] = $this->get_data();
//获取datatable的字段
$results['table'] = config('oc.default.oilcardbinding.panel');
//返回
return view('themes.metronic.ocback.backstage.purchasing.oilcardbinding')->with($results);
}
//获取数据
public function get_data(){
//获取关于user_id对应的油卡
return $results=$this->service->search(array('user_id'=>request()->user()->id));
}
}
<file_sep>/app/Repositories/Models/ReportTab.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use App\Traits\ModelTrait;
/**
* Class ReportTab.
*
* @package namespace App\Repositories\Models;
*/
class ReportTab extends Model implements Transformable
{
use TransformableTrait;
use ModelTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [];
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('reporttab', $this->id);
}
}
<file_sep>/routes/routes/drug-library/drug.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/16
* Time: 上午11:31
*/
$router->group([], function($router) {
$router->group(['prefix' => 'drug', 'as' => 'drug.'], function($router) {
$router->resource('drug', 'DrugController');
});
});
<file_sep>/routes/routes/report/value.php
<?php
$router->group(['prefix' => 'report/{reportid}', 'as' => 'report.'], function($router) {
$router->group(['prefix' => 'value', 'as' => 'value.'], function($router){
$router->get('reporttab/{reporttabid}/show', [
'uses' => "ValueController@reportTabHtmlShow",
'as' => 'reporttab.html.show',
]);
/*获取reporttab的html*/
$router->get('reporttab/{reporttabid}', [
'uses' => "ValueController@reportTabHtml",
'as' => 'reporttab.html',
]);
/*保存报告详情数据*/
$router->post('reporttab/{reporttabid}/save', [
'uses' => "ValueController@save",
'as' => 'reporttab.save',
]);
});
$router->resource('value', 'ValueController');
});<file_sep>/app/Traits/DictionariesTrait.php
<?php
namespace App\Traits;
use Hashids;
use DB;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use App\Repositories\Models\Dictionaries;
use Mockery\Exception;
Trait DictionariesTrait{
// use ServiceTrait, ResultTrait, ExceptionTrait;
/**
* 字典查询
* @param [type] $array [description]
* @param [type] [description]
* @return [type] [description]
*/
public function hasManyDictionaries($results)
{
if (is_array($results)) {
$dictionaries = new Dictionaries();
$comments = $dictionaries::whereIn('chinese', $results)->select('id')->get();
$data = $comments->each(function ($item,$key) {
$item->comments = $item->comments;
})->toArray();
return $data;
}else
{
return false;
}
}
}<file_sep>/app/Http/Controllers/Back/System/Workflow/WorkflowNodeController.php
<?php
namespace App\Http\Controllers\Back\System\Workflow;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\WorkflowNodeService as Service;
class WorkflowNodeController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.system.workflow.node';
protected $routePrefix = 'admin.workflow.node';
protected $routeHighLightPrefix = 'admin.workflow';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function setStoreReturnRoute()
{
$workflowId = getWorkflowId('', true);
$this->storeReturn = route('admin.workflow.setting', $workflowId);
}
public function setUpdateReturnRoute()
{
$workflowId = getWorkflowId('', true);
$this->updateReturn = route('admin.workflow.setting', $workflowId);
}
}
<file_sep>/app/Http/Middleware/ExchangeCompany.php
<?php
namespace App\Http\Middleware;
use Closure;
use App\Traits\EncryptTrait;
class ExchangeCompany
{
use EncryptTrait;
public function __construct()
{
$this->setEncryptConnection('company');
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$companyId = getRouteParam('company');
$companyId = $this->decodeId($companyId);
session(['company_id' => $companyId]);
return $next($request);
}
}
<file_sep>/app/Repositories/Interfaces/OcloginRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface LoginRepositoryRepository.
*
* @package namespace App\Repositories\Interfaces;
*/
interface OcloginRepository extends RepositoryInterface
{
//
}
<file_sep>/app/Http/ViewComposers/HeaderCompanyComposer.php
<?php
namespace App\Http\ViewComposers;
use Illuminate\View\View;
use App\Repositories\Interfaces\CompanyRepository;
class HeaderCompanyComposer
{
public function __construct()
{
$this->companyRepo = app(CompanyRepository::class);
}
/*输出数据 */
public function compose(View $view)
{
/*顶部公司*/
$headerCompanies = $this->companyRepo->all()->keyBy('id');
$view->with('headerCompanies', $headerCompanies);
$companyId = getCompanyId();
$currentCompanyName = isset($headerCompanies[$companyId]) && $headerCompanies[$companyId] ? $headerCompanies[$companyId]->name : '管理员界面';
$view->with('currentCompanyName', $currentCompanyName);
// $currentCompanyLogo = isset($headerCompanies[$companyId]) && $headerCompanies[$companyId] ? $headerCompanies[$companyId]->logo : '管理员界面';
// $view->with('currentCompanyLogo', $currentCompanyLogo);
}
}<file_sep>/app/Services/OcService/SupplierCamiloService.php
<?php
namespace App\Services\OcService;
use Yajra\DataTables\Html\Builder;
use App\Services\Service;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DB;
use DataTables;
class SupplierCamiloService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function search()
{
$this->searchArray();
}
public function platform_search($fields)
{
return $this->platformRepo->findWhere($fields)->all();
}
}<file_sep>/app/Http/Controllers/Back/Home/Management/ManagementController.php
<?php
namespace App\Http\Controllers\Back\Home\Management;
//use App\Events\Questioning\questioning;
use Illuminate\Http\Request;
use App\Traits\EncryptTrait;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\ManagementService as Service;
class ManagementController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'ocback.managements';
/*路由*/
protected $routePrefix = 'admin.management';
/*加密id*/
protected $encryptConnection = 'management';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
$this->setEncryptConnection($this->encryptConnection);
}
/*油卡管理列表*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
/*油卡添加*/
public function create(){
//模拟数据
$results = $this->service->create();
return response()->json($results);
}
/*油卡修改*/
public function update($id)
{
$results = $this->service->update($id);
return response()->json($results);
}
/*油卡删除*/
public function delete($id)
{
$results = $this->service->destroy($id);
return response()->json($results);
}
//修改页面
public function store()
{
dd(121);
}
public function excel()
{
$results = $this->service->excel();
return response()->json($results);
}
}
<file_sep>/app/Services/Report/SupervisionsService.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/30
* Time: 下午8:17
*/
namespace App\Services\Report;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use Exception;
use Yajra\DataTables\Html\Builder;
use Yajra\DataTables\DataTables;
use DB;
use App\Services\Service;
class SupervisionsService extends Service{
use ServiceTrait,ResultTrait,ExceptionTrait;
protected $builder;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function datatables()
{
$model = $this->reportMainpageRepo->all();
return DataTables::of($model)
->editColumn('id', '{{ $id_hash }}')
->addColumn('action', getThemeTemplate('back.report.supervision.datatable'))
->make();
}
public function index()
{
$html = $this->builder->columns([
['data' => 'report_identifier', 'name' => 'report_identifier', 'title' => '报告编号'],
['data' => 'received_from_id', 'name' => 'received_from_id', 'title' => '企业报告类型'],
['data' => 'report_first_received_date', 'name' => 'report_first_received_date', 'title' => '收到报告日期'],
['data' => 'first_drug_name', 'name' => 'first_drug_name', 'title' => '药品名称'],
['data' => 'first_event_term', 'name' => 'first_event_term', 'title' => '不良事件'],
['data' => 'received_fromid_id', 'name' => 'received_fromid_id', 'title' => '报告类型'],
['data' => 'regulation_id', 'name' => 'regulation_id', 'title' => '严重性标准'],
['data' => 'id', 'name' => 'id', 'title' => '因果关系'],
['data' => 'id', 'name' => 'id', 'title' => '上报状态'],
['data' => 'id', 'name' => 'id', 'title' => '国家ADR编号'],
['data' => 'id', 'name' => 'id', 'title' => '上报时间'],
['data' => 'action', 'name' => 'action', 'title' => '操作'],
])
->ajax([
'url' => route('admin.supervision.index'),
'type' => 'GET',
]);
return [
'html' => $html,
'drug_class'=>[] #左侧树型分类
];
}
public function immediately($id){
#TODO::
}
public function noNeed($id){
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->reportMainpageRepo->decodeId($id);
# 无须上报,即把上报状态改为无须上报状态
if ($source = $this->reportMainpageRepo->update(['' => 1], $id)) {
#TODO:: other logic
} else {
throw new Exception(trans('code/supervision.noNeed.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/supervision.noNeed.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/supervision.noNeed.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/app/Listeners/Report/Task/SetRedundanceDataListener.php
<?php
namespace App\Listeners\Report\Task;
use App\Events\Report\Task\SetRedundanceData;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repositories\Interfaces\ReportTaskRepository;
class SetRedundanceDataListener
{
/**
* Create the event listener.
*
* @return void
*/
protected $reportTaskRepo;
public function __construct(
ReportTaskRepository $reportTaskRepo
)
{
$this->reportTaskRepo = $reportTaskRepo;
}
/**
* Handle the event.
*
* @param SetRedundanceData $event
* @return void
*/
public function handle(SetRedundanceData $event)
{
$companyId = $event->companyId;
$reportId = $event->reportId;
$data = $event->data;
$where = [
'company_id' => $companyId,
'report_id' => $reportId,
];
$this->reportTaskRepo->updateWhere($data, $where);
}
}
<file_sep>/app/Http/Controllers/Back/Basic/EnterpriseController.php
<?php
namespace App\Http\Controllers\Back\Basic;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use App\Traits\ModelTrait;
use App\Services\EnterpriseService as Service;
use Illuminate\Validation\Rule;
class EnterpriseController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back.basic.enterprise';
protected $routePrefix = 'admin.basic';
protected $encryptConnection = 'basic';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return $this->service->datatables();
//
// if( request()->ajax() ) {
// return $this->service->datatables($sourceId);
// } else {
// $results = $this->service->index();
//
// return view(getThemeTemplate($this->folder . '.index'))->with($results);
// }
}
}<file_sep>/app/Repositories/Eloquents/PermissionRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\PermissionRepository;
use App\Permission;
use App\Repositories\Validators\PermissionValidator;
use App\Traits\EncryptTrait;
use Illuminate\Container\Container as Application;
/**
* Class PermissionRepositoryEloquent
* @package namespace App\Repositories\Eloquents;
*/
class PermissionRepositoryEloquent extends BaseRepository implements PermissionRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('permission');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Permission::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return PermissionValidator::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/routes/routes/report/source.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/29
* Time: 上午10:37
*/
$router->group([], function($router) {
$router->group(['prefix' => 'source', 'as' => 'source.'], function($router) {
#下载原始资料
$router->get('download/{id}', [
'uses' => 'SourcesController@download',
'as' => "download"
]);
#分发原始资料
// $router->get('issue/{id}', [
// 'uses' => 'SourcesController@issue',
// 'as' => "issue"
// ]);
$router->match(['get','post'],'issue/{id}', [
'uses' => 'SourcesController@issue',
'as' => "issue"
]);
#回收原始资料
$router->get('recycling/{id}', [
'uses' => 'SourcesController@recycling',
'as' => "recycling"
]);
});
$router->resource('source', 'SourcesController');
});<file_sep>/app/Services/WorkflowNodeService.php
<?php
namespace App\Services;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DataTables;
use Exception;
use DB;
use App\Repositories\Criterias\FilterCompanyIdCriteria;
class WorkflowNodeService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function create()
{
/*通用验证*/
$commonChecks = getCommonCheck();
/*组织结构的值*/
$roleOrganizes = getRoleOrganize();
/*获取组织结构对应的角色*/
$organizeRoleId = getRoleOrganizeValue('source_manager');
$roles = $this->roleRepo->organizeRoles($organizeRoleId)->pluck('name', 'id_hash');
return [
'commonChecks' => $commonChecks,
'roleOrganizes' => $roleOrganizes,
'roles' => $roles,
];
}
public function edit($id)
{
try {
/*获取用户信息*/
$id = $this->workflowNodeRepo->decodeId($id);
$workflowNode = $this->workflowNodeRepo->find($id);
/*通用验证*/
$commonChecks = getCommonCheck();
/*组织结构的值*/
$roleOrganizes = getRoleOrganize();
/*获取组织结构对应的角色*/
$roles = $this->roleRepo->organizeRoles($workflowNode->organize_role_id)->pluck('name', 'id_hash');
return [
'workflowNode' => $workflowNode,
'commonChecks' => $commonChecks,
'roleOrganizes' => $roleOrganizes,
'roles' => $roles,
];
} catch (Exception $e) {
abort(404);
}
}
/**
* 保存
* @return [type] [description]
*/
public function store()
{
try {
$exception = DB::transaction(function() {
/*不允许直接设置company信息*/
$data = request()->except('company_id');
/*设置默认排序 1*/
$data['sort'] = 1;
/*解密角色id*/
$data['role_id'] = $this->roleRepo->decodeId($data['role_id']);
if($workflowNode = $this->workflowNodeRepo->create($data)) {
/*抛出设置单位的事件*/
$companyId = getCompanyId();
event(new \App\Events\SetCompany($workflowNode, $companyId, false));
/*设置工作流id*/
$workflowId = getWorkflowId();
event(new \App\Events\WorkflowNode\SetWorkflowId($workflowNode, $workflowId));
/*设置排序*/
$prevNodeId = $this->workflowNodeRepo->decodeId($data['prev_node_id']);
event(new \App\Events\WorkflowNode\Sort($prevNodeId, $workflowNode));
} else {
throw new Exception(trans('code/workflow.store.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/workflow.store.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/workflow.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 修改保存
* @param [type] $id [description]
* @return [type] [description]
*/
public function update($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->workflowNodeRepo->decodeId($id);
$data = request()->except('company_id');
/*解密角色id*/
$data['role_id'] = $this->roleRepo->decodeId($data['role_id']);
if( $workflowNode = $this->workflowNodeRepo->update($data, $id) ) {
} else {
throw new Exception(trans('code/workflow.update.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/workflow.update.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/workflow.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 删除用户
* @param [type] $id [description]
* @return [type] [description]
*/
public function destroy($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->workflowNodeRepo->decodeId($id);
if( $workflow = $this->workflowNodeRepo->delete($id) ){
} else {
throw new Exception(trans('code/workflow.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/workflow.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/workflow.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 排序
* @return [type] [description]
*/
public function sort()
{
try {
$exception = DB::transaction(function() {
$prevNodeId = $this->workflowNodeRepo->decodeId(request('prev_node_id', 0));
$curNodeId = $this->workflowNodeRepo->decodeId(request('cur_node_id', 0));
$curNode = $this->workflowNodeRepo->find($curNodeId);
/*设置排序*/
event(new \App\Events\WorkflowNode\Sort($prevNodeId, $curNode));
return array_merge($this->results, [
'result' => true,
'message' => trans('code/workflow.store.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/workflow.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/routes/routes/systems/regulations.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/18
* Time: 下午7:06
*/
$router->group([], function($router) {
$router->group(['prefix' => 'rule', 'as' => 'rule.'], function($router) {
});
$router->resource('rule', 'RegulationsController');
});<file_sep>/resources/lang/en/code/source.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/29
* Time: 上午10:52
*/
return [
'store' => [
'fail' => '原始资料创建失败',
'success' => '原始资料创建成功',
],
'update' => [
'fail' => '原始资料修改失败',
'success' => '原始资料修改成功',
],
'destroy' => [
'fail' => '原始资料删除失败',
'success' => '原始资料删除成功',
],
'sort' => [
'fail' => '原始资料排序失败',
'success' => '原始资料排序成功',
],
'recycling' => [
'fail' => '原始资料回收失败',
'success' => '原始资料回收成功',
],
'issue' => [
'fail' => '原始资料分发失败',
'success' => '原始资料分发成功',
],
'download' => [
'fail' => '原始资料下载失败',
'success' => '原始资料下载成功',
],
'issueCreate' => [
'source_no_exists' => '原始资料数据不存在',
'success' => '原始资料下载成功',
],
'attach' => [
'attach_no_exists' => '附件资料不存在',
'success' => '原始资料下载成功',
],
];<file_sep>/app/Services/Report/Task/NewVersionService.php
<?php
namespace App\Services\Report\Task;
use App\Services\Service;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use Exception;
use DB;
class NewVersionService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
/**
* 报告任务-创建新版本
* @param [type] $id [description]
* @return [type] [description]
*/
public function index($id)
{
try {
$reportTaskId = $this->reportTaskRepo->decodeId($id);
$reportTask = $this->reportTaskRepo->find($reportTaskId);
$source = $this->sourceRepo->find($reportTask->source_id);
return [
'reportTask' => $reportTask,
'source' => $source
];
} catch (Exception $e) {
abort(404);
}
}
/**
* 报告任务-保存新版本
* @param [type] $id [description]
* @return [type] [description]
*/
public function store($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$taskId = $this->reportTaskRepo->decodeId($id);
$task = $this->reportTaskRepo->find($taskId);
/*报告编号*/
$reportIdentify = $this->checkParam('report_identify', '');
$reportFirstReceivedDate = $this->checkParam('report_first_received_date', '');
$reportDrugSafetyDate = $this->checkParam('report_drug_safety_date', '');
$newVersionReason = $this->checkParam('new_version_reason', '');
/*公司id*/
$companyId = getCompanyId();
$sourceId = $task->source_id;
/*调用创建新版本*/
event(new \App\Events\Report\Main\PushReportEvent($reportIdentify,$reportFirstReceivedDate,$reportDrugSafetyDate, $newVersionReason, $sourceId, $companyId));
return array_merge($this->results, [
'result' => true,
'message' => trans('code/report.task.newversion.store.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/report.task.newversion.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/app/Services/WorkflowService.php
<?php
namespace App\Services;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DataTables;
use Exception;
use DB;
use App\Repositories\Criterias\FilterCompanyIdCriteria;
use App\Repositories\Criterias\OrderBySortCriteria;
class WorkflowService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function index()
{
$html = $this->builder->columns([
// ['data' => 'id', 'name' => 'id', 'title' => 'Id'],
['data' => 'name', 'name' => 'name', 'title' => '名称'],
['data' => 'created_at', 'name' => 'created_at', 'title' => '创建时间'],
['data' => 'updated_at', 'name' => 'updated_at', 'title' => '修改时间'],
['data' => 'status', 'name' => 'status', 'title' => '是否有效'],
['data' => 'is_use', 'name' => 'is_use', 'title' => '是否默认'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false],
])
->ajax([
'url' => route('admin.workflow.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
public function datatables()
{
$companyId = getCompanyId();
$this->workflowRepo->pushCriteria(new FilterCompanyIdCriteria($companyId));
$data = $this->workflowRepo->all(['id', 'name', 'created_at', 'updated_at', 'status', 'is_use']);
return DataTables::of($data)
->editColumn('id', '{{$id_hash}}')
->editColumn('status', '{{ getCommonCheckShowValue($status, "有效", "无效") }}')
->editColumn('is_use', getThemeTemplate('back.system.workflow.is_use'))
->addColumn('action', getThemeTemplate('back.system.workflow.datatable'))
->make();
}
public function create()
{
/*通用验证*/
$commonChecks = getCommonCheck();
return [
'commonChecks' => $commonChecks,
];
}
public function edit($id)
{
try {
/*获取用户信息*/
$id = $this->workflowRepo->decodeId($id);
$workflow = $this->workflowRepo->find($id);
/*通用验证*/
$commonChecks = getCommonCheck();
return [
'workflow' => $workflow,
'commonChecks' => $commonChecks,
];
} catch (Exception $e) {
abort(404);
}
}
/**
* 保存
* @return [type] [description]
*/
public function store()
{
try {
$exception = DB::transaction(function() {
/*不允许直接设置company信息*/
$data = request()->except('company_id');
if($workflow = $this->workflowRepo->create($data)) {
/*抛出设置单位的事件*/
$companyId = getCompanyId();
event(new \App\Events\SetCompany($workflow, $companyId));
/*如果此工作是正常,则停用其他工作流*/
if($workflow->is_use == getCommonCheckValue(true)) {
/*停用此公司下所有工作流*/
$companyId = getCompanyId();
event(new \App\Events\Workflow\CloseWorkflow($companyId));
/*启用工作流*/
event(new \App\Events\Workflow\OpenWorkflow($companyId, $workflow->id));
}
} else {
throw new Exception(trans('code/workflow.store.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/workflow.store.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/workflow.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 修改保存
* @param [type] $id [description]
* @return [type] [description]
*/
public function update($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->workflowRepo->decodeId($id);
if( $workflow = $this->workflowRepo->update(request()->all(), $id) ) {
/*如果此工作是正常,则停用其他工作流*/
if($workflow->is_use == getCommonCheckValue(true)) {
/*停用此公司下所有工作流*/
$companyId = getCompanyId();
event(new \App\Events\Workflow\CloseWorkflow($companyId));
/*启用工作流*/
event(new \App\Events\Workflow\OpenWorkflow($companyId, $workflow->id));
}
} else {
throw new Exception(trans('code/workflow.update.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/workflow.update.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/workflow.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 删除用户
* @param [type] $id [description]
* @return [type] [description]
*/
public function destroy($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->workflowRepo->decodeId($id);
if( $workflow = $this->workflowRepo->delete($id) ){
} else {
throw new Exception(trans('code/workflow.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/workflow.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/workflow.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 工作流配置
* @return [type] [description]
*/
public function setting($id)
{
try {
$workflowId = $this->workflowRepo->decodeId($id);
$workflow = $this->workflowRepo->find($workflowId);
event(new \App\Events\Workflow\SetWorkflowId($workflow->id));
$companyId = getCompanyId();
$where = [
'workflow_id' => $workflow->id,
'company_id' => $companyId,
];
$this->workflowNodeRepo->pushCriteria(new OrderBySortCriteria('asc'));
$workflowNodes = $this->workflowNodeRepo->findWhere($where);
return [
'workflowIdHash' => $workflowId,
'workflowNodes' => $workflowNodes
];
} catch (Exception $e) {
abort(404);
}
}
/**
* 启用工作流
* @param [type] $id [description]
* @return [type] [description]
*/
public function open($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->workflowRepo->decodeId($id);
/*停用此公司下所有工作流*/
$companyId = getCompanyId();
event(new \App\Events\Workflow\CloseWorkflow($companyId));
/*启用工作流*/
event(new \App\Events\Workflow\OpenWorkflow($companyId, $id));
return array_merge($this->results, [
'result' => true,
'message' => trans('code/workflow.open.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/workflow.open.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/app/Repositories/Eloquents/SubdictionariesRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use App\Repositories\Models\Subdictionaries;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\SubdictionariesRepository;
use App\Repositories\Models\Subdictonaries;
use App\Repositories\Validators\SubdictonariesValidator;
/**
* Class SubdictonariesRepositoryEloquent
* @package namespace App\Repositories\Eloquents;
*/
class SubdictionariesRepositoryEloquent extends BaseRepository implements SubdictionariesRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Subdictionaries::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/config/back/datatables-cfg.php
<?php
return [
'basic' => [
'language' => [
'url' => '/vendor/datatables/lang/zh_CN.json',
],
'bStateSave' => true,
'pagingType' => "bootstrap_extended",
'autoWidth' => false,
'drawCallback' => 'function(){PVJs.tableInit.apply(this,arguments);}',
]
];<file_sep>/app/Http/Controllers/Back/Report/MainpageController.php
<?php
namespace App\Http\Controllers\Back\Report;
use App\Traits\DictionariesTrait;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use App\Traits\ModelTrait;
use App\Services\Report\MainpageService as Service;
use Illuminate\Validation\Rule;
class MainpageController extends Controller
{
use ControllerTrait;
use EncryptTrait;
use DictionariesTrait;
/*模板文件夹*/
protected $folder = 'back.report.mainpage';
protected $routePrefix = 'admin.report';
protected $encryptConnection = 'report';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index($source_id = '')
{
if(request()->ajax()) {
return $this->service->datatables($source_id);
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
/*新建查询*/
public function create()
{
$results = $this->service->create();
return response()->json($results);
}
/*复制查询*/
public function copy($id)
{
$results = $this->service->copyData($id);
return response()->json($results);
}
/*删除 修改状态*/
public function edit($id)
{
$results = $this->service->edit($id);
return response()->json($results);
}
/*查询*/
public function show($id)
{
return '';
}
/*新建版本*/
public function newreport($id)
{
$results = $this->service->newReport($id);
return response()->json($results);
}
}<file_sep>/app/Http/Controllers/Card/Index/LeftMeauController.php
<?php
namespace App\Http\Controllers\Card\Index;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class LeftMeauController extends Controller
{
public function index(){
// dd(13);
return view('themes.metronic.ocback.backstage.purchasing.left_meau');
}
}
<file_sep>/routes/oc_routes/backstage/p_index.php
<?php
$router->group(['prefix' => "backstage",'as' => 'backstage.'], function($router) {
// $router->get('p_index',function (){
// dd('123456');
// })->name('p_index');
$router->get('p_index',[
'uses' => 'LeftMeauController@index',
'as' => 'p_index'
]);
});
<file_sep>/app/Repositories/Eloquents/EnterpriseRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\enterpriseRepository;
use App\Repositories\Models\Enterprise;
use App\Repositories\Validators\EnterpriseValidator;
/**
* Class EnterpriseRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class EnterpriseRepositoryEloquent extends BaseRepository implements EnterpriseRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Enterprise::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/app/Repositories/Models/ReportTask.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use App\Traits\ModelTrait;
/**
* Class ReportTask.
*
* @package namespace App\Repositories\Models;
*/
class ReportTask extends Model implements Transformable
{
use TransformableTrait;
use ModelTrait;
protected $dates = [
'task_countdown', 'report_countdown', 'assigned_at', 'report_first_received_date'
];
/**
* The attributes that are mass assignable.
*
* @var arrayreport_complete_countdown
*/
protected $fillable = [
'report_id','report_identify','report_first_received_date', 'assigned_at', 'drug_name', 'first_drug_name', 'event_term', 'first_event_term','seriousness','standard_of_seriousness','case_causality','report_cate','task_user_id','task_user_name','organize_role_id','organize_role_name','received_from_id','status','source_id','task_countdown', 'report_countdown', 'regulation_id', 'data_insert_countdown', 'data_qc_countdown', 'medical_exam_countdown', 'medical_exam_qc_countdown', 'report_submit_countdown', 'report_complete_countdown', 'countdown_unit'
];
protected $appends = [
'id_hash', 'report_id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('reporttask', $this->id);
}
public function getReportIdHashAttribute()
{
return $this->encodeId('reportmainpage', $this->report_id);
}
}
<file_sep>/routes/oc_routes/purchasing/oil_binding.php
<?php
$router->group(['namespace'=>'Card\Purchasing'], function($router) {
$router->group(['prefix' => 'oil_binding', 'as' => 'oil_binding.'], function($router) {
$router->get('index', [
'uses' => 'OilCardBindingController@index',
'as' => 'index'
]);
$router->post('create', [
'uses' => 'OilCardBindingController@create',
'as' => 'create'
]);
});
});<file_sep>/resources/lang/en/code/user.php
<?php
return [
'store' => [
'fail' => '用户创建失败',
'success' => '用户创建成功',
],
'update' => [
'fail' => '用户修改失败',
'success' => '用户修改成功',
],
'destroy' => [
'fail' => '用户删除失败',
'success' => '用户删除成功',
],
'resetpass' => [
'fail' => '重置用户密码失败',
'success' => '重置用户密码成功',
],
'lock' => [
'fail' => '锁定用户失败',
'success' => '锁定用户成功',
],
'unlock' => [
'fail' => '解锁用户失败',
'success' => '解锁用户成功',
],
];<file_sep>/app/Repositories/Presenters/AttachmentModelPresenter.php
<?php
namespace App\Repositories\Presenters;
use App\Repositories\Transformers\AttachmentModelTransformer;
use Prettus\Repository\Presenter\FractalPresenter;
/**
* Class AttachmentModelPresenter.
*
* @package namespace App\Repositories\Presenters;
*/
class AttachmentModelPresenter extends FractalPresenter
{
/**
* Transformer
*
* @return \League\Fractal\TransformerAbstract
*/
public function getTransformer()
{
return new AttachmentModelTransformer();
}
}
<file_sep>/routes/routes/homepage/questioning.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'questioning', 'as' => 'questioning.'], function($router){
/*发送质疑页面*/
$router->get('{id}/open',[
'uses'=>'QuestioningController@open',
'as'=>'open',
]);
/*发送质疑*/
$router->post('create',[
'uses'=>'QuestioningController@create',
'as'=>'create',
]);
/*关闭质疑*/
$router->put('{id}/close',[
'uses'=>'QuestioningController@close',
'as'=>'close',
]);
/*查看tab详情页*/
$router->put('{id}/tabs', [
'uses' => 'QuestionController@tabs',
'as' => 'tabs'
]);
});
/*资源路由*/
$router->resource('questioning', 'QuestioningController');
//create show destroy
});<file_sep>/app/Services/DataTraceService.php
<?php
namespace App\Services;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DataTables;
use Exception;
use DB;
class DataTraceService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function index()
{
$html = $this->builder->columns([
['data' => 'report_identify', 'name' => 'report_identify', 'title' => '报告编号'],
['data' => 'report_tab_id', 'name' => 'report_tab_id', 'title' => '页'],
['data' => 'field', 'name' => 'field', 'title' => '字段', 'class' => 'text-center'],
['data' => 'old_value', 'name' => 'old_value', 'title' => '旧值'],
['data' => 'new_value', 'name' => 'new_value', 'title' => '新值'],
['data' => 'action_status', 'name' => 'action_status', 'title' => '操作状态'],
['data' => 'action_description', 'name' => 'action_description', 'title' => '操作说明'],
['data' => 'user_name', 'name' => 'user_name', 'title' => '操作人'],
['data' => 'user_role', 'name' => 'user_role', 'title' => '操作人角色'],
['data' => 'updated_at', 'name' => 'updated_at', 'title' => '操作时间'],
['data' => 'created_at', 'name' => 'created_at', 'title' => '创建时间'],
])
->ajax([
'url' => route('admin.datatrace.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
public function datatables()
{
$data = $this->dataTraceRepo->all(['report_identify', 'report_tab_id', 'field', 'old_value', 'new_value', 'action_status', 'action_description', 'user_name', 'user_role', 'updated_at', 'created_at']);
return DataTables::of($data)->make();
}
}<file_sep>/routes/routes/drug-library/route.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/17
* Time: 上午10:39
*/
$router->group(['namespace' => 'Back\DrugLibrary'], function($router) {
// 药品-上市前/上市后
require(__DIR__ . '/drug.php');
// 药品上市前
require(__DIR__ . '/pre-drug.php');
// 药品上市后
require(__DIR__ . '/post-drug.php');
});<file_sep>/app/Repositories/Eloquents/OilCardRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\OilCardRepository;
use App\Repositories\Models\OilCard;
use App\Repositories\Validators\OilCardValidator;
/**
* Class OilCardRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class OilCardRepositoryEloquent extends BaseRepository implements OilCardRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return OilCard::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/config/seeder/menu.php
<?php
return [
'structure' => [
'system' => [
'next' => [
'user' => [
'route' => 'admin.user.index',
'icon' => 'fa fa-user',
'permission' => 'manage-user',
'route_prefix' => 'admin.user',
],
'role' => [
'route' => 'admin.role.index',
'icon' => 'fa fa-user',
'permission' => 'manage-role',
'route_prefix' => 'admin.role',
],
'permission' => [
'route' => 'admin.permission.index',
'icon' => 'fa fa-user',
'permission' => 'manage-permission',
'route_prefix' => 'admin.permission',
],
'menu' => [
'route' => 'admin.menu.index',
'icon' => 'fa fa-user',
'permission' => 'manage-menu',
'route_prefix' => 'admin.menu',
],
'workflow' => [
'route' => 'admin.workflow.index',
'icon' => 'fa fa-user',
'permission' => 'manage-workflow',
'route_prefix' => 'admin.workflow',
],
/*字典管理*/
'dictionaries' => [
'route' => 'admin.dictionaries.index',
'icon' => 'fa fa-user',
'permission' => 'manage-workflow',
'route_prefix' => 'admin.dictionaries',
],
/*报告规则*/
'rule' => [
'route' => 'admin.rule.index',
'icon' => 'fa fa-user',
'permission' => 'manage-workflow',
'route_prefix' => '',
],
],
'icon' => 'fa fa-user',
'permission' => 'manage-system',
'route_prefix' => '',
],
'base' => [
'next' => [
'after' => [
'route' => 'admin.drug.index1',
'icon' => 'fa fa-user',
'permission' => 'manage-user',
'route_prefix' => 'admin.user',
],
'before' => [
'route' => 'admin.drug.index',
'icon' => 'fa fa-user',
'permission' => 'manage-role',
'route_prefix' => 'admin.role',
],
],
'icon' => 'fa fa-user',
'permission' => 'manage-system',
'route_prefix' => '',
],
/*系统首页*/
'index' => [
'next' => [
/*报告任务*/
'report-task' => [
'route' => 'admin.report.task.index',
'icon' => 'fa fa-user',
'permission' => 'manage-user',
'route_prefix' => 'admin.report.task',
],
'question-task' => [
'route' => 'admin.questioning.index',
'icon' => 'fa fa-user',
'permission' => 'manage-user',
'route_prefix' => '',
],
],
'icon' => 'fa fa-user',
'permission' => 'manage-system',
'route_prefix' => '',
],
'quality' => [
'next' => [
'question' => [
'route' => 'admin.question.index',
'icon' => 'fa fa-user',
'permission' => 'manage-user',
'route_prefix' => 'admin.question',
],
'datatrace' => [
'route' => 'admin.datatrace.index',
'icon' => 'fa fa-user',
'permission' => 'manage-user',
'route_prefix' => 'admin.datatrace',
],
],
'icon' => 'fa fa-user',
'permission' => 'manage-system',
'route_prefix' => '',
],
],
'maps' => [
'system' => '系统管理',
'user' => "用户管理",
'role' => '角色管理',
'permission' => '权限管理',
'menu' => '菜单管理',
'workflow' => '工作流管理',
'base' => '基础信息',
'after' => '药品信息-上市后',
'before' => '药品信息-上市前',
'index' => "系统首页",
'report-task' => "报告任务",
'dictionaries' => '字典管理',
'question-task' => '质疑任务',
'rule' => '报告规则',
'quality' => '质量管理',
'question' => "质疑管理",
'datatrace' => "稽查管理",
],
];<file_sep>/config/back/global.php
<?php
return [
/**
* 可选为 metronic
*/
'theme' => [
/**
* 主题文件夹
*/
'folder' => 'themes',
/**
* 主题名称
*/
'name' => 'metronic',
],
/**
* redis 配置
*/
'redis' => [
/**
* 前缀
*/
'prefix' => 'back:',
],
/**
* cache 配置
*/
'cache' => [
/**
* 前缀
*/
'prefix' => 'back_'
],
/*开关配置*/
'switch' => [
/*注册开关是否开启*/
'register' => true,
],
/*性别*/
'sex' => [
'value' => [
'1' => '男',
'2' => '女',
'3' => '其他'
],
'map' => [
'male' => '1',
'female' => '2',
'other' => '3',
]
],
/* 通用验证是否 */
'commoncheck' => [
'value' => [
'1' => '是',
'2' => "否"
],
'map' => [
'true' => 1,
'false' => 2,
]
],
/* 用于用户权限,文字对应 */
'module' => [
'value' => [
'user' => '用户',
'role' => '角色',
'permission' => '权限',
'menu' => '菜单',
],
],
/* 项目角色对应组织架构 */
'role_organize' => [
'value' => [
'1' => "资料管理员",
'2' => "数据录入员",
'3' => "数据质控QC",
'4' => "医学审评",
'5' => "医学审评QC",
'6' => "报告递交",
'7' => '企业管理员',
],
'map' => [
'source_manager' => 1,
'data_insert' => 2,
'data_qc' => 3,
'medical_exam' => 4,
'medical_exam_qc' => 5,
'report_submit' => 6,
'company_manager' => 7,
],
],
'report' => [
'tab' => [
'value' => [
'1' => "概览",
'2' => "基本信息",
'3' => "患者信息",
'4' => "药物信息",
'5' => "不良事件",
'6' => "报告评价",
'7' => "事件描述",
'8' => "问卷",
'9' => "附件信息",
],
'map' => [
'overview' => 1,
'basic' => 2,
'patient' => 3,
'drug' => 4,
'event' => 5,
'appraise' => 6,
'describe' => 7,
'question' => 8,
'attachment' => 9,
],
],
],
/*菜单位置*/
'menu_position' => [
'value' => [
'1' => '通用',
'2' => '后台',
'3' => '公司',
],
'map' => [
'all' => 1,
'admin' => 2,
'company' => 3,
],
],
];<file_sep>/app/Listeners/Regulation/UpdateListener.php
<?php
namespace App\Listeners\Regulation;
use App\Events\Regulation\Update;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repositories\Interfaces\ReportTaskRepository;
use App\Traits\Services\Report\TaskTrait;
class UpdateListener implements ShouldQueue
{
use InteractsWithQueue, TaskTrait;
/**
* The name of the connection the job should be sent to.
*
* @var string|null
*/
public $connection = 'beanstalkd';
/**
* The name of the queue the job should be sent to.
*
* @var string|null
*/
public $queue = 'high';
/**
* Create the event listener.
*
* @return void
*/
protected $reportTaskRepo;
public function __construct()
{
$this->reportTaskRepo = app(ReportTaskRepository::class);
}
/**
* Handle the event.
*
* @param Update $event
* @return void
*/
public function handle(Update $event)
{
/*报告规则模型*/
$model = $event->model;
$this->setRegulationBak($model);
/*获取报告任务*/
$reportTasks = $this->reportTaskRepo->findWhere($where);
$organizeMaps = array_flip(getRoleOrganizeMap());
/*报告任务不为空*/
if( $reportTasks->isNotEmpty() ) {
foreach($reportTasks as $reportTask) {
$this->setCountdown($reportTask, $organizeMaps);
}
}
}
}
<file_sep>/app/Repositories/Eloquents/AttachmentRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\AttachmentRepository;
use App\Repositories\Models\Attachment;
use App\Repositories\Validators\AttachmentValidator;
use App\Traits\EncryptTrait;
use Illuminate\Container\Container as Application;
/**
* Class AttachmentRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class AttachmentRepositoryEloquent extends BaseRepository implements AttachmentRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('attachment');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Attachment::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return AttachmentValidator::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/routes/oc_routes/backstage.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'backstage', 'as' => 'backstage.'], function($router) {
/*默认首页*/
require(__DIR__ . '/purchasing/c_recharge.php');
require(__DIR__ . '/purchasing/camilo.php');
require(__DIR__ . '/purchasing/d_recharge.php');
require(__DIR__ . '/purchasing/list.php');
require(__DIR__ . '/purchasing/oil_binding.php');
require(__DIR__ . '/purchasing/user_message.php');
require(__DIR__ . '/supplier/supplierlist.php');
require(__DIR__ . '/supplier/suppliercamilo.php');
require(__DIR__ . '/supplier/supplierdirectly.php');
});
});<file_sep>/app/Http/Controllers/Back/System/CategoryController.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/23
* Time: 下午3:52
*/
namespace App\Http\Controllers\Back\System;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\CategoryService as Service;
/**
* Class RegulationsController.
*
* @package namespace App\Http\Controllers;
*/
class CategoryController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.system.category';
protected $routePrefix = 'admin.cate';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index()
{
if (request()->ajax()) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
}<file_sep>/app/Repositories/Eloquents/RegulationRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use App\Traits\EncryptTrait;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\RegulationRepository;
use App\Repositories\Models\Regulation;
use App\Repositories\Validators\RegulationValidator;
use Illuminate\Container\Container as Application;
/**
* Class RegulationRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class RegulationRepositoryEloquent extends BaseRepository implements RegulationRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('regulation');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Regulation::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return RegulationValidator::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
public function getRegulationsBySeverity($companyId, $severity)
{
try{
$regulation = $this->model->companyId($companyId)->severity($severity)->first();
if(empty($regulation)) throw new \Exception(trans('code/regulation.show.fail'),2);
return $regulation;
}
catch (\Exception $e){
return false;
}
}
}
<file_sep>/config/hashids.php
<?php
/*
* This file is part of Laravel Hashids.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Default Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the connections below you wish to use as
| your default connection for all work. Of course, you may use many
| connections at once using the manager class.
|
*/
'default' => 'main',
/*
|--------------------------------------------------------------------------
| Hashids Connections
|--------------------------------------------------------------------------
|
| Here are each of the connections setup for your application. Example
| configuration has been included, but you may add as many connections as
| you would like.
|
*/
'connections' => [
'main' => [
'salt' => 'main',
'length' => '6',
],
'user' => [
'salt' => 'user',
'length' => '6',
],
'role' => [
'salt' => 'role',
'length' => '6',
],
'permission' => [
'salt' => 'permission',
'length' => '6',
],
'menu' => [
'salt' => 'menu',
'length' => '6',
],
'company' => [
'salt' => 'company',
'length' => '6',
],
'recursiverelation' => [
'salt' => 'recursiverelation',
'length' => '6',
],
'drug' => [
'salt' => 'drug',
'length' => '6',
],
'workflow' => [
'salt' => 'workflow',
'length' => '6',
],
'workflownode' => [
'salt' => 'workflownode',
'length' => '6',
],
'reportmainpage' => [
'salt' => 'reportmainpage',
'length' => '6',
],
'reporttask' => [
'salt' => 'reporttask',
'length' => '6',
],
'reporttab' => [
'salt' => 'reporttab',
'length' => '6',
],
'regulation' => [
'salt' => 'regulation',
'length' => '6',
],
'category' => [
'salt' => 'category',
'length' => '6',
],
'source' => [
'salt' => 'source',
'length' => '6',
],
/*附件*/
'attachment' => [
'salt' => 'attachment',
'length' => '6',
],
'logistics' => [
'salt' => 'logistics',
'length' => '6',
],
],
];
<file_sep>/app/Http/Controllers/Back/Report/Task/ReassignController.php
<?php
namespace App\Http\Controllers\Back\Report\Task;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use App\Services\Report\Task\ReassignService as Service;
class ReassignController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back.report.task.reassign';
protected $routePrefix = 'admin.report.task.reassign';
protected $encryptConnection = 'reporttask';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index($id)
{
$results = $this->service->index($id);
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
/**
* 报告任务重新分发
* @param [type] $id [description]
* @return [type] [description]
*/
public function store($id)
{
$results = $this->service->store($id);
return response()->json($results);
}
}
<file_sep>/app/Services/UserService.php
<?php
namespace App\Services;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DataTables;
use Exception;
use DB;
class UserService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function index()
{
$html = $this->builder->columns([
// ['data' => 'id', 'name' => 'id', 'title' => '用户ID'],
['data' => 'name', 'name' => 'name', 'title' => '用户名'],
['data' => 'email', 'name' => 'email', 'title' => '邮箱'],
['data' => 'status', 'name' => 'status', 'title' => '状态', 'class' => 'text-center'],
['data' => 'created_at', 'name' => 'created_at', 'title' => '创建时间'],
['data' => 'updated_at', 'name' => 'updated_at', 'title' => '修改时间'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false],
])
->ajax([
'url' => route('admin.user.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
public function datatables()
{
$data = $this->userRepo->all(['id', 'name', 'email', 'created_at', 'updated_at', 'status']);
return DataTables::of($data)
->editColumn('id', '{{$id_hash}}')
->editColumn('status', getThemeTemplate('back.system.user.listTag'))
->addColumn('action', getThemeTemplate('back.system.user.datatable'))
->make();
}
public function create()
{
/*角色*/
$roles = $this->roleRepo->all();
/*性别*/
$sexes = getSex();
/*单位*/
$companies = $this->companyRepo->all();
/*通用验证*/
$commonChecks = getCommonCheck();
return [
'roles' => $roles,
'sexes' => $sexes,
'companies' => $companies,
'commonChecks' => $commonChecks,
];
}
public function edit($id)
{
try {
/*获取用户信息*/
$id = $this->userRepo->decodeId($id);
$user = $this->userRepo->find($id);
/*用户选中角色*/
$userRoles = $user->roles->keyBy('id')->keys()->toArray();
/*所有角色*/
$roles = $this->roleRepo->all();
/*性别*/
$sexes = getSex();
/*单位*/
$companies = $this->companyRepo->all();
/*通用验证*/
$commonChecks = getCommonCheck();
return [
'user' => $user,
'roles' => $roles,
'userRoles' => $userRoles,
'sexes' => $sexes,
'companies' => $companies,
'commonChecks' => $commonChecks,
];
} catch (Exception $e) {
abort(404);
}
}
/**
* 保存
* @return [type] [description]
*/
public function store()
{
try {
$exception = DB::transaction(function() {
if($user = $this->userRepo->create(request()->all())) {
/*用户绑定角色*/
$roleIds = $this->checkParam('role', [], false);
$companyId = $this->checkParam('company', '', false);
event(new \App\Events\User\BindRole($user, $roleIds, $companyId));
/*设置密码*/
event(new \App\Events\User\SetPassword($user));
/*设置单位信息*/
event(new \App\Events\SetCompany($user, $companyId));
/*清除用户菜单缓存*/
event(new \App\Events\Menu\ClearUserMenuCache($user->id));
} else {
throw new Exception(trans('code/user.store.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/user.store.success')
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/user.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 修改保存
* @param [type] $id [description]
* @return [type] [description]
*/
public function update($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->userRepo->decodeId($id);
$data = request()->except(['password']);
if( $user = $this->userRepo->update(request()->all(), $id) ) {
/*用户绑定角色*/
$roleIds = $this->checkParam('role', [], false);
$companyId = $this->checkParam('company', '', false);
event(new \App\Events\User\BindRole($user, $roleIds, $companyId));
/*设置单位信息*/
event(new \App\Events\SetCompany($user, $companyId));
/*清除用户菜单缓存*/
event(new \App\Events\Menu\ClearUserMenuCache($user->id));
} else {
throw new Exception(trans('code/user.update.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/user.update.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/user.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 删除用户
* @param [type] $id [description]
* @return [type] [description]
*/
public function destroy($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->userRepo->decodeId($id);
if( $user = $this->userRepo->delete($id) ){
/*清除用户菜单缓存*/
event(new \App\Events\Menu\ClearUserMenuCache($id));
} else {
throw new Exception(trans('code/user.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/user.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/user.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 重置密码
* @return [type] [description]
*/
public function resetPass($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->userRepo->decodeId($id);
$user = $this->userRepo->find($id);
/*设置密码*/
event(new \App\Events\User\SetPassword($user));
return array_merge($this->results, [
'result' => true,
'message' => trans('code/user.resetpass.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/user.resetpass.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 锁定用户
* @param [type] $id [description]
* @return [type] [description]
*/
public function lock($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->userRepo->decodeId($id);
$user = $this->userRepo->find($id);
/*锁定用户*/
event(new \App\Events\User\Lock($user));
return array_merge($this->results, [
'result' => true,
'message' => trans('code/user.lock.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/user.lock.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 解锁用户
* @param [type] $id [description]
* @return [type] [description]
*/
public function unlock($id)
{
try {
$exception = DB::transaction(function() use ($id) {
$id = $this->userRepo->decodeId($id);
$user = $this->userRepo->find($id);
/*锁定用户*/
event(new \App\Events\User\Unlock($user));
return array_merge($this->results, [
'result' => true,
'message' => trans('code/user.unlock.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/user.unlock.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/app/Repositories/Models/WorkflowNode.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use App\Traits\ModelTrait;
class WorkflowNode extends Model implements Transformable
{
use TransformableTrait;
use ModelTrait;
protected $fillable = [
'company_id', 'workflow_id', 'name', 'en_name', 'is_message_notice', 'is_email_notice', 'organize_role_id', 'role_id', 'rule', 'description', 'sort'
];
protected $appends = [
'id_hash', 'role_id_hash',
];
public function getIdHashAttribute()
{
return $this->encodeId('workflownode', $this->id);
}
public function getRoleIdHashAttribute()
{
return $this->encodeId('role', $this->role_id);
}
public function role()
{
return $this->hasOne(\App\Role::class, 'id', 'role_id');
}
}
<file_sep>/app/Repositories/Models/Workflow.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use App\Traits\ModelTrait;
class Workflow extends Model implements Transformable
{
use TransformableTrait;
use ModelTrait;
protected $fillable = ['name', 'company_id', 'company_name', 'status', 'is_use'];
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('workflow', $this->id);
}
/**
* 获取工作流节点
* @return [type] [description]
*/
public function nodes()
{
return $this->hasMany(WorkflowNode::class, 'workflow_id', 'id')
->orderBy('sort', 'asc');
}
}
<file_sep>/app/Repositories/Models/Purchasing.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
/**
* Class Purchasing.
*
* @package namespace App\Repositories\Models;
*/
class Purchasing extends Model implements Transformable
{
use TransformableTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $table = 'purchasing';
protected $fillable = ['oc_number','name','card_number','user_id','status','province','province_id','order_type','number'];
}
<file_sep>/app/Repositories/Eloquents/SupervisionRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\SupervisionRepository;
use App\Repositories\Models\Supervision;
use App\Repositories\Validators\SupervisionValidator;
/**
* Class SupervisionRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class SupervisionRepositoryEloquent extends BaseRepository implements SupervisionRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Supervision::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return SupervisionValidator::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/app/Services/MailService.php
<?php
namespace App\Services;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DataTables;
use Exception;
use DB;
class MailService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
/*添加*/
public function create()
{
try {
$exception = DB::transaction(function() {
if( $info = $this->mailRepo->create(request()->all())){
} else {
throw new Exception(trans('code/mail.create.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/mail.create.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/mail.create.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/app/Http/Controllers/Back/DrugLibrary/PostDrugController.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/16
* Time: 上午11:06
*/
namespace App\Http\Controllers\Back\DrugLibrary;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\DrugLibraryService as Service;
use Illuminate\Validation\Rule;
class PostDrugController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.drug-library';
protected $routePrefix = 'admin.postdrug';
protected $routeHighLightPrefix = 'admin.postdrug';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* 上市后药品列表
* @return [type] [description]
*/
public function postIndex()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.postIndex'))->with($results);
}
}
/**
* 上市后药品信息创建
* @return [type] [description]
*/
public function postCreate()
{
$this->routeHighLightPrefix = 'admin.postdrug';
$info = $this->service->create();
return view(getThemeTemplate($this->folder . '.postCreate'))->with($info);
}
/**
* 修改药品信息
* @return [type] [description]
*/
public function postEdit()
{
$info = $this->service->edit(request('id'));
return view(getThemeTemplate($this->folder . '.postEdit'))->with($info);
}
/**
* 删除药品
* @return [type] [description]
*/
public function remove()
{
return $this->service->destroy(request('id'));
}
private function storeRules(){
$type = \request('type');
#上市前
if($type == 1){
return [
'common_zh_name' => 'required',
'common_en_name' => 'required',
'common_standard_name' => 'required',
'active_ingredients' => 'required',
'drug_class' => 'required',
'manufacturer' => 'required',
'formulation' => 'required',
];
}
#上市后
if($type == 2){
# TODO:: 原型上没有具体标,暂不处理
return [
'approval_number' => 'required',
'product_en_name' => 'required',
'product_zh_name' => 'required',
'common_zh_name' => 'required',
'common_en_name' => 'required',
'common_standard_name' => 'required',
'active_ingredients' => 'required',
'drug_class' => 'required',
'manufacturer' => 'required',
'formulation' => 'required',
];
}
}
private function updateRules(){
$type = \request('type');
#上市前
if($type == 1){
return [
'common_zh_name' => 'required',
'common_en_name' => 'required',
'common_standard_name' => 'required',
'active_ingredients' => 'required',
'drug_class' => 'required',
'manufacturer' => 'required',
'formulation' => 'required',
];
}
#上市后
if($type == 2){
# TODO:: 原型上没有具体标,暂不处理
return [
'approval_number' => 'required',
'product_en_name' => 'required',
'product_zh_name' => 'required',
'common_zh_name' => 'required',
'common_en_name' => 'required',
'common_standard_name' => 'required',
'active_ingredients' => 'required',
'drug_class' => 'required',
'manufacturer' => 'required',
'formulation' => 'required',
];
}
}
private function messages()
{
return [
'common_zh_name.required' => '通用中文名称不能为空',
'common_en_name.required' => '通用英文名称不能为空',
'common_standard_name.required' => '标准通用名称不能为空',
'active_ingredients.required' => '活性成份不能为空',
'drug_class.required' => '药品分类不能为空',
'manufacturer.required' => '生产厂家不能为空',
'formulation.required' => '剂型不能为空',
];
}
}<file_sep>/app/Services/DrugLibraryService.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/16
* Time: 上午11:35
*/
namespace App\Services;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use Exception;
use Yajra\DataTables\Html\Builder;
use Yajra\DataTables\DataTables;
use DB;
class DrugLibraryService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
protected $builder;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function store()
{
$data = request()->all();
$data['company_id'] = getCompanyId();
try {
$exception = DB::transaction(function () use ($data) {
if ($drug = $this->drugRepo->create($data)) {
# TODO:: exec other logic
} else {
throw new Exception(trans('code/drug.store.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/drug.store.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/drug.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function datatables()
{
$type = request()->type;
$model = $this->drugRepo->makeModel();
$model = $model->type($type);
$model = $model->status(1);
if($type == 2){
return DataTables::of($model)
->editColumn('drug_id', '{{ $id_hash }}')
->addColumn('action', getThemeTemplate('back.drug-library.pre-datatable'))
->make();
}else{
return DataTables::of($model)
->editColumn('drug_id', '{{ $id_hash }}')
->addColumn('action', getThemeTemplate('back.drug-library.post-datatable'))
->make();
}
}
public function index($type = 1)
{
if ($type == 1) { #上市前
$html = $this->builder->columns([
['data' => 'active_ingredients', 'name' => 'active_ingredients', 'title' => '活性成份'],
['data' => 'common_zh_name', 'name' => 'common_zh_name', 'title' => '通用名称'],
['data' => 'manufacturer', 'name' => 'manufacturer', 'title' => '生产厂家'],
['data' => 'formulation', 'name' => 'formulation', 'title' => '剂型'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false],
])
->ajax([
'url' => route('admin.predrug.index'),
'type' => 'GET',
'data'=> 'function(d) { d.type = '.$type.'; }',
])->parameters(config('back.datatables-cfg.basic'));
}
else{ #上市后
$html = $this->builder->columns([
['data' => 'product_en_name', 'name' => 'product_en_name', 'title' => '商品名称'],
['data' => 'common_zh_name', 'name' => 'common_zh_name', 'title' => '通用名称'],
['data' => 'approval_number', 'name' => 'approval_number', 'title' => '批号'],
['data' => 'drug_class', 'name' => 'drug_class', 'title' => '药品分类', 'class' => 'text-center'],
['data' => 'manufacturer', 'name' => 'manufacturer', 'title' => '生产厂家'],
['data' => 'is_import', 'name' => 'is_import', 'title' => '国产/进口'],
['data' => 'adverse_reactions', 'name' => 'adverse_reactions', 'title' => '不良反应'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false],
])
->ajax([
'url' => route('admin.postdrug.index'),
'type' => 'GET',
'data'=> 'function(d) { d.type = '.$type.'; }',
])->parameters(config('back.datatables-cfg.basic'));
}
return [
'html' => $html
];
}
public function create()
{
#药品分类
$drugClass = getDrugClass();
#进口 || 国产
$drugImport = drugImport();
#剂型
$formulation = formulation();
#给药企途径
$medicationWay = medicationWay();
#通用验证
$commonChecks = getCommonCheck();
return [
'drugClass' => $drugClass,
'drugImport' => $drugImport,
'formulation' => $formulation,
'medicationWay' => $medicationWay,
'commonChecks' => $commonChecks
];
}
public function edit($id)
{
try {
#获取某个药品
$id = $this->drugRepo->decodeId($id);
$drug = $this->drugRepo->find($id);
#药品分类
$drugClass = getDrugClass();
#进口 || 国产
$drugImport = drugImport();
#剂型
$formulation = formulation();
#给药企途径
$medicationWay = medicationWay();
#通用验证
$commonChecks = getCommonCheck();
return [
'drug' => $drug,
'drugClass' => $drugClass,
'drugImport' => $drugImport,
'formulation' => $formulation,
'medicationWay' => $medicationWay,
'commonChecks' => $commonChecks
];
} catch (Exception $e) {
abort(404);
}
}
/**
* 修改保存
* @param [type] $id [description]
* @return [type] [description]
*/
public function update($id)
{
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->drugRepo->decodeId($id);
$data = request()->all();
// $data = array(
// 'common_zh_name' => '头孢1',
// 'common_en_name' => 'toubao1',
// 'common_standard_name' => '头孢那什么',
// 'active_ingredients' => '当归',
// 'drug_class' => '1',
// 'manufacturer' => '上海拜耳制药',
// 'formulation' => '口服',
// 'type' => '1'
// );
if ($drug = $this->drugRepo->update($data, $id)) {
#TODO:: exec other logic
} else {
throw new Exception(trans('code/drug.update.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/drug.update.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/drug.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 删除药品
* @param [type] $id [description]
* @return [type] [description]
*/
public function destroy($id)
{
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->drugRepo->decodeId($id);
#删除
if ($drug = $this->drugRepo->update(['status' => 2], $id)) {
} else {
throw new Exception(trans('code/drug.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/drug.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/drug.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/app/Repositories/Models/Dictionaries.php
<?php
namespace App\Repositories\Models;
use Laratrust\Traits\LaratrustUserTrait;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
class Dictionaries extends Model implements Transformable
{
use TransformableTrait;
use LaratrustUserTrait;
use Notifiable;
// use TransformableTrait;
//关闭自动更新时间戳
public $timestamps = false;
protected $fillable = [
'serial','chinese','english','forpage','structure','dict_id','created_at','updated_at'
];
/*定义字典模型关系*/
public function data()
{
// dd(1);
return $this->hasMany('App\Repositories\Models\Subdictionaries','dict_id','id');
}
}
<file_sep>/database/seeds/ReportTabe.php
<?php
use Illuminate\Database\Seeder;
use App\Repositories\Models\ReportTab;
class ReportTabe extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->command->info('Truncating ReportTab tables');
$this->truncateTables();
$config = config('seeder.report.tab');
$this->createData($config);
}
private function createData($config)
{
foreach($config as $key => $value) {
ReportTab::create($value);
}
}
private function truncateTables()
{
Schema::disableForeignKeyConstraints();
ReportTab::truncate();
Schema::enableForeignKeyConstraints();
}
}
<file_sep>/app/Repositories/Models/Purchase.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
/**
* Class Purchase.
*
* @package namespace App\Repositories\Models;
*/
class Purchase extends Model implements Transformable
{
use TransformableTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $table = 'purchase';
protected $fillable = ['purchase_number','denomination','number','commodity','price','total_price','status'];
}
<file_sep>/app/Http/Controllers/Back/System/CompanyController.php
<?php
namespace App\Http\Controllers\Back\System;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\MenuService as Service;
class CompanyController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.system.company';
protected $routePrefix = 'admin.company';
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* 切换公司
* @param [type] $id [description]
* @return [type] [description]
*/
public function exchange($id)
{
// return view(getThemeTemplate($this->folder . '.exchange'));
return redirect()->route('admin.dash.index');
}
}
<file_sep>/app/Repositories/Interfaces/SubdictionariesRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface SubdictonariesRepository
* @package namespace App\Repositories\Interfaces;
*/
interface SubdictionariesRepository extends RepositoryInterface
{
//
}
<file_sep>/resources/lang/en/module/workflow.php
<?php
return [
'create' => [
'title' => '工作流添加',
'submit' => '添加',
'reset' => '重置',
],
'edit' => [
'title' => '工作流修改',
'submit' => '修改',
'reset' => '重置',
],
'index' => [
'create' => '添加',
'destroy' => [
'confirm' => '确定要删除吗?',
'fail' => '删除失败',
]
],
'node' => [
'create' => [
'title' => '工作流-节点属性-添加',
'submit' => '添加',
'reset' => '重置',
],
'edit' => [
'title' => '工作流-节点属性-修改',
'submit' => '修改',
'reset' => '重置',
],
],
];<file_sep>/app/Repositories/Interfaces/PlatformConfigRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface PlatformConfigRepository.
*
* @package namespace App\Repositories\Interfaces;
*/
interface PlatformConfigRepository extends RepositoryInterface
{
//
}
<file_sep>/app/Repositories/Eloquents/DictionariesRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\DictionariesRepository;
use App\Repositories\Models\Dictionaries;
use App\Repositories\Validators\DictionariesValidator;
/**
* Class DictionariesRepositoryEloquent
* @package namespace App\Repositories\Eloquents;
*/
class DictionariesRepositoryEloquent extends BaseRepository implements DictionariesRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Dictionaries::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
// public function datatables($data)
// {
// $diction = $this->model();
// $diction->add($data);
// return $diction;
// }
}
<file_sep>/routes/oc_routes/supplier/route.php
<?php
$router->group(['namespace'=>'Card\Supplier'], function($router) {
//采购商
// require(__DIR__.'/suppliercamilo.php');
});<file_sep>/app/Providers/EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
protected $subscribe = [
'App\Subscribes\UserEventSubscribe',
'App\Subscribes\RoleEventSubscribe',
'App\Subscribes\MenuEventSubscribe',
'App\Subscribes\WorkflowEventSubscribe',
'App\Subscribes\WorkflowNodeEventSubscribe',
'App\Subscribes\ReportTaskEventSubscribe',
'App\Subscribes\ReportValueEventSubscribe',
'App\Subscribes\DataTraceEventSubscribe',
];
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
/*清除缓存*/
'App\Events\FlushCache' => [
'App\Listeners\FlushCacheListener',
],
/*设置 数据表company_id, company_name*/
'App\Events\SetCompany' => [
'App\Listeners\SetCompanyListener',
],
/*修改报告任务中的报告规则*/
'App\Events\Regulation\Update' => [
'App\Listeners\Regulation\UpdateListener',
],
/*创建新版本*/
'App\Events\Report\Main\PushReportEvent'=>[
'App\Listeners\ReportEventListener',
],
/*修改报告任务冗余数据*/
'App\Events\Report\Task\SetRedundanceData' => [
'App\Listeners\Report\Task\SetRedundanceDataListener',
],
/*修改报告详情冗余数据*/
'App\Events\Report\Value\SetRedundanceData' => [
'App\Listeners\Report\Value\SetRedundanceDataListener',
],
/*修改报告主页面的冗余数据*/
'App\Events\Report\Value\SetReportMainData' => [
'App\Listeners\Report\Value\SetReportMainDataListener',
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
<file_sep>/app/Repositories/Eloquents/DrugLibraryRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use App\Traits\EncryptTrait;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\DrugLibraryRepository;
use App\Repositories\Models\DrugLibrary;
use App\Repositories\Validators\DrugLibraryValidator;
use Illuminate\Container\Container as Application;
/**
* Class DrugLibraryRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class DrugLibraryRepositoryEloquent extends BaseRepository implements DrugLibraryRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('drug');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return DrugLibrary::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/app/Services/OcService/OilCardBindingService.php
<?php
namespace App\Services\OcService;
use Yajra\DataTables\Html\Builder;
use App\Services\Service;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DB;
use DataTables;
class OilCardBindingService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function search($fields)
{
return $this->oilcardbindingRepo->findWhere($fields)->all();
}
public function create(){
$request = request()->except(['_token']);
$request['user_id'] = request()->user()->id;
$info = $this->oilcardbindingRepo->create($request);
}
}
<file_sep>/app/Traits/ServiceTrait.php
<?php
namespace App\Traits;
use Exception;
Trait ServiceTrait
{
public function index()
{
return [];
}
public function create()
{
return [];
}
public function store()
{
return [];
}
public function show($id)
{
return [];
}
public function edit($id)
{
return [];
}
public function update($id)
{
return [];
}
/**
* 验证产品并返回,默认不能为空
* @param [type] $key [description]
* @param [type] $default [description]
* @param boolean $bool [description]
* @return [type] [description]
*/
public function checkParam($key, $default, $bool = true)
{
$val = request($key);
if($bool) {
if(!$val) {
throw new Exception("参数不能为空", 2);
}
} else {
$val = $val ?: $default;
}
return $val;
}
public function checkParamValue($val, $default, $bool = true)
{
if($bool) {
if(!$val) {
throw new Exception("参数不能为空", 2);
}
} else {
$val = $val ?: $default;
}
return $val;
}
/**
* 获取请求中的参数的值
* @param array $fields [description]
* @return [type] [description]
*/
public function searchArray($fields=[])
{
$results = [];
if (is_array($fields)) {
foreach($fields as $field => $operator) {
if(request()->has($field) && $value = $this->checkParam($field, '', false)) {
$results[$field] = [$field, $operator, "%{$value}%"];
}
}
}
return $results;
}
//获取config里面配置的查询字段和结果表的字段
public function get_config_blade($arr){
//循环查询字段
if(!empty($arr['query'])){
foreach($arr['query'] as &$value){
//如果是select,匹配field里面的option
if($value['type'] == 'select'){
$url = 'oc.field.'.$value['name'];
$value['option'] = config($url);
}
}
}else{
$arr['query'] = '';
}
//返回
return $arr;
}
}<file_sep>/resources/lang/en/code/logistics.php
<?php
/**
* Created by PhpStorm.
* User: lvxinxin
* Date: 2018/02/06
* Email: <EMAIL>
*/
return [
'store' => [
'fail' => '上报信息创建失败',
'success' => '上报信息创建成功',
],
'update' => [
'fail' => '上报信息修改失败',
'success' => '上报信息修改成功',
],
'destroy' => [
'fail' => '上报信息删除失败',
'success' => '上报信息删除成功',
],
'sort' => [
'fail' => '上报信息排序失败',
'success' => '上报信息排序成功',
],
'recycling' => [
'fail' => '上报信息回收失败',
'success' => '上报信息回收成功',
],
];<file_sep>/app/Http/Controllers/Back/Quality/QuestionController.php
<?php
namespace App\Http\Controllers\Back\Quality;
use App\Events\Question\question;
use Illuminate\Http\Request;
use App\Traits\EncryptTrait;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Services\QuestionService as Service;
class QuestionController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back.quality.question';
/*路由*/
protected $routePrefix = 'admin.question';
protected $encryptConnection = 'question';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
$this->setEncryptConnection($this->encryptConnection);
}
/*展示页面*/
public function index()
{
if( request()->ajax() ) {
// dd(1);
return $this->service->datatables();
} else {
// dd(2);
return view(getThemeTemplate($this->folder . '.index'));
}
}
/*查看跳转到Tab*/
public function show($id)
{
return 'Tab页面'.$id;
}
}
<file_sep>/app/Listeners/ReportEventListener.php
<?php
namespace App\Listeners;
use App\Events\Report\Main\PushReportEvent;
use App\Repositories\Interfaces\ReportMainpageRepository;
use App\Repositories\Models\ReportMainpage;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Traits\Services\Report\MainTrait;
class ReportEventListener
{
use MainTrait;
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
}
/**
* Handle the event.
*
* @param PushReportEvent $event
* @return void
*/
public function handle(PushReportEvent $event)
{
//报告编号
$report_identifier = $event->report_identifier;
//接受报告时间
$report_first_received_date = $event->report_first_received_date;
//pv部门报告时间
$report_drug_safety_date = $event->report_drug_safety_date;
//创建新版本的原因
$create_version_cause = $event->create_version_cause;
/*当前单位id*/
$companyId = $event->companyId;
/*原始资料id*/
$sourceId = $event->sourceId;
/*获取用户*/
$user = getUser();
/*用户id*/
$user_id = $user->id;
/*用户所在的公司*/
$company = $user->company;
$company_id = $this->getReportCompanyId($report_identifier);
$report = $this->getReportValue($company,$user_id,$company_id,$report_first_received_date,$report_drug_safety_date,$create_version_cause);
$newReport = $this->createReportInformation($report);
/*更改报告任务数据*/
event(new \App\Events\Report\Task\UpdateData($newReport, $companyId, $sourceId));
/*复制报告详情数据*/
event(new \App\Events\Report\Value\Copy($report['id'], $newReport));
}
public function getReportCompanyId($report_identifier)
{
return app(ReportMainpageRepository::class)->findWhere(['report_identifier'=>$report_identifier])->pluck('company_id');
}
public function getReportValue($company,$user_id,$company_id,$report_first_received_date,$report_drug_safety_date,$create_version_cause)
{
//当前所有的编号
$reportSome = $this->getReportIdentifier($company_id);
foreach($reportSome as $key=>$item){
if(substr($item,0,strrpos($item,'-'))){
$id = app(ReportMainpageRepository::class)->findWhere(['report_identifier'=>$item])->first()->id;
} else {
$id = $key;
}
}
$company_now_id = $company->id;
$report = $this->getReportCommonAll($id);
$reportFinally = $this->finallyReportCheck($report,$user_id,$company_now_id,$report_first_received_date,$report_drug_safety_date,$create_version_cause);
return $reportFinally;
}
public function getReportIdentifier($company_id)
{
return app(ReportMainpageRepository::class)->findWhere(['company_id'=>$company_id])->pluck('report_identifier', 'id');
}
public function getReportCommonAll($id)
{
return app(ReportMainpageRepository::class)->find($id)->toArray();
}
public function finallyReportCheck($report,$user_id,$company_now_id,$report_first_received_date,$report_drug_safety_date,$create_version_cause)
{
//更新数据
$report['user_id'] = $user_id; /*用户*/
$versionName = $this->getEdition($report['report_identifier'],$company_now_id); /*版本编号*/
$report['report_identifier'] = $versionName;
$report['report_first_received_date'] = $report_first_received_date;/*报告时间*/
$report['report_drug_safety_date'] = $report_drug_safety_date;/*pv报告时间*/
$report['create_version_cause'] = $create_version_cause;/*创建原因*/
$report['report_identifier_status']=1;/*更新新增数据状态*/
return $report;
}
public function createReportInformation($report)
{
return app(ReportMainpageRepository::class)->create($report);
}
}
<file_sep>/app/Services/Report/ValueService.php
<?php
namespace App\Services\Report;
use App\Services\Service;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use App\Traits\QueueTrait;
use Exception;
use DB;
class ValueService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait, QueueTrait;
/*报告数据显示*/
public function index($reportId)
{
try {
$tabs = $this->reportTabRepo->all();
return [
'tabs' => $tabs,
'reportId' => $reportId,
'saveBtn' => $this->canSave($reportId),
];
} catch (Exception $e) {
abort(404);
}
}
/**
* 报告详情是否可以保存
* @return [type] [description]
*/
private function canSave($reportId)
{
/*获取报告数据*/
$reportId = $this->reportMainpageRepo->decodeId($reportId);
$report = $this->reportMainpageRepo->find($reportId);
/*获取当前用户*/
$user = getUser();
$roles = $user->roles;
/*报告状态*/
$reportStatus = $report->role_organize_status;
return checkRoleHasOrganizeRoleId($roles, $reportStatus) && $user->id == $report->user_id;
}
/**
* 获取数据html
* @return [type] [description]
*/
public function reportTabHtml($reportId, $reportTabId)
{
try {
/*获取公司*/
$companyId = getCompanyId();
/*获取报告id*/
$reportId = $this->reportMainpageRepo->decodeId($reportId);
/*获取报告tab的id*/
$reportTabId = $this->reportTabRepo->decodeId($reportTabId);
$where = [
'report_id' => $reportId,
'report_tab_id' => $reportTabId,
'company_id' => $companyId,
];
$datas = $this->reportValueRepo->findWhere($where);
$datas = $this->dealData($datas);
return [
'reportTabId' => $reportTabId,
'datas' => $datas,
];
} catch (Exception $e) {
abort(404);
}
}
/**
* 处理数据
* @return [type] [description]
*/
private function dealData($datas)
{
$results = [];
if($datas->isNotEmpty()) {
foreach($datas as $data) {
if($colDatas = $this->dealColData($results, $data)) {
$results = $colDatas;
continue;
}
if($tableDatas = $this->dealTableData($results,$data)) {
$results = $tableDatas;
continue;
}
$results['basic'][$data->name] = $data->value;
}
}
return $results;
}
/**
* 处理 tab 分类数据
* @param [type] $data [description]
* @return [type] [description]
*/
private function dealColData($results, $data)
{
if($data->col) {
if(!isset($results['col'][$data->col])) {
$results['col'][$data->col]['col_name'] = $data->col_name;
}
if($result = $this->dealTableData($results['col'][$data->col], $data)) {
$results['col'][$data->col]['tables'] = $result['tables'];
} else {
$results['col'][$data->col]['basic'][$data->name] = $data->value;
}
return $results;
}
return '';
}
private function dealTableData($results, $data)
{
if($data->is_table == getCommonCheckValue(true)) {
$results['tables'][$data->table_alias][$data->table_row_id][$data->name] = $data->value;
return $results;
}
return '';
}
/**
* 报告数据保存
* @return [type] [description]
*/
public function save($reportId, $reportTabId)
{
try {
$exception = DB::transaction(function() use ($reportId, $reportTabId){
if( !$this->canSave($reportId) ) {
throw new Exception(trans('code/report.value.save.nopermission'), 2);
}
/*获取公司*/
$companyId = getCompanyId();
/*获取报告id*/
$reportId = $this->reportMainpageRepo->decodeId($reportId);
/*获取报告tab的id*/
$reportTabId = $this->reportTabRepo->decodeId($reportTabId);
/*当前用户id*/
$userId = getUserId();
$valueWhere = [
'company_id' => $companyId,
'report_id' => $reportId,
'report_tab_id' => $reportTabId
];
$oldValues = $this->reportValueRepo->findWhere($valueWhere);
/*清除table数据*/
event(new \App\Events\Report\Value\ClearTableData($companyId, $reportId, $reportTabId));
/*tab的数据*/
$results = json_decode(request('tab'), true);
if($results && is_array($results)) {
/*保存数据*/
$this->saveData($results, $companyId, $reportId, $reportTabId);
/*推送报告任务冗余数据*/
$this->pushReportTaskRedundance($companyId, $reportId, $reportTabId, $results);
/*推送报告主页面冗余数据*/
$this->pushReportRedundance($companyId, $reportId, $reportTabId, $results);
/*推送报告详情冗余数据*/
$this->pushReportValueRedundance($companyId, $reportId, $reportTabId, $results);
}
$newValues = $this->reportValueRepo->findWhere($valueWhere);
// dd($newValues->toArray(), $oldValues->toArray());
$attributes = [
'company_id' => $companyId,
'report_tab_id' => $reportTabId
];
event(new \App\Events\DataTrace\ReportValueCreate($oldValues, $newValues, $attributes, $reportId, $userId));
return array_merge($this->results, [
'result' => true,
'message' => trans('code/report.value.save.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/report.value.save.fail')),
]);
}
return array_merge($this->results, $exception);
}
/**
* 推送报告任务冗余数据
* @param [type] $companyId [description]
* @param [type] $reportId [description]
* @param [type] $reportTabId [description]
* @param [type] $results [description]
* @return [type] [description]
*/
private function pushReportTaskRedundance($companyId, $reportId, $reportTabId, $results)
{
$reportTabMaps = getReportTab('map');
$reportTabMapsByKey = array_flip($reportTabMaps);
if( isset($reportTabMapsByKey[$reportTabId]) && $reportTabMapsByKey[$reportTabId]) {
/*tab的标识*/
$reportTabIdentify = $reportTabMapsByKey[$reportTabId];
/*有需要推送的字段*/
if( $fields = getReportTaskRedundanceField($reportTabIdentify) ) {
$redundanceData = $this->pushRedundance($companyId, $reportId, $reportTabId, $results, $fields);
/*推送报告任务冗余数据*/
$this->runSetReportTaskRedundanceData($companyId, $reportId, $redundanceData);
}
}
}
/**
* 推送报告冗余数据
* @param [type] $companyId [description]
* @param [type] $reportId [description]
* @param [type] $reportTabId [description]
* @param [type] $results [description]
* @return [type] [description]
*/
private function pushReportRedundance($companyId, $reportId, $reportTabId, $results)
{
$reportTabMaps = getReportTab('map');
$reportTabMapsByKey = array_flip($reportTabMaps);
if( isset($reportTabMapsByKey[$reportTabId]) && $reportTabMapsByKey[$reportTabId]) {
/*tab的标识*/
$reportTabIdentify = $reportTabMapsByKey[$reportTabId];
/*有需要推送的字段*/
if( $fields = getReportRedundanceField($reportTabIdentify) ) {
$redundanceData = $this->pushRedundance($companyId, $reportId, $reportTabId, $results, $fields);
/*推送报告主页面冗余数据*/
$this->runSetReportRedundanceData($companyId, $reportId, $redundanceData);
}
}
}
/**
* 推送报告详情冗余数据
* @param [type] $companyId [description]
* @param [type] $reportId [description]
* @param [type] $reportTabId [description]
* @param [type] $results [description]
* @return [type] [description]
*/
private function pushReportValueRedundance($companyId, $reportId, $reportTabId, $results)
{
$reportTabMaps = getReportTab('map');
$reportTabMapsByKey = array_flip($reportTabMaps);
if( isset($reportTabMapsByKey[$reportTabId]) && $reportTabMapsByKey[$reportTabId]) {
/*tab的标识*/
$reportTabIdentify = $reportTabMapsByKey[$reportTabId];
/*有需要推送的字段*/
if( $fields = getReportValueRedundanceField($reportTabIdentify) ) {
$redundanceData = $this->pushRedundance($companyId, $reportId, $reportTabId, $results, $fields);
/*推送报告详情冗余数据*/
event(new \App\Events\Report\Value\SetRedundanceData($companyId, $reportId, $redundanceData));
}
}
}
/**
* 推送冗余数据
* @param [type] $companyId [description]
* @param [type] $reportId [description]
* @param [type] $reportTabId [description]
* @param [type] $results [description]
* @return [type] [description]
*/
private function pushRedundance($companyId, $reportId, $reportTabId, $results, $fields)
{
$reportTabMaps = getReportTab('map');
$reportTabMapsByKey = array_flip($reportTabMaps);
if( isset($reportTabMapsByKey[$reportTabId]) && $reportTabMapsByKey[$reportTabId]) {
/*tab的标识*/
$reportTabIdentify = $reportTabMapsByKey[$reportTabId];
/*药物信息*/
$drug = getReportTabValue('drug');
/*不良*/
$event = getReportTabValue('event');
/*基础信息*/
$basic = getReportTabValue('basic');
/*冗余数据*/
$redundanceData = array_fill_keys(array_keys($fields), []);
/*判断*/
switch($reportTabId) {
case $basic :
/*获取首要数据*/
$curResult = current($results);
if( $datas = $curResult['data'] ) {
if( $tables = $datas['tables'] ) {
foreach($tables as $table) {
if( $values = $table['values']) {
foreach( $values as $value ) {
if( isset($value['primary_reporter'])) {
if( $value['primary_reporter'] == getCommonCheckValue(true) ) {
/*处理首要冗余数据*/
$redundanceData = $this->dealFirstRedundanceDataByArray($value, $fields, $redundanceData);
}
} else {
break;
}
}
}
}
}
}
break;
case $drug :
/*获取首要数据*/
$curResult = current($results);
/*处理首要冗余数据*/
$redundanceData = $this->dealFirstRedundanceData($curResult, $fields, $redundanceData);
break;
case $event :
/*获取首要数据*/
$curResult = current($results);
foreach($results as $result) {
if( $datas = $result['data'] ) {
$basicData = array_except($datas, ['tables']);
/*判断是否是首要报告*/
if( isset($basicData['initial_report']) && $basicData['initial_report'] == getCommonCheckValue(true)) {
$curResult = $result;
break;
}
}
}
/*处理首要冗余数据*/
$redundanceData = $this->dealFirstRedundanceData($curResult, $fields, $redundanceData);
break;
default :
break;
}
/*处理报告任务冗余数据*/
$redundanceData = $this->dealCommonRedundanceData($results, $fields, $redundanceData);
/*最后拼接处理报告任务数据*/
return array_map(function($arr){
return implode(',', $arr);
}, $redundanceData);
}
}
/**
* 处理冗余数据的首要数据
* @param [type] $result [description]
* @param [type] $fields [description]
* @param [type] $redundanceData [description]
* @return [type] [description]
*/
private function dealFirstRedundanceData($result, $fields, $redundanceData)
{
if( $datas = $result['data'] ) {
$basicData = array_except($datas, ['tables']);
// dd($basicData, $fields, $redundanceData);
$redundanceData = $this->dealFirstRedundanceDataByArray($basicData, $fields, $redundanceData);
}
return $redundanceData;
}
private function dealFirstRedundanceDataByArray($basicData, $fields, $redundanceData)
{
/*处理常规字段*/
foreach($fields as $field => $position) {
if( $position == 'first') {
if( isset($basicData[$field]) ) {
/*设置数据*/
$redundanceData[$field][] = $basicData[$field];
}
}
if( $position == 'table_first') {
if( isset($basicData[$field]) ) {
/*设置数据*/
$redundanceData[$field][] = $basicData[$field];
}
}
/*处理首页数据, 处理带有first_开头的数据*/
if(starts_with($field, 'first_')) {
$curField = str_replace('first_', '', $field);
if( isset($basicData[$curField]) ) {
/*设置数据*/
$redundanceData[$field][] = $basicData[$curField];
}
}
}
/*处理额外拼接字段*/
/*处理first_drug_name*/
if( in_array('first_drug_name', array_keys($fields)) ) {
$brandName = isset($basicData['brand_name']) && $basicData['brand_name'] ? $basicData['brand_name'] . '/' : '';
$genericName = isset($basicData['generic_name']) ? $basicData['generic_name'] : '';
$redundanceData['first_drug_name'][] = $brandName . $genericName;
}
return $redundanceData;
}
/**
* 处理冗余的常规数据
* @return [type] [description]
*/
private function dealCommonRedundanceData($results, $fields, $redundanceData)
{
/*处理常规字段信息*/
foreach($results as $result) {
/*获取提交的数据*/
if( $datas = $result['data'] ) {
$basicData = array_except($datas, ['tables']);
/*处理常规字段*/
foreach($fields as $field => $position) {
/*针对多列的数据*/
if( $position == 'first') {
continue;
}
if( isset($basicData[$field]) ) {
$redundanceData[$field][] = $basicData[$field];
}
}
/*处理额外拼接字段*/
/*处理drug_name*/
if( in_array('drug_name', array_keys($fields)) ) {
$brandName = isset($basicData['brand_name']) && $basicData['brand_name'] ? $basicData['brand_name'] . '/' : '';
$genericName = isset($basicData['generic_name']) ? $basicData['generic_name'] : '';
$redundanceData['drug_name'][] = $brandName . $genericName;
}
}
}
return $redundanceData;
}
/**
* 保存数据
* @param [type] $results [description]
* @return [type] [description]
*/
private function saveData($results, $companyId, $reportId, $reportTabId)
{
foreach($results as $result) {
$colId = $result['col_id'];
$colName = $result['col_name'] ?: '';
/*字段数据*/
$allData = $result['data'];
$tableData = $allData['tables'];
/*处理基础数据*/
$attributes = [
'company_id' => $companyId,
'report_id' => $reportId,
'report_tab_id' => $reportTabId,
'col' => $colId,
'deleted_at' => null,
];
$values = [
'col_name' => $colName,
];
/*处理所有数据*/
foreach($allData as $key => $info) {
/*处理表格数据*/
if($key == 'tables') {
$this->saveTableData($info, $attributes, $values);
continue;
}
/*处理基础数据*/
$this->saveBasicData($key, $info, $attributes, $values);
}
}
}
private function saveBasicData($key, $value, $attributes, $values)
{
$attributes = array_merge($attributes, [
'name' => $key,
'table_row_id' => 0,
]);
$values = array_merge($values, [
'value' => $value,
'is_table' => getCommonCheckValue(false),
'table_alias' => 0,
]);
$this->reportValueRepo->updateOrCreate($attributes, $values);
}
/*保存表格数据*/
private function saveTableData($tables, $attributes, $values)
{
if($tables) {
foreach($tables as $table) {
$tableId = $table['table_id'];
/*表格的数据*/
if($tableValues = $table['values']) {
foreach($tableValues as $row => $value) {
if($value && is_array($value)) {
foreach($value as $key => $val) {
/*处理基础数据*/
$attributes = array_merge($attributes, [
'name' => $key,
'table_row_id' => $row,
]);
$values = array_merge($values, [
'value' => $val,
'is_table' => getCommonCheckValue(true),
'table_alias' => $tableId,
]);
$this->reportValueRepo->updateOrCreate($attributes, $values);
}
}
}
}
}
}
}
}<file_sep>/app/Traits/EncryptTrait.php
<?php
namespace App\Traits;
use Hashids;
Trait EncryptTrait
{
private $HashidsConnection = 'main';
/**
* 设置 加密 链接
* @param
* @author <EMAIL>
* @date 2016-05-12 10:47:00
* @return
*/
public function setEncryptConnection($connection = 'main'){
$this->HashidsConnection = $connection;
}
public function getEncryptConnection(){
return $this->HashidsConnection;
}
/**
* 加密id
* @param
* @author <EMAIL>
* @date 2016-05-12 10:47:11
* @return
*/
public function encodeId($id){
// id无效直接返回
if(!$id) return $id;
if(checkEncrypt($this->getEncryptConnection())){
return Hashids::connection($this->getEncryptConnection())->encode($id);
}else{
return $id;
}
}
/**
* 解密id
* @param
* @author <EMAIL>
* @date 2016-05-12 10:47:16
* @return
*/
public function decodeId($id){
// id无效直接返回
if(!$id) return $id;
if(checkEncrypt($this->getEncryptConnection())){
$ids = Hashids::connection($this->getEncryptConnection())->decode($id);
if(isset($ids[0])){
return $ids[0];
}else{
if(!request()->ajax()){
throw new \Exception(trans('code/global.encrypt_fail'));
}else{
return response()->json([
'result' => false,
'message' => trans('code/global.encrypt_fail')
]);
}
}
}else{
return $id;
}
}
}<file_sep>/resources/lang/en/field/role.php
<?php
return [
'name' => [
'label' => '角色名称',
'name' => 'name',
'placeholder' => '请输入角色名称',
'rules' => [
'required' => '角色名称不能为空',
]
],
'display_name' => [
'label' => '角色显示名称',
'name' => 'display_name',
'placeholder' => '请输入角色显示名称',
'rules' => [
'required' => '角色显示名称不能为空',
]
],
'description' => [
'label' => '角色描述',
'name' => 'description',
'placeholder' => '请输入角色描述',
'rules' => [
'required' => '角色描述不能为空',
]
]
];<file_sep>/app/Http/Controllers/Card/AttachmentController.php
<?php
/**
* 附件控制器
* lt
*/
namespace App\Http\Controllers\Card;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use App\Services\OcService\AttachmentService as Service;
class AttachmentController extends Controller
{
use ControllerTrait;
use EncryptTrait;
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* 上传附件
* @return [type] [description]
*/
public function upload()
{
$results = $this->service->upload();
return response()->json($results);
}
/**
* 查看附件
* @param [type] $id [description]
* @return [type] [description]
*/
public function show($id)
{
$results = $this->service->show($id);
return response()->file($results);
}
}
<file_sep>/app/Repositories/Presenters/DataTracePresenter.php
<?php
namespace App\Repositories\Presenters;
use App\Repositories\Transformers\DataTraceTransformer;
use Prettus\Repository\Presenter\FractalPresenter;
/**
* Class DataTracePresenter.
*
* @package namespace App\Repositories\Presenters;
*/
class DataTracePresenter extends FractalPresenter
{
/**
* Transformer
*
* @return \League\Fractal\TransformerAbstract
*/
public function getTransformer()
{
return new DataTraceTransformer();
}
}
<file_sep>/app/Services/SubdictionariesService.php
<?php
namespace App\Services;
use App\Services\Service as BasicService;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DataTables;
use Exception;
use DB;
Class SubdictionariesService extends BasicService{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function index()
{
$html = $this->builder->columns([
['data' => 'id', 'name' => 'id', 'title' => 'Id'],
['data' => 'sub_chinese', 'name' => 'sub_chinese', 'title' => 'Sub_chinese'],
['data' => 'sub_english', 'name' => 'sub_english', 'title' => 'Sub_english'],
['data' => 'dict_id', 'name' => 'dict_id', 'title' => 'Dict_id'],
['data' => 'e_name', 'name' => 'e_name', 'title' => 'E_name'],
['data' => 'e_formate', 'name' => 'e_formate', 'title' => 'E_formate'],
['data' => 'is_desc', 'name' => 'is_desc', 'title' => 'Is_desc'],
['data' => 'created_at', 'name' => 'created_at', 'title' => 'Created At'],
['data' => 'updated_at', 'name' => 'updated_at', 'title' => 'Updated At'],
['data' => 'action', 'name' => 'action', 'title' => 'action', 'class' => 'text-center', 'sorting' => false],
])
->ajax([
'url' => route('admin.Subdictionaries.index'),
'type' => 'GET',
]);
return [
'html' => $html
];
}
public function datatables()
{
$data = $this->subdictionariesRepo->all(['id','is_desc', 'sub_chinese', 'sub_english', 'created_at', 'updated_at']);
return DataTables::of($data)
->editColumn('id', '{{$id_hash}}')
->addColumn('action', getThemeTemplate('back.system.subdictionaries.datatable'))
->make();
}
}<file_sep>/app/Services/RegulationService.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/18
* Time: 下午7:17
*/
namespace App\Services;
use App\Traits\QueueTrait;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use Exception;
use Yajra\DataTables\Html\Builder;
use Yajra\DataTables\DataTables;
use DB;
class RegulationService extends Service
{
use ServiceTrait,ResultTrait,ExceptionTrait,QueueTrait;
protected $builder;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function store()
{
$data = request()->all();
$data['company_id'] = getCompanyId() ;
try {
$exception = DB::transaction(function () use ($data) {
if ($regulation = $this->regulaRepo->create($data)) {
# TODO:: exec other logic
} else {
throw new Exception(trans('code/regulation.store.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/regulation.store.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/regulation.store.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function datatables()
{
$model = $this->regulaRepo->makeModel();
$model = $model->status(1);
return DataTables::of($model)
->editColumn('id', '{{ $id_hash }}')
->addColumn('action', getThemeTemplate('back.system.regulation.datatable'))
->make();
}
public function index()
{
//dd($this->regulaRepo->getRegulationsBySeverity(0,1));
$html = $this->builder->columns([
['data' => 'title', 'name' => 'title', 'title' => '规则名称'],
['data' => 'severity', 'name' => 'severity', 'title' => '严重性'],
['data' => 'priority', 'name' => 'priority', 'title' => '优先级'],
['data' => 'updated_at', 'name' => 'updated_at', 'title' => '修改时间'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false],
])
->ajax([
'url' => route('admin.rule.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
public function create()
{
#严重性
$severity = severity();
return [
'severity' => $severity,
];
}
public function edit($id)
{
try {
#获取某个规则
$id = $this->regulaRepo->decodeId($id);
$regulation = $this->regulaRepo->find($id);
#严重性
$severity = severity();
return [
'regulation' => $regulation,
'severity' => $severity,
];
} catch (Exception $e) {
abort(404);
}
}
public function update($id)
{
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->regulaRepo->decodeId($id);
$data = request()->all();
if ($regulation = $this->regulaRepo->update($data, $id)) {
#TODO::修改规则,要更新当前规则下的报告
#$this->runRugulationUpdate($regulation);
} else {
throw new Exception(trans('code/regulation.update.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/regulation.update.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/regulation.update.fail')),
]);
}
return array_merge($this->results, $exception);
}
public function destroy($id)
{
try {
$exception = DB::transaction(function () use ($id) {
$id = $this->regulaRepo->decodeId($id);
#删除
if ($regulation = $this->regulaRepo->update(['status' => 2], $id)) {
#TODO:: 删除规则时,要判断下该规则下的报告,否则,禁止删除
} else {
throw new Exception(trans('code/regulation.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/regulation.destroy.success'),
]);
});
} catch (Exception $e) {
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/regulation.destroy.fail')),
]);
}
return array_merge($this->results, $exception);
}
}<file_sep>/app/Repositories/Models/DataTrace.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
/**
* Class DataTrace.
*
* @package namespace App\Repositories\Models;
*/
class DataTrace extends Model implements Transformable
{
use TransformableTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'company_id', 'report_id', 'report_identify', 'report_tab_id', 'field', 'old_value', 'new_value', 'action_status', 'action_description', 'user_id', 'user_name', 'user_role',
];
}
<file_sep>/routes/routes/systems/dictionaries.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'dictionaries', 'as' => 'dictionaries.'], function($router){
$router->get('search/{page?}/{keyword?}',[
'uses'=>'DictionariesController@search',
'as'=>'search',
]);
$router->get('subup/{id}',[
'uses'=>'DictionariesController@fieldUp',
'as'=>'subup'
]);
$router->post('create',[
'uses'=>'DictionariesController@create',
'as'=>'create',
]);
$router->get('hasmanydictionaries',[
'uses'=>'DictionariesController@hasmanydictionaries',
'as'=>'hasManyDictionaries',
]);
});
//资源控制器
$router->resource('dictionaries', 'DictionariesController');
});
?><file_sep>/app/Repositories/Eloquents/SourceRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use App\Traits\EncryptTrait;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\SourceRepository;
use App\Repositories\Models\Source;
use App\Repositories\Validators\SourceValidator;
use Illuminate\Container\Container as Application;
/**
* Class SourceRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class SourceRepositoryEloquent extends BaseRepository implements SourceRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('source');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Source::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return SourceValidator::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/app/Http/Controllers/Back/Quality/DataTraceController.php
<?php
/**
* 稽查管理
* hsky
* 2018-1-26
*/
namespace App\Http\Controllers\Back\Quality;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use App\Traits\EncryptTrait;
use App\Services\DataTraceService as Service;
use Illuminate\Validation\Rule;
class DataTraceController extends Controller
{
use ControllerTrait;
use EncryptTrait;
/*模板文件夹*/
protected $folder = 'back.quality.datatrace';
protected $routePrefix = 'admin.datatrace';
protected $encryptConnection = 'datatrace';
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
$this->setEncryptConnection($this->encryptConnection);
}
/**
* 稽查管理
* @return [type] [description]
*/
public function index()
{
if( request()->ajax() ) {
return $this->service->datatables();
} else {
$results = $this->service->index();
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
}
}
<file_sep>/app/Repositories/Eloquents/CompanyRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\CompanyRepository;
use App\Company;
use App\Repositories\Validators\CompanyValidator;
use App\Traits\EncryptTrait;
use Illuminate\Container\Container as Application;
/**
* Class TeamRepositoryEloquent
* @package namespace App\Repositories\Eloquents;
*/
class CompanyRepositoryEloquent extends BaseRepository implements CompanyRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('company');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Company::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return CompanyValidator::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/routes/routes/basic/enterprise.php
<?php
$router->group(['prefix' => 'basic', 'as' => 'basic.'], function($router) {
$router->group(['prefix' => 'enterprise', 'as' => 'enterprise.'], function ($router) {
/*列表*/
$router->get('index',[
'uses'=>'EnterpriseController@index',
'as'=>'index',
]);
});
$router->resource('enterprise','EnterpriseController');
});<file_sep>/app/Http/Controllers/Card/Index/BackstageController.php
<?php
namespace App\Http\Controllers\Card\Index;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class BackstageController extends Controller
{
public function index(){
return view('themes.metronic.ocback.backstage.index.backstage');
}
}
<file_sep>/app/Company.php
<?php
namespace App;
use Laratrust\Models\LaratrustTeam;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use App\Traits\ModelTrait;
class Company extends LaratrustTeam implements Transformable
{
use TransformableTrait;
use ModelTrait;
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('company', $this->id);
}
}
<file_sep>/app/Http/Controllers/Auth/RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'truename' => 'required|string|max:255',
'sex' => 'required|string|max:255',
// 'city' => 'required|string|max:255',
// 'mobile' => 'required|string|max:255',
// 'qq_num' => 'required|string|max:255',
// 'bank' => 'required|string|max:255',
// 'bank_name' => 'required|string|max:255',
// 'open_bank' => 'required|string|max:255',
// 'identity' => 'required|string|max:255',
// 'is_check_email' => 'required|string|max:255',
// 'company_name' => 'required|string|max:255',
// 'company_id' => 'required|string|max:255',
// 'referee_id' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => '<PASSWORD>',
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'truename' => $data['truename'],
'sex' => $data['sex'],
// 'city' => $data['city'],
// 'mobile' => $data['mobile'],
// 'qq_num' => $data['qq_num'],
// 'bank' => $data['bank'],
// 'bank_name' => $data['bank_name'],
// 'open_bank' => $data['open_bank'],
// 'identity' => $data['identity'],
// 'is_check_email' => $data['is_check_email'],
// 'company_name' => $data['company_name'],
// 'company_id' => $data['company_id'],
// 'referee_id' => $data['referee_id'],
'email' => $data['email'],
'password' => <PASSWORD>($data['<PASSWORD>']),
]);
}
}
<file_sep>/resources/lang/en/code/quality.php
<?php
return [
'datatrace' => [],
];<file_sep>/app/Repositories/Models/Attachment.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Attachment.
*
* @package namespace App\Repositories\Models;
*/
class Attachment extends Model implements Transformable
{
use TransformableTrait;
use SoftDeletes;
use ModelTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'origin_name', 'file_size', 'path', 'file_ext', 'ext_info', 'status', 'user_id', 'user_name',
];
public function getIdHashAttribute()
{
return $this->encodeId('attachment', $this->id);
}
}
<file_sep>/app/Repositories/Interfaces/WorkflowNodeRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface WorkflowNodeRepository
* @package namespace App\Repositories\Interfaces;
*/
interface WorkflowNodeRepository extends RepositoryInterface
{
//
}
<file_sep>/app/Repositories/Models/Subdictionaries.php
<?php
namespace App\Repositories\Models;
use Laratrust\Traits\LaratrustUserTrait;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
class Subdictionaries extends Model implements Transformable
{
protected $table = 'subdictionaries';
use TransformableTrait;
use LaratrustUserTrait;
use Notifiable;
// use TransformableTrait;
//关闭自动更新时间戳
public $timestamps = false;
protected $fillable = ['sub_chinese','sub_english','dict_id','e_formate','e_name','created_at','updated_at'];
}
<file_sep>/app/Subscribes/WorkflowEventSubscribe.php
<?php
namespace App\Subscribes;
use App\Repositories\Interfaces\WorkflowRepository;
class WorkflowEventSubscribe
{
/**
* 锁定用户
* @param [type] $event [description]
* @return [type] [description]
*/
public function onSetWorkflowId($event)
{
$workflowId = $event->workflowId;
session(['workflow_id' => $workflowId]);
}
/**
* 停用工作流
* @param [type] $event [description]
* @return [type] [description]
*/
public function onCloseWorkflow($event)
{
$companyId = $event->companyId;
app(WorkflowRepository::class)->closeWorkflow($companyId);
}
/**
* 启用工作流
* @param [type] $event [description]
* @return [type] [description]
*/
public function onOpenWorkflow($event)
{
$companyId = $event->companyId;
$workflowId = $event->workflowId;
app(WorkflowRepository::class)->openWorkflow($companyId, $workflowId);
}
public function subscribe($events)
{
/*设置workflowId*/
$events->listen(
'App\Events\Workflow\SetWorkflowId',
'App\Subscribes\WorkflowEventSubscribe@onSetWorkflowId'
);
/*停用工作流*/
$events->listen(
'App\Events\Workflow\CloseWorkflow',
'App\Subscribes\WorkflowEventSubscribe@onCloseWorkflow'
);
/*启用工作流*/
$events->listen(
'App\Events\Workflow\OpenWorkflow',
'App\Subscribes\WorkflowEventSubscribe@onOpenWorkflow'
);
}
}
<file_sep>/app/Repositories/Models/Questioning.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
class Questioning extends Model implements Transformable
{
use TransformableTrait;
public $timestamps = false;
protected $table = 'send_information';
protected $fillable = ['question_id','end_date','status','content','email','email_theme','phone:_number','express','ems_express','sending'];
}
<file_sep>/routes/routes/homepage/route.php
<?php
$router->group(['namespace' => 'Back\Homepage'], function($router) {
/*报告任务*/
// require(__DIR__.'/Presentation.php');
/*质疑任务*/
require(__DIR__ . '/questioning.php');
});
<file_sep>/app/Repositories/Eloquents/WorkflowNodeRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\WorkflowNodeRepository;
use App\Repositories\Models\WorkflowNode;
use App\Repositories\Validators\WorkflowNodeValidator;
use App\Traits\EncryptTrait;
use Illuminate\Container\Container as Application;
/**
* Class WorkflowNodeRepositoryEloquent
* @package namespace App\Repositories\Eloquents;
*/
class WorkflowNodeRepositoryEloquent extends BaseRepository implements WorkflowNodeRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('workflownode');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return WorkflowNode::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return WorkflowNodeValidator::class;
}
/**
* 工作流节点中,自动递增sort
* @param [type] $workflowId [description]
* @param [type] $sort [description]
* @return [type] [description]
*/
public function incrementLargerSort($workflowId, $sort)
{
$results = $this->model
->where('workflow_id', $workflowId)
->where('sort', '>', $sort)
->increment('sort', 1);
$this->resetModel();
return $results;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/app/Subscribes/DataTraceEventSubscribe.php
<?php
namespace App\Subscribes;
use App\Repositories\Interfaces\DataTraceRepository;
use App\Repositories\Interfaces\ReportMainpageRepository;
use App\Repositories\Interfaces\UserRepository;
class DataTraceEventSubscribe
{
/**
* 添加稽查数据
* @param [type] $event [description]
* @return [type] [description]
*/
public function onReportValueCreate($event)
{
$oldValues = $event->oldValues;
$newValues = $event->newValues;
$attributes = $event->attributes;
$reportId = $event->reportId;
$userId = $event->userId;
/*获取报告对象*/
$report = app(ReportMainpageRepository::class)->find($reportId);
/*获取用户对象*/
$user = app(UserRepository::class)->find($userId);
/*老数据*/
$oldValues = $this->mapGroupValues($oldValues);
/*新数据*/
$newValues = $this->mapGroupValues($newValues);
/*删除数据对象*/
$deleteValues = [];
/*处理修改数据--痕迹*/
foreach($oldValues as $oldKey => $oldValue) {
if( isset($newValues[$oldKey]) && $tempNewValue=$newValues[$oldKey] ) {
if( $tempNewValue['value'] != $oldValue['value'] ) {
/*痕迹管理--修改*/
$data = array_merge($attributes, [
'field' => $oldValue['name'],
'old_value' => $oldValue['value'],
'new_value' => $tempNewValue['value'],
'action_status' => '修改',
]);
$this->createTrace($data, $report, $user);
}
unset($newValues[$oldKey]);
} else {
/*数据点被删除*/
$deleteValues[$oldKey] = $oldValue;
}
}
/*处理新加数据--痕迹*/
foreach( $newValues as $newValue ) {
/*痕迹管理 -- 增加*/
$data = array_merge($attributes, [
'field' => $newValue['name'],
'old_value' => '',
'new_value' => $newValue['value'],
'action_status' => '增加',
]);
$this->createTrace($data, $report, $user);
}
/*处理删除数据--痕迹*/
foreach( $deleteValues as $deleteValue ) {
/*痕迹管理 -- 删除*/
$data = array_merge($attributes, [
'field' => $newValue['name'],
'old_value' => $deleteValue['value'],
'new_value' => '',
'action_status' => '删除',
]);
$this->createTrace($data, $report, $user);
}
}
private function mapGroupValues($values)
{
return $values->mapWithKeys(function($item, $key) {
$key = $item['report_id'] . $item['report_tab_id'] . $item['col'] . $item['table_alias'] . $item['table_row_id'] . $item['name'];
return [
$key => $item,
];
})->toArray();
}
/**
* 创建事件稽查数据
* @param [type] $event [description]
* @return [type] [description]
*/
public function onEventCreate($event)
{
$attributes = $event->attributes;
$user = $event->user;
$report = $event->report;
/*痕迹管理--修改*/
$attributes = array_merge($attributes, [
'user_id' => $user->id,
'user_name' => $user->name,
'user_role' => $report->role_organize_status,
'report_id' => $report->id,
'report_identify' => $report->report_identifier,
]);
return app(DataTraceRepository::class)->create($attributes);
}
/**
* 添加痕迹管理数据
* @param [type] $attributes [description]
* @param [type] $report [description]
* @param [type] $user [description]
* @return [type] [description]
*/
private function createTrace($attributes, $report, $user)
{
/*痕迹管理--修改*/
$attributes = array_merge($attributes, [
'user_id' => $user->id,
'user_name' => $user->name,
'user_role' => $report->role_organize_status,
'report_id' => $report->id,
'report_identify' => $report->report_identifier,
]);
return app(DataTraceRepository::class)->create($attributes);
}
public function subscribe($events)
{
/*创建数据稽查数据*/
$events->listen(
'App\Events\DataTrace\ReportValueCreate',
'App\Subscribes\DataTraceEventSubscribe@onReportValueCreate'
);
/*创建事件稽查数据*/
$events->listen(
'App\Events\DataTrace\EventCreate',
'App\Subscribes\DataTraceEventSubscribe@onEventCreate'
);
}
}
<file_sep>/app/Repositories/Models/Source.php
<?php
namespace App\Repositories\Models;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use Illuminate\Database\Eloquent\Builder;
/**
* Class Source.
*
* @package namespace App\Repositories\Models;
*/
class Source extends Model implements Transformable
{
use TransformableTrait,ModelTrait;
protected $dates = [
'accept_report_date'
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'accept_report_date',
'solution_number',
'file_class',
'file_source',
'remark',
'issue',
'status',
'creator_uuid',
'creator_name',
];
protected static function boot()
{
parent::boot(); // TODO: Change the autogenerated stub
static::creating(function(Source $source){
$source->creator_uuid = auth()->id();
$source->creator_name = auth()->user()->name;
});
}
protected $table = 'source';
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('source', $this->id);
}
/**
* 获取附件
* @return [type] [description]
*/
public function attachments()
{
return $this->morphToMany(Attachment::class, 'attachment_model');
}
public function ScopeStatus(Builder $builder, $status, $not_in = false)
{
if (is_array($status)) {
if ($not_in) {
return $builder->whereNotIn('status', $status);
}
return $builder->whereIn('status', $status);
} else {
if ($not_in) {
return $builder->where('status', '<>', $status);
}
return $builder->where('status', $status);
}
}
public function ScopeIssue(Builder $builder,$issue,$not_in = false)
{
if (is_array($issue)) {
if ($not_in) {
return $builder->whereNotIn('issue', $issue);
}
return $builder->whereIn('issue', $issue);
} else {
if ($not_in) {
return $builder->where('issue', '<>', $issue);
}
return $builder->where('issue', $issue);
}
}
}
<file_sep>/resources/lang/en/code/category.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/23
* Time: 下午4:32
*/
return [
'store' => [
'fail' => '分类创建失败',
'success' => '分类创建成功',
],
'update' => [
'fail' => '分类修改失败',
'success' => '分类修改成功',
],
'destroy' => [
'fail' => '分类删除失败',
'success' => '分类删除成功',
],
'sort' => [
'fail' => '分类排序失败',
'success' => '分类排序成功',
],
];<file_sep>/app/Repositories/Eloquents/PurchasingRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\PurchasingRepository;
use App\Repositories\Models\Purchasing;
use App\Repositories\Validators\PurchasingValidator;
/**
* Class PurchasingRepositoryEloquent.
*
* @package namespace App\Repositories\Eloquents;
*/
class PurchasingRepositoryEloquent extends BaseRepository implements PurchasingRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Purchasing::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/config/back/encrypt.php
<?php
return [
'default' => true,
'user' => true,
'role' => true,
'permission' => true,
'menu' => true,
'workflow' => true,
'workflownode' => true,
'company' => true,
'drug' => true,
'regulation' => true,
'category' => true,
'source' => false,
'reporttask' => false,
'reportmainpage' => false,
'reporttab' => false,
'attachment' => true,
'logistics' => true,
];<file_sep>/routes/routes/report/logistics.php
<?php
/**
* Created by PhpStorm.
* User: lvxinxin
* Date: 2018/02/05
* Email: <EMAIL>
*/
$router->group([], function($router) {
$router->group(['prefix' => 'logistics', 'as' => 'logistics.'], function($router) {
#物流列表
$router->get('lists/{id}', [
'uses' => 'LogisticsController@lists',
'as' => "lists"
]);
#其它形式的上报
$router->match(['get','post'],'other/{id}', [
'uses' => 'SupervisionsController@other',
'as' => "other"
]);
#无需上报
$router->post('no-need/{id}', [
'uses' => 'SupervisionsController@noNeed',
'as' => "no-need"
]);
});
$router->resource('logistics', 'LogisticsController');
});<file_sep>/resources/lang/en/module/permission.php
<?php
return [
'create' => [
'title' => '权限添加',
'submit' => '添加',
'reset' => '重置',
],
'edit' => [
'title' => '权限修改',
'submit' => '修改',
'reset' => '重置',
],
'index' => [
'create' => '添加',
'destroy' => [
'confirm' => '确定要删除吗?',
'fail' => '删除失败',
]
],
];<file_sep>/app/Http/Controllers/Back/Report/Task/NewVersionController.php
<?php
/**
* 报告任务新建版本
*/
namespace App\Http\Controllers\Back\Report\Task;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\Report\Task\NewVersionService as Service;
use App\Traits\ControllerTrait;
class NewVersionController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'back.report.task.newversion';
protected $routePrefix = 'admin.report.task.newversion';
public function __construct(Service $service)
{
$this->service = $service;
}
/**
* 报告任务-创建新版本
* @param [type] $id [description]
* @return [type] [description]
*/
public function index($id)
{
$results = $this->service->index($id);
return view(getThemeTemplate($this->folder . '.index'))->with($results);
}
/**
* 报告任务-保存新版本
* @param [type] $id [description]
* @return [type] [description]
*/
public function store($id)
{
$results = $this->service->store($id);
return response()->json($results);
}
}
<file_sep>/app/Events/Report/Task/Copy.php
<?php
namespace App\Events\Report\Task;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class Copy
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
/*被复制报告id*/
public $reportId;
/*报告任务执行者*/
public $taskUserId;
/*报告规则*/
public $regulation;
/*报告首次接受日期*/
public $reportFirstReceivedData;
/*新报告*/
public $newReport;
public function __construct($reportId, $taskUserId, $regulation, $reportFirstReceivedData, $newReport)
{
$this->reportId = $reportId;
$this->taskUserId = $taskUserId;
$this->regulation = $regulation;
$this->reportFirstReceivedData = $reportFirstReceivedData;
$this->newReport = $newReport;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
<file_sep>/app/Repositories/Models/Menu.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use App\Traits\ModelTrait;
class Menu extends Model implements Transformable
{
use TransformableTrait;
use ModelTrait;
protected $fillable = [
'name', 'route', 'icon', 'permission', 'description', 'sort', 'route_prefix', 'position'
];
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('menu', $this->id);
}
public function parentMenu()
{
return $this->morphToMany(Menu::class, 'recursive', 'recursive_relations', 'current_id', 'recursive_id');
}
public function sonMenus()
{
return $this->morphToMany(Menu::class, 'recursive', 'recursive_relations', 'recursive_id', 'current_id')
->orderBy('sort', 'asc');
}
/**
* Mutator
*/
public function getUrlRouteAttribute()
{
$urlRoute = url('/');
try {
$urlRoute = route($this->route);
} catch (\Exception $e) {
}
return $urlRoute;
}
}
<file_sep>/routes/routes/management/management.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'management', 'as' => 'management.'], function ($router) {
/*油卡管理*/
// $router->get('index', [
// 'uses' => 'ManagementController@index',
// 'as' => 'index'
// ]);
$router->get('index', function(){
dd(122);
});
/*油卡添加*/
$router->post('create', [
'uses' => 'ManagementController@create',
'as' => 'create'
]);
/*油卡删除*/
$router->get('{id}/delete', [
'uses' => 'ManagementController@delete',
'as' => 'delete'
]);
/*油卡状态修改*/
$router->get('{id}/update', [
'uses' => 'ManagementController@update',
'as' => 'update'
]);
/*excel*/
$router->get('excel', [
'uses' => 'ManagementController@excel',
'as' => 'excel'
]);
});
/*资源路由*/
$router->resource('management', 'ManagementController');
});<file_sep>/routes/routes/systems/menu.php
<?php
$router->group([], function($router) {
$router->group(['prefix' => 'menu', 'as' => 'menu.'], function($router) {
/*菜单排序*/
$router->post('sort', [
'uses' => 'MenuController@sort',
'as' => "sort"
]);
});
$router->resource('menu', 'MenuController');
});<file_sep>/app/Services/OcService/SupplierListService.php
<?php
namespace App\Services\OcService;
use App\Services\Service as BasicService;
use Mockery\Exception;
use Yajra\DataTables\Html\Builder;
use App\Services\Service;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use DB;
use DataTables;
use Excel;
class SupplierListService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function datatables()
{
$fields = [
'name_of_card_supply' => 'like',
'supply_status' => '=',
'denomination' => 'like',
'supply_time' => '=',
];
//获取条件
$where = $this->searchArray($fields);
$data = $this->supplierRepo->findWhere($where);
return $data;
}
public function index()
{
$results = $this->get_config_blade(config('oc.supplier.supplierlist'));
$results['data'] = '';
return $results;
}
public function showUserInfo()
{
//获取当前用户信息
$userInformation = getUser();
return $userInformation;
}
//保存用户信息
public function store($id)
{
try{
$exception = DB::transaction(function() use ($id) {
if( $info = $this->supplierRepo->update(request()->all(),$id) ){
} else {
throw new Exception(trans('code/store.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/store.destroy.success'),
]);
});
} catch(Exception $e){
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/store.destroy.fail')),
]);
}
return array_merge($this->results,$exception);
}
//卡密供货页面
public function cardIndex()
{
try{
} catch(Exception $e){
abort(404);
}
}
//卡密供货
public function cardPassEncryption()
{
try{
$exception = DB::transaction(function() {
#TODO 上传文件上传获取文件内容&添加的卡密信息 结构数组的形式
//1:导入excel和添加卡密
//2:导入excel
//3;添加卡密
if( 1 ){
} else {
throw new Exception(trans('code/store.destroy.fail'), 2);
}
return array_merge($this->results, [
'result' => true,
'message' => trans('code/store.destroy.success'),
]);
});
} catch(Exception $e){
$exception = array_merge($this->results, [
'result' => false,
'message' => $this->handler($e, trans('code/store.destroy.fail')),
]);
}
return array_merge($this->results,$exception);
}
}<file_sep>/app/Repositories/Models/ReportMainpage.php
<?php
namespace App\Repositories\Models;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
class ReportMainpage extends Model implements Transformable
{
use TransformableTrait,ModelTrait;
protected $table = 'report_mainpage';
protected $fillable = ['report_first_received_date','report_drug_safety_date','aecountry_id','ae_country','received_fromid_id','received_from_id','research_id','scheme_num','center_number','delayed_reason','brand_name','first_brand_name','drug_name','first_drug_name','first_generic_name',
'first_event_term','generic_name','event_term','event_of_onset','report_identifier','report_identifier_status','report_type','reporter_name','reporter_organisation','reporter_department','reporter_country','reporter_country_id','reporter_stateor_province','reporter_city','reporter_post','reporter_telephone_number','patient_name',
'subject_number','date_of_birth','age','company_id','age_at_time_of_onset_unit','sex','patient_contact_information','literature_published_year','literature_author','literature_published_journals','literature_title','regulation_id','severity','is_first_report','first_report_id','is_last_report'];
/**
* 获取附件
* @return [type] [description]
*/
public function attachments()
{
return $this->morphToMany(Attachment::class, 'attachment_model');
}
protected $appends = [
'id_hash'
];
public function getIdHashAttribute()
{
return $this->encodeId('reportmainpage', $this->id);
}
}
<file_sep>/app/Subscribes/RoleEventSubscribe.php
<?php
namespace App\Subscribes;
use App\Repositories\Interfaces\PermissionRepository;
class RoleEventSubscribe
{
/**
* 绑定角色权限
* @param [type] $event [description]
* @return [type] [description]
*/
public function onBindPermission($event)
{
/*获取角色和权限id*/
$role = $event->role;
$permissionIds = $event->permissionIds;
/*重置可用权限id*/
$permissions = app(PermissionRepository::class)->findWhereIn('id', $permissionIds);
$bindPermissionIds = $permissions->keyBy('id')->keys()->toArray();
$role->syncPermissions($bindPermissionIds);
}
public function subscribe($events)
{
/*绑定角色*/
$events->listen(
'App\Events\Role\BindPermission',
'App\Subscribes\RoleEventSubscribe@onBindPermission'
);
}
}
<file_sep>/app/Http/Controllers/Card/DashController.php
<?php
namespace App\Http\Controllers\Card;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ControllerTrait;
use Mockery\Exception;
class DashController extends Controller
{
use ControllerTrait;
/*模板文件夹*/
protected $folder = 'ocback.backstage.index';
/**/
protected $routePrefix = 'admin.dash';
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
try{
// return redirect()->route('create');
//echo url()->current();
// return view('themes.metronic.ocback.backstage.purchasing.left_meau');
return redirect()->route('admin.backstage.p_index');
//return redirect($url);
} catch (Exception $e){
dd($e);
}
//dd(route('admin/backstage/p_index'));
// dd(123);
//return view(getThemeTemplate($this->folder . '.index'));
}
}
<file_sep>/routes/routes/report/supervision.php
<?php
/**
* Created by PhpStorm.
* User: lvxinxin
* Date: 2018/02/01
* Email: <EMAIL>
*/
$router->group([], function($router) {
$router->group(['prefix' => 'supervision', 'as' => 'supervision.'], function($router) {
#立即上报
$router->post('immediately/{id}', [
'uses' => 'SupervisionsController@immediately',
'as' => "immediately"
]);
#其它形式的上报
$router->match(['get','post'],'other/{id}', [
'uses' => 'SupervisionsController@other',
'as' => "other"
]);
#无需上报
$router->post('no-need/{id}', [
'uses' => 'SupervisionsController@noNeed',
'as' => "no-need"
]);
});
$router->resource('supervision', 'SupervisionsController');
});<file_sep>/app/helpers/common.php
<?php
if ( !function_exists('getRouteParam') ) {
function getRouteParam($key)
{
return request()->route($key) ?: '';
}
}
/**
* 获取当前登录用户
*/
if ( !function_exists('getUser') ) {
function getUser()
{
return auth()->user();
}
}
/**
* 获取当前登录用户id
*/
if ( !function_exists('getUserId') ) {
function getUserId()
{
$user = getUser();
return $user->id;
}
}
/**
* 获取单位id
*/
if ( !function_exists('getCompanyId') ) {
function getCompanyId($companyId = 0)
{
#TODO: sidlee modify by 2018-01-22
return $companyId ?: session('company_id',0);
}
}
/**
* 获取工作流id
*/
if ( !function_exists('getWorkflowId') ) {
function getWorkflowId($workflowId = '', $encrypt = false)
{
$workflowId = $workflowId ?: session('workflow_id');
if (!$encrypt) {
return $workflowId;
} else {
return app(\App\Repositories\Interfaces\WorkflowRepository::class)->encodeId($workflowId);
}
}
}
/**
* 是否显示菜单
*/
if ( !function_exists('checkMenuPosition') ) {
function checkMenuPosition($position)
{
$menuPositions = getCompanyId() ? [getMenuPositionValue('all'), getMenuPositionValue('company')] : [getMenuPositionValue('all'), getMenuPositionValue('admin')];
return in_array($position, $menuPositions);
}
}
/**
* 计算倒计时
*/
if ( !function_exists('calcCarbonCountdown') ) {
function calcCarbonCountdown($value)
{
$value = new \Carbon\Carbon($value);
/*当前时间*/
$now = new \Carbon\Carbon();
$string = '';
$isOverdue = $value >= $now ? true : false;
if(!$diffDays = $value->diffInDays($now, true)) {
if( !$diffHours = $value->diffInHours($now, true) ) {
if( !$diffMinutes = $value->diffInMinutes($now, true) ) {
$string = $isOverdue ? '0m' : '-1m';
}else {
$string = $isOverdue ? $diffMinutes : -$diffMinutes;
$string .= 'm';
}
} else {
$string = $isOverdue ? $diffHours : -$diffHours;
$string .= 'h';
}
} else {
$string = $isOverdue ? $diffDays : -$diffDays;
$string .= 'd';
}
return $string;
}
}
/**
* 计算文件大小
*/
if ( !function_exists('calcFileSize') ) {
function calcFileSize($value, $unit = 'MB')
{
switch( $unit ) {
case 'MB' :
$value = number_format($value / 1024 /1024, 2);
break;
case 'KB' :
$value = number_format($value / 1024, 2);
break;
}
return $value . $unit;
}
}
<file_sep>/resources/lang/en/code/attachment.php
<?php
return [
'upload' => [
'success' => '附件上传成功',
'fail' => '附件上传失败',
'selectfile' => '请先选择文件',
],
];<file_sep>/app/Services/EnterpriseService.php
<?php
namespace App\Services;
use App\Services\Service as BasicService;
use Illuminate\Http\Request;
use Yajra\DataTables\Html\Builder;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use Yajra\DataTables\DataTables;
use Exception;
use DB;
Class EnterpriseService extends BasicService{
use ResultTrait , ExceptionTrait , ServiceTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function datatables()
{
$data = $this->enterpriseRepo->all('sort_id','name','enterprise_type','parent company_name','enterprise_adress');
return DataTables::of($data)
->editColumn('id', '{{$id_hash}}')
->editColumn('status', getThemeTemplate('back.basic.enterprise.index'))
->addColumn('action', getThemeTemplate('back.basic.enterprise.datatable'))
->make();
}
public function index()
{
$html = $this->builder->columns([
['data' => 'question_num', 'name' => 'question_num', 'title' => '质疑编号', 'class' => 'text-center'],
['data' => 'report_num', 'name' => 'report_num', 'title' => '报告编号', 'class' => 'text-center'],
['data' => 'operation_name', 'name' => 'operation_name', 'title' => '操作人', 'class' => 'text-center'],
['data' => 'status', 'name' => 'status', 'title' => '状态'],
['data' => 'operation_date', 'name' => 'operation_date', 'title' => '操作时间', 'class' => 'text-center'],
['data' => 'content', 'name' => 'content', 'title' => '内容'],
['data' => 'end_date', 'name' => 'end_date', 'title' => '截止时间', 'class' => 'text-center'],
['data' => 'sending', 'name' => 'sending', 'title' => '发送次数', 'class' => 'text-center'],
['data' => 'action', 'name' => 'action', 'title' => '操作', 'class' => 'text-center', 'sorting' => false]
])
->ajax([
'url' => route('admin.question.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
}
<file_sep>/resources/lang/en/module/source.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/29
* Time: 上午11:17
*/
return [
'create' => [
'title' => '原始资料添加',
'submit' => '添加',
'reset' => '重置',
],
'edit' => [
'title' => '原始资料修改',
'submit' => '修改',
'reset' => '重置',
],
'index' => [
'create' => '原始资料',
'destroy' => [
'confirm' => '确定要删除吗?',
'fail' => '删除失败',
]
],
];<file_sep>/app/Repositories/Models/ReportValues.php
<?php
namespace App\Repositories\Models;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\ModelTrait;
class ReportValues extends Model implements Transformable
{
use TransformableTrait;
use SoftDeletes;
use ModelTrait;
protected $fillable = [
'report_id', 'report_tab_id', 'col', 'col_name', 'name', 'description', 'value', 'is_table', 'table_alias', 'table_row_id', 'company_id',
];
protected $appends = [
'report_id_hash'
];
public function getReportIdHashAttribute()
{
return $this->encodeId('reportmainpage', $this->report_id);
}
}
<file_sep>/routes/routes/systems/category.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/23
* Time: 下午4:57
*/
$router->group([], function($router) {
$router->group(['prefix' => 'cate', 'as' => 'cate.'], function($router) {
});
$router->resource('cate', 'CategoryController');
});<file_sep>/app/Http/Controllers/Card/Purchasing/ListController.php
<?php
namespace App\Http\Controllers\Card\Purchasing;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Traits\ServiceTrait;
use App\Services\OcService\ListService as Service;
class ListController extends Controller
{
protected $service;
public function __construct(Service $service)
{
$this->service = $service;
}
public function index(){
$results=$this->service->get_config_blade(config('oc.default.list'));
//dd($results);
return view('themes.metronic.ocback.backstage.purchasing.list')->with($results);
}
public function search(){
$results=$this->service->search();
return response()->json($results);
}
}
<file_sep>/app/Traits/Services/Permission/PermissionTrait.php
<?php
namespace App\Traits\Services\Permission;
Trait PermissionTrait
{
/**
* 权限选择
* @return [type] [description]
*/
public function permissionSelect($permissionSelected = [])
{
$results = [];
/*所有的权限*/
$permissions = $this->permissionRepo->all();
if($permissions->isNotEmpty()) {
foreach($permissions as $key => $permission) {
$name = $permission->name;
$nameArr = explode('-', $name);
/*获取模块名称*/
$lastNameArrValue = $nameArr[count($nameArr) - 1];
if(in_array($permission->name, $permissionSelected)) {
$results[$lastNameArrValue][$permission->id] = [
'dispaly_name' => $permission->display_name,
'selected' => true,
];
} else {
$results[$lastNameArrValue][$permission->id] = [
'dispaly_name' => $permission->display_name,
'selected' => false,
];
}
}
}
return $results;
}
}<file_sep>/app/Repositories/Eloquents/WorkflowRepositoryEloquent.php
<?php
namespace App\Repositories\Eloquents;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\Interfaces\WorkflowRepository;
use App\Repositories\Models\Workflow;
use App\Repositories\Validators\WorkflowValidator;
use App\Traits\EncryptTrait;
use Illuminate\Container\Container as Application;
/**
* Class WorkflowRepositoryEloquent
* @package namespace App\Repositories\Eloquents;
*/
class WorkflowRepositoryEloquent extends BaseRepository implements WorkflowRepository
{
use EncryptTrait;
public function __construct(Application $app)
{
parent::__construct($app);
$this->setEncryptConnection('workflow');
}
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Workflow::class;
}
/**
* Specify Validator class name
*
* @return mixed
*/
public function validator()
{
return WorkflowValidator::class;
}
/**
* 停用工作流
* @param [type] $companyId [description]
* @return [type] [description]
*/
public function closeWorkflow($companyId)
{
$results = $this->model->where('company_id', $companyId)->update([
'is_use' => getCommonCheckValue(false)
]);
$this->resetModel();
return $results;
}
/**
* 启用工作流
* @param [type] $companyId [description]
* @return [type] [description]
*/
public function openWorkflow($companyId, $workflowId)
{
$results = $this->model
->where('company_id', $companyId)
->where('id', $workflowId)
->update([
'is_use' => getCommonCheckValue(true)
]);
$this->resetModel();
return $results;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
<file_sep>/routes/routes/quality/route.php
<?php
$router->group(['namespace' => 'Back\Quality'], function($router) {
require(__DIR__.'/question.php');
require(__DIR__.'/datatrace.php');
});
<file_sep>/app/Listeners/FlushCacheListener.php
<?php
namespace App\Listeners;
use App\Events\FlushCache;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Artisan;
class FlushCacheListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param FlushCache $event
* @return void
*/
public function handle(FlushCache $event)
{
Artisan::call('cache:clear');
}
}
<file_sep>/resources/lang/en/code/regulation.php
<?php
/**
* Created by PhpStorm.
* User: xinxin.lv
* Date: 2018/1/23
* Time: 上午9:49
*/
return [
'store' => [
'fail' => '报告规则创建失败',
'success' => '报告规则创建成功',
],
'update' => [
'fail' => '报告规则修改失败',
'success' => '报告规则修改成功',
],
'destroy' => [
'fail' => '报告规则删除失败',
'success' => '报告规则删除成功',
],
'sort' => [
'fail' => '报告规则排序失败',
'success' => '报告规则排序成功',
],
'show' =>[
'fail' => '规则数据不存在',
],
];<file_sep>/routes/oc_routes/backstage/s_index.php
<?php
$router->group(['prefix' => "backstage",'as' => 'backstage.'], function($router) {
$router->get('s_index',[
'uses' => 'SupplierMeauController@index',
'as' => 's_index'
]);
});<file_sep>/app/Services/Report/TaskService.php
<?php
namespace App\Services\Report;
use Yajra\DataTables\Html\Builder;
use DataTables;
use App\Services\Service;
use App\Traits\ResultTrait;
use App\Traits\ExceptionTrait;
use App\Traits\ServiceTrait;
use Exception;
use DB;
use App\Repositories\Criterias\OrderBySortCriteria;
use App\Repositories\Criterias\FilterCompanyIdCriteria;
use App\Repositories\Criterias\FilterByFieldCriteria;
class TaskService extends Service
{
use ServiceTrait, ResultTrait, ExceptionTrait;
public function __construct(Builder $builder)
{
parent::__construct();
$this->builder = $builder;
}
public function index()
{
$html = $this->builder->columns([
['data' => 'report_identify', 'name' => 'report_identify', 'title' => '报告编号'],
['data' => 'report_first_received_date', 'name' => 'report_first_received_date', 'title' => '获知时间'],
['data' => 'drug_name', 'name' => 'drug_name', 'title' => '药物名称', 'class' => 'text-center'],
['data' => 'first_event_term', 'name' => 'first_event_term', 'title' => '不良事件'],
['data' => 'seriousness', 'name' => 'seriousness', 'title' => '严重性'],
['data' => 'standard_of_seriousness', 'name' => 'standard_of_seriousness', 'title' => '严重性标准'],
['data' => 'case_causality', 'name' => 'case_causality', 'title' => '因果关系'],
['data' => 'received_from_id', 'name' => 'received_from_id', 'title' => '首次/随访'],
['data' => 'task_user_name', 'name' => 'task_user_name', 'title' => '处理人'],
['data' => 'organize_role_name', 'name' => 'organize_role_name', 'title' => '任务进度'],
['data' => 'task_countdown', 'name' => 'task_countdown', 'title' => '任务倒计时'],
['data' => 'report_countdown', 'name' => 'report_countdown', 'title' => '报告倒计时'],
['data' => 'action', 'name' => 'action', 'title' => '操作'],
])
->ajax([
'url' => route('admin.report.task.index'),
'type' => 'GET',
])->parameters(config('back.datatables-cfg.basic'));
return [
'html' => $html
];
}
public function datatables()
{
/*公司id*/
$companyId = getCompanyId();
/*当前用户id*/
$user = getUser();
$roles = $user->roles;
$userId = getUserId();
$fields = ['id', 'report_id', 'report_identify', 'report_first_received_date', 'drug_name', 'first_event_term', 'seriousness', 'standard_of_seriousness', 'case_causality', 'received_from_id', 'task_user_name', 'organize_role_name', 'task_countdown', 'report_countdown', 'source_id'];
/*查询的字段*/
$searchFields = [
'report_identify' => 'like',
'drug_name' => 'like',
'event_term' => 'like',
'organize_role_id' => '=',
'case_causality' => '=',
'report_type' => '=',
'task_user_id' => '=',
'status' => '=',
];
/*获取查询条件*/
$where = $this->searchArray($searchFields);
/*获取数据*/
$this->reportTaskRepo->pushCriteria(new OrderBySortCriteria('asc', 'task_countdown'));
/*查询公司*/
$this->reportTaskRepo->pushCriteria(new FilterCompanyIdCriteria($companyId));
/*判断是否不是企业管理员*/
if( !isCompanyManager($roles) ) {
/*查询当前拥有者*/
$this->reportTaskRepo->pushCriteria(new FilterByFieldCriteria('task_user_id', $userId));
}
$data = $this->reportTaskRepo->findWhere($where, $fields);
return DataTables::of($data)
->editColumn('id', '{{$id_hash}}')
->editColumn('report_id', '{{ $report_id_hash }}')
->addColumn('action', getThemeTemplate('back.report.task.datatable'))
->editColumn('task_countdown', '{{ calcCarbonCountdown($task_countdown) }}')
->editColumn('report_countdown', '{{ calcCarbonCountdown($report_countdown) }}')
->make();
}
}<file_sep>/app/Subscribes/MenuEventSubscribe.php
<?php
namespace App\Subscribes;
use App\Repositories\Interfaces\MenuRepository;
use Cache;
class MenuEventSubscribe
{
/**
* 绑定角色权限
* @param [type] $event [description]
* @return [type] [description]
*/
public function onBindParentMenu($event)
{
/*获取角色和权限id*/
$menu = $event->menu;
$parentMenuId = $event->parentMenuId;
/*重置可用权限id*/
if($parentMenuId) {
$parentMenu = app(MenuRepository::class)->find($parentMenuId);
$this->bindParentMenu($menu, $parentMenu->id);
}
}
/**
* 删除菜单关系
* @param [type] $event [description]
* @return [type] [description]
*/
public function onDetachMenuRelation($event)
{
$menu = $event->menu;
$menu->parentMenu()->detach();
$menu->sonMenus()->detach();
}
/**
* 排序当前菜单
* @param [type] $event [description]
* @return [type] [description]
*/
public function onSortCurrentMenu($event)
{
$menu = $event->menu;
$sort = $event->sort;
$parentMenu = $event->parentMenu;
/*保存菜单排序*/
$menu->sort = $sort;
$menu->save();
/*绑定父级菜单*/
if($parentMenu) {
$bindData[$parentMenu->id] = [
'sort' => $sort,
];
} else {
$bindData = [];
}
$this->bindParentMenu($menu, $bindData);
}
/**
* 绑定父级菜单
* @param [type] $menu [description]
* @param [type] $parentMenuId [description]
* @return [type] [description]
*/
private function bindParentMenu($menu, $bindData)
{
$menu->parentMenu()->sync($bindData);
}
/**
* 清除用户菜单缓存
* @param [type] $event [description]
* @return [type] [description]
*/
public function onClearUserMenuCache($event)
{
$userId = $event->userId;
$key = getCacheUserMenu($userId);
Cache::forget($key);
}
/**
* 清除所有菜单缓存
*/
public function onClearAllMenuCache($event)
{
$key = getCacheAllMenu();
Cache::forget($key);
}
public function subscribe($events)
{
/*绑定角色*/
$events->listen(
'App\Events\Menu\BindParentMenu',
'App\Subscribes\MenuEventSubscribe@onBindParentMenu'
);
/*删除菜单关系*/
$events->listen(
'App\Events\Menu\DetachMenuRelation',
'App\Subscribes\MenuEventSubscribe@onDetachMenuRelation'
);
/*排序当前菜单*/
$events->listen(
'App\Events\Menu\SortCurrentMenu',
'App\Subscribes\MenuEventSubscribe@onSortCurrentMenu'
);
/*清楚用户菜单缓存*/
$events->listen(
'App\Events\Menu\ClearUserMenuCache',
'App\Subscribes\MenuEventSubscribe@onClearUserMenuCache'
);
/*清除所有菜单缓存*/
$events->listen(
'App\Events\Menu\ClearAllMenuCache',
'App\Subscribes\MenuEventSubscribe@onClearAllMenuCache'
);
}
}
<file_sep>/resources/lang/en/field/workflow.php
<?php
return [
'name' => [
'label' => '名称',
'name' => 'name',
'placeholder' => '请输入名称',
'rules' => [
'required' => '名称不能为空',
]
],
'status' => [
'label' => '是否有效',
'name' => 'status',
'placeholder' => '请输入是否有效',
'rules' => [
'required' => '是否有效不能为空',
]
],
'is_use' => [
'label' => '是否默认',
'name' => 'is_use',
'placeholder' => '请输入是否默认',
'rules' => [
'required' => '是否默认不能为空',
]
],
];<file_sep>/app/Repositories/Interfaces/ManagementRepository.php
<?php
namespace App\Repositories\Interfaces;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface ManagementRepository.
*
* @package namespace App\Repositories\Interfaces;
*/
interface ManagementRepository extends RepositoryInterface
{
//
}
| 6c0f6977e6ca31579f4f2d176046fb193bd740a1 | [
"Markdown",
"JavaScript",
"PHP",
"Shell"
] | 274 | PHP | larkin2296/OC | 6a3f6407bfcfe7a2b9923af34a1919bf742d4885 | 6e48a775d5d7539b44371f9450baae7fb56cda6c |
refs/heads/master | <file_sep>package com.example.android.scorekeeperapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.android.scorekeeperapp.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int scoreWarriors = 0;
/**
* Displays the given score for Team A.
*/
public void displayForWarriors(int score) {
TextView scoreView = (TextView) findViewById(R.id.golden_score);
scoreView.setText(String.valueOf(score));
}
public void submitThreeA(View view) {
scoreWarriors = scoreWarriors + 3;
displayForWarriors(scoreWarriors);
}
public void submitTwoA(View view) {
scoreWarriors = scoreWarriors + 2;
displayForWarriors(scoreWarriors);
}
public void submitOneA(View view) {
scoreWarriors = scoreWarriors + 1;
displayForWarriors(scoreWarriors);
}
int scoreLakers = 0;
/**
* Displays the given score for Team A.
*/
public void displayForLakers(int score) {
TextView scoreView = (TextView) findViewById(R.id.lakers_score);
scoreView.setText(String.valueOf(score));
}
public void submitThreeB(View view) {
scoreLakers = scoreLakers + 3;
displayForLakers(scoreLakers);
}
public void submitTwoB(View view) {
scoreLakers = scoreLakers + 2;
displayForLakers(scoreLakers);
}
public void submitOneB(View view) {
scoreLakers = scoreLakers + 1;
displayForLakers(scoreLakers);
}
public void submitReset(View view) {
scoreWarriors= 0;
scoreLakers = 0;
displayForWarriors(scoreWarriors);
displayForLakers(scoreLakers);
}
}
<file_sep># ScoreKeeperApp
Design and implement an app to track scores between two teams within a basketball game.



| b4f94e1afaf3c14edb7244e5914d01724fc96361 | [
"Markdown",
"Java"
] | 2 | Java | ddeleon92/ScoreKeeper | 7ff748e1a804bf6d1258a2f6249ccf166c16a857 | e2c7f616edbf8488c6acc23bb0050fb5ce98ecbb |
refs/heads/master | <file_sep>//---function converts a geolocation string into an array and return the map center array for openlayers
function getGeolocArray4String(pGeolocString,pMapCenter) {
//e.g. pGeolocString = "-1.81185,52.443141";
var vCenter = "";
try {
eval("vCenter = ["+pGeolocString+"]");
} catch (e) {
// eval failed and show error message
alert(e);
vCenter = pMapCenter;
};
return vCenter;
};
//----- function return the current zoom factor of the map
function getZoom() {
return map.getView().getZoom();
};
function saveGeolocation(pLocation) {
localStorage.setItem("mapcenter",pLocation);
localStorage.setItem("zoom",getZoom());
console.log("mapcenter="+pLocation+" and zoom="+getZoom()+" settings stored in LocalStorage");
}
<file_sep># Select a Geolocation with OpenLayers and CallBack
Demo that creates a selector for a geolocation on a map by using [OpenLayers](https://www.openlayers.org). Geolocation Button allows to center map on current geolocation and callback url shows how to call this tool remotely and return the selected geolocation.
## [Geolocation Select Demo](https://niebert.github.io/openlayer_selectlocation)
## Files of Demo
This demo consists of two file stored in `/docs`
* `index.html` and
* `selectlocation.html`.
`index.html` calls `selectlocation.html` and lets the user select a geolocation. After the users clicks on the map in `selectlocation.html` the OpenLayers map returns the selected geolocation back to `index.html`. In this example `index.html` reads the geolocation from the LinkParameter e.g. `index.html?geolocation=-12.213,65.123` and stores the geolocation in a input text element with the ID=mygeolocation in the HTML file `index.html`.
### Libraries
* `linkparam.js` The LinkParameter parameter are handled with a Javascript Class `docs/js/linkparam.js`.
* `openlayers3.js` is the OpenLayers3 version as JavaScript library. See [OpenLayers](https://www.openlayers.org) for more details.
### CSS
* `font-awesome` Font AweSome is preinstalled for offline use of buttons and further tests.
### Demo
* [Geolocation Select Demo](https://niebert.github.io/openlayer_selectlocation)
* [Download Demo](https://github.com/niebert/openlayer_selectlocation/archive/master.zip) unzip file and checkout the subdirectory `/docs`. The demo is stored in `/docs` because it is used at the same time as root directory for https://niebert.github.io/openlayer_selectlocation
### See also
* Open Layers - Display Markers with Popups on the Map [Demo Display Markers](https://niebert.github.io/openlayer_diplay_markers) - [Source Code](https://github.com/niebert/openlayer_diplay_markers) - [ZIP](https://github.com/niebert/openlayer_diplay_markers/archive/master.zip)
* Mapper4SDG - [Demo](https://niebert.github.io/Mapper4SDG) - [Source Code](https://github.com/niebert/Mapper4SDG) - [ZIP](https://github.com/niebert/Mapper4SDG/archive/master.zip)
* [Mixare](https://www.mixare.org) is an Augemented Reality App, that allows to place digital content in a camera image. [Demo](https://niebert.github.io/Mixare4JSON) - [Source Code](https://github.com/niebert/Mixare4JSON) - [ZIP](https://github.com/niebert/Mixare4JSON/archive/master.zip)
| 9d7a030ffdaa052328597224d4ff77b3038d1fed | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | niebert/openlayer_selectlocation | b57537c04fd8bf5441aa60ddf507113343a273fa | 4843a39004865fb7a9779e36baaabb84695d8ac0 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import './Contact.css';
export default class Contact extends Component {
render() {
return (
<div className="Contact">
<li>Contact Us:</li><br/>
<li>Email: <EMAIL></li><br/>
<li>Phone: 1-800-555-JOBS</li>
</div>
)
}
}<file_sep>import React, { Component } from 'react';
import './Header.css';
export default class Header extends Component {
render() {
return (
<header>
<h1>JOB FINDER</h1>
<img src="http://www.expressproswarwick.com/wp-content/uploads/2014/02/jobsearch.png" alt="logo"/>
<button onClick={ this.props.changeFavorites } className="button">{this.props.showFavorites? 'ALL LISTINGS': 'FAVORITES'}</button>
</header>
)
}
} | c4540ccf725e4df3140baf0877f5a4151d1007a8 | [
"JavaScript"
] | 2 | JavaScript | samabu/world-cup-2018 | 65a96261459e3bc0a34aa594e3f4e5c1f735c8f1 | 6f7fde94efd270a5ef40e1000bd0211098b0a9e0 |
refs/heads/main | <file_sep>### Hire-Youtubers-DjangoApp
#### pip install pipenv
### activate pip file
#### pipenv shell
#### pipenv install pillow
#### Document :https://docs.djangoproject.com/
#### pipenv install Django
### Create Django Project
#### django-admin startproject tubers
### Run server
#### python manage.py runserver
### Install Postgres and pg-admin from https://www.postgresql.org/ and https://www.pgadmin.org/download/
#### DB password dbname:postgres username:postgres password:<PASSWORD>
### Install psycopg2 as DB adapter for postgresql for python
#### pipenv install psycopg2
#### to use postgresql -> postgresql, pg-admin and psycopg2 needed
### Migration
#### python manage.py makemigrations
#### python manage.py migrate
### create admin user in gitbash and virtual env
#### winpty python manage.py createsuperuser
#### lco password:lco
### Django package url
### https://djangopackages.org/
### install djangocms-admin-style for admin css styling
#### pipenv install djangocms-admin-style
#### add in settings.py installed apps, 1st line djangocms_admin_style
#### run command
#### python manage.py migrate
#### python manage.py migrate djangocms_admin_style
### Github repo for django admin styling
#### https://github.com/django-cms/djangocms-admin-style
### settings.py file change for static files
### create folder under tubers and then run command
#### python manage.py collectstatic
<!-- STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = [os.path.join(BASE_DIR,'tubers/static')] -->
### create app
#### python manage.py startapp webpages
#### {% load static %}
#### <link rel="stylesheet" href="{% static './css/base.css' %}" />
#### {% include 'includes/footer.html' %}
#### pipenv install django-ckeditor // description with detailed edit
#### add ckeditor to settings.py file under installed apps
#### python manage.py startapp accounts
#### pipenv install django-allauth
#### https://django-allauth.readthedocs.io/en/latest/installation.html
#### settings.py -> apps -> django.contrib.sites
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.facebook',
SITE_ID=1
#### makemigrations and migrate
### Configure facebook
#### developer.facebook.com
#### create app -> consumer ->app connected -> name -> add product as facebook -> web -> site url localhost:8000 ->save ->
dashboard->settings->basic-> app id
#### Go to admin ->Add social applications-> facebook client id -> example.com to right->add site as localhost:8000
#### https://django-allauth.readthedocs.io/en/latest/providers.html#facebook
#### {% load socialaccount %} {% providers_media_js %}
#### settings.py -> LOGIN_REDIRECT_URL ='dashboard'
#### Google -> https://django-allauth.readthedocs.io/en/latest/providers.html#google
#### python manage.py startapp hiretubers
<file_sep>from django.contrib import admin
from .models import Slider, Team
from django.utils.html import format_html
# Register your models here.
#Admin customization as list
class TeamAdmin(admin.ModelAdmin):
def myphoto(self, object):
return format_html('<img src="{}" width="40" />'.format(object.first_name))
list_display = ('id', 'myphoto', 'first_name', 'role', 'created_date')
list_display_link = ('first_name','id')
search_fields = ('first_name','role')
list_filter = ('role',)
admin.site.register(Slider)
admin.site.register(Team, TeamAdmin) | 8f1c8f29065fd7f0134759c089420b7fa0609410 | [
"Markdown",
"Python"
] | 2 | Markdown | rupaku/Hire-Youtubers-DjangoApp | 91b63d024eece9e26b123c9aa61b9c2b79e2962b | c3d6e103da1c2e2553e29c5086ab11571de1e2e2 |
refs/heads/master | <repo_name>valarauca/libenumtrait<file_sep>/Cargo.toml
[package]
name = "libenumtrait"
version = "0.0.1"
authors = ["<NAME> <<EMAIL>>"]
edition = "2015"
[dependencies]
<file_sep>/src/lib.rs
/// Build Enum is used to construct a staggering amount of
/// boilerplate to make enum's slightly more ergonomic to
/// build abstractions around.
///
/// What this macro does is slightly strange. While
/// normally an `enum` is sufficient, when building
/// larger deserializers it is nice to have the ability
/// to implement methods on data which may not exist.
///
/// For example, say you are parsing data and a statement
/// (some arbitrary string of bytes) may contain a cat,
/// or it may not. Well when you construct a type to
/// encapsulate this statement you may with to have a
/// `Cat` enum within. But later you learn this statement
/// can also contain `Dog`, and `Lizard`. But modern
/// implements mostly just contain `Cat` or Nothing at all.
///
/// So when you build functions to operate on this statement
/// you'll likely want to methods to sell you if it contains
/// a `dog`, `lizard`, or `cat` irreguardless of what data
/// the statement contains.
///
/// This is what this library does. It constructs a `Trait`
/// which binds to `AsRef<TypeName>`. This `TypeName` is
/// a really just `Option<EnumName>`, so even if you have
/// a `Option::None` you can still call your `is_a_cat()`.
///
/// Furthermore because it exposes a `trait` you can accept
/// `<T: AsRef<TypeName>>` as a function argument instead of
/// `EnumName`, or `Option<EnumName>` which provides greater
/// flexability when operating on this data, as functions
/// can more easily operate on multiple data types.
#[macro_export]
macro_rules! build_enum {
(@AsSet
TypeName: $name: ident;
EnumName: $enum_name: ident;
IterName: $iter_name: ident;
TraitName: $trait_name: ident;
CollectionName: $collection_name: ident;
EnumMember: [ $({
Name: $member_name: ident;
Is: $is_name: ident;
As: $as_name: ident;
Get: $get_name: ident;
}),+];
) => {
#[repr(u8)]
#[derive(Copy,Clone,Debug,PartialEq,Eq,PartialOrd,Ord)]
pub enum $enum_name {
$($member_name),+
}
#[repr(packed)]
#[derive(Copy,Clone,Debug,PartialEq,Eq,PartialOrd,Ord)]
pub struct $name {
data: Option<$enum_name>,
}
impl Default for $name {
#[inline(always)]
fn default() -> Self {
Self{ data: None }
}
}
impl From<$enum_name> for $name {
#[inline(always)]
fn from(data: $enum_name) -> Self {
Self { data: Some(data) }
}
}
impl IntoIterator for $name {
type Item = $enum_name;
type IntoIter = $iter_name;
fn into_iter(self) -> Self::IntoIter {
$iter_name {
interior: self,
}
}
}
impl AsRef<$name> for $name {
fn as_ref<'a>(&'a self) -> &'a $name {
self
}
}
pub struct $iter_name {
interior: $name,
}
impl Iterator for $iter_name {
type Item = $enum_name;
fn next(&mut self) -> Option<Self::Item> {
match ::std::mem::replace(&mut self.interior.data, Option::None) {
Option::Some(data) => Some(data),
_ => None
}
}
}
pub trait $trait_name: AsRef<$name> {
$(
fn $is_name(&self) -> bool {
let x = self.as_ref();
match &x.data {
&Option::Some($enum_name::$member_name) => true,
_ => false
}
}
fn $as_name<'a>(&'a self) -> Option<&'a $enum_name> {
let x = self.as_ref();
match &x.data {
&Option::Some(ref interior) => {
if interior.clone() == $enum_name::$member_name {
Some(interior)
} else {
None
}
},
_ => None,
}
}
fn $get_name(&self) -> Option<$enum_name> {
let x = self.as_ref();
match &x.data {
&Option::Some($enum_name::$member_name) => Some(x.data.clone().unwrap()),
_ => None
}
}
)+
fn iter(&self) -> $iter_name {
self.as_ref().clone().into_iter()
}
}
impl $trait_name for $name { }
#[derive(Clone,Debug)]
pub struct $collection_name {
data: [$name; count!($($member_name),*)]
}
impl Default for $collection_name {
fn default() -> $collection_name {
$collection_name {
data: <[$name; count!($($member_name),*)]>::default(),
}
}
}
impl ::std::ops::Index<$enum_name> for $collection_name {
type Output = $name;
fn index<'a>(&'a self, index: $enum_name) -> &'a $name {
let index = index as u8 as usize;
if index < self.data.len() {
&self.data[index]
} else {
unreachable!()
}
}
}
impl ::std::ops::BitOr<$enum_name> for $enum_name {
type Output = $collection_name;
fn bitor(self, other: $enum_name) -> $collection_name {
let mut coll = $collection_name::default();
coll.data[self.clone() as usize] = $name{ data: Some(self.clone()) };
coll.data[other.clone() as usize] = $name{ data: Some(other.clone()) };
coll
}
}
impl ::std::ops::BitOr<$enum_name> for $name {
type Output = $collection_name;
fn bitor(self, other: $enum_name) -> $collection_name {
let mut coll = $collection_name::default();
coll.data[other.clone() as usize] = $name{ data: Some(other.clone()) };
match self.data {
Option::Some(x) => {
coll.data[x.clone() as usize] = $name{ data: Some(x.clone()) };
},
_ => { }
};
coll
}
}
impl ::std::ops::BitOr<$name> for $enum_name {
type Output = $collection_name;
fn bitor(self, other: $name) -> $collection_name {
let mut coll = $collection_name::default();
coll.data[self.clone() as usize] = $name{ data: Some(self.clone()) };
match other.data {
Option::Some(x) => {
coll.data[x.clone() as usize] = $name{ data: Some(x.clone()) };
},
_ => { }
};
coll
}
}
impl ::std::ops::BitOr<$enum_name> for $collection_name {
type Output = $collection_name;
fn bitor(self, other: $enum_name) -> $collection_name {
let mut coll = self;
coll.data[other.clone() as usize] = $name{ data: Some(other.clone()) };
coll
}
}
impl ::std::ops::BitOr<$name> for $collection_name {
type Output = $collection_name;
fn bitor(self, other: $name) -> $collection_name {
let mut coll = self;
match other.data {
Option::Some(x) => {
coll.data[x.clone() as usize] = $name{ data: Some(x.clone()) };
},
_ => { }
};
coll
}
}
impl ::std::ops::BitOrAssign<$enum_name> for $collection_name {
fn bitor_assign(&mut self, other: $enum_name) {
self.data[other as usize] = $name{ data: Some(other) } ;
}
}
impl ::std::ops::BitOrAssign<$name> for $collection_name {
fn bitor_assign(&mut self, other: $name) {
match other.data {
Option::Some(x) => {
self.data[x as usize] = $name{ data: Some(x) };
},
_ => { }
};
}
}
impl ::std::cmp::PartialEq<$enum_name> for $name {
fn eq(&self, other: &$enum_name) -> bool {
match &self.data {
&Option::Some(ref x) => x.eq(other),
_ => false
}
}
}
impl ::std::cmp::PartialEq<$name> for $enum_name {
fn eq(&self, other: &$name) -> bool {
other.eq(self)
}
}
impl ::std::cmp::PartialEq<$enum_name> for $collection_name {
fn eq(&self, other: &$enum_name) -> bool {
self[other.clone()].data.is_some()
}
}
impl ::std::cmp::PartialEq<$name> for $collection_name {
fn eq(&self, other: &$name) -> bool {
match other.data {
Option::None => false,
Option::Some(ref x) => self[x.clone()].data.is_some()
}
}
}
impl ::std::cmp::PartialEq<$collection_name> for $name {
fn eq(&self, other: &$collection_name) -> bool {
other.eq(self)
}
}
impl ::std::cmp::PartialEq<$collection_name> for $enum_name {
fn eq(&self, other: &$collection_name) -> bool {
other.eq(self)
}
}
};
(@WithInteriorData
TypeName: $name: ident;
EnumName: $enum_name: ident;
IterName: $iter_name: ident;
TraitName: $trait_name: ident;
EnumMember: [ $({
Name: $member_name: ident;
InteriorType: $data_type: ty;
InteriorTypeIdent: $data_ident: ident;
Is: $is_name: ident;
As: $as_name: ident;
Get: $get_name: ident;
}),+];
) => {
#[derive(Clone,Debug,PartialEq,Eq,PartialOrd,Ord)]
pub enum $enum_name {
$($member_name($data_ident)),+
}
#[derive(Clone,Debug,PartialEq,Eq,PartialOrd,Ord)]
pub struct $name {
data: Option<$enum_name>,
}
impl Default for $name {
#[inline(always)]
fn default() -> Self {
Self{ data: None }
}
}
impl IntoIterator for $name {
type Item = $enum_name;
type IntoIter = $iter_name;
fn into_iter(self) -> Self::IntoIter {
$iter_name {
interior: self,
}
}
}
impl AsRef<$name> for $name {
fn as_ref<'a>(&'a self) -> &'a $name {
self
}
}
pub struct $iter_name {
interior: $name,
}
impl Iterator for $iter_name {
type Item = $enum_name;
fn next(&mut self) -> Option<Self::Item> {
match ::std::mem::replace(&mut self.interior.data, Option::None) {
Option::Some(data) => Some(data),
_ => None
}
}
}
pub trait $trait_name: AsRef<$name> {
$(
fn $is_name(&self) -> bool {
let x = self.as_ref();
match &x.data {
&Option::Some($enum_name::$member_name(_)) => true,
_ => false
}
}
fn $as_name<'a>(&'a self) -> Option<&'a $data_type> {
let x = self.as_ref();
match &x.data {
&Option::Some($enum_name::$member_name(ref x)) => Some(x),
_ => None,
}
}
fn $get_name(&self) -> Option<$data_type> {
self.$as_name().map(|x| x.clone())
}
)+
fn iter(&self) -> $iter_name {
self.as_ref().clone().into_iter()
}
}
impl $trait_name for $name { }
};
(
TypeName: $name: ident;
EnumName: $enum_name: ident;
IterName: $iter_name: ident;
TraitName: $trait_name: ident;
EnumMember: [ $({
Name: $member_name: ident;
Is: $is_name: ident;
As: $as_name: ident;
Get: $get_name: ident;
}),+];
) => {
#[derive(Copy,Clone,Debug,PartialEq,Eq,PartialOrd,Ord)]
pub enum $enum_name {
$($member_name),+
}
#[derive(Copy,Clone,Debug,PartialEq,Eq,PartialOrd,Ord)]
pub struct $name {
data: Option<$enum_name>,
}
impl Default for $name {
#[inline(always)]
fn default() -> Self {
Self{ data: None }
}
}
impl IntoIterator for $name {
type Item = $enum_name;
type IntoIter = $iter_name;
fn into_iter(self) -> Self::IntoIter {
$iter_name {
interior: self,
}
}
}
impl AsRef<$name> for $name {
fn as_ref<'a>(&'a self) -> &'a $name {
self
}
}
pub struct $iter_name {
interior: $name,
}
impl Iterator for $iter_name {
type Item = $enum_name;
fn next(&mut self) -> Option<Self::Item> {
match ::std::mem::replace(&mut self.interior.data, Option::None) {
Option::Some(data) => Some(data),
_ => None
}
}
}
pub trait $trait_name: AsRef<$name> {
$(
fn $is_name(&self) -> bool {
let x = self.as_ref();
match &x.data {
&Option::Some($enum_name::$member_name) => true,
_ => false
}
}
fn $as_name<'a>(&'a self) -> Option<&'a $enum_name> {
let x = self.as_ref();
match &x.data {
&Option::Some(ref interior) => {
if interior.clone() == $enum_name::$member_name {
Some(interior)
} else {
None
}
},
_ => None,
}
}
fn $get_name(&self) -> Option<$enum_name> {
let x = self.as_ref();
match &x.data {
&Option::Some($enum_name::$member_name) => Some(x.data.clone().unwrap()),
_ => None
}
}
)+
fn iter(&self) -> $iter_name {
self.as_ref().clone().into_iter()
}
}
impl $trait_name for $name { }
};
}
/// AsRef makes implementing `AsRef` declarations easier
/// This also assists with declaring additional traits
/// inconjuction with the `build_enum` macro.
#[macro_export]
macro_rules! impl_as_ref {
(
AsRef: $orginal_type: ident => $field0 :ident => $new_type: ident;
Trait: $trait_name: ident;
) => {
impl AsRef<$new_type> for $orginal_type {
fn as_ref<'a>(&'a self) -> &'a $new_type {
self.$field0.as_ref()
}
}
impl $trait_name for $orginal_type { }
};
(
Path: $orginal_type:ident => $field0:ident => $field1: ident => => $field2: ident => $new_type:ident;
Trait: $trait_name: ident;
) => {
impl AsRef<$new_type> for $orginal_type {
#[inline(always)]
fn as_ref<'a>(&'a self) -> &'a $new_type {
&self.$field0.$field1.$field2
}
}
impl $trait_name for $orginal_type { }
};
(
Path: $orginal_type:ident => $field0:ident => $field1: ident => $new_type:ident;
Trait: $trait_name: ident;
) => {
impl AsRef<$new_type> for $orginal_type {
#[inline(always)]
fn as_ref<'a>(&'a self) -> &'a $new_type {
&self.$field0.$field1
}
}
impl $trait_name for $orginal_type { }
};
(
Path: $orginal_type:ident => $field0:ident => $new_type:ident;
Trait: $trait_name: ident;
) => {
impl AsRef<$new_type> for $orginal_type {
#[inline(always)]
fn as_ref<'a>(&'a self) -> &'a $new_type {
&self.$field0
}
}
impl $trait_name for $orginal_type { }
};
}
#[macro_export]
macro_rules! count {
() => { 0 };
($_: ident) => { 1 };
($_0: ident, $($_1:ident),*) => { 1 + count!($($_1),*) };
}
| 3dad6740df2a0cfe16eca16bbbb38ecb629df707 | [
"TOML",
"Rust"
] | 2 | TOML | valarauca/libenumtrait | 393a945eb4b508f43996c241eab4d477136d22db | c6b212ec2e22f4c996f663ff9a677f9a5e1ddc86 |
refs/heads/main | <repo_name>MorKalo/L5_HomeWork03-10-21<file_sep>/P36 EX2.py
#לבקשת איתי שימוש ב10 קלטים במקוםל 1000
i=1
_sum=int(input('insert a ticket'))
while i<=9:
ticket = int(input('insert a ticket'))
if _sum == ticket:
print('The number', ticket, 'is equal to the sum of all its predecessors')#המספר שהכנסת שווה לסכום כל קודמיו
break
_sum = _sum + ticket
i=i+1
if i==10:
print ('NOT FOUND')<file_sep>/P36 EX4.py
#לבקשת איתי שימוש ב10 קלטים בלבד
yes=0
no=0
avoid=0
veto=0
i=0
while i<=9:
choice=int(input('plz insert youre choice, 1 for YES; 2 for NO; 3 for AVOID; 4 for VETO'))
i=i+1
if choice==4:
print('the The serial number of the country is', i)
break
elif choice==1:
yes=yes+1
elif choice==2:
no=no+1
elif choice==3:
avoid=avoid+1
print('the number of Supporte:', yes)
print('the number of aggainst:', no)
print('the number of avoid:', avoid)
<file_sep>/README.md
# HomeWork041021
Homework
1) hoveret page 35: targilim 1, 2, 3, 4 *until the 10's only
2) input numbers from the user. print how many numbers above 77 were entered, and what is their sum. when zero is receieved the loop will break
3) input numberes from the user until a number that can be divided by 2 without a reminder will be entered (i.e. 4) , then input numbers from the user until a number that can be divided by 3 without a reminder will be entered (i.e. 9), then input numbers from the user until a number that can be divided by 4 without a reminder will be entered (i.e. 28) … until you reach 10, then break out of the loop. if the user enters a negative number just ignore it. *bonus: if the user enters the same number twice then break out of the loop
<file_sep>/T3.py
num=int(input('Plz insert a number'))
divided=2
while divided<=9:
while (num%divided==0) and (num>0):
# print ('yes', num)
divided=divided+1
# print('divided', divided )
num=int(input('Plz insert a number'))
<file_sep>/P36 EX1.py
#לבקשת איתי שימוש ב10 מספרים בלבד במקום 100
i=1
first=int(input('Plz insert a number'))
while i<=9:
second=int(input('Plz insert another number'))
if second<first:
print('The numbers are NOT sorted')
break
first = second
i=i+1
if i==10:
print ('The numbers are sorted')<file_sep>/T2.py
i=0
_sum=0
num=int(input('Plz insert a number'))
while num!=0:
if num>77:
i=i+1
_sum=_sum+num
num=int(input('Plz insert a number'))
print ('you enterd', i,'numbers that bigger then 77')
print('the sum of the numbers that bigger then 77 is', _sum )<file_sep>/P36 EX3.py
#לבקשת איתי שימוש בקליטת 10 כרטיסים בלבד
i=1
tmax=40
tmin=-5
while i<=9:
ticket = int(input('insert the temp'))
if tmin>ticket or ticket>=tmax:
print('WRONG value')
break
i=i+1
if i==10:
print ('GOOD value') | 87ce936848a17492b1a2d30da718a93f14548627 | [
"Markdown",
"Python"
] | 7 | Python | MorKalo/L5_HomeWork03-10-21 | 6a92b75f05adba31464b518c4e26c846abca6347 | f812904226d0069b97414e6db0a400ab0b866ba2 |
refs/heads/master | <file_sep>var assert = require('assert')
, file = require('../fileReader');
describe("fileIO", function() {
it("should return a defined list of one to many objects", function () {
var returnedList = file.formatGoodFromPhone();
assert(typeof returnedList === 'object', "returned value is not object-ish");
assert(returnedList.hasOwnProperty('length'), "the returned value did not hav property list");
assert(returnedList.length > 0, "The length of good from phone was 0");
});
});
describe("fileIO", function() {
it("should return a defined list of one to many 'good' objects", function() {
var returnedList = file.getGood();
assert(typeof returnedList === 'object', "returned value is not objectish");
assert(returnedList.hasOwnProperty("length"), "returned value is not listish");
assert(returnedList.length > 0, "returned value has length 0");
});
});
describe("fileIO", function() {
it("should return a defined list of one to many 'good' objects", function() {
var returnedList = file.getBad();
assert(typeof returnedList === 'object', "returned value is not objectish");
assert(returnedList.hasOwnProperty("length"), "returned value is not listish");
assert(returnedList.length > 0, "returned value has length 0");
});
});
describe("fileIO", function() {
it("should return a defined list of one to many 'good' objects", function() {
var returnedList = file.getKeywords();
assert(typeof returnedList === 'object', "returned value is not objectish");
assert(returnedList.hasOwnProperty("length"), "returned value is not listish");
assert(returnedList.length > 0, "returned value has length 0");
});
});
describe("fileIO", function() {
it("should only return type good from getGood()", function() {
var returnedList = file.getGood(), i, j, len, types;
for(i = 0, len = returnedList.length; i < len; i++) {
assert(returnedList[i].hasOwnProperty("types"), "did not return type information");
types = returnedList[i]["types"];
for(j = 0; j < types.length; j++) {
assert(types[j] === "good", "returned non-good type");
}
}
});
});
describe("fileIO", function() {
it("should only return type bad from getBad()", function() {
var returnedList = file.getBad(), i, j, len, types;
for(i = 0, len = returnedList.length; i < len; i++) {
assert(returnedList[i].hasOwnProperty("types"), "did not return type information");
types = returnedList[i]["types"];
for(j = 0; j < types.length; j++) {
assert(types[j] === "bad", "returned non-bad type");
}
}
});
});
<file_sep>!function() {
var natural = require('natural')
, tokenizer = new natural.WordTokenizer();
this.checkKeywords = function(keywords, sentence){
if(!(keywords && sentence))
return [];
var msgTokens = tokenizer.tokenize(sentence)
, matched = [];
keywords.forEach(function (e,i,a){
var type = e.type;
if(!e.words) return;
e.words.forEach(function (keyword,i,a) {
msgTokens.forEach(function (msgtoken, i, a){
if(msgtoken === keyword){
matched.push(type);
}
})
});
});
return matched;
}
/*
* Train the neural network.
*
*/
this.trainNN = function(net, bad, good){
var data = bad.splice(0,20).concat(good.splice(0,20))
, count = 0;
// Use NLP to break into keywords
var training = data.map(function(msg){
var msgTokens = tokenizer.tokenize(msg.data)
, input = {}
, output = {};
// Make each message into an object, with each token as a field, whos value is the occourance of the word.
// This forms the input for brain
// for example {drugs:1}
msgTokens.forEach(function (e,i,a){
input[e] = 1;
});
// Change tokens into format needed for input
// Make each type the message is associated with as 1 for the output
// For example {sexting:1,bullying:1}
msg.types.forEach(function (e,i,a){
output[e] = 1
});
return {input:input,output:output};
});
net.train(training);
return net;
}
// Classify using the Neural Network
this.classifyNN = function(net, msg){
if(!net) throw _argumentError(0, 'net');
if(!msg) throw _argumentError(1, 'msg');
var msgTokens = tokenizer.tokenize(msg)
, input = {}
msgTokens.forEach(function (e,i,a){
input[e] = 1;
});
return net.run(input);
}
// Train the BayesClassifier
this.trainBayes = function(classifier, bad, good){
var data = bad.concat(good);
for(var i = 0 ; i < data.length ; i ++){
classifier.addDocument(data[i].data, data[i].types[0]);
}
classifier.train();
return classifier;
}
// Classify using the BayesClassifier
this.classifyBayes = function(classifier, msg){
if(!classifier) throw _argumentError(0, "classifier");
if(!msg) throw _argumentError(1, "msg");
return classifier.classify(msg);
}
/* Private
********************/
function _argumentError(paramIndex, argName) {
return new Error("Function did not receive parameter " + paramIndex + ": "+argName);
}
return module.exports = this;
}();<file_sep>KGM---SMS-Identification
========================
Repayment for helping launch our ios app | d6741968ad5ab12e41771ff78de2b1905258154e | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | kjgorman/KGM-SMS-Identification | a7682d91d4d84bbb8f4a88f8797f7e0c2127da2b | 17cc9e41624080ba40c16ba5f6f5b4766b39febe |
refs/heads/master | <repo_name>shruti3105/HotelReservationSystem<file_sep>/README.md
#Welcome to HotelReservationSystem
<file_sep>/lib/src/main/java/HotelReservationSystem/Hotel.java
package HotelReservationSystem;
import java.util.ArrayList;
import java.util.List;
public class Hotel {
private String name;
private double regularWeekdayRates;
private double regularWeekendRates;
public Hotel(String name, double regularWeekdayRates, double regularWeekendRates) {
this.name = name;
this.regularWeekdayRates = regularWeekdayRates;
this.regularWeekendRates = regularWeekendRates;
}
public double getRegularWeekendRates() {
return regularWeekendRates;
}
public void setRegularWeekendRates(double regularWeekendRates) {
this.regularWeekendRates = regularWeekendRates;
}
public String getName() {
return name;
}
public double getRegularWeekdayRates() {
return regularWeekdayRates;
}
public void setRegularWeekdayRates(double regularWeekdayRates) {
this.regularWeekdayRates = regularWeekdayRates;
}
private static List<Hotel> hotelList = new ArrayList<>();
public static boolean addHotel(Hotel hotel) {
if (hotel == null)
return false;
if (hotelList.contains(hotel))
return false;
hotelList.add(hotel);
return true;
}
public static void main(String[] args) {
addHotel(new Hotel("Lakewood", 110, 90));
addHotel(new Hotel("Bridgewood", 160, 60));
addHotel(new Hotel("Ridgewood", 220, 150));
}
}<file_sep>/HotelReservationTest.java
import org.junit.jupiter.api.Test; import
org.junit.jupiter.api.Assertions;
import java.io.IOException;
import java.text.ParseException;
public class HotelReservationTest {
HotelReservationSystem hotelReservationSystem = new HotelReservationSystem();
/*@Test
public void whenNewHotelAdded_ShouldReturnTrue() {
Assertions.assertTrue(hotelReservationSystem.addHotel("Lakewood", 110));
Assertions.assertTrue(hotelReservationSystem.addHotel("Bridgewood", 160));
Assertions.assertTrue(hotelReservationSystem.addHotel("Ridgewood", 220));
}
@Test
public void whenFindCheapestHotelMethodCalled_shouldReturn_nameOfHotelAndMinimumRent() {
Assertions.assertTrue(hotelReservationSystem.addHotel("Lakewood", 110));
Assertions.assertTrue(hotelReservationSystem.addHotel("Bridgewood", 160));
Assertions.assertTrue(hotelReservationSystem.addHotel("Ridgewood", 220));
Assertions.assertEquals("Lakewood", hotelReservationSystem.findCheapestHotel("10Sep2020", "11Sep2020"));
}*/
@Test
public void whenWeekendRateAddedInTheHostelRate_ShouldReturnsTrue() {
Assertions.assertTrue(hotelReservationSystem.addHotel("Lakewood", 110, 90));
Assertions.assertTrue(hotelReservationSystem.addHotel("Bridgewood", 160, 60));
Assertions.assertTrue(hotelReservationSystem.addHotel("Ridgewood", 110, 150));
hotelReservationSystem.printHotels();
}
@Test
public void whenFindCheapestHotelIsCalled_shouldReturn_nameOfHotelWithCheapestRent() {
Assertions.assertTrue(hotelReservationSystem.addHotel("Lakewood", 110, 90));
Assertions.assertTrue(hotelReservationSystem.addHotel("Bridgewood", 160, 60));
Assertions.assertTrue(hotelReservationSystem.addHotel("Ridgewood", 220, 150));
Assertions.assertEquals("Bridgewood", hotelReservationSystem.findCheapestHotel("10Sep2020", "11Sep2020"));
}
}
<file_sep>/HotelReservationSystem.java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class HotelReservationSystem {
private static Map<String, Hotel> hotelMap;
public HotelReservationSystem() {
hotelMap = new HashMap<>();
}
public boolean addHotel(String name, int HotelRateRegularWeekdays) {
Hotel hotelObject = new Hotel(name, HotelRateRegularWeekdays);
hotelMap.put(name, hotelObject);
return true;
}
public void printHotels() {
System.out.println("********************************************************************************************");
System.out.println("Welcome in the online reservation of the hotel, you can book your hotel room online");
System.out.println("********************************************************************************************");
for (Map.Entry<String, Hotel> entry : hotelMap.entrySet()) {
System.out.println("Hotel Name : " + entry.getKey());
System.out.println("Rate on weekdays for regular customers : " + entry.getValue().getHotelRateRegularWeekDay());
}
}
public String findCheapestHotel(String fromDate, String toDate) {
Map<Integer, ArrayList<Hotel>> rateMap = createRateMap(fromDate, toDate);
int minimumRate = Integer.MAX_VALUE;
for (Map.Entry<Integer, ArrayList<Hotel>> entry : rateMap.entrySet()) {
if (entry.getKey() < minimumRate)
minimumRate = entry.getKey();
}
System.out.println(rateMap.get(minimumRate).get(0).getHotelName());
System.out.println("Total Rate : " + minimumRate*(numberOfDays(fromDate,toDate)+1));
return rateMap.get(minimumRate).get(0).getHotelName();
}
public static Map<Integer, ArrayList<Hotel>>createRateMap(String fromDate, String toDate) {
HashMap<Integer, ArrayList<Hotel>> rateMap = new HashMap<>();
int numOfDays = numberOfDays(fromDate, toDate);
for (Map.Entry<String, Hotel> entry : hotelMap.entrySet()) {
int rent = (entry.getValue().getHotelRateRegularWeekDay() * numOfDays);
rateMap.computeIfAbsent(rent, k -> new ArrayList<>()).add(entry.getValue());
}
return rateMap;
}
public static int numberOfDays(String startDate, String endDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyyyy");
LocalDate from = LocalDate.parse(startDate, formatter);
LocalDate to = LocalDate.parse(endDate, formatter);
int numOfDays = 0;
for (LocalDate date = from; date.isBefore(to); date = date.plusDays(1)) {
numOfDays++;
}
return numOfDays;
}
public static int isWeekend(String startDate, int numOfDays) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyyyy");
LocalDate from = LocalDate.parse(startDate, formatter);
DayOfWeek day1_OfWeek = DayOfWeek.of(from.get(ChronoField.DAY_OF_WEEK));
int count = 0;
switch (day1_OfWeek) {
case SATURDAY:
count = 2 ;
break;
case SUNDAY:
count = 1 ;
break;
default:
count = 0;
break;
}
return count;
}
public static void main(String[] args) {
System.out.println("Welcome to Hotel Reservation Program");
}
}
| bcb41308977888dbda17c8c6fd7c7a836239ff19 | [
"Markdown",
"Java"
] | 4 | Markdown | shruti3105/HotelReservationSystem | 47cc1ba1b9b657cee43bae5f6e47737f12308459 | b3145f16d31d6c9258063af45319ad00b2e8c7d9 |
refs/heads/main | <repo_name>jsmaks/goit-js-hw-02<file_sep>/js/task-6.js
let input;
let total = 0;
const numbers = [];
do {
input = prompt(`Введите число`);
let num = Number(input);
numbers.push(num);
if (input === null) {
alert('Пользователь отменил ввод')
}
}
while (input !== null) {
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
}
console.log(`Результат сложения чисел = ${total}`);
| d93a440f5e767747393cabcd7a76163b7336ea39 | [
"JavaScript"
] | 1 | JavaScript | jsmaks/goit-js-hw-02 | db1df8d8fce0effadb45609ba8ff9272aeb790b7 | b6ca1054921d33650dac062c421f81f2d9162e63 |
refs/heads/main | <file_sep>import React, {Component} from "react";
import {View, StyleSheet} from "react-native"; //menambah style elemen
import {Text, Input, Button} from "react-native-elements"; // Load Komponen Text, Input dan Button
import TopHeader from "../Component/TopHeader";
class BalokScreen extends Component {
constructor() {
super();
this.state = {
keliling: 0,
luas: 0,
volume: 0,
p: 0,
l: 0,
t: 0
}
}
hitungLuas = () => {
let p = Number(this.state.p); //ambil dan konversi nilai p ke numeric
let l = Number(this.state.l); //ambil dan konversi nilai l ke numeric
let t = Number(this.state.t); //ambil dan konversi nilai t ke numeric
let lu = 2 * (p * l + p * t + l * t);
this.setState({luas: lu});
}
hitungVolume = () => {
let p = Number(this.state.p);
let l = Number(this.state.l);
let t = Number(this.state.t);
let v = p * l * t;
this.setState({volume : v});
}
hitungKeliling = () => {
let p = Number(this.state.p);
let l = Number(this.state.l);
let t = Number(this.state.t);
let k = 4 * (p + l + t);
this.setState({keliling : k});
}
render() {
const styles = StyleSheet.create({
container: {
padding: 20,
justifyContent: "center"
},
input: {
marginTop: 20
},
labelInput:{
color:"orange"
},
result: {
fontSize: 25,
fontWeight: "bold",
marginTop: 10,
color: "black"
}
});
return(
<View>
<TopHeader navigation={this.props.navigation} title="Balok" />
<View style={styles.container}>
<Text h4> B<NAME> </Text>
<Input
label="<NAME>" labelStyle={styles.labelInput} keyboardType="numeric"
containerStyle={styles.input} onChangeText={(value) => this.setState({p: value}) }
value={this.state.p.toString()} />
<Input
label="<NAME>" labelStyle={styles.labelInput} keyboardType="numeric"
containerStyle={styles.input} onChangeText={(value) => this.setState({l: value}) }
value={this.state.l.toString()} />
<Input
label="<NAME>" labelStyle={styles0000000.labelInput} keyboardType="numeric"
containerStyle={styles.input} onChangeText={(value) => this.setState({t: value}) }
value={this.state.t.toString()} />
<Button containerStyle={styles.input} title="Hitung"
onPress={() => {this.hitungLuas(); this.hitungVolume(); this.hitungKeliling();}} />
<Text style={styles.result}>Keliling Balok = {this.state.keliling} </Text>
<Text style={styles.result}>Luas Permukaan Balok = {this.state.luas} </Text>
<Text style={styles.result}>Volume Balok = {this.state.volume} </Text>
</View>
</View>
);
}
}
export default BalokScreen;<file_sep>
import { createAppContainer } from "react-navigation";
import { createDrawerNavigator } from "react-navigation-drawer";
import BerandaScreen from "./Screen/BerandaScreen";
import TabungScreen from "./Screen/TabungScreen";
import KerucutScreen from "./Screen/KerucutScreen";
import KubusScreen from "./Screen/KubusScreen";
import BalokScreen from "./Screen/BalokScreen";
import BolaScreen from "./Screen/BolaScreen";
import DesimalScreen from "./Screen/DesimalScreen";
import BinerScreen from "./Screen/BinerScreen";
import OktalScreen from "./Screen/OktalScreen";
import HexaScreen from "./Screen/HexaScreen";
import CelciusScreen from "./Screen/CelciusScreen";
import BMIScreen from "./Screen/BMIScreen";
import SiswaScreen from "./Screen/SiswaScreen";
const AppNavigator = createDrawerNavigator({
Beranda : {
screen: BerandaScreen
},
Tabung : {
screen: TabungScreen
},
Kerucut : {
screen: KerucutScreen
},
Kubus : {
screen: KubusScreen
},
Balok : {
screen: BalokScreen
},
Bola : {
screen: BolaScreen
},
Desimal : {
screen: DesimalScreen
},
Biner : {
screen: BinerScreen
},
Oktal : {
screen: OktalScreen
},
Hexa :{
screen: HexaScreen
},
Celcius : {
screen: CelciusScreen
},
BMI : {
screen: BMIScreen
},
Siswa : {
screen: SiswaScreen
}
});
export default createAppContainer(AppNavigator);<file_sep>import React, { Component } from 'react';
import {View, Picker, PickerItem} from "react-native"; //menambah style elemen
import {Text, Input, Button} from "react-native-elements"; // Load Komponen Text,Input dan Button
import TopHeader from "../Component/TopHeader";
class HexaScreen extends Component {
constructor() {
super();
this.state = {
option: "10",
hexa: "",
result: ""
}
}
convertToDesimal = () => {
let hasil = parseInt(this.state.hexa,16).toString(10);
this.setState({result: hasil});
}
convertToBiner = () => {
let hasil = parseInt(this.state.hexa,16).toString(2);
this.setState({result: hasil});
}
convertToOktal = () => {
let hasil = parseInt(this.state.hexa,16).toString(8);
this.setState({result: hasil});
}
convert = () => {
if (this.state.option === "10") {
this.convertToDesimal();
}
else if (this.state.option === "2") {
this.convertToBiner();
}
else if (this.state.option === "8") {
this.convertToOktal();
}
}
render () {
return(
<View>
<TopHeader navigation={this.props.navigation} title="Konversi Hexa" />
<View style={{padding:10}}>
<Text h4>Konversi Bilangan Hexa</Text>
<Text h5>Opsi Konversi</Text>
<Picker
selectedValue={this.state.option} style={{width: 200, height: 80}}
onValueChange={(value) => this.setState({option: value})}
>
<Picker.Item label="Desimal" value="10" />
<Picker.Item label="Biner" value="2" />
<Picker.Item label="Oktal" value="8" />
</Picker>
<Input label="Masukkan Nilai Hexa" value={this.state.hexa}
onChangeText={(value) => this.setState({hexa: value})} />
<Button title="Convert" onPress={this.convert} />
<Text h5>Hasil: {this.state.result} </Text>
</View>
</View>
);
}
}
export default HexaScreen;<file_sep>import React, { Component } from 'react';
import {View, Picker, PickerItem} from "react-native"; //menambah style elemen
import {Text, Input, Button} from "react-native-elements"; // Load Komponen Text,Input dan Button
import TopHeader from "../Component/TopHeader";
class BinerScreen extends Component {
constructor() {
super();
this.state = {
option: "10",
biner: "",
result: ""
}
}
convertToDesimal = () => {
let hasil = parseInt(this.state.biner,2).toString(10);
this.setState({result: hasil});
}
convertToOktal = () => {
let hasil = parseInt(this.state.biner,2).toString(8);
this.setState({result: hasil});
}
convertToHexa = () => {
let hasil = parseInt(this.state.biner,2).toString(16).toUpperCase();
this.setState({result: hasil});
}
convert = () => {
if (this.state.option === "10") {
this.convertToDesimal();
}
else if (this.state.option === "8") {
this.convertToOktal();
}
else if (this.state.option === "16") {
this.convertToHexa();
}
}
render () {
return(
<View>
<TopHeader navigation={this.props.navigation} title="Konversi Biner" />
<View style={{padding:10}}>
<Text h4>Konversi Bilangan Biner</Text>
<Text h5>Opsi Konversi</Text>
<Picker
selectedValue={this.state.option} style={{width: 200, height: 80}}
onValueChange={(value) => this.setState({option: value})}
>
<Picker.Item label="Desimal" value="10" />
<Picker.Item label="Oktal" value="8" />
<Picker.Item label="Hexa" value="16" />
</Picker>
<Input label="Masukkan Nilai Biner" value={this.state.biner}
onChangeText={(value) => this.setState({biner: value})} />
<Button title="Convert" onPress={this.convert} />
<Text h5>Hasil: {this.state.result} </Text>
</View>
</View>
);
}
}
export default BinerScreen;<file_sep>import React, { Component } from 'react';
import {View, Picker} from "react-native"; //menambah style elemen
import {Text, Input, Button} from "react-native-elements"; // Load Komponen Text,Input dan Button
import TopHeader from "../Component/TopHeader";
class CelciusScreen extends Component {
constructor() {
super();
this.state = {
option: "4",
celcius: "",
result: ""
}
}
convertToReamur = () => {
let celcius = Number(this.state.celcius);
let hasil = celcius * 4/5;
this.setState({result: hasil});
}
convertToFahrenheit = () => {
let celcius = Number(this.state.celcius);
let hasil = (celcius * 9/5) + 32;
this.setState({result: hasil});
}
convertToKelvin = () => {
let celcius = Number(this.state.celcius);
let hasil = celcius+ 273;
this.setState({result: hasil});
}
convert = () => {
if (this.state.option === "4") {
this.convertToReamur();
}
else if (this.state.option === "9") {
this.convertToFahrenheit();
}
else if (this.state.option === "273") {
this.convertToKelvin();
}
}
render () {
return(
<View>
<TopHeader navigation={this.props.navigation} title="Konversi Suhu" />
<View style={{padding:10}}>
<Text h4>Konversi Suhu</Text>
<Text h5>Opsi Konversi</Text>
<Picker
selectedValue={this.state.option} style={{width: 200, height: 80}}
onValueChange={(value) => this.setState({option: value})}
>
<Picker.Item label="Reamur" value="4" />
<Picker.Item label="Fahrenheit" value="9" />
<Picker.Item label="Kelvin" value="273" />
</Picker>
<Input label="Masukkan <NAME>" value={this.state.celcius}
onChangeText={(value) => this.setState({celcius: value})} />
<Button title="Convert" onPress={this.convert} />
<Text h5>Hasil: {this.state.result} </Text>
</View>
</View>
);
}
}
export default CelciusScreen;<file_sep>import React, { Component } from "react";
import { Header, Icon } from "react-native-elements";
class TopHeader extends Component {
render() {
return(
<Header
backgroundColor = "#a3ffee"
leftComponent={
<Icon name="menu" color="#ff3b3b" onPress={ () => this.props.navigation.toggleDrawer()} />
}
centerComponent={
{
text: this.props.title,
style: {color: "#ff3b3b", fontWeight:"bold"}
}
}
statusBarProps={ {barStyle: "light-content"} }
/>
);
}
}
export default TopHeader;<file_sep>import React, { Component } from "react";
import {View, Text} from "react-native";
import TopHeader from "../Component/TopHeader";
class BerandaScreen extends Component {
render() {
return(
<View>
<TopHeader navigation={this.props.navigation} title="Beranda" />
<Text>Beranda</Text>
</View>
);
}
}
export default BerandaScreen;<file_sep>import React, {Component} from "react";
import {View, StyleSheet} from "react-native"; //menambah style elemen
import {Text, Input, Button} from "react-native-elements"; // Load Komponen Text, Input dan Button
import TopHeader from "../Component/TopHeader";
const styles = StyleSheet.create({
container: {
padding: 20,
justifyContent: "center"
},
input: {
marginTop: 20
},
labelInput:{
color:"pink"
},
result: {
fontSize: 25,
fontWeight: "bold",
marginTop: 10,
color: "black"
}
});
class BMIScreen extends Component {
constructor() {
super();
this.state = {
m: '',
h: '',
bmi: '',
ket: ''
}
}
hitungBMI = () => {
let m = Number(this.state.m);
let h = Number(this.state.h);
let b = m / (h*h);
if (b < 18.5) {
this.setState({ket: 'Kurus'});
}
else if (b > 18.5 && b < 22.9) {
this.setState({ket: 'Ideal'});
}
else if (b > 22.9 && b < 24.9){
this.setState({ket: 'OverWeight'});
}
else if (b > 24.9) {
this.setState({ket: 'Obesitas'});
}
this.setState({bmi: b});
}
render() {
return(
<View>
<TopHeader navigation={this.props.navigation} title="BMI" />
<View style={styles.container}>
<Text h4> Body Mass Index </Text>
<Input
label="Berat Badan Anda" labelStyle={styles.labelInput} keyboardType="numeric"
containerStyle={styles.input} onChangeText={(value) => this.setState({m: value}) }
value={this.state.m.toString()}
/>
<Input
label="Tinggi Badan Anda (dalam meter)" labelStyle={styles.labelInput} keyboardType="numeric"
containerStyle={styles.input} onChangeText={(value) => this.setState({h: value}) } value={this.state.h.toString()}
/>
<Button containerStyle={styles.input} title="Hitung"
onPress={this.hitungBMI} />
<Text style={styles.result}>BMI : {this.state.bmi} </Text>
<Text style={styles.result}>Keterangan : {this.state.ket} </Text>
</View>
</View>
);
}
}
export default BMIScreen; | 88c9c8aa46fe95ff04ff1904d113480b99f5eadf | [
"JavaScript"
] | 8 | JavaScript | RizaldyRaditya/ReactNative1 | 2e2091eed491d4d9df5da06b89fae2b9af4b3568 | 005efc19939546e268846d0ab36edcd009cd296c |
refs/heads/master | <repo_name>sriharivaleti/Angular-Best-Practices<file_sep>/src/app/components/sequence/sequence.component.ts
import { Component, OnInit } from '@angular/core';
import { NumberService } from 'src/app/providers/number/number.service';
@Component({
selector: 'app-sequence',
templateUrl: './sequence.component.html',
styleUrls: ['./sequence.component.scss']
})
export class SequenceComponent implements OnInit {
count = 1;
constructor(private numberService: NumberService) { }
ngOnInit() {
this.count = this.numberService.process(this.count);
}
}
<file_sep>/src/app/providers/number/number.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class NumberService {
constructor() { }
process(count) {
count += 1;
count /= 2;
return count;
}
}
| b0633f82a7f0853a568dc794d679ee60ab6dda35 | [
"TypeScript"
] | 2 | TypeScript | sriharivaleti/Angular-Best-Practices | 6d60edbc0005ac1ecee198b2ece62383b41233aa | 87bf3f9d85334ecd9a5fa89e81fb319f9390a2a4 |
refs/heads/main | <repo_name>2blackdragon/Web<file_sep>/main.py
from flask import Flask, render_template, redirect, request
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, IntegerField
from wtforms.validators import DataRequired
from user import User
from data import db_session
app = Flask(__name__)
app.config['SECRET_KEY'] = 'yandexlyceum_secret_key'
class LoginForm(FlaskForm):
login = StringField('Login / email', validators=[DataRequired()])
password1 = PasswordField('<PASSWORD>', validators=[DataRequired()])
password2 = PasswordField('Repeat password', validators=[DataRequired()])
surname = StringField('Surname', validators=[DataRequired()])
name = StringField('Name', validators=[DataRequired()])
age = IntegerField('Age', validators=[DataRequired()])
position = StringField('Position', validators=[DataRequired()])
speciality = StringField('Speciality', validators=[DataRequired()])
address = StringField('Address', validators=[DataRequired()])
submit = SubmitField('Submit')
@app.route('/<title>')
@app.route('/index/<title>')
def hello(title):
return render_template('base.html', title=title)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == "GET":
form = LoginForm()
if form.validate_on_submit():
return redirect('/success')
return render_template('index.html', title='Регистрация', form=form)
elif request.method == 'POST':
try:
user = User()
user.email = request.form["login"]
user.hashed_password = hash(request.form["login"])
user.name = request.form["name"]
user.surname = request.form["surname"]
user.age = int(request.form["age"])
user.position = request.form["position"]
user.speciality = request.form["speciality"]
user.address = request.form["address"]
database_name = "db/user_list.sqlite"
db_session.global_init(database_name)
db_sess = db_session.create_session()
db_sess.add(user)
db_sess.commit()
return render_template('answer.html', title='Регистрация', text='Форма успешно отправлена')
except Exception:
return render_template('answer.html', title='Регистрация', text='Произошла ошибка')
if __name__ == '__main__':
app.run(port=8080, host='127.0.0.1')
| 4195cb5c240b4dafa33e43a03ca83f8d634d718b | [
"Python"
] | 1 | Python | 2blackdragon/Web | 0aef3560804312cf8bb86da4212b0057c8c64875 | bba5e21bcfd81685bd21ec862be53a7f46d1f90f |
refs/heads/master | <repo_name>daihoangnam3it/react--tour-city<file_sep>/src/components/TourList/index.js
import React, { Component } from 'react';
import Tour from "../Tour";
import "./tourlist.scss";
import {tourData} from "../../tourData"
export default class index extends Component {
state={
tour:tourData
}
handleDelete=id=>{
const stored=this.state.tour.filter(item=>item.id!==id);
this.setState({
tour:stored
})
}
render() {
return (
<section className="tourlist">
{this.state.tour.map(item=><Tour key={item.id} data={item} handleDelete={this.handleDelete}/>)}
</section>
)
}
}
<file_sep>/src/components/Tour/Tour.js
import React, { Component } from 'react';
import './tour.scss';
export default class Tour extends Component {
state={
showInfo:false
}
handleShow=id=>{
this.setState({
showInfo:!this.state.showInfo
})
}
render() {
console.log(this.props)
const { id, city, img, name, info } = this.props.data;
const {handleDelete}=this.props;
return (
<article className='tour'>
<div className='img-container'>
<img src={img} alt='' />
<span onClick={()=>handleDelete(id)}>
<i className='fa fa-times' aria-hidden='true'></i>
</span>
</div>
<div className='info-container'>
<h2 className='city-name'>{city}</h2>
<h3>{name}</h3>
<h5>
Info{' '}
<span onClick={()=>this.handleShow(id)}>
<i className='fa fa-angle-down' aria-hidden='true'></i>
</span>
{this.state.showInfo?<p>{info}</p>:null}
</h5>
</div>
</article>
);
}
}
| 7ac9a126fb901bdfbc760e32e1c525d8e6ed9bd9 | [
"JavaScript"
] | 2 | JavaScript | daihoangnam3it/react--tour-city | 79c138dc1d803dd4e5f18cfa175f06d70a8a3527 | a6738e4f335f618111a73e80ec2772e7506e2e64 |
refs/heads/master | <file_sep>/* <NAME>
* Program 2
* CS 140-001
* 2-24-12
*/
package programtwo;
import javax.swing.JFrame;
import java.awt.*;
import java.util.Locale;
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.lang.Math;
public class ProgramTwo extends JFrame {
private static final int FRAME_SIZE = 500;
private static final int MAX_NUM = 40;
private static final int MIN_NUM = 10;
private static int lineNumber;
public static void main(String[] args) {
ProgramTwo guiWindow = new ProgramTwo ();
// Set the Frame Size
guiWindow.setSize(FRAME_SIZE, FRAME_SIZE);
guiWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
String valueString;
//Create input error trap to ask for Number of lines in the Grid
do{
valueString = JOptionPane.showInputDialog("Enter The Number of Lines in the Grid (10-40)");
guiWindow.lineNumber = Integer.parseInt(valueString);
} while(lineNumber < MIN_NUM || lineNumber > MAX_NUM);
//Sets window as Visible
guiWindow.setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics canvas = getContentPane().getGraphics();
int width = this.getContentPane().getWidth();
int height = this.getContentPane().getHeight();
//X Coord top left
double bottomBoarder = height*0.1;
int yBottom = (int)bottomBoarder;
//Y Coord top left
double topBoarder = height*0.9;
int yTop = (int)topBoarder;
//X coord bottom left
double leftBoarder = width*0.1;
int xLeft = (int)leftBoarder;
//Y coord bottom left
double rightBoarder = width*0.9;
int xRight = (int)rightBoarder;
//Draw the border
canvas.drawLine(xLeft,yBottom,xLeft,yTop);
canvas.drawLine(xRight,yBottom,xRight,yTop);
canvas.drawLine(xLeft,yTop,xRight,yTop);
canvas.drawLine(xLeft,yBottom,xRight,yBottom);
}
}
<file_sep>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
cout <<" ******************************************************** " << endl;
cout <<" * Darlene's Data Collector *" << endl;
cout <<" ********************************************************" << endl;
string fileName;
ofstream inFile;
cout <<"What File to Analyze Darlene? ";
getline(cin, fileName);
cout << endl;
inFile.open(fileName.c_str());
if(!inFile)
cout << "Opening File" << fileName << " has Failed!" << endl;
else
cout << fileName << " has been opened Successfully!" << endl;
}
<file_sep>/*<NAME>
* Program 4
* 4/1/2012
* 140-001
*/
package program4;
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class Program4 {
public static void main(String[] args) {
//Declare Variables
int MinLower = 0, MaxLower = 999, MinUpper = 80, upperBound, lowerBound;
//Declare Random Object as Instructed
Random randomNum = new Random();
//Declare Array
int[] myArray = new int[2000];
//Declare Scanner
Scanner keyboard = new Scanner(System.in);
//Input error for Lower Bound
do{
System.out.print("Enter the Lower bound (0.. 999): ");
lowerBound=keyboard.nextInt();
} while(lowerBound < MinLower || lowerBound > MaxLower);
//Input error for Upper Bound
do{
System.out.print("Enter the Upper bound (80.. 999): ");
upperBound=keyboard.nextInt();
} while(upperBound < MinUpper || upperBound > MaxLower);
//Assign Values to the Array
for(int i = 0;i < 2000; i++)
{
myArray[i] = randomNum.nextInt(2001);
//Return the Values that are between around Bounds Specified by user
if(myArray[i] >= lowerBound && myArray[i] <= upperBound){
System.out.printf("%d \n",myArray[i]);
}
}
System.out.println("There are " + myArray.length + " Numbers in the Range " + lowerBound + " to " + upperBound);
}
}
<file_sep>/*<NAME>
* 4/11/2012
*Lab12
*CS140-025
*/
package lab12;
import java.util.Scanner;
public class Lab12 {
public static int ARRAY_SIZE = 26;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Declare and instantiate the array to hold the letter counts
int[] arr = new int[ARRAY_SIZE];
String text;
//Ask the user to enter the text
System.out.println("Type some text and then press enter.");
text = keyboard.nextLine();
//Convert all letters to uppercase
text = text.toUpperCase();
parseLetters(arr, text);
//Print the counts for each character
for (int i = 0; i < ARRAY_SIZE; i++) {
System.out.println((char)('A' + i) + ": " + arr[i]);
}
}
//Given a string, this method will count the frequency of letters
//A-Z and store them in the array. The location corresponds with the
//letter. Example: array[0] contains count for 'A', array[25] holds
//count for 'Z'.
public static void parseLetters(int[] array, String text) {
for (int i = 0; i < text.length(); i++) {
int temp = text.charAt(i);
if (temp >= 'A' && temp <= 'Z') {
array[temp - 65]++;
}
}
}
}
| eb2698cf262c4bea2d32ba4824a7eb6e11b09462 | [
"Java",
"C++"
] | 4 | Java | Hoolig4n/University-Projects | 8e0786f545bf1069aadf218f4a9e9b10e02f3265 | 7cf9768600c372b3a2683cee96752dcba3a92ad9 |
refs/heads/master | <file_sep># SOLOMON-WebStudy-
웹공부하쟝
<file_sep>from django.urls import path
from .views import ReactSampleListView, ReactSampleDetailView
urlpatterns = [
path('', ReactSampleListView.as_view()),
path('<pk>', ReactSampleDetailView.as_view()),
]<file_sep>from rest_framework.generics import ListAPIView, RetrieveAPIView
from react_sample.models import ReactSample
from .serializer import ReactSampleSerializer
class ReactSampleListView(ListAPIView):
queryset = ReactSample.objects.all()
serializer_class = ReactSampleSerializer
class ReactSampleDetailView(RetrieveAPIView):
queryset = ReactSample.objects.all()
serializer_class = ReactSampleSerializer<file_sep>from django.shortcuts import render
# Create your views here.
#def react_sample(requests):
# return render(requests, 'draw_map_daum.html')<file_sep>from django.contrib import admin
from board.models import DjangoBoard
# Register your models here.
admin.site.register(DjangoBoard)<file_sep># pages/urls.py
from django.urls import path
from board.views import boardView
urlpatterns = [
path('', boardView, name='home')
]<file_sep># pages/urls.py
from django.urls import path
from react_sample.views import reactView
urlpatterns = [
path('', reactView, name='home')
]<file_sep>from django.contrib import admin
from react_sample.models import ReactSample
# Register your models here.
admin.site.register(ReactSample)
<file_sep>from rest_framework import serializers
from react_sample.models import ReactSample
class ReactSampleSerializer(serializers.ModelSerializer):
class Meta:
model = ReactSample
fields = ('title', 'content')
<file_sep>from django.http import HttpResponse
from board.models import DjangoBoard
from django.shortcuts import render_to_response
rowsPerPage = 5
def boardView(request):
boardList = DjangoBoard.objects.order_by('-id')[0:5]
current_page = 1
totalCnt = DjangoBoard.objects.all().count()
pagingHelperIns = pagingHelper()
totalPageList = pagingHelperIns.getTotalPageList(totalCnt, rowsPerPage)
print ('totalPageList', totalPageList)
return render_to_response('listSpecificPage.html', {'boardList':boardList,
'totalCnt':totalCnt, 'current_page':current_page, 'totalPageList': totalPageList})
class pagingHelper:
def getTotalPageList(self, total_cnt, rowsPerPage):
if ((total_cnt % rowsPerPage) == 0):
self.total_pages = int(total_cnt / rowsPerPage)
print ('getTotalPage #1')
else:
self.total_pages = int(total_cnt / rowsPerPage) + 1
print ('getTotalPage #2')
self.totalPageList = []
for j in range(self.total_pages):
self.totalPageList.append(j + 1)
return self.totalPageList
def __init__(self):
self.total_pages = 0
self.totalPageList = 0 | 67dbb77caa13777b8d992607a7e9736b0853fe48 | [
"Markdown",
"Python"
] | 10 | Markdown | 2SJ/SOLOMON-WebStudy- | ee28834a21e0683e333cb7941fc999b3ae1a7ace | ab1b22d442b84ec7612fcbaf1a46445f2b75b7aa |
refs/heads/master | <repo_name>g08m11/Debug<file_sep>/Source/Debug.swift
//
// Debug.swift
// Sample
//
// Created by g08m11 on 2015/09/18.
// Copyright (c) 2015年 Bloc. All rights reserved.
//
import Foundation
struct Debug {
static func debugInfoPlist(file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) {
var str = ""
for (k, v) in NSBundle.mainBundle().infoDictionary! {
str += "\(k) : \(v)\n"
}
log("\(str)", file: file, function: function, line: line)
}
static func log(message: AnyObject,
function: String = __FUNCTION__,
file: String = __FILE__,
line: Int = __LINE__) {
#if DEBUG
var str = "\(message)\n-- FileName: \(file)\n-- Method: \(function)\n-- Line: \(line)"
str = str.stringByReplacingOccurrencesOfString("\n", withString: "\n ")
print("\n*** \(str)\n", terminator: "")
#endif
}
}<file_sep>/README.md
The better way to deal with Debug in Swift
## Debug
## 実行環境
### Mac:OSX Yosemite Version 10.10.5
### Xcode:7.0
### Swift:2.0
# 使うまでの流れ
## 1.Debugのソースを落としてくる
[ここから](https://github.com/g08m11/Debug)
zipファイルをダウンロードして、「Resource」フォルダ内にある
「Debug.swift」だけ取り出し、使用したいプロジェクトへ追加する。
## 2.デバッグ時のみ実行したい設定にする
(既に設定されている方はスキップ可能です。)
### 2.1①TARGEETSから「マイプロジェクト」を選び、②「Build Settings」を選び、「Swift Compiler」から③「Other Swift Flags」を選ぶ。


### 2.2「+」を押し、「-D DEBUG」を入力して設定する。


### 2.3設定を確認する。

## 3.デバッグしたい所にコードを書く
(今回はViewControllerに書いてます。)
```ViewController.swift
class ViewController: UIViewController {
override func viewDidLoad() {
Debug.log("ここまできてる")
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
```
## 4.確認する
こちらはConsole側に出力されます。
こちらはConsoleのみにすると綺麗に見えます。

# 使い方
ただ呼ばれているか確認したいだけの場合
```
Debug.log("")
```
呼ばれていてメッセージも確認したい場合
```
Debug.log("g08m11")
```
インスタンス変数や変数の値を確認したい場合
```
str = "g08m11"
Debug.log("ここまできてる\(str)")
```
# 見方
```
*** MESSAGE
-- FileName: /Users/gushikenmasaru/work/swift/MyApps/test/test/ViewController.swift
-- Method: viewDidLoad()
-- Line: 14
```
### MESSAGE:
Debug.log("MESSAGE")など文字列を設定した場合に表示されます。
### FileName:
Debug.log()を追加したファイル名に該当します。
### Method:
Debug.log()を追加したファイルのメソッド名に該当します。
### Line:
Debug.log()を追加したファイルの行に該当します。
## 参考サイト:
http://oropon.hatenablog.com/entry/2014/06/05/030620
http://qiita.com/qmihara/items/a6b88b74fe64e1e05ca4
http://qiita.com/inamiy/items/c4e137309725485dc195
| 5c9dfc7c90cf07b9a586cb962d1d2bc39e3b88c6 | [
"Swift",
"Markdown"
] | 2 | Swift | g08m11/Debug | a6e6bf8144f6765721e6bebc305cf4d325930dc1 | da0ed5db76bf53f9630931454dc14171f074b1a6 |
refs/heads/master | <repo_name>lechdo/bookstore-api<file_sep>/bookstoreApi/api/serializers.py
from rest_framework import serializers
from .models import Category, Book, Chapter, SubChapter, BookImage
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ['id', 'name']
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['name', 'categories']
class ChapterSerialier(serializers.ModelSerializer):
class Meta:
model = Chapter
fields = ['name', 'book']
class SubChapterSerializer(serializers.ModelSerializer):
class Meta:
model = SubChapter
fields = ['name', 'content', 'chapter']
class BookImageSerializer(serializers.ModelSerializer):
class Meta:
model = BookImage
fields = ['name', 'path', 'book']
<file_sep>/bookstoreApi/api/views.py
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from django.http import JsonResponse, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from .serializers import ChapterSerialier, BookSerializer
from .models import Book, Chapter, Category
from rest_framework import status
import json
from django.core import serializers
@api_view(["GET"])
@csrf_exempt
def welcome(request):
content = {"message": "Welcome to the BookStore!"}
return JsonResponse(content)
@api_view(["GET"])
@csrf_exempt
def get_books(request):
books = Book.objects.all()
return JsonResponse({"books": [
{"id": book.id,
"name": book.name,
"categories": [cat.id for cat in book.categories.all()],
} for book in books
]}, content_type='JSON')
@api_view(["GET"])
@csrf_exempt
def get_book(request, book_id):
book = Book.objects.get(id=book_id)
chapters = Chapter.objects.filter(book=book).order_by("rank")
data = [{"id": chap.id, 'name': chap.name, 'rank': chap.rank} for chap in chapters]
return JsonResponse({'id': book.id,
'name': book.name,
'chapters': data,
}, safe=False, status=status.HTTP_200_OK)
@api_view(["GET"])
@csrf_exempt
def get_page(request, book_id, chapter_id, subchapter_id):
try:
book = Book.objects.get(id=book_id)
# chapter = book.chapters.all().order_by("rank")[chapter_id - 1]
chapter = book.chapters.get(id=chapter_id)
# subchapters = chapter.sub_chapters.all()
subchapter = chapter.sub_chapters.get(id=subchapter_id)
# subchapter = subchapters.order_by("rank")[subchapter_id - 1]
return JsonResponse({
'book_id': book.id,
'book_name': book.name,
'chapter_id': chapter.id,
'chapter_name': chapter.name,
'subchapter_id': subchapter.id,
'subchapter_name': subchapter.name,
'subchapter_content': subchapter.content,
'subchapters_len': len(subchapters)
}, safe=False, status=status.HTTP_200_OK)
except IndexError as e:
return HttpResponseNotFound("Cette page n'existe pas: {}".format(e))
@api_view(["POST"])
@csrf_exempt
def input_book(request):
book = Book()
book.name = request.data['name']
if request.data['categories']:
[book.categories.add(Category.objects.get(id=id)) for id in request.data['categories']]
book.save()
return JsonResponse({'id': book.id,
'name': book.name,
'categories': [cat.id for cat in book.categories.all()],
}, safe=False, status=status.HTTP_200_OK)
@api_view(["GET"])
@csrf_exempt
def get_categories(request):
categories = Category.objects.all()
return JsonResponse([
{
'id': cat.id,
'name': cat.name,
'image': cat.image,
} for cat in categories
], safe=False)
@api_view(["POST"])
@csrf_exempt
def add_category(request):
category = Category()
category.name = request.data['name']
category.image = request.data['image']
category.save()
return JsonResponse([
{
'id': category.id,
'name': category.name,
'image': category.image,
}
], safe=False)
<file_sep>/bookstoreApi/book_setter/main.py
# encoding: utf-8
from keyword import iskeyword
from json import loads, dumps
from os import path
from collections import MutableSequence, Mapping
from api.models import Book, Chapter, SubChapter
class FrozenJson:
"""
Class for making object-like read only json.
Very useful to state every dict key like an object attribute.
"""
def __new__(cls, arg):
if isinstance(arg, Mapping):
return super().__new__(cls)
elif isinstance(arg, MutableSequence):
return [cls(item) for item in arg]
else:
return arg
def __init__(self, mapping):
self._components = {}
for key, value in mapping.items():
# checking if the key is a keyword.
if iskeyword(key):
key += '_'
# checking if the key can be an attribute: this does not handle specials characters, only numbers.
if not key.isidentifier():
key = 'v_' + key
self._components[key] = value
def __getitem__(self, item):
if hasattr(self._components, item):
return getattr(self, item)
else:
return FrozenJson(self._components[item])
def __repr__(self):
return self._components
def __str__(self):
return self.__repr__()
def __call__(self):
return self._components
def __iter__(self):
if isinstance(self._components, MutableSequence):
return self._components
elif isinstance(self._components, Mapping):
return self._components
else:
raise TypeError("Cet élément n'est pas une liste ou un dictionnaire.")
def __len__(self):
if isinstance(self._components, MutableSequence) or isinstance(self._components, Mapping):
return len(self._components)
else:
raise TypeError("Cet élément n'est pas une liste ou un dictionnaire.")
def summary(dir):
"""
Get the summary data from the directory book. Return an object-like read only json.
:param dir:
:return:
"""
with open(dir + "\\summary.json", 'r', encoding="utf-8") as file:
data = loads(file.read())
return FrozenJson(data)
def get_book_structure(dir):
"""
Get the chapters names and theirs ranks from the book's manifest.
Return an object-like read only json.
:param dir:
:return:
"""
sum = summary(dir)
book = {}
for chapter, i in sum.chapters, range(len(sum.chapters)):
book[chapter] = {
"name": chapter,
"rank": i,
"sub_chapters": get_sub_chapters(dir, chapter, sum.sub_chapters.chapter)
}
return FrozenJson(book)
def get_sub_chapters(dir, chapter, subchapters):
"""
Get the subchapters names and theirs ranks from the book's manifest.
Return an object-like read only json.
:param dir:
:param chapter:
:param subchapters:
:return:
"""
data = {}
for subchap, i in subchapters, range(len(subchapters)):
with open(dir + "\\chapters\\{}\\{}".format(chapter, subchap.replace("?", "")), 'r', encoding="utf-8") as file:
content = file.read()
data[subchap] = {
"name": subchap,
"rank": i,
"content": content
}
return FrozenJson(data)
def get_book(dir):
"""
Beta version.
Persist the book data (except the pictures) with the manifest informations.
:param dir:
:return:
"""
data = get_book_structure(dir)
book = Book(name=path.split(dir)[-1])
book.save()
for chapter, _ in data:
new_chapter = Chapter(name=chapter,
book=book)
new_chapter.save()
book.chapters.add(new_chapter)
for subchapter in getattr(data, chapter).sub_chapters.keys():
cur_chapter = getattr(data, chapter)
cur_subchapter = getattr(cur_chapter.sub_chapters, subchapter)
new_subchapter = SubChapter(name=cur_subchapter.name,
chapter=new_chapter,
rank=cur_subchapter.rank,
content=cur_subchapter.content)
new_subchapter.save()
new_chapter.sub_chapters.add(new_subchapter)
new_chapter.save()
book.save()
<file_sep>/setup.py
import setuptools
from os import environ, curdir, path
from importlib import reload
import bookstoreApi as application
try:
version = environ["CI_COMMIT_TAG"]
except KeyError:
version = 'test-mode'
def overload_version():
with open(f"{curdir()/application.__name__}/__init__.py", 'r', encoding='utf-8') as file:
content = file.read()
content.replace(f"__version__ = {repr(application.__version__)}", f"__version__ = {repr(version)}")
with open(f"{path.abspath(curdir())}/{application.__name__}/__init__.py", 'w', encoding='utf-8') as file:
file.write(content)
reload(application)
overload_version()
setuptools.setup(
name="bookstoreApi",
version=version,
author="<NAME>",
author_email="<EMAIL>",
description="API pour la lecture de livres",
url="",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3.8",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
)
<file_sep>/bookstoreApi/api/migrations/0001_initial.py
# Generated by Django 3.0.8 on 2020-07-05 10:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
],
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('image', models.FilePathField()),
],
),
migrations.CreateModel(
name='Chapter',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Book')),
],
),
migrations.CreateModel(
name='SubChapter',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('content', models.TextField()),
('chapter', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Chapter')),
],
),
migrations.CreateModel(
name='BookImage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('path', models.FilePathField()),
('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Book')),
],
),
migrations.AddField(
model_name='book',
name='categories',
field=models.ManyToManyField(to='api.Category'),
),
]
<file_sep>/bookstoreApi/api/migrations/0003_auto_20200706_0807.py
# Generated by Django 3.0.8 on 2020-07-06 06:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20200706_0729'),
]
operations = [
migrations.AlterField(
model_name='bookimage',
name='path',
field=models.ImageField(upload_to='books_images'),
),
]
<file_sep>/bookstoreApi/__init__.py
# encoding: utf-8
__version__ = None<file_sep>/bookstoreApi/wsgi.py
from os import environ
from django.core.wsgi import get_wsgi_application
environ["DJANGO_SETTINGS_MODULE"] = "bookstoreApi.settings"
application = get_wsgi_application()
<file_sep>/bookstoreApi/api/models.py
# encoding:utf-8
from django.db import models
from abc import ABC, abstractmethod
def __repr_format(instance):
"""
Generic format for Models objects.
Return an assessable format of the object.
:param instance:
:return:
"""
attrs = []
for key in instance.__dict__:
if key not in ["_state", "id"]:
attrs.append(key)
params_repr = ', '.join(["{}={}".format(key, repr(getattr(instance, key))) for key in attrs])
return f"{type(instance).__name__}=({params_repr})"
def __str_format(instance):
"""
generic format for Models Objects. Return the 'name' attribute. If it not exists, return the standard format of
ModelBase class.
:param instance:
:return:
"""
try:
return instance.name
except AttributeError:
return instance.super().__str__()
# Monkey patching for avoiding multiple inheritances and meta class problems.
models.Model.__repr__ = __repr_format
models.Model.__str__ = __str_format
class Category(models.Model):
"""
Catégorie du livre.
"""
name = models.CharField(max_length=200)
image = models.FilePathField()
class Book(models.Model):
"""
Livre lui meme.
"""
name = models.CharField(max_length=200)
categories = models.ManyToManyField(Category)
class Chapter(models.Model):
"""
Chapitre d'un livre.
"""
name = models.CharField(max_length=200)
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="chapters")
rank = models.IntegerField(null=True)
class SubChapter(models.Model):
"""
Sous chapitre d'un chapitre d'un livre.
"""
name = models.CharField(max_length=200)
content = models.TextField()
chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, related_name="sub_chapters")
rank = models.IntegerField(null=True)
class BookImage(models.Model):
"""
Image contenue par un livre
"""
name = models.CharField(max_length=200)
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name="images")
path = models.TextField()
<file_sep>/bookstoreApi/api/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.welcome, name='index'),
path('/books', views.get_books, name='books'),
path('/<int:book_id>/book', views.get_book, name='book'),
path('/new_book', views.input_book, name='input_book'),
path('/categories', views.get_categories, name='categories'),
path('/<int:book_id>/book/<int:chapter_id>/<int:subchapter_id>', views.get_page, name='page'),
]
<file_sep>/bookstoreApi/api/migrations/0002_auto_20200706_0729.py
# Generated by Django 3.0.8 on 2020-07-06 05:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='chapter',
name='rank',
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name='subchapter',
name='rank',
field=models.IntegerField(null=True),
),
]
<file_sep>/bookstoreApi/api/migrations/0004_auto_20201221_1852.py
# Generated by Django 3.1.3 on 2020-12-21 17:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20200706_0807'),
]
operations = [
migrations.AlterField(
model_name='bookimage',
name='book',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='api.book'),
),
migrations.AlterField(
model_name='bookimage',
name='path',
field=models.TextField(),
),
migrations.AlterField(
model_name='chapter',
name='book',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='chapters', to='api.book'),
),
migrations.AlterField(
model_name='subchapter',
name='chapter',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sub_chapters', to='api.chapter'),
),
]
<file_sep>/bookstoreApi/workviews/apps.py
from django.apps import AppConfig
class WorkviewsConfig(AppConfig):
name = 'workviews'
| 0b80b1737231f0b938679d2289df1ca9c8a5b1c1 | [
"Python"
] | 13 | Python | lechdo/bookstore-api | a919ca47a70f6c3be153e9cf7dfa295e806ff1ab | a219d240223d5636c4a533542417ba92c83eeeff |
refs/heads/master | <file_sep>angular.module('main', [])
.directive('demo', function ($log) {
return {
scope: {
label: '@'
},
transclude: true,
template: '<div>{{ label }}<ng-transclude></ng-transclude></div>'
};
});
<file_sep># Racetrack
A sample application developed for the Packt Publishing course [Learning AngularJS Directives](https://www.packtpub.com/web-development/learning-angularjs-directivesvideo).
<file_sep>angular.module('main', [])
.directive('lightSwitch', function() {
return {
scope: {
},
controller: function($scope) {
$scope.state = 'on';
$scope.toggleSwitch = function() {
$scope.state = ($scope.state === 'on' ? 'off' : 'on');
};
this.getState = function() {
return $scope.state;
};
},
transclude: true,
template: '<div>' +
'<button class="btn btn-success" ' +
'ng-click="toggleSwitch()">Switch</button>' +
'<ng-transclude></ng-transclude>' +
'</div>'
};
})
.directive('lightbulb', function($log) {
return {
scope: {
},
require: '^^lightSwitch',
link: function(scope, element, attrs, controller) {
scope.bulbClass = function () {
return controller.getState() === 'on' ? 'lbOn' : 'lbOff';
}
},
template: '<div ng-class="bulbClass()">i am a lightbulb</div>',
priority: 10,
controller: function () {
$log.log('lightbulb');
}
};
})
.directive('peer', function ($log) {
return {
priority: 0,
controller: function () {
$log.log('peer');
}
};
})<file_sep>angular.module('main', [])
.controller('test', function ($scope) {
$scope.clicked = function (color) {
alert('clicked: ' + color);
};
})
.directive('helmet', function () {
return {
scope: {
helmetColor: '@',
helmetClick: '&'
},
link: function (scope, element, attrs) {
scope.functionProvided = false;
if (attrs.helmetClick != undefined) {
scope.functionProvided = true;
}
},
templateUrl: 'img/helmet.svg'
};
});<file_sep>angular.module('Racetrack', [])
.controller('MainController', function ($scope) {
$scope.appName = 'Learning AngularJS Directives';
});
<file_sep>angular.module('main', [])
.directive('demo', function () {
return {
controller: function () {
},
link: function () {
}
};
});<file_sep>angular.module('Racetrack')
.service('canvasDrawing', function () {
this.canvas = null;
this.context = null;
this.init = function (element) {
this.canvas = element;
this.context = this.canvas.getContext('2d');
};
// Clear the canvas to white.
this.blankPage = function blankPage(paperColor) {
var context = this.context;
context.fillStyle = paperColor;
context.fillRect(0, 0, this.canvas.width, this.canvas.height);
};
this.drawDot = function drawDot(point, radius, fillColor, strokeColor) {
var context = this.context;
context.beginPath();
context.arc(point.x * 10, point.y * 10, radius, 0, 2 * Math.PI, false);
context.fillStyle = fillColor;
context.fill();
context.lineWidth = 1;
context.strokeStyle = strokeColor;
context.stroke();
};
this.drawDots = function (from, to, dotColor) {
for (var x = from.x; x < to.x; x++) {
for (var y = from.y; y < to.y; y++) {
this.drawDot({ x: x, y : y }, 1, dotColor, dotColor);
}
}
};
this.getMousePos = function getMousePos(evt) {
var rect = this.canvas.getBoundingClientRect();
return {
x: Math.floor(((evt.clientX - rect.left) + 10) / 10),
y: Math.floor(((evt.clientY - rect.top) + 10) / 10)
};
};
this.onMouseMove = function (mouseMoveFunction) {
this.canvas.addEventListener('mousemove', mouseMoveFunction);
};
});<file_sep># FAQ
(where "frequently" === at least once)
## Section 1
**Q: Can you explain the concept of "a directive" to me?**
A: A directive is your chance to extend HTML with a new element specific to your needs. You use div, input, table, ul, etc. all the time when creating your pages. What if you could create one for costs-graph, search-form, or social-media-links if those are things you find yourself repeating over and over?
Why not extend HTML with some language specific to what you specifically are building? That's what a directive lets you do. Add a new element to the page that can have visible and invisible parts as well as interactive elements.
**Q: You said in the course that directives have a scope? Why do they have a scope?**
A: The flippant answer is that Google says that they should, but I think we can infer that they wanted them to be able to have their own scope so they could be more like HTML elements.
HTML elements normally take all of their content, styling cues, etc. from attributes applied directly to the elements themselves and not just from outer context. That allows us to have two divs one after another which appear different from each other because each has a different CSS class.
When building our own directives we need easy ways to say that one instance needs to use different data or has a different appearance from another by setting attributes of it and without worrying that that will carry over into our other directive instances.
**Q: Can you explain isolate scopes in more depth?**
A: Be sure to read the question just before this one because the two really go together.
While AngularJS allows us to have directives which inherit their scope from a parent they really come into their own when you isolate them from that scope.
Imagine you wanted to get a third party directive for displaying graphs within your pages. However, if it did not have an isolated scope you would suddenly have to worry about how that directive named its own variables and what variables it was creating in the shared scope because they would all be in the scope of the controller with which you wrap it.
That makes development more difficult and more dangerous (or at least more error prone). Some developers would have naming conventions like namespace_someName to prevent collisions but others would inevitably pick names like "color" or "data" and run headlong into other data in outside scopes.
Isolate scope protects you from that.
**Q: What happens if I have a variable in the scope of a directive with the same name as a variable in the scope of a controller which wraps it?**
A: Thanks to isolate scope. Nothing. The directive is working in its own world and does not need to worry about polluting the scope of another directive or controller which may wrap it. Both can choose to use the same variable names with impunity.
## Section 2
**Q: Do you have some real world examples of directives?**
A: AngularJS has pages of them, ng-repeat, ng-click, or anything on this page: <https://docs.angularjs.org/api/ng/directive>
But beyond those examples there are projects like AngularStrap (<http://mgcrea.github.io/angular-strap/>) which wraps Bootstrap controls in AngularJS wrappers and sites like <http://ngmodules.org/> which has hundreds of examples.
**Q: When do I need to use $observe in my directive?**
A: $observe is almost never needed because most of the time we are using isolate scope in our directives and $watch and $observe are exactly the same for bound variables in an isolate scope. I reference this which is considered one of the authoritative explations online: <http://stackoverflow.com/questions/14876112/difference-between-the-observe-and-watch-methods>
I have never needed $observe in a directive.
**Q: Isn't "controller as" syntax obsolete?**
A: No! I do not believe that at all. If anything I believe that Google is steering developers away from $scope and toward something more like "controller as" in the future.
**Q: Where can I learn about "controller as" outside of a directive?**
A: I like Todd Motto's explanation pretty well: <http://toddmotto.com/digging-into-angulars-controller-as-syntax/>
I also like that he talks about how it interacts with $watch, directives (also covered in the course), and ngRoute.
**Q: What exactly is “ng-transclude” attribute doing within the template?**
A: It's specifying the exact spot the contents of the directive (seen out in the HTML) will be placed when the directive is replaced with the template for that directive.
**Q: Are we limited to a single top-level tag in the template if I’m using transclusion?**
**Q: What happens if I place the “ng-transclude” attribute in multiple tags in the template?**
**Q: What happens if I don’t use the “ng-transclude” attribute at all, but I set “transclude: true”?**
A: Man, you have a lot of transclusion questions.
There is no restriction on the template that it should only have one top level tag as far as I know. I crafted an example with two different divs, each at the topmost level of the template and was able to embed the transcluded material into each one individually or both without problems. See also the next answer.
Multiple uses of ng-transclude just embeds the same content multiple spots in the compiled output. So use it as many times as you need the inner material to repeat in your template.
If you don’t use the ng-transclude at all but set transclude: true, nothing happens. It has no place to insert the contents so it does nothing.
## Section 3
**Q: What about communication between directives using $emit/$broadcast?**
A: I really recommend against that. When you're using events to communicate it can be very difficult to reason about why something happened. "This code over here triggered because of an event. Was it this code that generates that event or over there or over there?"
When functions are called directly there's often a call stack in the browser which I can trace back through to see the origin of a particular call and know why it happened.
I feel like this is reinforced by AngularJS itself. If you look through the framework you will not see many examples of where it is either emitting or sinking events itself. There is a place for communication via a loose mechanism like this but do not use it a lot. I think you will regret it.
**Q: Why are there different functions? Why controller and pre-link and post-link?**
A: That's an excellent question. The best answer I have is that, as shown in the course videos, they get called at different times within the life-cycle of a directive. Different points in time get different functions.
But you can imagine a world where there was only one function and the phase the directive was in during its life cycle was a parameter to the function. So this solution was probably not the only one possible, but it's the one which was picked.
**Q: Is the $scope that a controller can inject the same as the scope passed to the link function?**
A: Yes. And the very next question is a good follow up to that.
**Q: Why don't link function parameters have a $ at the beginning?**
A: A controller gets all its parameters via dependency injection. If you don't need a particular parameter, don't list it and you won't get it. So the naming conventions it follows are the standard ones for dependency injection in AngularJS. Getting a scope is done via injecting $scope whether we're talking about the controller in a directive or the controller attached to a view.
By contrast, the link gets a standard set of parameters, it does not get them via dependency injection and they arrive in a specific order. You can name that first parameter anything you like ($scope, scope, or penguins), but you're always going to get the scope there. So I assume that AngularJS names it slightly differently in the description of the link function to highlight that you cannot change the order of those parameters like you could in the controller.
<file_sep>angular.module('main', [])
.controller('test', function ($scope) {
$scope.appName = 'Learning AngularJS Directives';
})
.directive('pictureFrame', function () {
return {
template: '<div class="pF"></div>'
};
});<file_sep>angular.module('main', [])
.directive('demo', function ($http, $log) {
return {
controller: function ($scope, $element, $attrs) {
},
link: function (scope, iElement, iAttrs, controller, transcludeFn) {
}
};
});<file_sep>angular.module('main', [])
.controller('main', function ($scope, $log) {
$scope.racetrack = {
width: 50,
height: 50,
turn: 0,
cars: [
{
color: 'red',
vectorX: 2,
vectorY: 0,
positions: [
{ x: 25, y: 45 },
{ x: 26, y: 45 },
{ x: 28, y: 45 }
]
},
{
color: 'blue',
vectorX: 2,
vectorY: 1,
positions: [
{ x: 25, y: 47 },
{ x: 26, y: 47 },
{ x: 28, y: 48 }
]
}
]
};
})
.service('canvasDrawing', function () {
this.canvas = null;
this.context = null;
this.init = function (id) {
// Get a reference to the canvas object
this.canvas = document.getElementById(id);
this.context = this.canvas.getContext('2d');
};
// Clear the canvas to white.
this.blankPage = function blankPage(paperColor) {
var context = this.context;
context.fillStyle = paperColor;
context.fillRect(0, 0, this.canvas.width, this.canvas.height);
};
this.drawDot = function drawDot(x, y, radius, fillColor, strokeColor) {
var context = this.context;
context.beginPath();
context.arc(x * 20, y * 20, radius, 0, 2 * Math.PI, false);
context.fillStyle = fillColor;
context.fill();
context.lineWidth = 1;
context.strokeStyle = strokeColor;
context.stroke();
};
this.drawDots = function (width, height, dotColor) {
for (var x = 1; x < width; x++) {
for (var y = 1; y < height; y++) {
this.drawDot(x, y, 2, dotColor, dotColor);
}
}
};
this.drawCarPaths = function drawCarPaths(cars) {
var context = this.context;
_.each(cars, function (car) {
context.beginPath();
var firstPosition = _.first(car.positions);
context.moveTo(firstPosition.x * 20, firstPosition.y * 20);
_.each(_.rest(car.positions), function (position) {
context.lineTo(position.x * 20, position.y * 20);
});
context.strokeStyle = car.color;
context.lineWidth = 4;
context.stroke();
});
};
this.getMousePos = function getMousePos(evt) {
var rect = this.canvas.getBoundingClientRect();
return {
x: Math.floor(((evt.clientX - rect.left) + 10) / 20),
y: Math.floor(((evt.clientY - rect.top) + 10) / 20)
};
};
this.onMouseMove = function (mouseMoveFunction) {
this.canvas.addEventListener('mousemove', mouseMoveFunction);
};
})
.directive('helmet', function () {
// This is the second version of the directive, it shows a directive with bound attributes that
// allow the directive to feed back to the code and modify its appearance.
return {
scope: {
clicked: '&',
color: '@'
},
template: '<div ng-click="clicked()" ng-style="{ fill: color }">' +
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="4.5 -9.0 90.0 121.5" enable-background="new 0 0 90 90" xml:space="preserve" height="100px" width="100px">' +
'<circle cx="45.2" cy="42.9" r="1.4"/>' +
'<path d="M37.8,69.6c-0.7,0-1.3-0.4-1.5-1c-0.3-0.8,0.1-1.8,0.9-2.1c0.2-0.1,18.1-7.3,19.9-8.1c0.8-0.4,1.8,0,2.2,0.8 c0.4,0.8,0,1.8-0.8,2.2c-1.9,0.8-19.3,7.8-20,8.1C38.2,69.6,38,69.6,37.8,69.6z"/>' +
'<path d="M27.2,55c-0.1,0-0.2,0-0.3,0c-0.9-0.1-1.5-1-1.4-1.9l1.5-9.8c0.1-0.9,1-1.5,1.9-1.4c0.9,0.1,1.5,1,1.4,1.9l-1.5,9.8 C28.7,54.4,28,55,27.2,55z"/>' +
'<path d="M46.2,27.2c-10.9,0-15.6,7.1-17.4,10.8c-0.7,1.6,0.2,2.1,1.1,2.1c2.2,0.1,6.1,0.3,9.8,0.6c0,0,0.8,0.1,1.4-0.1 c0.7-0.2,2.9-1,2.9-1c0,0,0.1,0,0.1,0l0,0l0,0c0.3-0.1,0.6-0.1,1-0.1c1.9,0,3.5,1.6,3.5,3.5c0,0.8-0.3,1.5-0.7,2.1l0,0l-2.2,3.5 c-0.1,0.1-0.1,0.2-0.2,0.4l0,0l0,0c-0.3,0.3-0.8,0.6-1.5,1c-1.6,0.7-12.1,4.9-16.7,6.8c-0.7,0.3-1.7,1.1-1.7,2.3 c0,2.4,4.2,7.5,6.9,6.6c0,0,24.6-9.9,27.2-11.1c2.6-1.1,3-1.9,3.5-3.4c0.6-1.8,1.3-4.3,1.3-6.9C64.4,39.5,61.1,27.2,46.2,27.2z M60.3,40.2c-0.2,0.1-0.5,0.1-0.7,0.1c-0.6,0-1.2-0.4-1.5-1c-1.2-2.5-3.6-5.9-8.4-7.1c-0.9-0.2-1.4-1.1-1.2-2c0.2-0.9,1.1-1.4,2-1.2 c6,1.6,9,5.8,10.5,8.9C61.5,38.8,61.1,39.8,60.3,40.2z"/>' +
'</svg>' +
'</div>'
};
})
.directive('driverUi', function () {
return {
scope: {
car: '='
},
templateUrl: 'views/playerInfo.html'
};
})
.directive('racetrack', function (canvasDrawing, $log) {
return {
scope: {
trackData: '='
},
controller: function ($scope) {
canvasDrawing.init('racetrack');
},
link: function ($scope) {
var paperColor = 'white';
var dotColor = 'black';
var highlightColor = 'red';
// Draw a blank piece of paper.
canvasDrawing.blankPage(paperColor);
// Draw the dots which make up our "graph paper".
canvasDrawing.drawDots($scope.trackData.width, $scope.trackData.height, dotColor);
// Draw the cars atop that.
canvasDrawing.drawCarPaths($scope.trackData.cars);
//var lastX = null;
//var lastY = null;
//
//canvasDrawing.onMouseMove(function(evt) {
// var mousePos = canvasDrawing.getMousePos(evt);
//
// if (mousePos.x < 1 || mousePos.x > 49 || mousePos.y < 1 || mousePos.y > 49) {
// return;
// }
//
// if (lastX && lastY) {
// // This erases the bigger highlight dot.
// canvasDrawing.drawDot(lastX, lastY, 6, paperColor, paperColor);
//
// // And this redraws the normal dot.
// canvasDrawing.drawDot(lastX, lastY, 2, dotColor, dotColor);
// }
//
// lastX = mousePos.x;
// lastY = mousePos.y;
//
// canvasDrawing.drawDot(mousePos.x, mousePos.y, 4, highlightColor, highlightColor);
// canvasDrawing.drawCarPaths($scope.trackData.cars);
//}, false);
},
template: '<canvas id="racetrack" width="1000" height="1000"></canvas>'
};
});
<file_sep>angular.module('main', [])
.controller('test', function () {
this.users = [
{ name: 'john' },
{ name: 'paul' },
{ name: 'george' },
{ name: 'ringo' }
];
this.parentVariable = 'This should not change';
})
.directive('users', function () {
return {
scope: {
list: '='
},
controller: function () {
},
controllerAs: 'u',
bindToController: true,
template: '<div ng-repeat="user in u.list">' +
'{{ user.name }}' +
'</div>'
}
});
<file_sep>angular.module('main', [])
.controller('test', function ($scope) {
$scope.damage = {
remaining: 3,
max: 5
};
$scope.clicked = function () {
alert('clicked');
};
})
.directive('playerUi', function () {
return {
transclude: true,
template: '<div class="player-ui">' +
'<helmet></helmet>' +
'<div class="ui-controls">' +
'<ng-transclude></ng-transclude>' +
'</div>' +
'</div>'
};
})
.directive('damageDisplay', function () {
return {
scope: {
damage: '='
},
template: '<div class="display">Damage (remaining/max): {{ damage.remaining }}/{{ damage.max }}</div>'
};
})
.directive('pedalToTheMetal', function () {
return {
scope: {
clicked: '&'
},
template: '<div class="control"><a ng-click="clicked()">Put the pedal to the metal!</a></div>'
};
})
.directive('extremeBrake', function () {
return {
scope: {
clicked: '&'
},
template: '<div class="control"><a ng-click="clicked()">Extreme brake!</a></div>'
};
})
.directive('helmet', function () {
return {
scope: {
helmetColor: '@'
},
templateUrl: 'img/helmet.svg'
};
});<file_sep>angular.module('main', [])
.controller('test', function ($scope) {
$scope.list = [
{ name: 'john' },
{ name: 'paul' },
{ name: 'george' },
{ name: 'ringo' }
];
$scope.parentVariable = 'This should not change';
})
.directive('users', function () {
return {
scope: {
list: '='
},
link: function (scope) {
// scope.parentVariable = 'something other than test';
},
template: '<div ng-repeat="user in list">' +
'{{ user.name }}' +
'</div>' +
'<p>{{ parentVariable }}</p>'
};
});
<file_sep>angular.module('Racetrack')
.directive('racetrack', function (canvasDrawing, $log) {
return {
scope: {
trackData: '='
},
priority: 10,
controller: function ($scope, $element) {
var self = this;
var paperColor = 'white';
var dotColor = '#bdbdbd';
var hazardColor = 'green';
/////////////////////////////////////////////////////////////////
// Functions on the controller are available to other directives
/////////////////////////////////////////////////////////////////
this.pointOutOfRange = function (point) {
return (point.x < 1 || point.x > ($scope.trackData.width - 1) || point.y < 1 ||
point.y > ($scope.trackData.height - 1));
};
// Draw the dots which make up our "graph paper".
this.drawGraphPaperDot = function (point) {
canvasDrawing.drawDot(point, 1, dotColor, dotColor);
};
this.drawHazardDot = function (point) {
canvasDrawing.drawDot(point, 1, hazardColor, hazardColor);
};
this.eraseDot = function (point) {
canvasDrawing.drawDot(point, 3, paperColor, paperColor);
};
// Draw the cars atop that.
this.drawCars = function () {
_.each($scope.trackData.cars, function (car) {
canvasDrawing.drawDot(_.last(car.positions), 1, car.color, car.color);
});
};
this.redrawDot = function (point) {
// This is a crude way to do it, but it checks to see if the point is in the area we draw as "hazard".
if (point.x >= 10 && point.y >= 10 && point.x < $scope.trackData.width - 10 &&
point.y < $scope.trackData.height - 10) {
self.drawHazardDot(point)
} else {
self.drawGraphPaperDot(point);
}
// Finally, redraw the cars, just in case one of those was overwritten.
self.drawCars();
};
canvasDrawing.init($element[0]);
// Draw a blank piece of paper.
canvasDrawing.blankPage(paperColor);
canvasDrawing.drawDots({ x: 1, y: 1 },
{ x: $scope.trackData.width, y: $scope.trackData.height }, dotColor);
canvasDrawing.drawDots({ x: 10, y: 10 },
{ x: $scope.trackData.width - 10, y: $scope.trackData.height - 10 }, hazardColor);
this.drawCars();
// When the racetrack data changes, update the display.
$scope.$watch('trackData.cars', function (newValue, oldValue) {
// Note: This leaves ghost images of past positions for each car because I don't try and erase the previous
// positions. But I actually find I like seeing the previous positions so I've left it.
self.drawCars();
}, true);
}
};
});
<file_sep>angular.module('Racetrack', [])
.controller('MainController', function ($scope) {
$scope.helmetColor = 'red';
})
.directive('helmet', function () {
return {
scope: {
helmetColor: '=?'
},
templateUrl: 'img/helmet.svg',
link: function (scope) {
scope.helmetColor = 'green';
}
};
});
<file_sep>angular.module('Racetrack')
.directive('playerUi', function ($log) {
return {
scope: {
car: '=',
turn: '=',
adjustVector: '&'
},
templateUrl: 'js/playerUi.template.html'
};
});
<file_sep>angular.module('Racetrack')
.directive('mouseFollow', function (canvasDrawing) {
return {
require: 'racetrack',
priority: 0,
link: function (scope, iElement, iAttrs, controller) {
var lastPosition = null;
var highlightColor = 'red';
canvasDrawing.onMouseMove(function (evt) {
var mousePosition = canvasDrawing.getMousePos(evt);
if (controller.pointOutOfRange(mousePosition)) {
return;
}
if (lastPosition) {
// This erases the tracking dot.
controller.eraseDot(lastPosition);
// And this redraws whatever should be drawn in that spot.
controller.redrawDot(lastPosition);
}
lastPosition = mousePosition;
// We draw the tracking dot near where the mouse is located.
canvasDrawing.drawDot(mousePosition, 2, highlightColor, highlightColor);
}, false);
}
};
});
| 72e35130ae3540a0793a8388130eb121395420cd | [
"JavaScript",
"Markdown"
] | 18 | JavaScript | JohnMunsch/Racetrack | 043f7b349d00a9ff9b48e06b02ef73bb16531f63 | 3d3b764a33e3e3798a2435cc9fbc05d4b8cac513 |
refs/heads/master | <file_sep>def user_input(iteration, _game): # input = x,y; o=1, x=2
now_playing_o = iteration % 2
if now_playing_o:
move = input("o: ").split(",")
_game[int(move[0])-1][int(move[1])-1] = 1
return _game
else:
move = input("x: ").split(",")
_game[int(move[0])-1][int(move[1])-1] = 2
return _game
game = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
print(user_input(1, game))
<file_sep>lis = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lis2 = [1, 2, 3, 4, "yep"]
# print(lis[0])
num = int(input())
for element in lis:
if element <= num:
print(element)
print([output for output in lis if output <= num])<file_sep>def op():
_file = open("file.txt")
return _file
# file = op()
# print(file.read()) #everything
# file.close()
# file = op()
# print(file.readline()) # one line
# file.close()
file = op()
print(file.readlines()) #lines in list
file.close()
<file_sep>number = 19
swap = [1, 1, 2]
fib = []
if number == 1:
fib.append(1)
print(fib)
elif number == 2:
fib.append(1)
fib.append(1)
print(fib)
else:
fib.append(1)
fib.append(1)
fib.append(2)
for i in range(0, number-3):
swap[0] = swap[1]
swap[1] = swap[2]
swap[2] = swap[0] + swap[1]
fib.append(swap[2])
print(fib)
<file_sep>import requests
import bs4
#
# url = 'http://github.com'
# r = requests.get(url)
#
# r_html = r.text #r_html contain HTML
#
# soup = bs4.BeautifulSoup(r_html,features="lxml")
#
# title = soup.find('summary').text
#
# # print(r_html)
# print(title)
#
#
sauce = requests.get("https://niebezpiecznik.pl")
soup = bs4.BeautifulSoup(sauce.text, features="html.parser")
titles = soup.find_all()
# print(soup.find("h2").text)
for title in soup.find_all("h2"):
print(title.string)
<file_sep>while(1):
print("Player A: ")
a = input()
print("Player B: ")
b = input()
if a == b:
print("Rematch?")
print("y/n")
if input() == "n":
break
else:
continue
elif a =="rock" and b == "scissors":
print("A wins")
print("Rematch?")
print("y/n")
if input() == "n":
break
else:
continue
elif a =="paper" and b == "rock":
print("A wins")
print("Rematch?")
print("y/n")
if input() == "n":
break
else:
continue
elif a =="scissors" and b == "paper":
print("A wins")
print("Rematch?")
print("y/n")
if input() == "n":
break
else:
continue
else:
print("B wins")
print("Rematch?")
print("y/n")
if input() == "n":
break
else:
continue
<file_sep>import matplotlib.pyplot as plt
import json
birthday_dict = {}
with open("35_2.json", "r") as json_file:
json_data = json.load(json_file)
# print(json_data[January])
# - - - plot - - - #
plot_x = []
plot_y = []
for element in json_data:
plot_x.append(element)
plot_y.append(json_data[element])
plt.plot(plot_x, plot_y)
plt.show()
<file_sep>Easy Python exercises. Great for start with new language.<file_sep>import json
import collections
def switch(argument):
switcher = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
return switcher.get(argument, "Invaild month")
with open("34.json", "r") as json_file:
json_data = json.load(json_file)
birth_list = []
for date in json_data.values():
month = int(date.split("/")[1])
month = switch(month)
birth_list.append(month)
counted = collections.Counter(birth_list)
counted_dict = {}
for counter in counted:
counted_dict[counter] = counted[counter]
print("\"{}\": {}".format(counter, counted[counter]))
print(counted_dict)
<file_sep>import random
def check(guess, _word, transformed_word):
if guess not in set(_word):
return 0
else:
for i in range(0, len(_word)):
if _word[i] == guess:
transformed_word[i] = _word[i]
if "_" not in set(transformed_word):
return 10
return transformed_word
def word_begin(_word):
transform = []
for letter in _word.strip(): # del newline
transform.append("_")
return transform
def win(transformed_word):
if "_" not in set(transformed_word):
return True
# Read random word from file, lower letters, drop \n
with open("sowpods.txt", "r") as open_file:
words = open_file.readlines()
index = random.randint(0, len(words) + 1)
word = words[index].lower()
# input_word = "testing"
transformed = word_begin(word)
print(word)
print(" ".join(transformed))
moves_left = 6
while moves_left:
print("Moves left: " + str(moves_left))
user_input = input("letter: ")
result = check(user_input, word, transformed)
if result == 0:
print("Not found")
print(" ".join(transformed))
moves_left -= 1
if moves_left == 0:
decision = input("1 - try again, 2 - new word, 3 - quit: ")
if decision == "1":
print("Good luck")
print(" ".join(transformed))
moves_left = 6
transformed = word_begin(word)
elif decision == "2":
moves_left = 6
index = random.randint(0, len(words) + 1)
word = words[index].lower()
transformed = word_begin(word)
print("New word")
print(" ".join(transformed))
else:
break
elif result == 10:
print("Congratulations, word: " + word)
break
else:
print(" ".join(result))
<file_sep>import requests
import bs4
url = "http://www.vanityfair.com/society/2014/06/monica-lewinsky-humiliation-culture"
sauce = requests.get(url)
soup = bs4.BeautifulSoup(sauce.text, "lxml")
result = soup.find_all("p")
for i in result:
print(i.get_text()) # return only what is in <p>
# print(i) # return whole <p>
<file_sep>import random
# my_list = []
# length = 0
# with open("sowpods.txt", "r") as open_file:
#
# line = open_file.readline()
# my_list.append(line)
# while line:
# length += 1
# my_list.append(line)
# line = open_file.readline()
with open("sowpods.txt", "r") as open_file:
lines = open_file.readlines()
index = random.randint(0, len(lines) + 1)
print(lines[index])
<file_sep>number = int(input())
if number > 1:
for i in range (2,number):
if number%i == 0:
print("nope")
break
elif i == number - 1:
print("yep")
<file_sep>def cut(list):
new = [list[0], list[-1]]
print(new)
lis = [1,2,3,4,5]
cut(lis)<file_sep>def draw(_x, _y):
for i in range(0, _x): #first row
print(" ---", end="")
print()
for k in range(0, _y):
for i in range(0, _x + 1):
print("|", end="")
print(" ", end="")
print()
for i in range(0, _x):
print(" ---", end="")
print()
x = 10
y = 3
draw(x, y)
<file_sep>import random
user = 1
number = random.randint(0, 100)
maxn = 100
minn = 0
rounds = 1
while user:
print("Number " + number.__str__() + "?")
user = int(input("0 - correct, 1 - too low, 2 - too high: "))
if user == 1:
minn = number
elif user == 2:
maxn = number
elif user == 0:
print(rounds.__str__() + " rounds")
rounds += 1
number = random.randint(minn + 1, maxn - 1)
<file_sep>def check(guess, word, transformed_word):
if guess not in set(word):
return 0
else:
for i in range(0, len(word)):
if word[i] == guess:
transformed_word[i] = word[i]
if "_" not in set(transformed_word):
return 10
return transformed_word
def word_begin(word):
transform = []
for letter in word:
transform.append("_")
return transform
def win(transformed_word):
if "_" not in set(transformed_word):
return True
input_word = "testing"
transformed = word_begin(input_word)
print(" ".join(transformed))
while True:
x = input("letter: ")
result = check(x, input_word, transformed)
if result == 0:
print("Not found")
print(" ".join(transformed))
elif result == 10:
print("Congratulations, the word: " + input_word)
break
else:
print(" ".join(result))
<file_sep>primes = []
happy = []
with open("primenumbers.txt", "r") as primes_file:
line = primes_file.readline()
while line:
primes.append(int(line))
line = primes_file.readline()
with open("happynumbers.txt", "r") as happy_file:
line = happy_file.readline()
while line:
happy.append(int(line))
line = happy_file.readline()
overlap = [prime for prime in primes if prime in happy]
print(overlap)
<file_sep>#indexing
reverse = [1, 2, 3]
reverse = reverse[::-1]
print(reverse)
end = reverse[-1]
print(end)
#some fun
print([[number for number in reverse if number % 2 == 0]])
#uniq
a = [1, 1, 2, 2, 3, 3, 4, 4]
print(set(a))
#split + join
a = "lorem ipsum dolor sit amet"
a = a.split(" ")
print(a)
print("----join----".join(a))
<file_sep>import random
def score(_goal, _user_input):
bulls_counter = 0
cows_counter = 0
for i in range(0, 4):
if _user_input[i] == _goal[i]:
cows_counter += 1
bulls_counter -= 1
if _user_input[i] in set(_goal):
bulls_counter += 1
return cows_counter, bulls_counter
if __name__ == "__main__":
goal = str(random.randint(1000, 9999))
won = False
iterations = 1
temp_score = (0, 0)
print(goal)
while not won:
print("Please input number: ")
user_input = str(input())
tmp_score = score(goal, user_input)
# +ifs for language things
if tmp_score == (4, 0):
print("You won in " + str(iterations) + " turns")
won = True
else:
print(str(tmp_score[0]) + " cows, " + str(tmp_score[1]) + " bulls")
iterations += 1
<file_sep># from os import system, name
#
#
# def clear():
# system('cls' if name == 'nt' else 'clear')
def draw(_x, _y, moves):
for i in range(0, _x): #first row
print(" ---", end="")
print()
for k in range(0, _y):
for i in range(0, _x + 1):
print("|", end="")
if i < _x:
if moves[k][i] == 0:
print(" ", end="")
if moves[k][i] == 1:
print(" o ", end="")
if moves[k][i] == 2:
print(" x ", end="")
print()
for i in range(0, _x):
print(" ---", end="")
print()
def check(moves): # 1 - win "o", 2 - win "x", 404 - draw
draw = []
for i in range(0, 3):
draw.append(moves[0][i])
draw.append(moves[i][0])
if moves[i][0] != 0 and moves[i][0] == moves[i][1] and moves[i][1] == moves[i][2]: # horizontal
return moves[i][0]
elif moves[i][0] != 0 and moves[0][i] == moves[1][i] and moves[1][i] == moves[2][i]: # vertical
return moves[0][i]
if moves[0][0] != 0 and moves[0][0] == moves[1][1] and moves[1][1] == moves[2][2]: # 1st diagonal
return moves[0][0]
if moves[0][2] != 0 and moves[0][2] == moves[1][1] and moves[1][1] == moves[2][0]: # 2nd diagonal
return moves[2][0]
if 0 not in draw:
return 404
def user_input(iteration, moves): # input = x,y; o=1, x=2
now_playing_o = iteration % 2
if now_playing_o:
move = input("o: ").split(",")
moves[int(move[0]) - 1][int(move[1]) - 1] = 1
return moves
else:
move = input("x: ").split(",")
moves[int(move[0]) - 1][int(move[1]) - 1] = 2
return moves
game = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
play = True
while play:
play = int(input("Do you want play a game? 1-yes, 0-no "))
if play == 0:
break
iteration = 1
while True:
draw(3, 3, game)
user_input(iteration, game)
draw(3, 3, game)
result = check(game)
if result == 1:
print("o won")
break
elif result == 2:
print("x won")
break
elif result == 404:
print("It's a draw")
break
iteration += 1
<file_sep># TODO: complete in free time
def binary(_list, _element):
found = False
start_index = 1
end_index = len(_list) - 1
while 1:
center_index = (end_index - start_index)/2
element_from_center = int(_list[center_index])
if _element == element_from_center: # has center
found = True
break
elif _element > element_from_center:
end_index = center_index
else: # _element < center
start_index = center_index
if center_index < start_index or center_index > end_index or center_index < 0:
break
if _list[0] == _element:
found = True
return found
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 33, 88, 95, 123, 456, 789]
number = 33
print(binary(list, number))
<file_sep>import requests
import bs4
sauce = requests.get("https://niebezpiecznik.pl")
soup = bs4.BeautifulSoup(sauce.text, features="html.parser")
titles = soup.find_all()
with open("file.txt", "w") as open_file: # auto close file
for title in soup.find_all("h2"):
open_file.write(title.string + "\n")
<file_sep>def uniq(list):
new = [element for element in set(list)]
return new
a = [1, 1, 2, 2, 3, 3, 4, 4]
print(uniq(a))<file_sep>import random
x1 = random.randint(0, 100)
x2 = random.randint(0, 100)
x3 = random.randint(0, 100)
my_list = [x1, x2, x3]
my_list.sort()
print(my_list)
print(my_list[2])
<file_sep>print("Hello world") #ok
"""
that was easy
So that's not a comment
It's a string, but python doesn't care about it
Good python
"""
<file_sep>num = int(input())
for x in range(1,num+1):
if num%x==0:
print("Divisor: " + str(x))<file_sep>string = input()
reverse = string[::-1]
print(reverse)
if reverse == string:
print("yep")
else:
print("nope")<file_sep>price_dictionary = {
"banana": 1.50,
"avocado": 0.99,
"heirloom tomato": 0.89,
"cherry tomato pack": 3.00
}
print("Welcome to the price dictionary. We know the price of:")
for name in price_dictionary.keys():
print(name)
name = input("\nWho's birthday do you want to look up? ")
if price_dictionary.get(name):
print("\nPrice of {} is: {}".format(name, price_dictionary.get(name))) # can't print float, format like printf
else:
print("Price not found")
<file_sep>def binary(_list, _element):
found = False
while len(_list) > 1:
center = _list[int((len(_list) - 1) / 2)]
if _element == center: # has center
found = True
break
elif _element > center:
_list = _list[int((len(_list) - 1) / 2) + 1::+1]
else: # _element < center
_list = _list[0:int((len(_list) - 1) / 2):1]
if _list[0] == _element:
found = True
return found
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 33, 88, 95, 123, 456, 789]
number = 33
print(binary(list, number))
# contain = False
#
# for element in list:
# if element == number:
# print("yep")
# contain = True
# break
#
# if not contain:
# print("nope")
#
<file_sep>
input = "This is string"
swap = input.split(" ")
swap = swap[::-1]
print(" ".join(swap))<file_sep>dictionary = {}
with open("Training_01.txt", "r") as open_file:
line = open_file.readline()
while line:
category = line.split("/")
category = category[2]
if category in dictionary.keys():
dictionary[category] += 1
else:
dictionary[category] = 1
line = open_file.readline()
print(dictionary)
<file_sep>def check(moves): # 1,2 - win, 404 - draw
draw = []
for i in range(0, 3):
draw.append(moves[0][i])
draw.append(moves[i][0])
if moves[i][0] != 0 and moves[i][0] == moves[i][1] and moves[i][1] == moves[i][2]: # horizontal
return True, moves[i][0]
elif moves[i][0] != 0 and moves[0][i] == moves[1][i] and moves[1][i] == moves[2][i]: # vertical
return True, moves[0][i]
if moves[0][0] != 0 and moves[0][0] == moves[1][1] and moves[1][1] == moves[2][2]: # 1st diagonal
return True, moves[0][0]
if moves[0][2] != 0 and moves[0][2] == moves[1][1] and moves[1][1] == moves[2][0]: # 2nd diagonal
return True, moves[0][0]
if 0 not in draw:
return True, 404
game = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
game = [[1, 1, 2],
[2, 2, 1],
[1, 1, 2]]
print(check(game))
<file_sep>import json
def switch(argument):
switcher = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
return switcher.get(argument, "Invaild month")
birthday_dict = {}
with open("34.json", "r") as json_file:
json_data = json.load(json_file)
for date in json_data.values():
month = int(date.split("/")[1])
month = switch(month)
if month in birthday_dict.keys():
birthday_dict[month] += 1
else:
birthday_dict[month] = 1
with open("35.json", "w") as json_file:
json.dump(birthday_dict, json_file)<file_sep>import json
# json_data = {
# "name1": "01/01/2020",
# "name2": "01/01/2020",
# "name3": "01/01/2020",
# "name4": "01/02/2020",
# "name5": "01/02/2020",
# "name6": "01/03/2020",
# "name7": "01/04/2020",
# "name8": "01/05/2020",
# "name9": "01/06/2020"
# }
#
#
# with open("34.json", "w") as json_file:
# json.dump(json_data, json_file) # auto convert False -> false
#
# print(json_data.keys())
with open("34.json", "r") as json_file:
json_data = json.load(json_file)
print("Welcome to the price dictionary. We know the price of:")
for name in json_data.keys():
print(name)
name = input("\nWho's birthday do you want to look up? ")
if json_data.get(name):
print("\nPrice of {} is: {}".format(name, json_data.get(name))) # can't print float, format like printf
else:
print("Price not found")<file_sep>import random
user = 1
middle = 50
maximum = 100
minimum = 0
rounds = 1
while user:
print("Number " + middle.__str__() + "?")
user = int(input("0 - correct, 1 - too low, 2 - too high: "))
if user == 1:
minimum = middle
elif user == 2:
maximum = middle
elif user == 0:
print(rounds.__str__() + " rounds")
middle = int((minimum + maximum)/2)
rounds += 1
<file_sep>import random
length = 16
password = []
for i in range(0, length):
password.append(chr(random.randint(32, 126)))
print("".join(password))
<file_sep># test = input("waiting for you: ")
#
# test #ignored...
#
#
#
#
test = 5
# print(test+"ok") #not working
print(5+5)
print("test"+"ok")
print(4*"ok") #whoaaaaa...
print(int("4"))
# print(int("4f"))
# print("okok" - "ok")
<file_sep>import random
score = 0
loops = 0
while(1):
number = random.randint(1,9)
print("Your pick:")
kek = input()
if kek == "exit":
print("Score: " + str(score))
break
print("The number is: " + str(number))
if int(kek) == number:
print("Nice")
score += 1
elif int(kek) < number:
print("Too low")
elif int(kek) > number:
print("Too high")
loops += 1
print("Avg: " + str(score/loops))
| 0974401d73a74f946d192999300b82f371b2e18d | [
"Markdown",
"Python"
] | 39 | Python | ddoox/Practicepython.org | 58298d7fc3d846c2d7769a142afeb3a5d4bb81ac | d658886a73c627243720237b9c2fd655f0721295 |
refs/heads/master | <file_sep>/**
******************************************************************************
* @file :Main.c
* @author :<NAME>
* @version :V1.0
* @date
* @brief
******************************************************************************
***/
/* Includes ------------------------------------------------------------------*/
#include "Includes.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
//workmode:iBeacon & Eddyston & Remote
volatile uint8_t Work_Mode = Work_Mode_Help;
//fcunction
char *FunctionDisplay[11]={
"---------------------------iBeacon-----------------------\r\n",
"++ 1--Enable iBeacon function , APP: Wechat ++\r\n",
"*********************************************************\r\n",
"---------------------------Eddystone---------------------\r\n",
"++ 2--Enable Eddystone Uri, APP: EddystoneValidator++\r\n",
"++ 3--Enable Eddystone Uid, APP: EddystoneValidator++\r\n",
"++ 4--Enable Eddystone Tlm, APP: EddystoneValidator++\r\n",
"++ 5--Enable Remote function, 1 key function ++\r\n",
"*********************************************************\r\n",
"++ 0--Display all command ++\r\n",
"---------------------------------------------------------\r\n",
};
/* Private function prototypes -----------------------------------------------*/
/*******************************************************************************
* Function : main
* Parameter : void
* Returns : void
* Description:
* Note: :
*******************************************************************************/
void main(void)
{
uint8_t temp0=0;
//init mcu system
Init_System();
Rx_Buffer[Rx_Tx_Buffer_Cnt] = 0;
Rx_Tx_Buffer_Cnt = 0;
while(1)
{
//rx data . change work mode .
if((Rx_Tx_Buffer_Cnt == 1) && (Work_Mode == Work_Mode_Null))
{
Work_Mode = Rx_Buffer[0];
Rx_Buffer[0] = 0;
Rx_Tx_Buffer_Cnt = 0;
}
switch(Work_Mode)
{
case Work_Mode_Null:
break;
case Work_Mode_Help:
for(temp0=0;temp0<11;temp0++)
{
Uart_Send_String(FunctionDisplay[temp0]);
}
Uart_Send_String("\r\n");
Uart_Send_String("\r\n");
Uart_Send_String("\r\n");
Uart_Send_String("\r\n");
Uart_Send_String("\r\n");
Uart_Send_String("\r\n");
Work_Mode = Work_Mode_Null;
break;
case Work_Mode_iBeacon:
case Work_Mode_Eddystone_Uri:
case Work_Mode_Eddystone_Uid:
case Work_Mode_Eddystone_Tlm:
case Work_Mode_Remote:
/* IWDG configuration: IWDG is clocked by LSI = 38KHz */
/* IWDG timeout equal to 1.7 s (the timeout may varies due to LSI frequency dispersion) */
/* IWDG timeout = (RELOAD_VALUE + 1) * Prescaler / LSI = (254 + 1) * 256 / 38 000 = 1717.6 ms */
/* Enable the IWDG */
IWDG_Enable();
/* Enable write access to IWDG_PR and IWDG_RLR registers */
IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
/* Set IWDG timeout */
IWDG_SetPrescaler(IWDG_Prescaler_256);
IWDG_SetReload(254); //RELOAD_VALUE
/* Refresh IWDG */
IWDG_ReloadCounter();
//BLE initnal
BLE_Init();
//send
BLE_Beacon();
break;
default:
break;
}
}
}
<file_sep>/**
******************************************************************************
* @file :Main.c
* @author :<NAME>
* @version :V1.0
* @date
* @brief
******************************************************************************
***/
/* Includes ------------------------------------------------------------------*/
#include "Includes.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
//sleep interval(ms) between each channel
#define CNT_SLEEP 150
/* Private variables ---------------------------------------------------------*/
extern unsigned short tick;
//static unsigned char adv_data[18] = {2,1,4, 0x0a,0x09,0x4d,0x41,0x43,0x52,0x4f,0x47,0x49,0x47,0x41,0x03,0xff,0x00,0x09};
//BLE ADV_data .
//static uint8_t adv_data[30] = {0x02,0x01,0x04, 0x1a,0xff,0x4c,0x00,2,0x15, 0xfd,0xa5,0x06,0x93,0xa4,0xe2,0x4f,0xb1,0xaf,0xcf,0xc6,0xeb,0x07,0x64,0x78,0x25, 0x27,0x32,0x52,0xa9, 0xB6};
//static uint8_t adv_data[30] = {0x02,0x01,0x04, 0x1a,0xff,0x4c,0x00,2,0x15, 0xfd,0xa5,0x06,0x93,0xa4,0xe2,0x4f,0xb1,0xaf,0xcf,0xc6,0xeb,0x07,0x64,0x78,0x25, 0x27,0x38,0x9d,0x85, 0xB6};
static uint8_t adv_data[30] = {0};
//iBeacon data format
static uint8_t iBeacon_adv_data[] =
{
/*
02 # Number of bytes that follow in first AD structure
01 # Flags AD type
04 # Flags value
1A # Number of bytes that follow in second (and last) AD structure
FF # Manufacturer specific data AD type
4C 00 # Company identifier code (0x004C == Apple)
02 # Byte 0 of iBeacon advertisement indicator
15 # Byte 1 of iBeacon advertisement indicator
*/
//{
0x02, /* length 0x02*/
BLE_GAP_AD_TYPE_FLAGS, /* AD type = 01 */
GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED|GAP_ADTYPE_FLAGS_GENERAL, /* LE Mode = 0x06 */
//}
0x1a, /* length 0x1a*/
BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, /* AD type = 0xFF Manufacturer Specific Data */
/*CompanyID (AppleID 0x004C)https://www.bluetooth.com/specifications/assigned-numbers/company-Identifiers*/
0x4c,0x00, /* CompanyID = 0x004C */
0x02, /* iBeacon flag = 0x02 */
0x15, /* length 0x15 length :0x15 21byte (16B UUID+ 2B major, 2B minor, 1B Txpower)*/
/*UUID */
0xfd,0xa5,0x06,0x93,0xa4,0xe2,0x4f,0xb1,0xaf,0xcf,0xc6,0xeb,0x07,0x64,0x78,0x25,
/***************User set***********************/
0x27,0x38, /*Major*/
0x9d,0x85, /*Minjo*/
0xB6 /*Txpower*/
/***************User End***********************/
};
//Beacon remote data format
static uint8_t Beacon_Key_Press_adv_data[] =
{
0x02, /* length 0x02*/
BLE_GAP_AD_TYPE_FLAGS, /* AD type = 01 */
GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED|GAP_ADTYPE_FLAGS_GENERAL, /* LE Mode = 0x06 */
0x0a, /* length 0x1a*/
BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME, /* AD type = 0x09*/
'K','e','y','-','P','r','e','s', 's', /* use Ascii */
0x03, /* length 0x03*/
BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, /* AD type = 0xFF */
/***************User set***********************/
0x20,0x0b,
/***************User End***********************/
};
//Beacon remote data format
static uint8_t Beacon_Key_uP_adv_data[] =
{
0x02, /* length 0x02*/
BLE_GAP_AD_TYPE_FLAGS, /* AD type = 01 */
GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED|GAP_ADTYPE_FLAGS_GENERAL, /* LE Mode = 0x06 */
0x0a, /* length 0x1a*/
BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME, /* AD type = 0x09*/
'K','e','y','-','-','-','-','U', 'p',
0x03, /* length 0x03*/
BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, /* AD type = 0xFF */
/***************User set***********************/
0x10,0x0b,
/***************User End***********************/
};
//Eddystone data format
static uint8_t Eddystone_Uri_adv_data[]=
{
/***************User End***********************/
/*Service Data - 16-bit UUID. */
//BLE_GAP_AD_TYPE_SERVICE_DATA,
/*Google 16bit UUID */
//0xAA,0xFE,
//{
0x02, /* length 0x02*/
BLE_GAP_AD_TYPE_FLAGS, /* AD type = 01 */
GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED|GAP_ADTYPE_FLAGS_GENERAL, /* LE Mode = 0x06 */
//}
//{
/* Eddystone(https://github.com/google/eddystone/blob/master/protocol-specification.md) */
0x03, /* length 0x03 */
BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, /* AD type = Complete list of 16-bit UUIDs available */
0xAA, /* Eddystone service FEAA */
0xFE,
//}
//{
0x0b, /* length 12byte*/
BLE_GAP_AD_TYPE_SERVICE_DATA, /* AD type = Service Data type value */
0xAA, /* Eddystone service FEAA */
0xFE,
/* Eddystone-URL(https://github.com/google/eddystone/tree/master/eddystone-url) */
0x10, /* Frame Type: URL */
0xb6, /* Ranging Data */
0x00, /* URL Scheme: https:// */
'j','b','5','1',//'s','z','o','k','l','e',
0x0a,
//}
};
/*- INDICATION data -*/
uint8_t Eddystone_Uid_adv_data[] = {
/*Service Data - 16-bit UUID. */
//BLE_GAP_AD_TYPE_SERVICE_DATA,
/*Google 16bit UUID */
//0xAA,0xFE,
//{
0x02, /* length 0x02*/
BLE_GAP_AD_TYPE_FLAGS, /* AD type = 01 */
GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED|GAP_ADTYPE_FLAGS_GENERAL, /* LE Mode = 0x06 */
//}
//{
/* Eddystone(https://github.com/google/eddystone/blob/master/protocol-specification.md) */
0x03, /* length 0x03 */
BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, /* AD type = Complete list of 16-bit UUIDs available */
0xAA, /* Eddystone service FEAA */
0xFE,
//}
//{
0x17, /* length 12byte*/
BLE_GAP_AD_TYPE_SERVICE_DATA, /* AD type = Service Data type value */
0xAA, /* Eddystone service FEAA */
0xFE,
0x00, /* Frame Type: UID */
0xE7, /* Ranging Data */
0x16, 0xF7, 0x42, 0xf6, 0xA8, 0x8C, 0x57, 0x5B, 0x53, 0x24, /* Namespace:MSB 10Bytes*/
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, /* Instance */
0x00, /* Reserved */
0x00, /* Reserved */
//}
};
uint8_t Eddystone_Tlm_adv_data[] = {
/*Service Data - 16-bit UUID. */
//BLE_GAP_AD_TYPE_SERVICE_DATA,
/*Google 16bit UUID */
//0xAA,0xFE,
//{
0x02, /* length 0x02*/
BLE_GAP_AD_TYPE_FLAGS, /* AD type = 01 */
GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED|GAP_ADTYPE_FLAGS_GENERAL, /* LE Mode = 0x06 */
//}
//{
/* Eddystone(https://github.com/google/eddystone/blob/master/protocol-specification.md) */
0x03, /* length 0x03 */
BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, /* AD type = Complete list of 16-bit UUIDs available */
0xAA, /* Eddystone service FEAA */
0xFE,
//}
//{
0x11, /* length 12byte*/
BLE_GAP_AD_TYPE_SERVICE_DATA, /* AD type = Service Data type value */
0xAA, /* Eddystone service FEAA */
0xFE,
/* Eddystone-TLM(https://github.com/google/eddystone/tree/master/eddystone-tlm) */
0x20, /* Frame Type: TLM */
0x00, /* TLM Version */
0x0b, 0x54, /* Battery voltage 2900[mV] */
0x0b, 0x54, /* Beacon Temperature */
0x00, 0x00, 0x10, 0x00, /* Advertising PDU count */
0x01, 0x00, 0x00, 0x00, /* Time since power-on or reboot */
//}
};
/* Private function prototypes -----------------------------------------------*/
/*******************************************************************************
* Function : BLE_Mode_Sleep
* Parameter : void
* Returns : void
* Description:
* Note: : BLE enter sleep mode. current: 3ua
*******************************************************************************/
void BLE_Mode_Sleep(void)
{
uint8_t temp0[4];
temp0[0] = 0x02;
temp0[1] = 0xff;
temp0[2] = 0xff;
temp0[3] = 0xff;
SPI_Write_Buffer(SLEEP_WAKEUP,temp0,4);
}
/*******************************************************************************
* Function : BLE_Mode_Wakeup
* Parameter : void
* Returns : void
* Description:
* Note: : BLE reg:0x00--0x1f. write operation must or 0x20
*******************************************************************************/
void BLE_Mode_Wakeup(void)
{
SPI_Write_Reg(SLEEP_WAKEUP|0x20, 0x01);
}
/*******************************************************************************
* Function : BLE_Set_StartTime
* Parameter : uint32_t
* Returns : void
* Description:
* Note: :
*******************************************************************************/
void BLE_Set_StartTime(uint32_t htime)
{
uint8_t temp0[3];
uint32_t temp1 = htime;
temp0[0] = temp1 & 0xFF;
temp0[1] = (temp1>>8) & 0xFF;
temp0[2] = (temp1>>16) & 0xFF;
SPI_Write_Buffer(START_TIME,temp0,3);
}
/*******************************************************************************
* Function : BLE_GetClock
* Parameter : uint32_t *lfclk, uint32_t *hfclk
* Returns : void
* Description:
* Note: :
*******************************************************************************/
void BLE_Get_Clock(uint32_t *lfclk, uint32_t *hfclk)
{
uint8_t temp0[6];
//uint16_t temp1=0;
BLE_CSN_CLR();
SPI_Write_Byte(CLK_CNT);
temp0[0]=SPI_Read_Byte();
temp0[1]=SPI_Read_Byte();
temp0[2]=SPI_Read_Byte();
temp0[3]=SPI_Read_Byte();
temp0[4]=SPI_Read_Byte();
temp0[5]=SPI_Read_Byte();
BLE_CSN_SET();
*lfclk = ((uint32_t)temp0[5] << 16) + ((uint32_t)temp0[4] << 8) + temp0[3];
*hfclk = ((uint32_t)temp0[2] << 16) + ((uint32_t)temp0[1] << 8) + temp0[0];
}
/*******************************************************************************
* Function : BLE_Set_TimeOut
* Parameter : uint32_t data_us
* Returns : void
* Description: TX/RX timeout .unit:us
* Note: :
*******************************************************************************/
void BLE_Set_TimeOut(uint32_t data_us)
{
uint8_t temp0[3];
if(data_us < 0x10000)
{
temp0[0] = data_us & 0xff;
temp0[1] = (data_us >> 8) & 0xff;
temp0[2] = 0;
SPI_Write_Buffer(TIMEOUT, temp0, 3);
}
else
{
SPI_Read_Buffer(TIMEOUT,temp0,3);
if(temp0[2] == 0)
{
temp0[2] = 1;
SPI_Write_Buffer(TIMEOUT, temp0, 3);
}
}
}
/*******************************************************************************
* Function : void BLE_send(void)
* Parameter : void
* Returns : void
* Description: configure reg data. ready ble send data.
* Note: :
*******************************************************************************/
void BLE_send(void)
{
uint8_t temp0[4];
SPI_Write_Reg(0x20, 0x00);
SPI_Write_Reg(0x50, 0x53);
SPI_Write_Reg(0x33,0x01);
SPI_Write_Reg(0x35,0x01);
//Calibration frequency .
temp0[0] = 0xcf;//bf;
temp0[1] = 0x00;
SPI_Write_Buffer(0x14,temp0,2);
temp0[0] = 0x10;
temp0[1] = 0x08;
SPI_Write_Buffer(0x1e,temp0,2);
temp0[0] = 0x80;
temp0[1] = 0x00;
temp0[2] = 0x01;
SPI_Write_Buffer(0x12,temp0,3);
temp0[0] = 0x01;
temp0[1] = 0x22;
SPI_Write_Buffer(0x13,temp0,2);
temp0[0] = 0x00;
temp0[1] = 0x80;
temp0[2] = 0x01;
SPI_Write_Buffer(0x10,temp0,3);
SPI_Write_Reg(0x2f, 0x01);
temp0[0] = 0x00;
temp0[1] = 0x6e;
SPI_Write_Buffer(0x11,temp0,2);
SPI_Write_Reg(0x3d,0x04);
SPI_Write_Reg(0x3d,0x06);
Delay_us(10);
SPI_Write_Reg(0x3d,0x07);
Delay_us(40);
SPI_Write_Reg(0x3d,0x05);
Delay_us(120);
//set BLE TX Power
temp0[0] = 0x01;
temp0[1] = BLE_TX_POWER;
SPI_Write_Buffer(0x0f,temp0,2);
temp0[0] = 0x88;
temp0[1] = 0x80;
SPI_Write_Buffer(0x12,temp0,2);
temp0[0] = 0x00;
temp0[1] = 0x2e;
temp0[2] = 0x08;
temp0[3] = 0x0f;
SPI_Write_Buffer(0x11,temp0,4);
temp0[0] = 0x01;
temp0[1] = 0x20;
SPI_Write_Buffer(0x13,temp0,2);
SPI_Write_Reg(0x50, 0x56);
SPI_Write_Reg(0x20,0x01);
}
/*******************************************************************************
* Function : void BLE_Send_done(void)
* Parameter : void
* Returns : void
* Description: BLE send data finish . need configure reg data.
* Note: :
*******************************************************************************/
void BLE_Send_done(void)
{
uint8_t temp0[3];
SPI_Write_Reg(0x50, 0x53);
SPI_Write_Reg(0x31,0x24);
temp0[0] = 0x02;
temp0[1] = 0x00;
SPI_Write_Buffer(0x0f, temp0, 2);
SPI_Write_Reg(0x3e,0x10);
temp0[0] = 0x00;
temp0[1] = 0x00;
temp0[2] = 0x81;
SPI_Write_Buffer(0x12, temp0, 3);
temp0[0] = 0x81;
temp0[1] = 0x20;
SPI_Write_Buffer(0x13, temp0, 2);
Delay_us(100);
SPI_Write_Reg(0x33,0x01);
SPI_Write_Reg(0x35,0x00);
SPI_Write_Reg(0x3d,0x18);
SPI_Write_Reg(0x50,0x56);
}
/*******************************************************************************
* Function : BLE_Init
* Parameter : void
* Returns : void
* Description: power on .BLE must initnal reg .
* Note: : delay 30ms .
*******************************************************************************/
void BLE_Init(void)
{
uint8_t status;
uint8_t data_buf[3];
uint8_t ble_Addr[6];
//Delay_ms(30);
Uart_Send_String("BLE init \r\n");
SPI_Write_Reg(0x50, 0x51);
SPI_Write_Reg(0x50, 0x53);
SPI_Write_Reg(0x35, 0x00);
//xtal off for v16w1
SPI_Write_Reg(0x3d, 0x18);
do{
data_buf[0] = 0;
data_buf[1] = 0;
data_buf[2] = 1;
SPI_Write_Buffer(0x00, data_buf, 3);
SPI_Write_Reg(0x36, 0x8e);
SPI_Write_Reg(0x37, 0x8e);
SPI_Write_Reg(0x38, 0x88);
SPI_Write_Reg(0x39, 0x8e);
SPI_Write_Reg(0x50, 0x51);
SPI_Read_Reg(0x1e);
status = SPI_Read_Reg(CHIP_OK);
}while(status != 0x80);
//read chip version
status = SPI_Read_Reg(0x1e);
Uart_Send_String("chip version=");
Uart_Send_Byte(status);
Uart_Send_String("\r\n");
//power down,tx //add this for hot reset
SPI_Write_Reg(0X20, 0x78);
//1Mbps
SPI_Write_Reg(0X26, 0x06);
//power up
SPI_Write_Reg(0X20, 0x7a);
SPI_Write_Reg(0x50, 0x56);
SPI_Write_Reg(0x20, 0x01);
BLE_Mode_Sleep();
//read BLE address. BLE MAC Address
SPI_Read_Buffer(0x08, ble_Addr, 6);
Uart_Send_String("BleAddr=");
Uart_Send_Byte(ble_Addr[5]);
Uart_Send_Byte(ble_Addr[4]);
Uart_Send_Byte(ble_Addr[3]);
Uart_Send_Byte(ble_Addr[2]);
Uart_Send_Byte(ble_Addr[1]);
Uart_Send_Byte(ble_Addr[0]);
Uart_Send_String("\r\n");
}
/*******************************************************************************
* Function : BLE_Beacon
* Parameter : void
* Returns : void
* Description: Beacon data .process .
* Note: :
*******************************************************************************/
void BLE_Beacon(void)
{
uint8_t bank_buf[6];
uint8_t ch = 37;
uint8_t status;
uint32_t lfclk,tx_start,wakeup_time, hfclk;
uint8_t temp0=0;
//Workmode change .ready ble data
if(Work_Mode == Work_Mode_iBeacon)
{
for(temp0=0;temp0<(sizeof(iBeacon_adv_data)/sizeof(uint8_t));temp0++)
{
adv_data[temp0] = iBeacon_adv_data[temp0];
}
}
else if(Work_Mode == Work_Mode_Eddystone_Uri)
{
for(temp0=0;temp0<(sizeof(Eddystone_Uri_adv_data)/sizeof(uint8_t));temp0++)
{
adv_data[temp0] = Eddystone_Uri_adv_data[temp0];
}
}
else if(Work_Mode == Work_Mode_Eddystone_Uid)
{
for(temp0=0;temp0<(sizeof(Eddystone_Uid_adv_data)/sizeof(uint8_t));temp0++)
{
adv_data[temp0] = Eddystone_Uid_adv_data[temp0];
}
}
else if(Work_Mode == Work_Mode_Eddystone_Tlm)
{
for(temp0=0;temp0<(sizeof(Eddystone_Tlm_adv_data)/sizeof(uint8_t));temp0++)
{
adv_data[temp0] = Eddystone_Tlm_adv_data[temp0];
}
}
else if(Work_Mode == Work_Mode_Remote)
{
if(KEY_GET() != RESET)
{
for(temp0=0;temp0<(sizeof(Beacon_Key_Press_adv_data)/sizeof(uint8_t));temp0++)
{
adv_data[temp0] = Beacon_Key_Press_adv_data[temp0];
}
}
else
{
for(temp0=0;temp0<(sizeof(Beacon_Key_uP_adv_data)/sizeof(uint8_t));temp0++)
{
adv_data[temp0] = Beacon_Key_uP_adv_data[temp0];
}
}
}
LED_RED_ON();
//set BLE TX default channel:37.38.39
SPI_Write_Reg(CH_NO|0X20, ch);
//BLT FIFO write adv_data . max len:31 byte
SPI_Write_Buffer(W_TX_PAYLOAD, adv_data, sizeof(adv_data));
//set BLT PDU length:adv_data+6 mac adress.
bank_buf[0] = 0x02;//0x42;
bank_buf[1] = sizeof(adv_data)+6;
//PDU TYPE: 2 non-connectable undirected advertising . tx add:random address
SPI_Write_Buffer(ADV_HDR_TX, bank_buf, 2);
SPI_Write_Reg(0x50, 0x53);
bank_buf[1] = SPI_Read_Reg(0x08);
if(0 == bank_buf[1]){
bank_buf[1] = 0x11;
}
bank_buf[0] = 0xc0;
bank_buf[2] = 0x1D;
SPI_Write_Buffer(0x4, bank_buf, 3);
//calibration
SPI_Write_Reg(0x3F, 0x03);
do{
bank_buf[0] = SPI_Read_Reg(0x1F);
}while(bank_buf[0]&0x03);
SPI_Write_Reg(0x3F, 0x03);
do{
bank_buf[0] = SPI_Read_Reg(0x1F);
}while(bank_buf[0]&0x03);
SPI_Write_Reg(0x35, 0x01);
SPI_Write_Reg(0x32, 0x88);
bank_buf[0] = 0x01;
bank_buf[1] = 0x21;
SPI_Write_Buffer(0x13, bank_buf, 2);
bank_buf[0] = 0x01;
bank_buf[1] = 0x20;
SPI_Write_Buffer(0x13, bank_buf, 2);
SPI_Write_Reg(0x35, 0x00);
SPI_Write_Reg(0x50, 0x56);
Uart_Send_String("BLE_Beacon mode ");
Uart_Send_Byte(Work_Mode-'0');
Uart_Send_String("\r\n");
//clear all interrupt
SPI_Write_Reg(INT_FLAG|0X20, 0xff);
//BLE Wakeup mode
BLE_Mode_Wakeup();
while(1)
{
// //Workmode change .
if((Rx_Tx_Buffer_Cnt == 1))
{
Work_Mode = Rx_Buffer[0];
Rx_Tx_Buffer_Cnt = 0;
//sleep(power down)
SPI_Write_Reg(0x50, 0x51);
SPI_Write_Reg(0x20, 0x78);
SPI_Write_Reg(0x50, 0x56);
BLE_Mode_Sleep();
//exit loop .
break;
}
//remote .key press & up data
if(Work_Mode == Work_Mode_Remote)
{
if(KEY_GET() == RESET)
{
for(temp0=0;temp0<(sizeof(Beacon_Key_Press_adv_data)/sizeof(uint8_t));temp0++)
{
adv_data[temp0] = Beacon_Key_Press_adv_data[temp0];
}
}
else
{
for(temp0=0;temp0<(sizeof(Beacon_Key_uP_adv_data)/sizeof(uint8_t));temp0++)
{
adv_data[temp0] = Beacon_Key_uP_adv_data[temp0];
}
}
}
//BLE IRQ LOW
if (!BLE_IRQ_GET())
{
//clear interrupt flag
status = SPI_Read_Reg(INT_FLAG);
SPI_Write_Reg(INT_FLAG|0X20, status);
//Uart_Send_String("BLE_IRQ LOW work status=");
//Uart_Send_Byte(status);
//Uart_Send_String("\r\n");
//Tx done process
if(status == 0xFF)
{
BLE_Mode_Sleep();
BLE_Send_done();
}
//BLE sleep process
else if(status == INT_TYPE_SLEEP)//sleep
{
LED_GREEN_OFF();
IWDG_ReloadCounter();
//BLE channel
if (++ch > 39)
{
ch = 37;
}
SPI_Write_Reg(CH_NO|0X20, ch);
SPI_Write_Reg(0x50, 0x51);
switch(ch)
{
case 37:
SPI_Write_Reg(0x25, 0x02);
break;
case 38:
SPI_Write_Reg(0x25, 0x1a);
break;
case 39:
SPI_Write_Reg(0x25, 0x50);
break;
}
SPI_Write_Reg(0x50, 0x56);
//BLT FIFO write adv_data . max len:31 byte
SPI_Write_Buffer(W_TX_PAYLOAD, adv_data, sizeof(adv_data));
tick = CNT_SLEEP;
}
else if (status == INT_TYPE_WAKEUP) //BLE wakeup process
{
LED_GREEN_ON();
BLE_send();
//BLE work mode:TX mode
SPI_Write_Reg(MODE_TYPE|0X20, RADIO_MODE_ADV_TX);
tx_start = BLE_START_TIME;//HFCLK_1MS*TX_PRE;
BLE_Set_StartTime(tx_start);
}
else
{
//other interrupt
SPI_Write_Reg(INT_FLAG|0X20, 0xff);
//BLE Enter sleep
BLE_Mode_Sleep();
}
}else{
if(tick == 0){
SPI_Write_Reg(0x50, 0x53);
SPI_Write_Reg(0x3d, 0x1e);
SPI_Write_Reg(0x50, 0x56);
tick = 2; //2ms delay then wakeup
while(tick){};
BLE_Mode_Wakeup();
tick = CNT_SLEEP;
}
}
}
}
| a45e2516f7fed514b4cd427c0c79af04e29d8f24 | [
"C"
] | 2 | C | oklble/BleDemo | 9f52909ba75e8cd89f369b530a2831020207fca4 | e5502094d5c67c3d8dba7939d3ef08065b4dfac1 |
refs/heads/main | <repo_name>nqsjd178559344/shopping_cart_demo<file_sep>/src/App.js
import Item from './components/Item'
import Cart from './components/Cart'
import Mock, { Random } from 'mockjs'
import { inject, observer } from 'mobx-react'
import './App.less'
/**
* 设计:
* less + mock + mobx + mocha测试[未做]
*/
const data = Mock.mock({
'list|10-15': [
{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|+1': 1,
'imgWidth': '@integer(100,500)',
'imgHeight': '@integer(100,500)',
'name': '苹果-广西南宁自治县巴拉巴拉~',
'backgroundColor': Random.color(),
'backgroundImage': Random.image('500x@imgHeight'), // 高度不统一时宽度不可使用相同方式指定
"price|1-100.2": 1,
}
]
})
function App() {
return (
<div className="shopping-cart">
<header className="header">
<h2 className="header-title">
购物天堂
</h2>
<span className="header-cart">
<button>购物车</button>
<div className='cart-wrapper'>
<Cart />
</div>
</span>
</header>
<div className="content">
{
data.list.map(i => {
return <Item key={i.id} {...i} />
})
}
</div>
</div>
);
}
export default App;
<file_sep>/src/components/Item/index.js
import React from 'react'
import { inject, observer } from 'mobx-react'
import './index.less'
function Item(props) {
const { cartStore, ...item } = props
const handleAdd = () => {
cartStore.handleAdd(item)
}
return <div className="item">
<div className="img" style={{
backgroundImage: `url(${item.backgroundImage})`,
}}>
</div>
<div className="bottom">
<span className="item-name">
{item.name}
</span>
<div className="item-priceWrapper">
<span className="item-priceWrapper-price">
{item.price}
</span>
<span className="item-priceWrapper-addBtn">
<button onClick={handleAdd}>加入购物车</button>
</span>
</div>
</div>
</div>
}
export default inject('cartStore')(observer(Item))<file_sep>/src/store/index.js
import cartStore from './cart'
const stores = {
cartStore
}
export default stores
<file_sep>/config-overrides.js
/* config-overrides.js */
const BundleAnalyzer = require("webpack-bundle-analyzer").BundleAnalyzerPlugin // 输出dist每个文件的大小的树形图
// 方法1
const rewireLess = require('@joiner/react-app-rewire-less-modules');
// 方法2
// const rewireLess = require('@joiner/react-app-rewire-less');// todo 找不到包
// ? 1/2使用方法相同 => 均需要加入less-loader@^4.1.0
module.exports = function override(config, env) {
//do stuff with the webpack config...
config = rewireLess(config, env);
// let loaders = config.module.rules.find(rule => Array.isArray(rule.oneOf)).oneOf
// loaders.unshift({ // todo 报错与less-loader高版本一样
// test: /\.less$/,
// use: [
// require.resolve('style-loader'),
// {
// loader: require.resolve('css-loader')
// },
// // {
// // loader: 'postcss-loader',
// // options: { //! autoprefixer 需要配置浏览器版本 => postcss.config.js文件
// // // plugins: [require("autoprefixer")],
// // // config:{
// // // path:'postcss.config.js'
// // // }
// // // plugins: ()=>[require("autoprefixer")]
// // // postcssOptions: {
// // // plugins: [
// // // [
// // // "autoprefixer",
// // // {
// // // // Options
// // // },
// // // ],
// // // ],
// // // },
// // }
// // },
// {
// loader: require.resolve('less-loader')
// }
// ]
// })
if (config.plugins) {
config.plugins.push(new BundleAnalyzer())
}
return config;
}<file_sep>/src/store/cart.js
import { observable, action, decorate } from 'mobx'
class CartStore {
list = [];
handleAdd = (item) => {
let num = 1
if(item.num > 1){
num = item.num + 1
}
const hasItemBefore = this.list.find(i=>i.id === item.id)
// 新加入的项在最上面
if(hasItemBefore){ // 之前存在
this.list = this.list.map(i=>{
if(i.id === item.id){
i.num ++
}
return i
})
}else{
const target = {...item,num}
this.list.push(target);
}
}
// action
handleDel(item) {
this.list = this.list.filter(i => i.id !== item.id);
}
}
decorate(CartStore, {
list: observable,
handleAdd: action,
handleDel: action,
});
const cartStore = new CartStore()
export default cartStore;<file_sep>/src/components/Cart/index.js
import React from 'react'
import { inject, observer } from 'mobx-react'
import './index.less'
function Cart({ cartStore }) {
const handleDel = (item) => {
cartStore.handleDel(item)
}
const handleBuy = ()=>{
const sum = cartStore.list.reduce((prev,cur)=>{
const targetSum = cur.price * cur.num
return prev += targetSum
},0)
// 暂时处理精度问题
const newSum = sum.toFixed(2)
alert(newSum)
}
return <div className='cart'>
{
cartStore.list.map(i => {
return <div key={i.id} className='cart-item'>
<div className='cart-name'>
{i.name}
</div>
<span>
{i.price}
</span>
*
<span>
{i.num}
</span>
<span className='cart-del'>
<button onClick={() => handleDel(i)}>删除</button>
</span>
</div>
})
}
<button onClick={handleBuy}>购买</button>
</div>
}
export default inject('cartStore')(observer(Cart))
<file_sep>/README.md
目的功能: 热更新 + less + webpack打包 | 1ec7cbb48cfa0ef86d2ab621287f01968442d439 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | nqsjd178559344/shopping_cart_demo | 012f06c7855ff892c43d9e6ff13217ddb398365c | 93a71eefe01f095bddb25613357cf71b3d0f6a4a |
refs/heads/master | <file_sep>package org.bitcoinj.wallet;
import com.google.common.util.concurrent.Service;
import javafx.application.Platform;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Peer;
import org.bitcoinj.core.PeerGroup;
import org.bitcoinj.core.Utils;
import org.bitcoinj.core.listeners.DownloadProgressTracker;
import org.bitcoinj.kits.WalletAppKit;
import org.bitcoinj.params.MainNetParams;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.Executor;
public class WalletTest_1 {
@Test
public void createWallet() throws IOException {
NetworkParameters parameters = MainNetParams.get();
WalletAppKit kit = new WalletAppKit(parameters,new File("."),"wallet-"+parameters.getPaymentProtocolId()){
@Override
protected void onSetupCompleted() {
// Don't make the user wait for confirmations for now, as the intention is they're sending it
// their own money!
wallet().allowSpendingUnconfirmedTransactions();
}
};
kit.setDownloadListener(new ProgressBarUpdater())
.setBlockingStartup(false)
.setUserAgent("wallet","1.0");
if(kit.isChainFileLocked()){
return;
}
kit.addListener(new Service.Listener() {
@Override
public void failed(Service.State from, Throwable failure) {
System.out.println(failure.getMessage());
}
}, new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
kit.startAsync();
try {
Thread.sleep(30000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
PeerGroup peer = kit.peerGroup();
System.out.println("peer!!!");
// Wallet wallet = new Wallet(parameters);
//
// DeterministicSeed seed = wallet.getKeyChainSeed();
// System.out.println("seed: " + seed.toString());
// System.out.println("creation time: " + seed.getCreationTimeSeconds());
// System.out.println("mnemonicCode: " + Utils.join(seed.getMnemonicCode()));
}
private class ProgressBarUpdater extends DownloadProgressTracker {
@Override
protected void progress(double pct, int blocksLeft, Date date) {
super.progress(pct, blocksLeft, date);
}
@Override
protected void doneDownload() {
super.doneDownload();
}
}
}
| 3fefd172376b48928dfa3f6bb04ed5d704b6c43e | [
"Java"
] | 1 | Java | LiPengW/android-fork-bitcoinj | 4a1227851f685d72917a67f90df90d0a63cb3e5c | 3cbac0bff355c59983b81e72ea3bfbe649e83f97 |
refs/heads/master | <repo_name>67-6f-64/TheClownClub<file_sep>/Common/Shopify/ShopifyProducts.cs
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace Common.Shopify {
public partial class ShopifyProducts {
[JsonProperty("products")]
public List<ShopifyProduct> ProductsList { get; set; }
}
public partial class ShopifyProduct {
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("handle")]
public string Handle { get; set; }
[JsonProperty("body_html")]
public string BodyHtml { get; set; }
[JsonProperty("published_at")]
public DateTimeOffset PublishedAt { get; set; }
[JsonProperty("created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("updated_at")]
public DateTimeOffset UpdatedAt { get; set; }
[JsonProperty("vendor")]
public string Vendor { get; set; }
[JsonProperty("product_type")]
public string ProductType { get; set; }
[JsonProperty("tags")]
public List<string> Tags { get; set; }
[JsonProperty("variants")]
public List<ShopifyVariant> Variants { get; set; }
[JsonProperty("images")]
public List<ShopifyImage> Images { get; set; }
[JsonProperty("options")]
public List<ShopifyOption> Options { get; set; }
}
public partial class ShopifyImage {
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("updated_at")]
public DateTimeOffset UpdatedAt { get; set; }
[JsonProperty("product_id")]
public long ProductId { get; set; }
[JsonProperty("variant_ids")]
public List<object> VariantIds { get; set; }
[JsonProperty("src")]
public Uri Src { get; set; }
[JsonProperty("width")]
public long Width { get; set; }
[JsonProperty("height")]
public long Height { get; set; }
}
public partial class ShopifyOption {
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("values")]
public List<string> Values { get; set; }
}
public partial class ShopifyVariant {
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("option1")]
public string Option1 { get; set; }
[JsonProperty("option2")]
public string Option2 { get; set; }
[JsonProperty("option3")]
public string Option3 { get; set; }
[JsonProperty("sku")]
public string Sku { get; set; }
[JsonProperty("requires_shipping")]
public bool RequiresShipping { get; set; }
[JsonProperty("taxable")]
public bool Taxable { get; set; }
[JsonProperty("featured_image")]
public object FeaturedImage { get; set; }
[JsonProperty("available")]
public bool Available { get; set; }
[JsonProperty("price")]
public string Price { get; set; }
[JsonProperty("grams")]
public long Grams { get; set; }
[JsonProperty("compare_at_price")]
public string CompareAtPrice { get; set; }
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("product_id")]
public long ProductId { get; set; }
[JsonProperty("created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("updated_at")]
public DateTimeOffset UpdatedAt { get; set; }
}
public partial class ShopifyProducts {
public static ShopifyProducts FromJson(string json) => JsonConvert.DeserializeObject<ShopifyProducts>(json);
}
}
<file_sep>/Shopify/ShopifyBot.cs
using System;
using Common;
using Common.Shopify;
using Common.Supreme;
using Common.Types;
using Shopify.Tasks;
namespace Shopify {
public class ShopifyBot : Bot {
public string Domain { get; set; }
public bool PregenCart { get; set; }
public string CheckoutUrl { get; set; }
public string CheckoutAction { get; set; }
public ShopifyProducts ShopifyProducts { get; set; }
public ShopifyProduct ShopifyProduct { get; set; }
public ShopifyVariant ShopifyVariant { get; set; }
public ShopifyBot() : base(BotType.Shopify, new BillingProfile(), new SearchProduct()) {
Append(new PregenCartTask(this));
}
public ShopifyBot(BillingProfile profile, SearchProduct product) : base(BotType.Shopify, profile, product) {
Append(new PregenCartTask(this));
}
}
}
<file_sep>/README.md
# TheClownClub
A broken Supreme bot I made back in 2019, the project was ultimately abandoned and the code is garbage but there are concepts I believe people could learn from.<file_sep>/Shopify/Tasks/FindProductTask.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Common;
using Common.Services;
using HtmlAgilityPack;
namespace Shopify.Tasks {
class FindProductTask : BotTask {
public FindProductTask(Bot bot) : base(bot) { }
public override string Description() {
return "Find Product";
}
public override void Execute() {
var bot = (ShopifyBot) GetBot();
do {
Parallel.ForEach(bot.ShopifyProducts.ProductsList,
(product, state) => {
var isValid = !bot.SearchProduct.ProductKeywords.Any(keyword =>
keyword.StartsWith("-")
? !product.Title.IndexOf(keyword[1..],
StringComparison.CurrentCultureIgnoreCase).Equals(-1)
: product.Title.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase).Equals(-1));
if (!isValid) return;
bot.ShopifyProduct = product;
state.Stop();
});
} while (bot.ShopifyProduct is null);
}
public override int Priority() {
return 20;
}
public override bool Validate() {
GetBot().Status = "Waiting for Monitor";
while (((ShopifyBot)GetBot()).ShopifyProducts is null) { }
return true;
}
}
}
<file_sep>/SupremeUs/SupremeBot.cs
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Http;
using System.Text.Json.Serialization;
using Common;
using Common.Supreme;
using Common.Types;
using Newtonsoft.Json.Linq;
using Supreme.Tasks;
namespace Supreme {
public class SupremeBot : Bot {
[Browsable(false)] public MobileStock MobileStock { get; set; }
private TimeSpan _checkoutDelay;
[DisplayName("Checkout Delay"), Category("Configuration")]
public double CheckoutDelay {
get => _checkoutDelay.TotalMilliseconds;
set {
_checkoutDelay = TimeSpan.FromMilliseconds(value);
OnPropertyChanged();
}
}
[Browsable(false)] public Stopwatch DelayStopwatch;
private MobileStockProduct _mobileStockProduct;
[DisplayName("Product Name"), Category("Information")]
public MobileStockProduct MobileStockProduct {
get => _mobileStockProduct;
set {
_mobileStockProduct = value;
OnPropertyChanged();
}
}
[Browsable(false)] public SupremeProduct Product { get; set; }
private Style _style;
[DisplayName("Product Style"), Category("Information"), Newtonsoft.Json.JsonIgnore]
public Style ProductStyle {
get => _style;
set {
_style = value;
OnPropertyChanged();
}
}
private Size _size;
[DisplayName("Product Size"), Category("Information"), JsonIgnore]
public Size ProductSize {
get => _size;
set {
_size = value;
OnPropertyChanged();
}
}
[Browsable(false)] public string CheckoutHtml { get; set; }
[Browsable(false)] public string CsrfToken { get; set; }
[Browsable(false)] public FormUrlEncodedContent CheckoutFormUrlEncodedContent { get; set; }
[Browsable(false)] public JObject CheckoutJObject { get; set; }
[Browsable(false)] public string CheckoutSlug { get; set; }
[Browsable(false), JsonIgnore] public DateTime AtcTime { get; set; }
[DisplayName("Captcha Bypass (US)"), Category("Configuration")]
public bool CaptchaBypass { get; set; }
public SupremeBot() : base(BotType.Supreme, new BillingProfile(), new SearchProduct()) {
Append(new FindProductTask(this), new FindStyleAndSizeTask(this), new WaitForStockTask(this),
new AddToCartTask(this),
new ParseCheckoutTask(this), new CheckoutTask(this), new CheckoutQueueTask(this));
}
public SupremeBot(BillingProfile profile, SearchProduct product) : base(BotType.Supreme, profile, product) {
Append(new FindProductTask(this), new FindStyleAndSizeTask(this), new WaitForStockTask(this),
new AddToCartTask(this),
new ParseCheckoutTask(this), new CheckoutTask(this), new CheckoutQueueTask(this));
}
public bool ShouldSerializeMobileStock() {
return SerializeDebug;
}
public bool ShouldSerializeCheckoutHtml() {
return SerializeDebug;
}
public bool ShouldSerializeCsrfToken() {
return SerializeDebug;
}
public bool ShouldSerializeCheckoutFormUrlEncodedContent() {
return SerializeDebug;
}
public bool ShouldSerializeCheckoutJObject() {
return SerializeDebug;
}
public bool ShouldSerializeCheckoutSlug() {
return SerializeDebug;
}
public bool ShouldSerializeProduct() {
return SerializeDebug;
}
public bool ShouldSerializeMobileStockProduct() {
return SerializeDebug;
}
}
}<file_sep>/ActivityGen/Tasks/NewsTask.cs
using PuppeteerSharp;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace ActivityGen.Tasks {
class NewsTask : BotTask {
public async Task<BotTaskResult> Do(Bot bot) {
if (!bot.m_Page.Url.StartsWith("https://www.google.com/")) await bot.m_Page.GoToAsync("https://www.google.com/");
try {
bot.m_Status = "Browsing news...";
await bot.m_Page.WaitForXPathAsync("//*[@id=\"gbwa\"]/div[1]/a");
await bot.m_Page.XPathAsync("//*[@id=\"gbwa\"]/div[1]/a").ContinueWith(t => t.Result.FirstOrDefault().ClickAsync());
await bot.m_Page.WaitForXPathAsync("//*[@id=\"gb5\"]/span[1]", new WaitForSelectorOptions { Visible = true });
await bot.m_Page.XPathAsync("//*[@id=\"gb5\"]/span[1]").ContinueWith(t => t.Result.FirstOrDefault().ClickAsync());
await bot.m_Page.WaitForNavigationAsync(new NavigationOptions { Timeout = 5000 });
var articles = await bot.m_Page.QuerySelectorAllAsync("article");
Array.Resize(ref articles, Utils.RandomNumber(1, 10));
foreach (var article in articles) {
await article.HoverAsync();
await Task.Delay(Utils.RandomNumber(3000, 10000));
if (Utils.RandomNumber(0, 1000) > 800) {
bot.m_Status = "Reading article...";
await article.ClickAsync();
await Task.Delay(Utils.RandomNumber(10000, 90000));
bot.m_Status = "Browsing news...";
}
}
return BotTaskResult.Success;
}
catch (Exception) {
return BotTaskResult.Failed;
}
}
}
}
<file_sep>/ActivityGen/MainWindow.xaml.cs
using DiscordRPC;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Media.Imaging;
namespace ActivityGen {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
bool m_IsRunning = false;
public static int m_TaskDelay = 10000;
public static int m_LoginDelay = 10000;
public static ObservableCollection<Bot> m_Bots = new ObservableCollection<Bot>();
DiscordRpcClient m_DiscordClient;
CancellationTokenSource m_TokenSource = new CancellationTokenSource();
System.Timers.Timer m_UpdateTimer = new System.Timers.Timer(1000);
public MainWindow() {
InitializeComponent();
#region Discord RPC
m_DiscordClient = new DiscordRpcClient("620789728958087178");
//Set the logger
//client.Logger = new ConsoleLogger() { Level = LogLevel.Warning };
//Subscribe to events
//client.OnReady += (sender, e) =>
//{
// Console.WriteLine("Received Ready from user {0}", e.User.Username);
//};
//
//client.OnPresenceUpdate += (sender, e) =>
//{
// Console.WriteLine("Received Update! {0}", e.Presence);
//};
m_DiscordClient.Initialize();
m_DiscordClient.SetPresence(new RichPresence() {
Details = "You a clown.",
State = "Generating one clicks",
Assets = new Assets() {
LargeImageKey = "clown",
LargeImageText = "TheClown.Club",
SmallImageKey = "clown"
}
});
#endregion
m_Bots.CollectionChanged += (object sender, NotifyCollectionChangedEventArgs e) => {
lvBots.ItemsSource = m_Bots;
};
m_UpdateTimer.Elapsed += (object source, ElapsedEventArgs e) => {
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background,
new Action(() => { lvBots.ItemsSource = m_Bots; lvBots.Items.Refresh(); }));
};
m_UpdateTimer.Start();
}
private async void Start_Click(object sender, RoutedEventArgs e) {
//var bot = new Bot(txtEmail.Text, txtPassword.Password); // https://bot.sannysoft.com
//await bot.Init();
//await bot.Run(new NewsTask());
//await bot.Run(new YoutubeTask());
//await bot.m_Page.ScreenshotAsync("headless.png");
//await bot.m_Page.PdfAsync("headless.pdf");
//MessageBox.Show("done.");
if (m_IsRunning)
return;
m_TokenSource = new CancellationTokenSource();
var tasks = new List<Task>();
for (var i = 0; i < m_Bots.Count; i++) {
int index = i;
tasks.Add(Task.Run(async () => {
await m_Bots[index].Init();
if (m_Bots[index].m_Status.StartsWith("Signed in.")) {
await m_Bots[index].Run(m_TokenSource.Token);
}
}));
}
m_IsRunning = true;
await Task.WhenAll(tasks);
}
private void Stop_Click(object sender, RoutedEventArgs e) {
if (!m_IsRunning)
return;
m_TokenSource.Cancel();
m_IsRunning = true;
}
private void Button_Click(object sender, RoutedEventArgs e) {
try {
MailAddress m = new MailAddress(txtEmail.Text);
}
catch (FormatException) {
MessageBox.Show("Invalid email.");
return;
}
if (!string.IsNullOrEmpty(txtProxy.Text) &&
!Regex.IsMatch(txtProxy.Text, @"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):[\d]+$")) {
MessageBox.Show("Invalid proxy.");
return;
}
m_Bots.Add(new Bot(txtEmail.Text, txtPassword.Password, txtProxy.Text));
}
private void SliderDelay_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) {
int newVal = Convert.ToInt32(e.NewValue);
m_TaskDelay = newVal * 1000;
if (lblDelay != null && lblDelay.IsLoaded)
lblDelay.Content = newVal;
}
private void SliderLoginDelay_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) {
int newVal = Convert.ToInt32(e.NewValue);
m_LoginDelay = newVal * 1000;
if (lblDelaySignin != null && lblDelaySignin.IsLoaded)
lblDelaySignin.Content = newVal;
}
private async void Screenshot_Click(object sender, RoutedEventArgs e) {
if (lvBots.SelectedIndex == -1 || m_Bots[lvBots.SelectedIndex].m_Page == null)
return;
var img = await m_Bots[lvBots.SelectedIndex].m_Page.ScreenshotDataAsync();
using (var ms = new MemoryStream(img)) {
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
image.EndInit();
imgScreenshot.Source = image;
}
}
private void Captcha_Click(object sender, RoutedEventArgs e) {
if (lvBots.SelectedIndex == -1 || m_Bots[lvBots.SelectedIndex].m_Page == null)
return;
if (m_Bots[lvBots.SelectedIndex].m_CatpchaImage != null) {
using (var ms = new MemoryStream(m_Bots[lvBots.SelectedIndex].m_CatpchaImage)) {
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
image.EndInit();
imgScreenshot.Source = image;
}
}
else {
MessageBox.Show("null");
}
}
private void SubmitCaptcha_Click(object sender, RoutedEventArgs e) {
if (lvBots.SelectedIndex == -1 || m_Bots[lvBots.SelectedIndex].m_Page == null)
return;
if (!string.IsNullOrWhiteSpace(txtCaptcha.Text)) {
m_Bots[lvBots.SelectedIndex].m_CaptchaText = txtCaptcha.Text;
}
}
}
}
<file_sep>/ClownAIOClient/Globals.cs
using System.Threading;
using NotLiteCode.Client;
using NotLiteCode.Network;
using NotLiteCode.Serialization;
namespace ClownAIO {
internal class Globals {
public static CancellationTokenSource CancellationTokenSource = new CancellationTokenSource();
private static readonly NLCSocket NlcSocket = new NLCSocket(new GroBufSerializationProvider(), true, true);
public static readonly Client Client = new Client(NlcSocket);
}
}
<file_sep>/ActivityGen/Utils.cs
using System;
namespace ActivityGen {
class Utils {
public static int RandomNumber(int min, int max) {
Random random = new Random();
return random.Next(min, max);
}
}
}
<file_sep>/ClownAIOClient/LoginWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Printing.IndexedProperties;
using System.Reflection;
using System.Runtime.Loader;
using FirstFloor.ModernUI.Windows.Controls;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Common;
using Newtonsoft.Json;
using NotLiteCode.Client;
using NotLiteCode.Network;
using NotLiteCode.Serialization;
namespace ClownAIO {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class LoginWindow : ModernWindow {
public static async Task<bool> Auth(string authKey, string hwid) =>
await Globals.Client.RemoteCall<bool>("Auth", authKey, hwid);
public LoginWindow() {
InitializeComponent();
Globals.Client.Connect("localhost", 1338);
}
private async void Button_Click(object sender, RoutedEventArgs e) {
var authKey = AuthKey.Text.Trim();
var authed = await Auth(authKey, null);
if (!authed) return;
new LoadingWindow().Show();
Close();
}
}
}
<file_sep>/ClownAIOClient/BotConverter.cs
using System;
using Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Supreme;
namespace ClownAIO {
public class BotConverter : JsonConverter {
public override bool CanWrite => false;
public override bool CanRead => true;
public override bool CanConvert(Type objectType) {
return objectType == typeof(Bot);
}
public override void WriteJson(JsonWriter writer,
object value, JsonSerializer serializer) {
throw new InvalidOperationException("Use default serialization.");
}
public override object ReadJson(JsonReader reader,
Type objectType, object existingValue,
JsonSerializer serializer) {
var jsonObject = JObject.Load(reader);
var bot = default(Bot);
switch (jsonObject["BotType"].Value<int>()) {
case (int)BotType.Supreme:
bot = new Supreme.SupremeBot();
break;
}
serializer.Populate(jsonObject.CreateReader(), bot);
return bot;
}
}
}
<file_sep>/ClownAIOClient/CaptchaHarvesterWindow.xaml.cs
using FirstFloor.ModernUI.Windows.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
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;
using CefSharp;
using Common.Services;
using CefSharp.Wpf;
using ClownAIO.Classes;
namespace ClownAIO {
/// <summary>
/// Interaction logic for CaptchaHarvesterWindow.xaml
/// </summary>
public partial class CaptchaHarvesterWindow : ModernWindow {
private string Domain { get; }
private string SiteKey { get; }
public CaptchaHarvesterWindow(string domain, string sitekey) {
InitializeComponent();
Domain = domain;
SiteKey = sitekey;
Title = Domain;
ChromiumBrowser.Address = $"https://{Domain}/recaptcha";
ChromiumBrowser.MenuHandler = new NoContextMenuHandler();
ChromiumBrowser.RequestHandler = new CaptchaRequestHandler(domain, sitekey);
}
private void Button_Click(object sender, RoutedEventArgs e) {
ChromiumBrowser.Load($"https://{Domain}/recaptcha");
}
private void Button2_Click(object sender, RoutedEventArgs e) {
ChromiumBrowser.Load("https://www.google.com/");
}
private void ModernWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
CaptchaHarvester.RemoveWindow(SiteKey);
}
}
}
<file_sep>/ActivityGen/Bot.cs
using ActivityGen.Tasks;
using PuppeteerSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace ActivityGen {
public class Bot {
public CancellationToken m_Cancel { get; private set; }
public string m_Email { get; private set; }
public string m_Password { get; private set; }
public string m_Status { get; set; }
public string m_Proxy { get; private set; }
public byte[] m_CatpchaImage { get; set; }
public string m_CaptchaText { get; set; }
public Browser m_Browser { get; private set; }
public Page m_Page { get; private set; }
public async Task Init() {
m_Status = "Initializing browser...";
await InitBrowser();
m_Status = "Initializing page...";
await GeneratePage().ContinueWith(t => m_Page = t.Result);
var task = new SignInTask();
await task.Do(this).ContinueWith(t => t.Result == BotTaskResult.Success ? m_Status = "Signed in. Delaying..." : m_Status = "Failed to sign in.");
if (m_Status.Equals("Signed in. Delaying..."))
await Task.Delay(MainWindow.m_LoginDelay);
}
private async Task InitBrowser() {
var currentDirectory = Directory.GetCurrentDirectory();
var downloadPath = Path.Combine(currentDirectory, "ChromeRuntime");
if (!Directory.Exists(downloadPath)) {
Directory.CreateDirectory(downloadPath);
}
var browserFetcherOptions = new BrowserFetcherOptions { Path = downloadPath };
var browserFetcher = new BrowserFetcher(browserFetcherOptions);
await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);
var executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);
if (string.IsNullOrEmpty(executablePath)) {
throw new Exception("Failed to initialize browser.");
}
List<string> args = new List<string> {
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-infobars",
"--window-position=0,0",
"--ignore-certifcate-errors",
"--ignore-certifcate-errors-spki-list",
"--user-agent=\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\""
};
if (!m_Proxy.Equals("NONE"))
args.Add(string.Format("--proxy-server={0}", m_Proxy));
var options = new LaunchOptions {
Headless = true,
IgnoreHTTPSErrors = true,
ExecutablePath = executablePath,
Args = args.ToArray()
};
m_Browser = await Puppeteer.LaunchAsync(options);
}
private async Task<Page> GeneratePage() {
var page = await m_Browser.NewPageAsync();
await page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 1080 });
await page.SetJavaScriptEnabledAsync(true);
await page.EvaluateFunctionOnNewDocumentAsync(@"function() {
delete navigator.__proto__.webdriver
/* global MimeType MimeTypeArray PluginArray */
// Disguise custom functions as being native
const makeFnsNative = (fns = []) => {
const oldCall = Function.prototype.call
function call () {
return oldCall.apply(this, arguments)
}
// eslint-disable-next-line
Function.prototype.call = call
const nativeToStringFunctionString = Error.toString().replace(
/Error/g,
'toString'
)
const oldToString = Function.prototype.toString
function functionToString () {
for (const fn of fns) {
if (this === fn.ref) {
return `function ${fn.name}() { [native code] }`
}
}
if (this === functionToString) {
return nativeToStringFunctionString
}
return oldCall.call(oldToString, this)
}
// eslint-disable-next-line
Function.prototype.toString = functionToString
}
const mockedFns = []
const fakeData = {
mimeTypes: [
{
type: 'application/pdf',
suffixes: 'pdf',
description: '',
__pluginName: 'Chrome PDF Viewer'
},
{
type: 'application/x-google-chrome-pdf',
suffixes: 'pdf',
description: 'Portable Document Format',
__pluginName: 'Chrome PDF Plugin'
},
{
type: 'application/x-nacl',
suffixes: '',
description: 'Native Client Executable',
enabledPlugin: Plugin,
__pluginName: 'Native Client'
},
{
type: 'application/x-pnacl',
suffixes: '',
description: 'Portable Native Client Executable',
__pluginName: 'Native Client'
}
],
plugins: [
{
name: 'Chrome PDF Plugin',
filename: 'internal-pdf-viewer',
description: 'Portable Document Format'
},
{
name: 'Chrome PDF Viewer',
filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai',
description: ''
},
{
name: 'Native Client',
filename: 'internal-nacl-plugin',
description: ''
}
],
fns: {
namedItem: instanceName => {
// Returns the Plugin/MimeType with the specified name.
const fn = function (name) {
if (!arguments.length) {
throw new TypeError(
`Failed to execute 'namedItem' on '${instanceName}': 1 argument required, but only 0 present.`
)
}
return this[name] || null
}
mockedFns.push({ ref: fn, name: 'namedItem' })
return fn
},
item: instanceName => {
// Returns the Plugin/MimeType at the specified index into the array.
const fn = function (index) {
if (!arguments.length) {
throw new TypeError(
`Failed to execute 'namedItem' on '${instanceName}': 1 argument required, but only 0 present.`
)
}
return this[index] || null
}
mockedFns.push({ ref: fn, name: 'item' })
return fn
},
refresh: instanceName => {
// Refreshes all plugins on the current page, optionally reloading documents.
const fn = function () {
return undefined
}
mockedFns.push({ ref: fn, name: 'refresh' })
return fn
}
}
}
// Poor mans _.pluck
const getSubset = (keys, obj) =>
keys.reduce((a, c) => ({ ...a, [c]: obj[c] }), {})
function generateMimeTypeArray () {
const arr = fakeData.mimeTypes
.map(obj => getSubset(['type', 'suffixes', 'description'], obj))
.map(obj => Object.setPrototypeOf(obj, MimeType.prototype))
arr.forEach(obj => {
arr[obj.type] = obj
})
// Mock functions
arr.namedItem = fakeData.fns.namedItem('MimeTypeArray')
arr.item = fakeData.fns.item('MimeTypeArray')
return Object.setPrototypeOf(arr, MimeTypeArray.prototype)
}
const mimeTypeArray = generateMimeTypeArray()
Object.defineProperty(navigator, 'mimeTypes', {
get: () => mimeTypeArray
})
function generatePluginArray () {
const arr = fakeData.plugins
.map(obj => getSubset(['name', 'filename', 'description'], obj))
.map(obj => {
const mimes = fakeData.mimeTypes.filter(
m => m.__pluginName === obj.name
)
// Add mimetypes
mimes.forEach((mime, index) => {
navigator.mimeTypes[mime.type].enabledPlugin = obj
obj[mime.type] = navigator.mimeTypes[mime.type]
obj[index] = navigator.mimeTypes[mime.type]
})
obj.length = mimes.length
return obj
})
.map(obj => {
// Mock functions
obj.namedItem = fakeData.fns.namedItem('Plugin')
obj.item = fakeData.fns.item('Plugin')
return obj
})
.map(obj => Object.setPrototypeOf(obj, Plugin.prototype))
arr.forEach(obj => {
arr[obj.name] = obj
})
// Mock functions
arr.namedItem = fakeData.fns.namedItem('PluginArray')
arr.item = fakeData.fns.item('PluginArray')
arr.refresh = fakeData.fns.refresh('PluginArray')
return Object.setPrototypeOf(arr, PluginArray.prototype)
}
const pluginArray = generatePluginArray()
Object.defineProperty(navigator, 'plugins', {
get: () => pluginArray
})
// Make mockedFns toString() representation resemble a native function
makeFnsNative(mockedFns)
window.chrome = {
runtime: {}
}
try {
/* global WebGLRenderingContext */
const getParameter = WebGLRenderingContext.getParameter
WebGLRenderingContext.prototype.getParameter = function (parameter) {
// UNMASKED_VENDOR_WEBGL
if (parameter === 37445) {
return 'Intel Inc.'
}
// UNMASKED_RENDERER_WEBGL
if (parameter === 37446) {
return 'Intel Iris OpenGL Engine'
}
return getParameter(parameter)
}
} catch (err) {}
try {
if (window.outerWidth && window.outerHeight) {
return // nothing to do here
}
const windowFrame = 85 // probably OS and WM dependent
window.outerWidth = window.innerWidth
window.outerHeight = window.innerHeight + windowFrame
} catch (err) {}
const originalQuery = window.navigator.permissions.query
// eslint-disable-next-line
window.navigator.permissions.__proto__.query = parameters =>
parameters.name === 'notifications'
? Promise.resolve({ state: Notification.permission }) //eslint-disable-line
: originalQuery(parameters)
// Inspired by: https://github.com/ikarienator/phantomjs_hide_and_seek/blob/master/5.spoofFunctionBind.js
const oldCall = Function.prototype.call
function call () {
return oldCall.apply(this, arguments)
}
// eslint-disable-next-line
Function.prototype.call = call
const nativeToStringFunctionString = Error.toString().replace(
/Error/g,
'toString'
)
const oldToString = Function.prototype.toString
function functionToString () {
if (this === window.navigator.permissions.query) {
return 'function query() { [native code] }'
}
if (this === functionToString) {
return nativeToStringFunctionString
}
return oldCall.call(oldToString, this)
}
// eslint-disable-next-line
Function.prototype.toString = functionToString
}
");
return page;
}
public Bot(string email, string password, string proxy = "") {
m_Email = email;
m_Password = <PASSWORD>;
if (!string.IsNullOrEmpty(m_Proxy) && !proxy.Equals("0.0.0.0:65535"))
m_Proxy = proxy;
else
m_Proxy = "NONE";
m_Status = "Idle";
}
public async Task RunTask(BotTask task) {
await task.Do(this).ContinueWith(t => t.Result == BotTaskResult.Success ? m_Status = "Completed task." : m_Status = "Failed task.");
}
public async Task Run(CancellationToken token) {
while (!token.IsCancellationRequested) {
switch (Utils.RandomNumber(0, 1)) {
case 0: {
await RunTask(new YoutubeTask());
break;
}
case 1: {
await RunTask(new NewsTask());
break;
}
}
if (token.IsCancellationRequested)
break;
m_Status = "Delaying...";
await Task.Delay(MainWindow.m_TaskDelay);
}
m_Status = "Idle";
}
}
}
<file_sep>/Common/Services/CaptchaRequestHandler.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using CefSharp;
using CefSharp.Handler;
namespace Common.Services {
public class CaptchaRequestHandler : RequestHandler {
private string Domain { get; }
private string SiteKey { get; }
public CaptchaRequestHandler(string domain, string sitekey) {
Domain = domain;
SiteKey = sitekey;
}
protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling) {
return new CaptchaResourceHandler(Domain, SiteKey);
}
}
}
<file_sep>/ClownAIOClient/Pages/ProfilesPage.xaml.cs
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using Common;
using Common.Types;
using Microsoft.Win32;
using Newtonsoft.Json;
namespace ClownAIO.Pages {
/// <summary>
/// Interaction logic for PropertyGrid.xaml
/// </summary>
public partial class ProfilesPage : UserControl {
public ProfilesPage() {
InitializeComponent();
ProfilePropertyGrid.DataContext = new ProfileTaskGridViewModel();
ProfilesListView.ItemsSource = BotContext.Profiles;
BotContext.Profiles.CollectionChanged += (sender, args) => { ProfilesListView.ItemsSource = BotContext.Profiles; };
}
private void AddProfileButton_OnClick(object sender, RoutedEventArgs e) {
if (string.IsNullOrWhiteSpace(FirstName.Text)
|| string.IsNullOrWhiteSpace(LastName.Text)) {
MessageBox.Show("First/last name cannot be blank.");
return;
}
try {
var mailAddress = new MailAddress(Email.Text);
}
catch (FormatException) {
MessageBox.Show("Invalid email.");
return;
}
if (!Regex.Match(Phone.Text, @"\d\d\d-\d\d\d-\d\d\d\d").Success) {
MessageBox.Show("Invalid phone number.");
return;
}
if (string.IsNullOrWhiteSpace(Address.Text)) {
MessageBox.Show("Address cannot be blank.");
return;
}
if (string.IsNullOrWhiteSpace(City.Text)) {
MessageBox.Show("City cannot be blank.");
return;
}
if (!Regex.Match(CcNumber.Text, @"\d\d\d\d-\d\d\d\d-\d\d\d\d-\d\d\d\d").Success) {
MessageBox.Show("Invalid card number.");
return;
}
if (!Regex.Match(CcCvv.Text, @"\d\d\d").Success) {
MessageBox.Show("Invalid CVV.");
return;
}
BotContext.Profiles.Add(ProfileName.Text, new BillingProfile(FirstName.Text, LastName.Text, Email.Text,
Phone.Text,
Address.Text, Address2.Text, Address3.Text, Zip.Text, City.Text, State.Text, Country.Text,
CcType.Text.ToLower().Replace(" ", "_"), CcNumber.Text, CcExpir.Value ?? DateTime.Now, CcCvv.Text));
}
private void TaskListView_OnSelectionChanged(object sender, SelectionChangedEventArgs e) {
((ProfileTaskGridViewModel) ProfilePropertyGrid.DataContext).BillingProfile = BotContext.Profiles.First().Value;
}
private void SaveProfileButton_OnClick(object sender, RoutedEventArgs e) {
if (ProfilesListView.SelectedItems.Count <= 0) return;
var sfd = new SaveFileDialog
{Title = "Choose file to export profiles to...", Filter = "JSON|*.json|All Files|*"};
var result = sfd.ShowDialog();
if (result != true) return;
try {
File.WriteAllText(sfd.FileName, JsonConvert.SerializeObject(ProfilesListView.SelectedItems));
}
catch (Exception) {
MessageBox.Show("Failed to save profiles.");
}
}
private void LoadProfileButton_OnClick(object sender, RoutedEventArgs e) {
var ofd = new OpenFileDialog
{Title = "Open exported profiles...", Filter = "JSON|*.json|All Files|*"};
var result = ofd.ShowDialog();
if (result != true) return;
try {
var profiles =
JsonConvert.DeserializeObject<BillingProfile[]>(File.ReadAllText(ofd.FileName));
foreach (var profile in profiles) {
BotContext.Profiles.Add(profile.Email, profile);
}
}
catch (Exception) {
MessageBox.Show("Failed to load profiles.");
}
}
}
public sealed class ProfileTaskGridViewModel : INotifyPropertyChanged {
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private BillingProfile _billingProfile;
public BillingProfile BillingProfile {
get => _billingProfile;
set {
_billingProfile = value;
OnPropertyChanged();
}
}
}
}
<file_sep>/SupremeUs/Tasks/CheckoutTask.cs
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using Common;
using Common.Services;
using Newtonsoft.Json.Linq;
namespace Supreme.Tasks {
class CheckoutTask : BotTask {
public CheckoutTask(Bot bot) : base(bot) { }
public override bool Validate() {
var bot = (SupremeBot)GetBot();
return bot.CheckoutFormUrlEncodedContent != null && !bot.GetCancellationToken().IsCancellationRequested;
}
public override void Execute() {
var bot = (SupremeBot) GetBot();
string checkoutResponse;
using (var request = new HttpRequestMessage {
RequestUri = new Uri($"https://www.supremenewyork.com/checkout.json"),
Method = HttpMethod.Post,
}) {
using var client = new HttpClient(bot.GetClientHandler(), false);
request.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("Refer", "https://www.supremenewyork.com/mobile");
request.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.8,en-GB;q=0.6");
//request.Headers.Add("X-CSRF-Token", bot.CsrfToken); // Not needed anymore, we use mobile endpoint
request.Content = bot.CheckoutFormUrlEncodedContent;
while (bot.CheckoutDelay > bot.DelayStopwatch.ElapsedMilliseconds) { }
checkoutResponse = HttpHelper.GetStringSync(request, client, out _, bot.GetCancellationToken());
bot.RequestsList.Add(new Tuple<HttpRequestMessage, string>(request, checkoutResponse));
}
if (string.IsNullOrEmpty(checkoutResponse) || bot.GetCancellationToken().IsCancellationRequested) return;
bot.CheckoutJObject = JObject.Parse(checkoutResponse);
var checkoutStatus = bot.CheckoutJObject["status"].Value<string>();
if (checkoutStatus.Equals("queued")) bot.CheckoutSlug = bot.CheckoutJObject["slug"].Value<string>();
bot.Status = $"Checkout: {char.ToUpper(checkoutStatus[0]) + checkoutStatus.Substring(1)}";
Debug.WriteLine("checkout response: " + checkoutResponse);
}
public override int Priority() {
return 60;
}
public override string Description() {
return "Checkout";
}
}
}
<file_sep>/SupremeUs/Tasks/ParseCheckoutTask.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.XPath;
using Common;
using Common.Services;
using HtmlAgilityPack;
namespace Supreme.Tasks {
class ParseCheckoutTask : BotTask {
public ParseCheckoutTask(Bot bot) : base(bot) { }
public override bool Validate() {
var bot = (SupremeBot)GetBot();
string checkoutHtml;
using (var request = new HttpRequestMessage() {
RequestUri = new Uri($"https://www.supremenewyork.com/mobile#checkout"),
Method = HttpMethod.Get,
}) {
using var client = new HttpClient(bot.GetClientHandler(), false);
request.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
checkoutHtml = HttpHelper.GetStringSync(request, client, out _, bot.GetCancellationToken());
bot.RequestsList.Add(new Tuple<HttpRequestMessage, string>(request, checkoutHtml));
}
if (bot.GetCancellationToken().IsCancellationRequested) return false;
bot.CheckoutHtml = checkoutHtml;
return !string.IsNullOrEmpty(checkoutHtml);
}
public override void Execute() { // TODO: improve parser and verify we have all required fields
var bot = (SupremeBot) GetBot();
var checkoutDoc = new HtmlDocument();
checkoutDoc.LoadHtml(bot.CheckoutHtml);
//bot.CsrfToken = checkoutDoc.DocumentNode.SelectSingleNode("//meta[@name=\"csrf-token\"]").GetAttributeValue("content", "");
HtmlNode form = null;
foreach (var script in checkoutDoc.DocumentNode.Descendants("script")) {
try {
var scriptDoc = new HtmlDocument();
scriptDoc.LoadHtml(script.InnerHtml);
if (!scriptDoc.DocumentNode.Descendants("form").First().GetAttributeValue("action", "")
.Equals("https://www.supremenewyork.com/checkout.json")) continue;
form = scriptDoc.DocumentNode.Descendants("form").First();
}
catch (Exception) { }
}
if (form is null) return;
var formContentList = new ConcurrentQueue<KeyValuePair<string, string>>();
var inputLoop = Task.Run(() => {
foreach (var node in form.Descendants("input")) {
var nodeName = node.GetAttributeValue("name", "");
if (node.GetAttributeValue("type", "").Equals("hidden")) {
formContentList.Enqueue(nodeName.Equals("cookie-sub")
? new KeyValuePair<string, string>(nodeName, $"{{\"{bot.ProductSize.Id}\":1}}")
: new KeyValuePair<string, string>(nodeName, node.GetAttributeValue("value", "")));
}
else {
if (nodeName.Contains("name")) {
formContentList.Enqueue(new KeyValuePair<string, string>(nodeName,
bot.BillingProfile.FirstName + " " + bot.BillingProfile.LastName));
}
else if (nodeName.Contains("email")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.Email));
}
else if (nodeName.Contains("tel")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.Phone));
}
else if (nodeName.Contains("address_2")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.Address2));
}
else if (nodeName.Contains("address_3")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.Address2));
}
else if (nodeName.Contains("billing_address")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.Address));
}
else if (nodeName.Contains("city")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.City));
}
else if (nodeName.Contains("zip")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.ZipCode));
}
else if (nodeName.Contains("vvv")) {
formContentList.Enqueue(new KeyValuePair<string, string>(nodeName, bot.BillingProfile.Cvv));
}
else if (nodeName.Contains("term")) {
formContentList.Enqueue(new KeyValuePair<string, string>(nodeName, "1"));
}
else {
var nodePlaceholder = node.GetAttributeValue("placeholder", "");
if (nodePlaceholder.Contains("number")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.CcNumber));
}
else if (nodePlaceholder.Contains("cvv")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.Cvv));
}
}
}
}
});
var selectLoop = Task.Run(() => {
foreach (var node in form.Descendants("select")) {
var nodeName = node.GetAttributeValue("name", "");
if (node.GetAttributeValue("type", "").Equals("hidden")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, node.GetAttributeValue("value", "")));
}
else {
if (nodeName.Contains("state")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.State));
}
else if (nodeName.Contains("country")) {
formContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, bot.BillingProfile.Country));
}
else if (nodeName.Contains("month")) {
formContentList.Enqueue(new KeyValuePair<string, string>(nodeName,
bot.BillingProfile.CcExpiration.Month.ToString("d2")));
}
else if (nodeName.Contains("year")) {
formContentList.Enqueue(new KeyValuePair<string, string>(nodeName,
bot.BillingProfile.CcExpiration.Year.ToString()));
}
else if (nodeName.Contains("card[type]")) {
formContentList.Enqueue(new KeyValuePair<string, string>(nodeName,
bot.BillingProfile.CcType));
}
else {
if (node.SelectNodes("option").Single(node => node.GetAttributeValue("value", "").Equals("visa")) != null) {
formContentList.Enqueue(new KeyValuePair<string, string>(nodeName,
bot.BillingProfile.CcType));
}
}
}
}
});
Task.WaitAll(inputLoop, selectLoop);
if (!bot.CaptchaBypass) {
bot.Status = "Waiting for Captcha";
var captchaKeyValuePair = new KeyValuePair<DateTime, string>();
do {
if (!CaptchaHarvester.Tokens.ContainsKey("<KEY>")) continue;
CaptchaHarvester.Tokens["<KEY>"]
.TryDequeue(out captchaKeyValuePair);
if (string.IsNullOrEmpty(captchaKeyValuePair.Value)) continue;
if (captchaKeyValuePair.Key < bot.AtcTime
|| DateTime.Now - captchaKeyValuePair.Key > TimeSpan.FromSeconds(110)) {
captchaKeyValuePair = new KeyValuePair<DateTime, string>();
}
} while (captchaKeyValuePair.Value is null);
formContentList.Enqueue(new KeyValuePair<string, string>("g-recaptcha-response", captchaKeyValuePair.Value));
}
bot.CheckoutFormUrlEncodedContent = new FormUrlEncodedContent(formContentList);
}
public override int Priority() {
return 50;
}
public override string Description() {
return "Parse Checkout";
}
}
}
<file_sep>/SupremeUs/Tasks/WaitForStockTask.cs
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using Common;
using Common.Services;
using Common.Supreme;
namespace Supreme.Tasks {
class WaitForStockTask : BotTask {
public WaitForStockTask(Bot bot) : base(bot) { }
public override bool Validate() {
var bot = (SupremeBot) GetBot();
return bot.ProductSize != null && bot.ProductSize.StockLevel.Equals(0);
}
public override void Execute() { // TODO: check keyword logic
var bot = (SupremeBot) GetBot();
do {
string productJson;
using (var request = new HttpRequestMessage() {
RequestUri = new Uri($"https://www.supremenewyork.com/shop/{bot.MobileStockProduct.Id}.json"),
Method = HttpMethod.Get,
}) {
using var client = bot.GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
productJson = HttpHelper.GetStringSync(request, client, out _, bot.GetCancellationToken());
bot.RequestsList.Add(new Tuple<HttpRequestMessage, string>(request, productJson));
}
if (string.IsNullOrEmpty(productJson) || bot.GetCancellationToken().IsCancellationRequested) return;
try {
bot.Product = SupremeProduct.FromJson(productJson);
bot.ProductStyle = bot.Product.Styles.First(style => style.Id.Equals(bot.ProductStyle.Id));
bot.ProductSize = bot.ProductStyle.Sizes.First(size => size.Id.Equals(bot.ProductSize.Id));
}
catch (Exception) { }
} while (bot.ProductSize.StockLevel.Equals(0));
}
public override int Priority() {
return 30;
}
public override string Description() {
return "Wait For Stock";
}
}
}
<file_sep>/ClownAIOServer/App.xaml.cs
using NotLiteCode.Network;
using NotLiteCode.Server;
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Windows;
using NotLiteCode.Serialization;
namespace ClownClubServer {
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application {
private static X509Certificate2 GenerateSelfSignedCert(string CertificateName, string HostName) {
SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
sanBuilder.AddDnsName(HostName);
X500DistinguishedName distinguishedName = new X500DistinguishedName($"CN={CertificateName}");
using (RSA rsa = RSA.Create(2048)) {
var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(
new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));
request.CertificateExtensions.Add(sanBuilder.Build());
var certificate = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650)));
certificate.FriendlyName = CertificateName;
return new X509Certificate2(certificate.Export(X509ContentType.Pfx));
}
}
private void Initialize(object sender, StartupEventArgs e) {
DatabaseManager.Init();
_ = BotStartup.RunAsync();
var serverSocket = new NLCSocket(new GroBufSerializationProvider(), UseSSL: true, ServerCertificate: GenerateSelfSignedCert("TheClownClub", "theclown.club"));
var server = new Server<NLC.SharedClass>(serverSocket);
server.Start();
var window = new MainWindow();
window.Show();
}
}
}
<file_sep>/ClownAIOServer/DiscordModules/Commands.cs
using ClownClubServer.Classes;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace ClownClubServer.DiscordModules {
[Name("Base")]
[RequireContext(ContextType.Guild | ContextType.DM)]
public class Commands : ModuleBase<SocketCommandContext> {
private static Random random = new Random();
public static string RandomString(int length) {
const string chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
[Command("register")]
[Summary("Register user.")]
[RequireBotPermission(GuildPermission.ManageRoles)]
public async Task Register(string code) {
if (DatabaseManager.Users.Exists(x => x.Id.Equals(Context.User.Id))) {
await ReplyAsync($"{Context.User.Mention} you already have an auth key.");
}
else if (DatabaseManager.Invites.Exists(x => x.Id.Equals(code))) {
Invite invite = DatabaseManager.Invites.FindOne(x => x.Id.Equals(code));
DatabaseManager.Invites.Delete(code);
string key = RandomString(32);
DatabaseManager.Users.Insert(new User(Context.User.Id, key, invite));
var role = Context.Guild.Roles.FirstOrDefault(x => x.Name.Equals("Verified"));
await (Context.User as IGuildUser).AddRoleAsync(role);
await Context.User.SendMessageAsync($"**Auth Key:** {key}");
await ReplyAsync($"{Context.User.Mention} check your DMs.");
}
else {
await ReplyAsync($"{Context.User.Mention} invalid invite.");
}
}
[Command("invite")]
[Summary("Generates an invite if user has met requirements.")]
public async Task Invite() {
var account = DatabaseManager.Users.FindOne(x => x.Id.Equals(Context.User.Id));
if (account is null) {
await ReplyAsync($"{Context.User.Mention} you are not registered.");
return;
}
if (account.RegistrationDate < DateTime.Now.AddMonths(3)) {
await ReplyAsync(
$"{Context.User.Mention} you must be registered for at least 3 months to get an invite.");
return;
}
if (account.LastInviteDate < DateTime.Now.AddMonths(3)) {
await ReplyAsync($"{Context.User.Mention} you can only get 1 invite every 3 months.");
return;
}
if (DatabaseManager.Invites.Exists(x => x.Inviter.Equals(Context.User.Id))) {
await ReplyAsync($"{Context.User.Mention} you can only have 1 unused invite at a time.");
return;
}
var code = RandomString(16);
DatabaseManager.Invites.Insert(new Invite(code, Context.User.Id));
await Context.User.SendMessageAsync($"**Invite Code:** {code}");
await ReplyAsync($"{Context.User.Mention} check your DMs.");
account.LastInviteDate = DateTime.Now;
DatabaseManager.Users.Update(account);
}
[Command("adminvite")]
[Summary("Generates an invite for the user specified by the admin.")]
[RequireUserPermission(GuildPermission.Administrator)]
public async Task AdminviteUser(SocketUser user = null) {
var code = RandomString(16);
if (user is null) {
DatabaseManager.Invites.Insert(new Invite(code, Context.User.Id));
await Context.User.SendMessageAsync($"**Invite Code:** {code}");
await ReplyAsync($"{Context.User.Mention} check your DMs.");
return;
}
if (!DatabaseManager.Users.Exists(x => x.Id.Equals(user.Id))) {
await ReplyAsync($"{Context.User.Mention} that user is not registered.");
return;
}
DatabaseManager.Invites.Insert(new Invite(code, user.Id));
await user.SendMessageAsync($"**Invite Code:** {code}");
await ReplyAsync($"{user.Mention} check your DMs.");
}
[Command("invitewave")]
[Summary("Gives an invite to every user.")]
[RequireUserPermission(GuildPermission.Administrator)]
public async Task InviteWave() {
var invites = 0;
foreach (var user in DatabaseManager.Users.FindAll()) {
var discordUser = Context.Client.GetUser(user.Id);
if (discordUser is null)
continue;
var code = RandomString(16);
DatabaseManager.Invites.Insert(new Invite(code, discordUser.Id));
await Context.User.SendMessageAsync($"**Invite Code:** {code}");
invites++;
}
await ReplyAsync($"{invites} invite(s) given out.");
}
[Command("invitewave")]
[Summary("Gives an invite to every user until the maximum is reached.")]
[RequireUserPermission(GuildPermission.Administrator)]
public async Task InviteWave(int max) {
var invites = 0;
foreach (var user in DatabaseManager.Users.FindAll()) {
if (invites >= max)
break;
var discordUser = Context.Client.GetUser(user.Id);
if (discordUser is null)
continue;
var code = RandomString(16);
DatabaseManager.Invites.Insert(new Invite(code, discordUser.Id));
await Context.User.SendMessageAsync($"**Invite Code:** {code}");
invites++;
}
await ReplyAsync($"{invites} invite(s) given out.");
}
[Command("clearinvites")]
[Summary("Deletes all invites.")]
[RequireUserPermission(GuildPermission.Administrator)]
public async Task ClearInvites(SocketUser user = null) {
if (user is null) {
var count = DatabaseManager.Invites.Count();
DatabaseManager.Database.DropCollection("invites");
await ReplyAsync($"{count} invite(s) deleted.");
}
else {
var count = DatabaseManager.Invites.Find(x => x.Inviter.Equals(user.Id)).Count();
DatabaseManager.Invites.Delete(x => x.Inviter.Equals(user.Id));
await ReplyAsync($"{count} invite(s) deleted.");
}
}
[Command("whoami")]
[Summary("Returns user's Discord ID.")]
public async Task WhoAmI() {
await ReplyAsync($"{Context.User.Mention} {Context.User.Id}");
}
[Command("whois")]
[Summary("Gives information about a specified user.")]
public async Task WhoIs(SocketUser user = null) {
if (user is null) {
await ReplyAsync($"{Context.User.Mention} invalid user.");
return;
}
if (!DatabaseManager.Users.Exists(x => x.Id.Equals(user.Id))) {
await ReplyAsync($"{Context.User.Mention} that user is not registered.");
return;
}
var account = DatabaseManager.Users.FindOne(x => x.Id.Equals(user.Id));
var inviter = Context.Client.GetUser(account.InviteCode.Inviter);
var embed = new EmbedBuilder().WithAuthor(user)
.WithFooter(footer => footer.Text = "TheClown.Club")
.WithColor(Color.Blue)
.WithTitle("User Information")
.AddField("Discord ID", user.Id)
.AddField("Registered", account.RegistrationDate)
.AddField("Invited By", inviter == null ? account.InviteCode.Inviter.ToString() : inviter.Username)
.WithCurrentTimestamp()
.Build();
await ReplyAsync(embed: embed);
}
[Command("genlicense")]
[Summary("Generates a license key for an admin.")]
[RequireUserPermission(GuildPermission.Administrator)]
public async Task GenLicense(LicenseType licenseType, int time, string span, int amount = 1) {
TimeSpan timeSpan;
switch (span) {
case "hour":
case "hours": {
timeSpan = TimeSpan.FromHours(time);
break;
}
case "day":
case "days": {
timeSpan = TimeSpan.FromDays(time);
break;
}
case "month":
case "months": {
timeSpan = TimeSpan.FromDays(31 * time);
break;
}
case "year":
case "years": {
timeSpan = TimeSpan.FromDays(365 * time);
break;
}
default: {
await ReplyAsync($"{Context.User.Mention} invalid time span.");
return;
}
}
for (var i = 0; i < amount; i++) {
var license = new License(licenseType, timeSpan);
DatabaseManager.Licenses.Insert(license);
await Context.User.SendMessageAsync($"**License Code:** {license.Code}");
}
await ReplyAsync($"{Context.User.Mention} check your DMs.");
}
[Command("redeem")]
[Summary("Gives information about a specified user.")]
[RequireUserPermission(GuildPermission.Administrator)]
public async Task RedeemLicense(string code) {
var account = DatabaseManager.Users.FindOne(x => x.Id.Equals(Context.User.Id));
if (account is null) {
await ReplyAsync($"{Context.User.Mention} you are not registered.");
return;
}
var license = DatabaseManager.Licenses.FindOne(x => x.Code.Equals(code));
if (license is null) {
await ReplyAsync($"{Context.User.Mention} invalid key, please ensure it has been typed correctly.");
return;
}
license.RedeemedTime = DateTime.Now;
account.Licenses.Add(license);
DatabaseManager.Users.Update(account);
DatabaseManager.Licenses.Delete(x => x.Code.Equals(license.Code));
var embed = new EmbedBuilder().WithFooter(footer => footer.Text = "TheClown.Club")
.WithColor(Color.Blue)
.WithTitle("License Information")
.AddField("Type", license.Type)
.AddField("Length", license.ExpirationTime)
.AddField("Expiration Date", license.RedeemedTime + license.ExpirationTime)
.WithCurrentTimestamp()
.Build();
await ReplyAsync(embed: embed);
}
}
}
<file_sep>/ClownAIOClient/Pages/SettingsPage.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using Common.Services;
namespace ClownAIO.Pages {
/// <summary>
/// Interaction logic for SettingsPage.xaml
/// </summary>
public partial class SettingsPage : UserControl {
public SettingsPage() {
InitializeComponent();
}
private void RefreshSlider_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) {
SupremeMonitor.RefreshInterval = TimeSpan.FromMilliseconds(e.NewValue);
}
private void StartMonitorButton_OnClick(object sender, RoutedEventArgs e) {
try {
SupremeMonitor.SetProxy(MonitorProxy.Text);
}
catch (Exception) {
MessageBox.Show("Failed to set proxy. Invalid format?");
}
SupremeMonitor.Start();
}
private void StopMonitorButton_OnClick(object sender, RoutedEventArgs e) {
try {
SupremeMonitor.Stop();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
}
<file_sep>/ClownAIOServer/NLC/SharedClass.cs
using NotLiteCode.Server;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using ClownClubServer.Classes;
using Newtonsoft.Json;
namespace ClownClubServer.NLC {
class SharedClass : IDisposable {
private string AuthKey { get; set; }
[NLCCall("Auth")]
public bool Auth(string authKey, string hwid) {
var user = DatabaseManager.Users.FindOne(potentialUser => potentialUser.AuthKey.Equals(authKey));
if (user is null) return false;
//if (string.IsNullOrEmpty(user.Hwid)) {
// user.Hwid = hwid;
// DatabaseManager.Users.Update(user);
//}
//else if (!user.Hwid.Equals(hwid)) {
// return false;
//}
AuthKey = authKey;
return true;
}
private static bool LicenseValidFor(List<License> licenses, LicenseType licenseType) {
return licenses.Exists(x => !x.IsExpired() && (x.Type.Equals(LicenseType.All) || x.Type.Equals(LicenseType.Admin) || x.Type.Equals(licenseType)));
}
[NLCCall("GetCommon")]
public string GetCommon() {
if (string.IsNullOrEmpty(AuthKey)) return null;
var user = DatabaseManager.Users.FindOne(potentialUser => potentialUser.AuthKey.Equals(AuthKey));
var assemblyQueue = new Queue<byte[]>();
assemblyQueue.Enqueue(File.ReadAllBytes("Common.dll"));
if (LicenseValidFor(user.Licenses, LicenseType.Supreme))
assemblyQueue.Enqueue(File.ReadAllBytes("Supreme.dll"));
return JsonConvert.SerializeObject(assemblyQueue );
}
public void Dispose() { }
}
}
<file_sep>/Common/Shopify/ShopifySingleProduct.cs
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Common.Shopify {
public partial class ProductInfo {
[JsonProperty("product")] public Product Product { get; set; }
}
public partial class Product {
[JsonProperty("id")] public long Id { get; set; }
[JsonProperty("title")] public string Title { get; set; }
[JsonProperty("body_html")] public string BodyHtml { get; set; }
[JsonProperty("vendor")] public string Vendor { get; set; }
[JsonProperty("product_type")] public string ProductType { get; set; }
[JsonProperty("created_at")] public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("handle")] public string Handle { get; set; }
[JsonProperty("updated_at")] public DateTimeOffset UpdatedAt { get; set; }
[JsonProperty("published_at")] public DateTimeOffset PublishedAt { get; set; }
[JsonProperty("template_suffix")] public string TemplateSuffix { get; set; }
[JsonProperty("tags")] public string Tags { get; set; }
[JsonProperty("published_scope")] public string PublishedScope { get; set; }
[JsonProperty("variants")] public List<Variant> Variants { get; set; }
[JsonProperty("options")] public List<Option> Options { get; set; }
[JsonProperty("images")] public List<Image> Images { get; set; }
[JsonProperty("image")] public Image Image { get; set; }
}
public partial class Image {
[JsonProperty("id")] public long Id { get; set; }
[JsonProperty("product_id")] public long ProductId { get; set; }
[JsonProperty("position")] public long Position { get; set; }
[JsonProperty("created_at")] public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("updated_at")] public DateTimeOffset UpdatedAt { get; set; }
[JsonProperty("alt")] public string Alt { get; set; }
[JsonProperty("width")] public long Width { get; set; }
[JsonProperty("height")] public long Height { get; set; }
[JsonProperty("src")] public Uri Src { get; set; }
[JsonProperty("variant_ids")] public List<object> VariantIds { get; set; }
}
public partial class Option {
[JsonProperty("id")] public long Id { get; set; }
[JsonProperty("product_id")] public long ProductId { get; set; }
[JsonProperty("name")] public string Name { get; set; }
[JsonProperty("position")] public long Position { get; set; }
[JsonProperty("values")] public List<string> Values { get; set; }
}
public partial class Variant {
[JsonProperty("id")] public long Id { get; set; }
[JsonProperty("product_id")] public long ProductId { get; set; }
[JsonProperty("title")] public string Title { get; set; }
[JsonProperty("price")] public string Price { get; set; }
[JsonProperty("sku")] public string Sku { get; set; }
[JsonProperty("position")] public long Position { get; set; }
[JsonProperty("inventory_policy")] public string InventoryPolicy { get; set; }
[JsonProperty("compare_at_price")] public string CompareAtPrice { get; set; }
[JsonProperty("fulfillment_service")] public string FulfillmentService { get; set; }
[JsonProperty("inventory_management")] public string InventoryManagement { get; set; }
[JsonProperty("option1")] public string Option1 { get; set; }
[JsonProperty("option2")] public string Option2 { get; set; }
[JsonProperty("option3")] public string Option3 { get; set; }
[JsonProperty("created_at")] public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("updated_at")] public DateTimeOffset UpdatedAt { get; set; }
[JsonProperty("taxable")] public bool Taxable { get; set; }
[JsonProperty("barcode")] public string Barcode { get; set; }
[JsonProperty("grams")] public long Grams { get; set; }
[JsonProperty("image_id")] public object ImageId { get; set; }
[JsonProperty("weight")] public long Weight { get; set; }
[JsonProperty("weight_unit")] public string WeightUnit { get; set; }
[JsonProperty("inventory_item_id")] public long InventoryItemId { get; set; }
[JsonProperty("inventory_quantity")] public long InventoryQuantity { get; set; }
[JsonProperty("old_inventory_quantity")]
public long OldInventoryQuantity { get; set; }
[JsonProperty("tax_code")] public string TaxCode { get; set; }
[JsonProperty("requires_shipping")] public bool RequiresShipping { get; set; }
}
public partial class ProductInfo {
public static ProductInfo FromJson(string json) => JsonConvert.DeserializeObject<ProductInfo>(json);
}
}<file_sep>/ActivityGen/Tasks/YoutubeTask.cs
using System;
using System.Threading.Tasks;
using YoutubeExplode;
namespace ActivityGen.Tasks {
class YoutubeTask : BotTask {
public async Task<BotTaskResult> Do(Bot bot) {
try {
bot.m_Status = "Browsing YouTube...";
await bot.m_Page.GoToAsync("https://www.youtube.com/");
await bot.m_Page.WaitForXPathAsync("//*[@id=\"video-title\"]");
var videos = await bot.m_Page.XPathAsync("//*[@id=\"video-title\"]");
int clickNum = Utils.RandomNumber(1, videos.Length);
int i = 1;
foreach (var video in videos) {
await video.HoverAsync();
await Task.Delay(Utils.RandomNumber(250, 2500));
if (i.Equals(clickNum)) {
await video.ClickAsync();
break;
}
i++;
}
await bot.m_Page.WaitForNavigationAsync();
}
catch (Exception) {
return BotTaskResult.Failed;
}
TimeSpan duration = TimeSpan.FromMilliseconds(60000);
try {
var id = YoutubeClient.ParseVideoId(bot.m_Page.Url);
var client = new YoutubeClient();
var video = await client.GetVideoAsync(id);
duration = video.Duration;
}
catch (Exception) { }
bot.m_Status = "Watching YouTube...";
await Task.Delay(duration);
//if (Utils.RandomNumber(1, 1000) > 900) {
// try {
// await bot.m_Page.WaitForSelectorAsync("#subscribe-button");
// await bot.m_Page.ClickAsync("#subscribe-button");
// await bot.m_Page.WaitForXPathAsync("//button[starts-with(\"aria-label\", \"like this\")]");
// await bot.m_Page.XPathAsync("//button[starts-with(\"aria-label\", \"like this\")]").ContinueWith(t => t.Result.FirstOrDefault().ClickAsync());
// MessageBox.Show("liked and subscribed");
// }
// catch (Exception) { }
//}
//else if (Utils.RandomNumber(1, 100) > 30) {
// try {
// await bot.m_Page.WaitForXPathAsync("//button[starts-with(\"aria-label\", \"like this\")]");
// await bot.m_Page.XPathAsync("//button[starts-with(\"aria-label\", \"like this\")]").ContinueWith(t => t.Result.FirstOrDefault().ClickAsync());
// MessageBox.Show("liked");
// }
// catch (Exception) { }
//}
//else {
// try {
// await bot.m_Page.WaitForXPathAsync("//button[starts-with(\"aria-label\", \"dislike this\")]");
// await bot.m_Page.XPathAsync("//button[starts-with(\"aria-label\", \"dislike this\")]").ContinueWith(t => t.Result.FirstOrDefault().ClickAsync());
// MessageBox.Show("disliked");
// }
// catch (Exception) { }
//}
return BotTaskResult.Success;
}
}
}<file_sep>/ClownScript/CSChild.cs
using CSScript = System.Func<ClownScript.CSManager, int>;
namespace ClownScript {
/// <summary>
/// Handler for all successive calls after the initial Execute in the CSManager.
/// </summary>
public class CSChild {
private readonly CSManager csMngr;
private readonly int identifier;
public CSChild(CSManager mngr, int retVal) {
csMngr = mngr;
identifier = retVal;
}
public CSChild Then(params CSScript[] func) {
return new CSChild(csMngr, func[identifier](csMngr));
}
}
}
<file_sep>/Common/Shopify/ShopifyCart.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Common.Shopify {
namespace Shopify {
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class ShopifyCart {
[JsonProperty("token")] public string Token { get; set; }
[JsonProperty("note")] public object Note { get; set; }
[JsonProperty("attributes")] public /* Attributes */ object Attributes { get; set; }
[JsonProperty("original_total_price")] public long OriginalTotalPrice { get; set; }
[JsonProperty("total_price")] public long TotalPrice { get; set; }
[JsonProperty("total_discount")] public long TotalDiscount { get; set; }
[JsonProperty("total_weight")] public double TotalWeight { get; set; }
[JsonProperty("item_count")] public long ItemCount { get; set; }
[JsonProperty("items")] public List<Item> Items { get; set; }
[JsonProperty("requires_shipping")] public bool RequiresShipping { get; set; }
[JsonProperty("currency")] public string Currency { get; set; }
[JsonProperty("items_subtotal_price")] public long ItemsSubtotalPrice { get; set; }
[JsonProperty("cart_level_discount_applications")]
public List<object> CartLevelDiscountApplications { get; set; }
}
public partial class Attributes { }
public partial class Item {
[JsonProperty("id")] public long Id { get; set; }
[JsonProperty("properties")] public object Properties { get; set; }
[JsonProperty("quantity")] public long Quantity { get; set; }
[JsonProperty("variant_id")] public long VariantId { get; set; }
[JsonProperty("key")] public string Key { get; set; }
[JsonProperty("title")] public string Title { get; set; }
[JsonProperty("price")] public long Price { get; set; }
[JsonProperty("original_price")] public long OriginalPrice { get; set; }
[JsonProperty("discounted_price")] public long DiscountedPrice { get; set; }
[JsonProperty("line_price")] public long LinePrice { get; set; }
[JsonProperty("original_line_price")] public long OriginalLinePrice { get; set; }
[JsonProperty("total_discount")] public long TotalDiscount { get; set; }
[JsonProperty("discounts")] public List<object> Discounts { get; set; }
[JsonProperty("sku")] public string Sku { get; set; }
[JsonProperty("grams")] public long Grams { get; set; }
[JsonProperty("vendor")] public string Vendor { get; set; }
[JsonProperty("taxable")] public bool Taxable { get; set; }
[JsonProperty("product_id")] public long ProductId { get; set; }
[JsonProperty("product_has_only_default_variant")]
public bool ProductHasOnlyDefaultVariant { get; set; }
[JsonProperty("gift_card")] public bool GiftCard { get; set; }
[JsonProperty("final_price")] public long FinalPrice { get; set; }
[JsonProperty("final_line_price")] public long FinalLinePrice { get; set; }
[JsonProperty("url")] public string Url { get; set; }
[JsonProperty("featured_image")] public FeaturedImage FeaturedImage { get; set; }
[JsonProperty("image")] public Uri Image { get; set; }
[JsonProperty("handle")] public string Handle { get; set; }
[JsonProperty("requires_shipping")] public bool RequiresShipping { get; set; }
[JsonProperty("product_type")] public string ProductType { get; set; }
[JsonProperty("product_title")] public string ProductTitle { get; set; }
[JsonProperty("product_description")] public string ProductDescription { get; set; }
[JsonProperty("variant_title")] public string VariantTitle { get; set; }
[JsonProperty("variant_options")] public List<string> VariantOptions { get; set; }
[JsonProperty("options_with_values")] public List<OptionsWithValue> OptionsWithValues { get; set; }
[JsonProperty("line_level_discount_allocations")]
public List<object> LineLevelDiscountAllocations { get; set; }
}
public partial class FeaturedImage {
[JsonProperty("url")] public Uri Url { get; set; }
[JsonProperty("aspect_ratio")] public long AspectRatio { get; set; }
[JsonProperty("alt")] public string Alt { get; set; }
}
public partial class OptionsWithValue {
[JsonProperty("name")] public string Name { get; set; }
[JsonProperty("value")] public string Value { get; set; }
}
public partial class ShopifyCart {
public static ShopifyCart FromJson(string json) => JsonConvert.DeserializeObject<ShopifyCart>(json);
}
}
}
<file_sep>/Common/BotTask.cs
using System;
using System.Collections.Generic;
namespace Common {
public abstract class BotTask {
/// <summary>
/// The parent bot for this task
/// </summary>
private readonly Bot _bot;
/// <summary>
/// List of tasks sorted by ascending priority
/// </summary>
private readonly SortedSet<BotTask> _tasks =
new SortedSet<BotTask>(Comparer<BotTask>.Create((a, b) => a.Priority() - b.Priority()));
protected BotTask(Bot bot) {
_bot = bot;
}
/// <summary>
/// The priority which determines the order in which the tasks will be ran
/// </summary>
/// <returns>The priority of this task</returns>
public abstract int Priority();
/// <summary>
/// Checks whether the task should be ran under the current conditions
/// </summary>
/// <returns>A boolean representing whether or not the task should run</returns>
public abstract bool Validate();
/// <summary>
/// Runs the task
/// </summary>
public abstract void Execute();
/// <summary>
/// Used to give a description of the task
/// </summary>
/// <returns>Description of task</returns>
public abstract string Description();
/// <summary>
/// Add child tasks to parent task
/// </summary>
/// <param name="tasks">All the tasks to be added</param>
public void Append(params BotTask[] tasks) {
Array.ForEach(tasks, task => _tasks.Add(task));
}
public Bot GetBot() {
return _bot;
}
}
}<file_sep>/ClownScript/CSManager.cs
using CSScript = System.Func<ClownScript.CSManager, int>;
namespace ClownScript {
/// <summary>
/// Used to manage tasks/"scripts" and determines which script should be called by the return value of the script before it.
/// </summary>
public class CSManager {
private readonly RequestManager requestManager;
public CSManager() {
requestManager = new RequestManager();
}
public CSChild Execute(CSScript script) {
return new CSChild(this, script(this));
}
public RequestManager GetRequestManager() {
return requestManager;
}
}
}
<file_sep>/ClownAIOServer/MainWindow.xaml.cs
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Windows;
using ClownClubServer.NLC;
using NotLiteCode.Network;
using NotLiteCode.Serialization;
using NotLiteCode.Server;
namespace ClownClubServer {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
private static readonly NLCSocket Socket = new NLCSocket(new GroBufSerializationProvider(), true, ServerCertificate: GenerateSelfSignedCert("TheClownClub", "localhost"));
private static readonly Server<SharedClass> Server = new Server<SharedClass>(Socket);
public MainWindow() {
InitializeComponent();
Server.Start(1338);
}
public static X509Certificate2 GenerateSelfSignedCert(string certificateName, string hostName) {
var sanBuilder = new SubjectAlternativeNameBuilder();
sanBuilder.AddDnsName(hostName);
var distinguishedName = new X500DistinguishedName($"CN={certificateName}");
using (var rsa = RSA.Create(2048)) {
var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(
new X509KeyUsageExtension(
X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment |
X509KeyUsageFlags.DigitalSignature, false));
request.CertificateExtensions.Add(sanBuilder.Build());
var certificate = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)),
new DateTimeOffset(DateTime.UtcNow.AddDays(3650)));
return new X509Certificate2(certificate.Export(X509ContentType.Pfx));
}
}
}
}
<file_sep>/ClownAIOClient/BotContext.cs
using System;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Runtime.Loader;
using Common;
using Common.Types;
namespace ClownAIO {
internal static class BotContext {
public static readonly ObservableConcurrentDictionary<BotType, Type> BotTypes = new ObservableConcurrentDictionary<BotType, Type>();
public static readonly ObservableCollection<Bot> Bots = new ObservableCollection<Bot>();
public static readonly ObservableConcurrentDictionary<string, BillingProfile> Profiles = new ObservableConcurrentDictionary<string, BillingProfile>();
}
}
<file_sep>/Shopify/Tasks/PregenCartTask.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using Common;
using Common.Services;
using HtmlAgilityPack;
namespace Shopify.Tasks {
class PregenCartTask : BotTask {
public PregenCartTask(Bot bot) : base(bot) { }
public override string Description() {
return "Generating Cart";
}
public override void Execute() {
var bot = (ShopifyBot)GetBot();
using (var request = new HttpRequestMessage {
RequestUri = new Uri($"https://{bot.Domain}/cart/add.js?quantity=1&id={bot.ShopifyProducts.ProductsList.First().Variants.First().Id}"),
Method = HttpMethod.Get,
}) {
using var client = bot.GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
var atcResponse = HttpHelper.GetStringSync(request, client, out _, bot.GetCancellationToken());
}
using (var request = new HttpRequestMessage {
RequestUri = new Uri($"https://{bot.Domain}/checkout.json"),
Method = HttpMethod.Get,
}) {
using var client = bot.GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
var beginCheckoutResponse = HttpHelper.GetResponse(request, client, bot.GetCancellationToken()).Result;
var checkoutDoc = new HtmlDocument();
checkoutDoc.LoadHtml(beginCheckoutResponse.Content.ReadAsStringAsync().Result);
bot.CheckoutUrl = beginCheckoutResponse.RequestMessage.RequestUri.ToString();
bot.CheckoutAction = checkoutDoc.DocumentNode.SelectSingleNode("//form[@class=\"edit_checkout\"]").GetAttributeValue("action", "");
}
}
public override int Priority() {
return 10;
}
public override bool Validate() {
if (!((ShopifyBot)GetBot()).PregenCart) return false;
GetBot().Status = "Waiting for Monitor";
while (((ShopifyBot)GetBot()).ShopifyProducts is null) { }
return true;
}
}
}
<file_sep>/SupremeUs/Tasks/FindStyleAndSizeTask.cs
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using Common;
using Common.Services;
using Common.Supreme;
namespace Supreme.Tasks {
public class FindStyleAndSizeTask : BotTask {
public FindStyleAndSizeTask(Bot bot) : base(bot) { }
private bool UpdateProductJson() {
var bot = (SupremeBot) GetBot();
string productJson;
do {
using var request = new HttpRequestMessage {
RequestUri = new Uri($"https://www.supremenewyork.com/shop/{bot.MobileStockProduct.Id}.json"),
Method = HttpMethod.Get,
};
using var client = bot.GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
productJson = HttpHelper.GetStringSync(request, client, out _,
bot.GetCancellationToken());
bot.RequestsList.Add(new Tuple<HttpRequestMessage, string>(request, productJson));
} while (string.IsNullOrEmpty(productJson));
if (bot.GetCancellationToken().IsCancellationRequested) return false;
try {
bot.Product = SupremeProduct.FromJson(productJson);
}
catch (Exception) {
try {
bot.Product = SupremeProduct.FromJson(productJson);
}
catch (Exception) { }
}
return true;
}
public override bool Validate() {
var bot = (SupremeBot) GetBot();
return !bot.GetCancellationToken().IsCancellationRequested && bot.MobileStockProduct != null &&
UpdateProductJson();
}
public override void Execute() { // TODO: check the keyword logic
var bot = (SupremeBot) GetBot();
if (bot.SearchProduct.AnyStyle && bot.SearchProduct.AnySize) {
do {
Size anySize = null;
var anyStyle = bot.Product.Styles.FirstOrDefault(potentialStyle => {
anySize = potentialStyle.Sizes.FirstOrDefault(potentialSize =>
potentialSize.StockLevel > 0);
return anySize != null;
});
if (anyStyle is null || anySize is null) {
UpdateProductJson();
continue;
}
bot.ProductStyle = anyStyle;
bot.ProductSize = anySize;
} while (bot.ProductSize is null);
return;
}
Style style;
if (bot.SearchProduct.AnyStyle) {
do {
style = bot.Product.Styles.FirstOrDefault(potentialStyle =>
potentialStyle.Sizes.FirstOrDefault(potentialSize => potentialSize.StockLevel > 0) != null);
if (style is null) UpdateProductJson();
} while (style is null);
}
else {
style = bot.Product.Styles.FirstOrDefault(potentialStyle => bot.SearchProduct.StyleKeywords.Any(
keyword =>
!potentialStyle.Name.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase)
.Equals(-1)));
}
if (style is null) return;
bot.ProductStyle = style;
Size size;
if (bot.SearchProduct.AnySize) {
do {
size = bot.ProductStyle.Sizes.FirstOrDefault(potentialSize => potentialSize.StockLevel > 0);
if (size is null) UpdateProductJson();
} while (size is null);
}
else {
size = bot.ProductStyle.Sizes.FirstOrDefault(potentialSize =>
potentialSize.Name.Equals(bot.SearchProduct.SizeKeyword,
StringComparison.CurrentCultureIgnoreCase));
}
if (size is null) return;
bot.ProductSize = size;
}
public override int Priority() {
return 20;
}
public override string Description() {
return "Find Style/Size";
}
}
}
<file_sep>/Common/Types/Proxy.cs
namespace Common.Types {
public class Proxy {
public string IP { get; set; }
public string Port { get; set; }
public string GetAddress() {
return IP + ":" + Port;
}
public Proxy(string ip, string port) {
IP = ip;
Port = port;
}
}
}
<file_sep>/ClownAIOServer/DiscordServices/LoggingService.cs
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Threading.Tasks;
namespace ClownClubServer.DiscordServices {
public class LoggingService {
private readonly DiscordSocketClient _discord;
private readonly CommandService _commands;
// DiscordSocketClient and CommandService are injected automatically from the IServiceProvider
public LoggingService(DiscordSocketClient discord, CommandService commands) {
_discord = discord;
_commands = commands;
_discord.Log += OnLog;
_commands.Log += OnLog;
}
private async Task OnLog(LogMessage msg) {
var logText = $"{DateTime.UtcNow:hh:mm:ss} [{msg.Severity}] {msg.Source}: {msg.Exception?.ToString() ?? msg.Message}";
await Task.Delay(0);
}
}
}
<file_sep>/ActivityGen/Tasks/BotTask.cs
using System.Threading.Tasks;
namespace ActivityGen.Tasks {
public enum BotTaskResult {
Success,
Failed
}
public interface BotTask {
Task<BotTaskResult> Do(Bot bot);
}
}
<file_sep>/Common/Supreme/SearchProduct.cs
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace Common.Supreme {
public class SearchProduct : INotifyPropertyChanged {
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
[DisplayName("Category"), ReadOnly(true)]
public string Category { get; set; }
private List<string> _productKeywords;
[DisplayName("Product Keywords")]
public List<string> ProductKeywords {
get => _productKeywords;
set {
_productKeywords = value;
OnPropertyChanged();
}
}
[DisplayName("Any Style?")]
public bool AnyStyle { get; set; }
private List<string> _styleKeywords;
[DisplayName("Style Keywords")]
public List<string> StyleKeywords {
get => _styleKeywords;
set {
_styleKeywords = value;
OnPropertyChanged();
}
}
[DisplayName("Any Size?")]
public bool AnySize { get; set; }
private string _sizeKeyword;
[DisplayName("Size Keyword")]
public string SizeKeyword {
get => _sizeKeyword;
set {
_sizeKeyword = value;
OnPropertyChanged();
}
}
public SearchProduct() {
}
public SearchProduct(List<string> product) {
Category = "new";
ProductKeywords = product;
AnyStyle = true;
AnySize = true;
}
public SearchProduct(List<string> product, List<string> style) {
Category = "new";
ProductKeywords = product;
StyleKeywords = style;
AnySize = true;
}
public SearchProduct(List<string> product, string size) {
Category = "new";
ProductKeywords = product;
SizeKeyword = size;
AnySize = true;
}
public SearchProduct(List<string> product, List<string> style, string size) {
Category = "new";
ProductKeywords = product;
StyleKeywords = style;
SizeKeyword = size;
AnyStyle = false;
AnySize = false;
}
public SearchProduct(string category, List<string> product) {
Category = category;
ProductKeywords = product;
AnyStyle = true;
AnySize = true;
}
public SearchProduct(string category, List<string> product, List<string> style) {
Category = category;
ProductKeywords = product;
StyleKeywords = style;
AnySize = true;
}
public SearchProduct(string category, List<string> product, string size) {
Category = category;
ProductKeywords = product;
SizeKeyword = size;
AnySize = true;
}
public SearchProduct(string category, List<string> product, List<string> style, string size) {
Category = category;
ProductKeywords = product;
StyleKeywords = style;
SizeKeyword = size;
AnyStyle = false;
AnySize = false;
}
public override string ToString() {
if (ProductKeywords.Count().Equals(1)) return ProductKeywords.First();
var stringBuilder = new StringBuilder();
foreach (var keyword in ProductKeywords) {
stringBuilder.Append(ProductKeywords.Last().Equals(keyword) ? $"{keyword}" : $"{keyword}, ");
}
return stringBuilder.ToString();
}
}
}
<file_sep>/SupremeUs/Tasks/CheckoutQueueTask.cs
using System;
using System.Net;
using System.Net.Http;
using Common;
using Common.Services;
using Newtonsoft.Json.Linq;
namespace Supreme.Tasks {
class CheckoutQueueTask : BotTask {
public CheckoutQueueTask(Bot bot) : base(bot) { }
public override bool Validate() {
var bot = (SupremeBot)GetBot();
return !string.IsNullOrEmpty(bot.CheckoutSlug) && !bot.GetCancellationToken().IsCancellationRequested;
}
public override void Execute() {
var bot = (SupremeBot)GetBot();
do {
string slugResponse;
using (var request = new HttpRequestMessage() {
RequestUri = new Uri($"https://www.supremenewyork.com/checkout/{bot.CheckoutSlug}/status.json"),
Method = HttpMethod.Get,
Version = new Version(2, 0)
}) {
using var client = new HttpClient(bot.GetClientHandler(), false);
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("Refer", "https://www.supremenewyork.com/checkout");
request.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.8,en-GB;q=0.6");
request.Headers.Add("X-CSRF-Token", bot.CsrfToken);
slugResponse = HttpHelper.GetStringSync(request, client, out _,
bot.GetCancellationToken());
bot.RequestsList.Add(new Tuple<HttpRequestMessage, string>(request, slugResponse));
}
if (string.IsNullOrEmpty(slugResponse) || bot.GetCancellationToken().IsCancellationRequested) return;
bot.CheckoutJObject = JObject.Parse(slugResponse);
var checkoutStatus = bot.CheckoutJObject["status"].Value<string>();
bot.Status = $"Checkout: {char.ToUpper(checkoutStatus[0]) + checkoutStatus.Substring(1)}";
} while (bot.CheckoutJObject["status"].Value<string>()
.Equals("queued", StringComparison.CurrentCultureIgnoreCase));
}
public override int Priority() {
return 70;
}
public override string Description() {
return GetBot().Status;
}
}
}
<file_sep>/SupremeUs/Tasks/AddToCartTask.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using Common;
using Common.Services;
using Common.Supreme;
using Newtonsoft.Json.Linq;
namespace Supreme.Tasks {
class AddToCartTask : BotTask {
public AddToCartTask(Bot bot) : base(bot) { }
public override bool Validate() {
var bot = (SupremeBot)GetBot();
return bot.MobileStockProduct != null && bot.ProductStyle != null && bot.ProductSize != null; // we don't use bot.Product
}
public override void Execute() {
var bot = (SupremeBot)GetBot();
string atcResponse;
using (var addToCartRequest = new HttpRequestMessage() {
RequestUri = new Uri($"https://www.supremenewyork.com/shop/{bot.MobileStockProduct.Id}/add.json"),
Method = HttpMethod.Post
}) {
using var client = new HttpClient(bot.GetClientHandler(), false);
addToCartRequest.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) CriOS/62.0.3202.70 Mobile/14G60 Safari/602.1");
addToCartRequest.Headers.TryAddWithoutValidation("Accept", "*/*");
addToCartRequest.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
addToCartRequest.Headers.TryAddWithoutValidation("Content-Type",
"application/x-www-form-urlencoded");
addToCartRequest.Headers.TryAddWithoutValidation("Refer", "http://www.supremenewyork.com/mobile");
addToCartRequest.Content = bot.MobileStockProduct.PriceEuro is null
? new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("st", bot.ProductStyle.Id.ToString()),
new KeyValuePair<string, string>("s", bot.ProductSize.Id.ToString()),
new KeyValuePair<string, string>("qty", "1")
})
: new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("style", bot.ProductStyle.Id.ToString()),
new KeyValuePair<string, string>("size", bot.ProductSize.Id.ToString()),
new KeyValuePair<string, string>("qty", "1")
});
atcResponse = HttpHelper.GetStringSync(addToCartRequest, client, out _,
bot.GetCancellationToken());
bot.RequestsList.Add(new Tuple<HttpRequestMessage, string>(addToCartRequest, atcResponse));
}
CaptchaHarvester.AddWindow("supremenewyork.com", "6LeWwRkUAAAAAOBsau7KpuC9AV-6J8mhw4AjC3Xz");
if (string.IsNullOrEmpty(atcResponse) || bot.GetCancellationToken().IsCancellationRequested) return;
bot.AtcTime = DateTime.Now;
bot.DelayStopwatch = Stopwatch.StartNew();
}
public override int Priority() {
return 40;
}
public override string Description() {
return "Add to Cart";
}
}
}
<file_sep>/Common/Supreme/MobileStock.cs
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace Common.Supreme {
public partial class MobileStock {
[JsonProperty("unique_image_url_prefixes")]
public List<object> UniqueImageUrlPrefixes { get; set; }
[JsonProperty("products_and_categories")]
public Dictionary<string, List<MobileStockProduct>> ProductsAndCategories { get; set; }
[JsonProperty("last_mobile_api_update")]
public DateTimeOffset LastMobileApiUpdate { get; set; }
[JsonProperty("release_date")] public string ReleaseDate { get; set; }
[JsonProperty("release_week")] public string ReleaseWeek { get; set; }
public object Clone() {
return MemberwiseClone();
}
}
public class Style {
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("description")]
public object Description { get; set; }
[JsonProperty("image_url")]
public string ImageUrl { get; set; }
[JsonProperty("image_url_hi")]
public string ImageUrlHi { get; set; }
[JsonProperty("swatch_url")]
public string SwatchUrl { get; set; }
[JsonProperty("swatch_url_hi")]
public string SwatchUrlHi { get; set; }
[JsonProperty("mobile_zoomed_url")]
public string MobileZoomedUrl { get; set; }
[JsonProperty("mobile_zoomed_url_hi")]
public string MobileZoomedUrlHi { get; set; }
[JsonProperty("bigger_zoomed_url")]
public string BiggerZoomedUrl { get; set; }
[JsonProperty("sizes")]
public List<Size> Sizes { get; set; }
[JsonProperty("additional")]
public List<Additional> Additional { get; set; }
public override string ToString() {
return Name;
}
}
public partial class Additional {
[JsonProperty("swatch_url")]
public string SwatchUrl { get; set; }
[JsonProperty("swatch_url_hi")]
public string SwatchUrlHi { get; set; }
[JsonProperty("image_url")]
public string ImageUrl { get; set; }
[JsonProperty("image_url_hi")]
public string ImageUrlHi { get; set; }
[JsonProperty("zoomed_url")]
public string ZoomedUrl { get; set; }
[JsonProperty("zoomed_url_hi")]
public string ZoomedUrlHi { get; set; }
[JsonProperty("bigger_zoomed_url")]
public string BiggerZoomedUrl { get; set; }
}
public partial class Size {
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("stock_level")]
public long StockLevel { get; set; }
public override string ToString() {
return Name;
}
}
public class MobileStockProduct {
[JsonProperty("name")] public string Name { get; set; }
[JsonProperty("id")] public long Id { get; set; }
[JsonProperty("image_url")] public string ImageUrl { get; set; }
[JsonProperty("image_url_hi")] public string ImageUrlHi { get; set; }
[JsonProperty("price")] public long Price { get; set; }
[JsonProperty("sale_price")] public long SalePrice { get; set; }
[JsonProperty("new_item")] public bool NewItem { get; set; }
[JsonProperty("position")] public long Position { get; set; }
[JsonProperty("category_name")] public string CategoryName { get; set; }
[JsonProperty("price_euro")] public long? PriceEuro { get; set; }
[JsonProperty("sale_price_euro")] public long? SalePriceEuro { get; set; }
public override string ToString() {
return Name;
}
}
public partial class MobileStock {
public static MobileStock FromJson(string json) => JsonConvert.DeserializeObject<MobileStock>(json,
new JsonSerializerSettings {MissingMemberHandling = MissingMemberHandling.Ignore});
}
}
<file_sep>/Common/Types/BillingProfile.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace Common.Types {
public class BillingProfile {
[Display(Name ="First Name", Order = 0)]
public string FirstName { get; set; }
[Display(Name = "Last Name", Order = 1)]
public string LastName { get; set; }
[Display(Name = "Email", Order = 2)]
public string Email { get; set; }
[Display(Name = "Phone", Order = 3)]
public string Phone { get; set; }
[Display(Name = "Address", Order = 4)]
public string Address { get; set; }
[Display(Name = "Address 2", Order = 5)]
public string Address2 { get; set; }
[Display(Name = "Address 3", Order = 6)]
public string Address3 { get; set; }
[Display(Name = "Zip Code", Order = 7)]
public string ZipCode { get; set; }
[Display(Name = "City", Order = 8)]
public string City { get; set; }
[Display(Name = "State", Order = 9)]
public string State { get; set; }
[Display(Name = "Country", Order = 10)]
public string Country { get; set; }
[Display(Name = "Card Type", Order = 12)]
public string CcType { get; set; }
[Display(Name = "Card Number", Order = 12)]
public string CcNumber { get; set; }
[Display(Name = "Card Expiration", Order = 13)]
public DateTime CcExpiration { get; set; }
[Display(Name = "CVV", Order = 14)]
public string Cvv { get; set; }
public BillingProfile() { }
public BillingProfile(string first, string last, string email, string phone, string address, string address2, string address3,
string zip, string city, string state, string country, string ccType, string ccNumber, DateTime ccExpiration, string cvv) {
FirstName = first;
LastName = last;
Email = email;
Phone = phone;
Address = address;
Address2 = address2;
Address3 = address3;
ZipCode = zip;
City = city;
State = state;
Country = country;
CcType = ccType;
CcNumber = ccNumber;
CcExpiration = ccExpiration;
Cvv = cvv;
}
[Browsable(false), JsonIgnore]
public string SafeCardNumber =>
new Regex(@"\d", RegexOptions.None).Replace(CcNumber.Substring(0, CcNumber.Length - 4), "*") +
CcNumber.Substring(CcNumber.Length - 4, CcNumber.Length - 15);
public override string ToString() {
return SafeCardNumber;
}
}
}
<file_sep>/SupremeUs/Tasks/FindProductTask.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using Common;
using Common.Services;
using Common.Supreme;
namespace Supreme.Tasks {
class FindProductTask : BotTask {
public FindProductTask(Bot bot) : base(bot) { }
public override bool Validate() {
var bot = (SupremeBot) GetBot();
bot.Status = "Waiting for Monitor";
while (SupremeMonitor.MobileStock is null && !bot.GetCancellationToken().IsCancellationRequested) { }
return !bot.GetCancellationToken().IsCancellationRequested &&
SupremeMonitor.MobileStock.ProductsAndCategories.ContainsKey(bot.SearchProduct.Category);
}
public override void Execute() { // TODO: check keyword logic
var bot = (SupremeBot) GetBot();
do {
bot.MobileStock = (MobileStock) SupremeMonitor.MobileStock.Clone();
Parallel.ForEach(bot.MobileStock.ProductsAndCategories[bot.SearchProduct.Category],
(product, state) => {
var isValid = !bot.SearchProduct.ProductKeywords.Any(keyword =>
keyword.StartsWith("-")
? !product.Name.IndexOf(keyword[1..],
StringComparison.CurrentCultureIgnoreCase).Equals(-1)
: product.Name.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase).Equals(-1));
if (!isValid) return;
bot.MobileStockProduct = product;
state.Stop();
});
} while (bot.MobileStockProduct is null);
}
public override int Priority() {
return 10;
}
public override string Description() {
return "Find Product";
}
}
}
<file_sep>/TestApp/Program.cs
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Common.Services;
using Common.Shopify;
using Common.Shopify.Shopify;
using Discord;
using Discord.WebSocket;
using HtmlAgilityPack;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace TestApp {
static class Program {
private static DiscordSocketClient _client;
private static int RandomNumber(int min, int max) {
var random = new Random();
return random.Next(min, max);
}
private static readonly HttpMessageHandler HttpMessageHandler = new HttpClientHandler {
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.GZip,
UseProxy = false
};
private static HttpClient GetNewHttpClient() {
return new HttpClient(HttpMessageHandler, false) { Timeout = TimeSpan.FromSeconds(2) };
}
private static bool _isReady = false;
private const string InviteRegex = @"discord\.gift\/(.{16})";
private const string AuthToken = "<KEY>";
private static void RedeemGift(ulong channelId, string inviteCode) {
using var request = new HttpRequestMessage {
RequestUri = new Uri($"https://discordapp.com/api/v6/entitlements/gift-codes/{inviteCode}/redeem"),
Method = HttpMethod.Post,
};
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) discord/0.0.305 Chrome/69.0.3497.128 Electron/4.0.8 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("Authorization", $"{AuthToken}");
request.Content = new StringContent($"{{\"channel_id\":\"{channelId}\"}}", Encoding.UTF8, "application/json");
var inviteRedeemResponse = HttpHelper.GetStringSync(request, client, out _, CancellationToken.None);
Console.WriteLine(inviteRedeemResponse);
}
private static void Main(string[] args) {
_client = new DiscordSocketClient(new DiscordSocketConfig {
MessageCacheSize = 100,
LogLevel = LogSeverity.Info
});
_client.Ready += () => {
if (_isReady) return Task.FromResult(0);
Console.WriteLine($"Logged into {_client.CurrentUser.Username}#{_client.CurrentUser.Discriminator}");
_isReady = true;
return Task.FromResult(0);
};
_client.MessageReceived += msg => {
if (msg.Author.Id.Equals(_client.CurrentUser.Id)) return Task.FromResult(0);
try {
var match = Regex.Match(msg.Content, InviteRegex);
if (!match.Success) return Task.FromResult(0);
Console.WriteLine(
$"Found Invite // ID: {match.Groups[1].Value} // Channel ID: {msg.Channel.Id} // From: {msg.Author.Username}#{msg.Author.Discriminator}");
RedeemGift(msg.Channel.Id, match.Groups[1].Value);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
return Task.FromResult(0);
};
Task.Run(async () => {
await _client.LoginAsync(0, AuthToken);
await _client.StartAsync();
});
Console.ReadLine();
}
private static void ShopifyMain(string[] args) {
ShopifyProducts products;
using (var request = new HttpRequestMessage {
RequestUri = new Uri($"https://bdgastore.com/products.json?limit={RandomNumber(1000000, int.MaxValue)}"),
Method = HttpMethod.Get,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
var productsJson = HttpHelper.GetStringSync(request, client, out _, CancellationToken.None);
products = ShopifyProducts.FromJson(productsJson);
}
var shopifyProduct = products.ProductsList.First();
using (var request = new HttpRequestMessage {
RequestUri = new Uri($"https://bdgastore.com/cart/add.js?quantity=1&id={shopifyProduct.Variants.First().Id}"),
Method = HttpMethod.Get,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
var atcResponse = HttpHelper.GetStringSync(request, client, out _, CancellationToken.None);
}
string checkoutUrl, checkoutAction, checkoutGateway;
using (var request = new HttpRequestMessage {
RequestUri = new Uri($"https://bdgastore.com/checkout.json"),
Method = HttpMethod.Get,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
var beginCheckoutResponse = HttpHelper.GetResponse(request, client, CancellationToken.None).Result;
var checkoutDoc = new HtmlDocument();
checkoutDoc.LoadHtml(beginCheckoutResponse.Content.ReadAsStringAsync().Result);
checkoutUrl = beginCheckoutResponse.RequestMessage.RequestUri.ToString();
checkoutAction = checkoutDoc.DocumentNode.SelectSingleNode("//form[@class=\"edit_checkout\"]").GetAttributeValue("action", "");
}
var keywordsList = new List<string> {
"air",
"force",
"mtaa"
};
var colorKeywords = new List<string> {
"blue"
};
var sizeKeyword = "10.5";
ShopifyProduct foundProduct = null;
Parallel.ForEach(products.ProductsList,
(product, state) => {
var isValid = !keywordsList.Any(keyword =>
keyword.StartsWith("-")
? !product.Title.IndexOf(keyword.Substring(1, keyword.Length - 1),
StringComparison.CurrentCultureIgnoreCase).Equals(-1)
: product.Title.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase).Equals(-1));
if (!isValid) return;
foundProduct = product;
state.Stop();
});
Console.WriteLine(foundProduct != null ? foundProduct.Title : "not found");
var foundVariant = foundProduct.Variants.FirstOrDefault(potentialVariant => {
return colorKeywords.Any(keyword =>
keyword.StartsWith("-")
? !string.IsNullOrEmpty(potentialVariant.Option1) &&
!potentialVariant.Option1.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase)
.Equals(-1)
|| !string.IsNullOrEmpty(potentialVariant.Option2) &&
!potentialVariant.Option2.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase)
.Equals(-1)
|| !string.IsNullOrEmpty(potentialVariant.Option3) &&
!potentialVariant.Option3.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase)
.Equals(-1)
: !string.IsNullOrEmpty(potentialVariant.Option1) &&
potentialVariant.Option1.IndexOf(keyword.Substring(1, keyword.Length - 1),
StringComparison.CurrentCultureIgnoreCase)
.Equals(-1)
|| !string.IsNullOrEmpty(potentialVariant.Option2) &&
potentialVariant.Option2.IndexOf(keyword.Substring(1, keyword.Length - 1),
StringComparison.CurrentCultureIgnoreCase)
.Equals(-1)
|| !string.IsNullOrEmpty(potentialVariant.Option3) &&
potentialVariant.Option3.IndexOf(keyword.Substring(1, keyword.Length - 1),
StringComparison.CurrentCultureIgnoreCase)
.Equals(-1)
)
&& !string.IsNullOrEmpty(potentialVariant.Option1) &&
potentialVariant.Option1.Equals(sizeKeyword)
|| !string.IsNullOrEmpty(potentialVariant.Option2) &&
potentialVariant.Option2.Equals(sizeKeyword)
|| !string.IsNullOrEmpty(potentialVariant.Option3) &&
potentialVariant.Option3.Equals(sizeKeyword);
});
Console.WriteLine($"{foundVariant.Title}");
using (var request = new HttpRequestMessage {
RequestUri = new Uri($"https://bdgastore.com/cart/update.json"),
Method = HttpMethod.Post,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
var values = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>($"updates[{foundVariant.Id}]", "1"),
new KeyValuePair<string, string>($"updates[{shopifyProduct.Variants.First().Id}]", "0")
};
var formContent = new FormUrlEncodedContent(values);
request.Content = formContent;
var atcResponse = HttpHelper.GetStringSync(request, client, out _, CancellationToken.None);
}
//using (var request = new HttpRequestMessage {
// RequestUri = new Uri($"https://bdgastore.com/cart/add.js?quantity=1&id={foundVariant.Id}"),
// Method = HttpMethod.Get,
//}) {
// using var client = GetNewHttpClient();
//
// request.Headers.TryAddWithoutValidation("User-Agent",
// "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
// request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
// request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
//
// var atcResponse = HttpHelper.GetStringSync(request, client, out _, CancellationToken.None);
// Console.WriteLine(atcResponse);
//}
var checkoutFormContentList = new Queue<KeyValuePair<string, string>>();
FormUrlEncodedContent checkoutFormContent;
var doc = new HtmlDocument();
using (var request = new HttpRequestMessage {
RequestUri = new Uri($"https://bdgastore.com/checkout.json"),
Method = HttpMethod.Get,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
var beginCheckoutResponse = HttpHelper.GetResponse(request, client, CancellationToken.None).Result;
checkoutUrl = beginCheckoutResponse.RequestMessage.RequestUri.ToString(); // TODO: check for queue or oos (stock_problems)
doc.LoadHtml(beginCheckoutResponse.Content.ReadAsStringAsync().Result);
}
var form = doc.DocumentNode.SelectSingleNode("//form[@class=\"edit_checkout\"]");
foreach (var node in form.Descendants("input")) {
if (node.GetAttributeValue("data-honeypot", "").Equals("true")) continue;
var nodeName = node.GetAttributeValue("name", "");
if (node.GetAttributeValue("type", "").Equals("hidden")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, node.GetAttributeValue("value", "")));
}
else {
if (nodeName.Contains("email")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, "<EMAIL>"));
}
else if (nodeName.Contains("first_name")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, "Trey"));
}
else if (nodeName.Contains("last_name")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, "Phillips"));
}
else if (nodeName.Contains("company")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, ""));
}
else if (nodeName.Contains("address1")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, "3610 Swicegood Rd"));
}
else if (nodeName.Contains("address2")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, ""));
}
else if (nodeName.Contains("city")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, "Linwood"));
}
else if (nodeName.Contains("province")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, "North Carolina"));
}
else if (nodeName.Contains("zip")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, "27299"));
}
else if (nodeName.Contains("phone")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, "(336) 999-4585"));
}
else {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, node.GetAttributeValue("value", "")));
}
}
}
foreach (var node in form.Descendants("select")) {
var nodeName = node.GetAttributeValue("name", "");
if (node.GetAttributeValue("type", "").Equals("hidden")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, node.GetAttributeValue("value", "")));
}
else {
if (nodeName.Contains("country")) {
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, "United States"));
}
}
}
checkoutFormContentList.Enqueue(
new KeyValuePair<string, string>("g-recaptcha-response", "<KEY>"));
checkoutFormContent = new FormUrlEncodedContent(checkoutFormContentList);
var shippingDoc = new HtmlDocument();
using (var request = new HttpRequestMessage {
RequestUri = new Uri(checkoutUrl),
Method = HttpMethod.Post,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
request.Content = checkoutFormContent;
var beginCheckoutResponse = HttpHelper.GetResponse(request, client, CancellationToken.None).Result;
shippingDoc.LoadHtml(beginCheckoutResponse.Content.ReadAsStringAsync().Result);
}
string shippingCode = "", shippingControlName = "";
int minShippingCents = int.MaxValue;
var shippingContentList = new Queue<KeyValuePair<string, string>>();
var shippingForm = shippingDoc.DocumentNode.SelectSingleNode("//form[@class=\"edit_checkout\"]");
foreach (var node in shippingForm.Descendants("input")) {
var nodeName = node.GetAttributeValue("name", "");
if (node.GetAttributeValue("type", "").Equals("hidden")) {
shippingContentList.Enqueue(
new KeyValuePair<string, string>(nodeName, node.GetAttributeValue("value", "")));
}
else {
if (nodeName.Contains("shipping_rate")) {
int shippingCents = int.Parse(node.GetAttributeValue("data-checkout-total-shipping-cents", "2147483647"));
if (shippingCents >= minShippingCents) continue;
minShippingCents = shippingCents;
shippingCode = node.GetAttributeValue("value", "shopify-UPS%20Ground%20(oz-2lbs)-10.00");
shippingControlName = nodeName;
}
}
}
shippingContentList.Enqueue(new KeyValuePair<string, string>(shippingControlName, shippingCode));
var shippingContent = new FormUrlEncodedContent(shippingContentList);
Console.WriteLine(checkoutUrl);
using (var request = new HttpRequestMessage {
RequestUri = new Uri(checkoutUrl),
Method = HttpMethod.Post,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
request.Content = shippingContent;
var beginCheckoutResponse = HttpHelper.GetResponse(request, client, CancellationToken.None).Result;
}
string continueUrl;
using (var request = new HttpRequestMessage {
RequestUri = new Uri(checkoutUrl),
Method = HttpMethod.Post,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
request.Content = shippingContent;
var beginCheckoutResponse = HttpHelper.GetResponse(request, client, CancellationToken.None).Result;
continueUrl = beginCheckoutResponse.RequestMessage.RequestUri.ToString();
}
var storeId = checkoutAction.Split("/")[1];
var checkoutId = checkoutAction.Split("/")[3];
Console.WriteLine($"{storeId} {checkoutId}");
string ccVerifyCode;
using (var request = new HttpRequestMessage {
RequestUri = new Uri($"https://elb.deposit.shopifycs.com/sessions"),
Method = HttpMethod.Post,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "application/json");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("Origin", "https://checkout.us.shopifycs.com");
request.Headers.TryAddWithoutValidation("Referer", $"https://checkout.us.shopifycs.com/number?identifier={checkoutId}&location=https%3A%2F%2Fbdgastore.com%2F{storeId}%2Fcheckouts%2F0c232d8876fdfb16ef5b451f3a8db21f%3Fprevious_step%3Dshipping_method%26step%3Dpayment_method?previous_step=shipping_method&step=payment_method&dir=ltr");
var payload = "{\"credit_card\":{\"number\":\"" + "4242-4242-4242-4242".Replace("-", " ") + "\",\"name\":\"" + "Trey" + " " + "Phillips" + "\",\"month\":" + "9" + ",\"year\":" + "2020" + "," + "\"verification_value\":\"" + "123" + "\"}}";
request.Content = new StringContent(payload);
var beginCheckoutResponse = HttpHelper.GetResponse(request, client, CancellationToken.None).Result;
Console.WriteLine(beginCheckoutResponse.Content.ReadAsStringAsync().Result);
ccVerifyCode = JObject.Parse(beginCheckoutResponse.Content.ReadAsStringAsync().Result).Value<string>("id");
}
var finalDoc = new HtmlDocument();
using (var request = new HttpRequestMessage {
RequestUri = new Uri(checkoutUrl + "?step=payment_method"),
Method = HttpMethod.Get,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
var beginCheckoutResponse = HttpHelper.GetString(request, client, CancellationToken.None).Result;
finalDoc.LoadHtml(beginCheckoutResponse);
}
var paymentGatewayList = new Queue<KeyValuePair<string, string>>();
bool firstPaymentGateway = true, firstBillingAddressDifferent = true;
var finalForm = finalDoc.DocumentNode.SelectSingleNode("//form[@class=\"edit_checkout\" and @data-payment-form]");
foreach (var node in finalForm.Descendants("input")) {
if (node.GetAttributeValue("data-honeypot", "").Equals("true")) continue;
var nodeName = node.GetAttributeValue("name", "");
if (node.GetAttributeValue("type", "").Equals("hidden")) {
if (nodeName.Contains("payment_gateway")) continue;
else if (nodeName.Equals("s")) {
paymentGatewayList.Enqueue(
new KeyValuePair<string, string>(nodeName, ccVerifyCode));
}
else if (nodeName.Contains("redirect")) { }
else {
paymentGatewayList.Enqueue(
new KeyValuePair<string, string>(nodeName, node.GetAttributeValue("value", "")));
}
Console.WriteLine($"Hidden Input: {nodeName}");
}
else {
if (nodeName.Contains("different_billing") && firstBillingAddressDifferent) {
paymentGatewayList.Enqueue(
new KeyValuePair<string, string>(nodeName, node.GetAttributeValue("value", "")));
firstBillingAddressDifferent = false;
}
else if (nodeName.Contains("payment_gateway") && firstPaymentGateway) {
paymentGatewayList.Enqueue(
new KeyValuePair<string, string>(nodeName, node.GetAttributeValue("value", "")));
firstPaymentGateway = false;
}
Console.WriteLine($"Visible Input: {nodeName}");
}
}
using (var request = new HttpRequestMessage {
RequestUri = new Uri(checkoutUrl),
Method = HttpMethod.Post,
}) {
using var client = GetNewHttpClient();
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
request.Content = new FormUrlEncodedContent(paymentGatewayList);
var beginCheckoutResponse = HttpHelper.GetResponse(request, client, CancellationToken.None).Result;
continueUrl = beginCheckoutResponse.RequestMessage.RequestUri.ToString();
Console.WriteLine(continueUrl);
Console.WriteLine(beginCheckoutResponse.Content.ReadAsStringAsync().Result);
}
}
}
}
<file_sep>/Common/Services/SupremeMonitor.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Common.Supreme;
using Common.Types;
namespace Common.Services {
public static class SupremeMonitor {
private static readonly Dictionary<string, string> cyrillicDictionary = new Dictionary<string, string> {
{ "а", "a" },
{ "б", "b" },
{ "в", "v" },
{ "г", "g" },
{ "д", "d" },
{ "е", "e" },
{ "ё", "yo" },
{ "ж", "zh" },
{ "з", "z" },
{ "и", "i" },
{ "й", "j" },
{ "к", "k" },
{ "л", "l" },
{ "м", "m" },
{ "н", "n" },
{ "о", "o" },
{ "п", "p" },
{ "р", "r" },
{ "с", "s" },
{ "т", "t" },
{ "у", "u" },
{ "ф", "f" },
{ "х", "h" },
{ "ц", "c" },
{ "ч", "ch" },
{ "ш", "sh" },
{ "щ", "sch" },
{ "ъ", "j" },
{ "ы", "i" },
{ "ь", "j" },
{ "э", "e" },
{ "ю", "yu" },
{ "я", "ya" },
{ "А", "A" },
{ "Б", "B" },
{ "В", "V" },
{ "Г", "G" },
{ "Д", "D" },
{ "Е", "E" },
{ "Ё", "Yo" },
{ "Ж", "Zh" },
{ "З", "Z" },
{ "И", "I" },
{ "Й", "J" },
{ "К", "K" },
{ "Л", "L" },
{ "М", "M" },
{ "Н", "N" },
{ "О", "O" },
{ "П", "P" },
{ "Р", "R" },
{ "С", "S" },
{ "Т", "T" },
{ "У", "U" },
{ "Ф", "F" },
{ "Х", "H" },
{ "Ц", "C" },
{ "Ч", "Ch" },
{ "Ш", "Sh" },
{ "Щ", "Sch" },
{ "Ъ", "J" },
{ "Ы", "I" },
{ "Ь", "J" },
{ "Э", "E" },
{ "Ю", "Yu" },
{ "Я", "Ya" }
};
public static TimeSpan RefreshInterval = TimeSpan.FromSeconds(2);
public static MobileStock MobileStock;
private static HttpMessageHandler HttpMessageHandler;
static SupremeMonitor() {
try {
HttpMessageHandler = new Http2WinHttpHandler {
AutomaticRedirection = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.GZip,
WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy
};
}
catch (PlatformNotSupportedException) {
HttpMessageHandler = new HttpClientHandler {
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.GZip,
UseProxy = false
};
}
}
private static Task _task;
private static CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
public static void Start() {
if (_task != null) Stop();
_task = Task.Run(async () => {
do {
string mobileStockJson;
do {
await Task.Delay(RefreshInterval, _cancellationTokenSource.Token);
using (var request = new HttpRequestMessage {
RequestUri = new Uri("https://www.supremenewyork.com/shop.json"),
Method = HttpMethod.Get,
}) {
using (var client = new HttpClient(HttpMessageHandler, false)
{Timeout = TimeSpan.FromSeconds(2)}) {
request.Headers.TryAddWithoutValidation("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
mobileStockJson = HttpHelper.GetStringSync(request, client, out _, _cancellationTokenSource.Token);
}
}
} while (string.IsNullOrEmpty(mobileStockJson) &&
!_cancellationTokenSource.IsCancellationRequested);
if (_cancellationTokenSource.IsCancellationRequested) return;
mobileStockJson = cyrillicDictionary.Aggregate(mobileStockJson,
(current, pair) => current.Replace(pair.Key, pair.Value));
try {
MobileStock = MobileStock.FromJson(mobileStockJson);
}
catch (Exception ex) {
Debug.WriteLine(ex.Message);
}
} while (!_cancellationTokenSource.IsCancellationRequested);
});
}
public static void Stop() {
_cancellationTokenSource.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
}
public static void SetProxy(string proxy = null) {
WebProxy newProxy;
try {
newProxy = new WebProxy("http://" + proxy);
}
catch (Exception) { return; }
if (HttpMessageHandler.GetType() == typeof(Http2WinHttpHandler)) {
HttpMessageHandler = new Http2WinHttpHandler {
AutomaticRedirection = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.GZip,
WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy,
Proxy = newProxy
};
}
else {
HttpMessageHandler = new HttpClientHandler {
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.GZip,
Proxy = newProxy,
UseProxy = true
};
}
}
}
}
<file_sep>/ActivityGen/Tasks/SignInTask.cs
using PuppeteerSharp;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace ActivityGen.Tasks {
class SignInTask : BotTask {
public async Task<BotTaskResult> Do(Bot bot) {
bot.m_Status = "Signing into Google...";
try {
await bot.m_Page.GoToAsync("https://www.google.com/");
await bot.m_Page.WaitForXPathAsync("//*[@id=\"gb_70\"]");
await bot.m_Page.XPathAsync("//*[@id=\"gb_70\"]").ContinueWith(t => t.Result.FirstOrDefault().ClickAsync());
await bot.m_Page.WaitForSelectorAsync("input[type=\"email\"]");
await bot.m_Page.TypeAsync("input[type=\"email\"]", bot.m_Email);
await bot.m_Page.Keyboard.PressAsync("Enter");
await bot.m_Page.WaitForSelectorAsync("input[type=\"password\"]", new WaitForSelectorOptions { Visible = true });
await bot.m_Page.TypeAsync("input[type=\"password\"]", bot.m_Password);
await bot.m_Page.Keyboard.PressAsync("Enter");
await bot.m_Page.WaitForNavigationAsync();
try {
do {
await bot.m_Page.WaitForXPathAsync("//*[@id=\"captchaimg\"]", new WaitForSelectorOptions { Timeout = 3000 });
//var captchaimgxpath = await bot.m_Page.XPathAsync("//*[@id=\"captchaimg\"]");
//var captchaimg = captchaimgxpath.FirstOrDefault();
//var bbox = await captchaimg.BoundingBoxAsync();
//bot.m_CatpchaImage = await bot.m_Page.ScreenshotDataAsync(new ScreenshotOptions { Clip = new PuppeteerSharp.Media.Clip { Height = bbox.Height, Width = bbox.Width, X = bbox.X, Y = bbox.Y } });
bot.m_Status = "Waiting for Captcha...";
while (string.IsNullOrWhiteSpace(bot.m_CaptchaText)) { await Task.Delay(1000); }
var xpaths = await bot.m_Page.XPathAsync("//*[@id=\"ca\"]");
await xpaths.FirstOrDefault().TypeAsync(bot.m_CaptchaText);
bot.m_CaptchaText = null;
await bot.m_Page.TypeAsync("input[type=\"password\"]", bot.m_Password);
await bot.m_Page.Keyboard.PressAsync("Enter");
await bot.m_Page.WaitForNavigationAsync();
try {
await bot.m_Page.WaitForXPathAsync("//*[@id=\"gb_71\"]", new WaitForSelectorOptions { Timeout = 5000 });
return BotTaskResult.Success;
}
catch (Exception) { }
} while (true);
}
catch (Exception) { }
await bot.m_Page.WaitForXPathAsync("//*[@id=\"gb_71\"]", new WaitForSelectorOptions { Timeout = 5000 });
return BotTaskResult.Success;
}
catch (Exception) {
return BotTaskResult.Failed;
}
}
}
}
<file_sep>/ClownAIOServer/DatabaseManager.cs
using ClownClubServer.Classes;
using LiteDB;
namespace ClownClubServer {
class DatabaseManager {
public static LiteDatabase Database { get; private set; }
public static LiteCollection<User> Users { get; private set; }
public static LiteCollection<Invite> Invites { get; private set; }
public static LiteCollection<License> Licenses { get; private set; }
public static void Init() {
Database = new LiteDatabase("clown.db");
Users = Database.GetCollection<User>("users");
Invites = Database.GetCollection<Invite>("invites");
Licenses = Database.GetCollection<License>("licenses");
}
}
}
<file_sep>/ClownScript/RequestManager.cs
namespace ClownScript {
/// <summary>
/// Used to manage requests for every bot, an instance is stored in every CSManager instance.
/// </summary>
public class RequestManager {
}
}
<file_sep>/ClownAIOClient/MainWindow.xaml.cs
using System;
using System.Threading.Tasks;
using System.Windows;
using CefSharp;
using CefSharp.Wpf;
using Common.Services;
using FirstFloor.ModernUI.Windows.Controls;
namespace ClownAIO {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : ModernWindow {
public MainWindow() {
if (Globals.Client is null) Environment.Exit(0);
Cef.Initialize(new CefSettings());
Task.Run(async () => {
while (true) {
await CaptchaHarvester.RequestWindowChannel.Reader.WaitToReadAsync();
var (domain, sitekey) = await CaptchaHarvester.RequestWindowChannel.Reader.ReadAsync();
if (string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(sitekey)) continue;
await CaptchaHarvester.ReceiveWindowChannel.Writer.WaitToWriteAsync();
Application.Current.Dispatcher.Invoke(() => {
var window = new CaptchaHarvesterWindow(domain, sitekey);
window.Show();
CaptchaHarvester.ReceiveWindowChannel.Writer.WriteAsync(window);
});
}
});
CaptchaHarvester.WindowType = typeof(CaptchaHarvesterWindow);
InitializeComponent();
}
}
}
<file_sep>/ClownAIOClient/LoadingWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Loader;
using System.Windows;
using Common;
using Common.Services;
using Newtonsoft.Json;
using PuppeteerSharp;
namespace ClownAIO {
/// <summary>
/// Interaction logic for LoadingDialog.xaml
/// </summary>
public partial class LoadingWindow : Window {
public LoadingWindow() {
InitializeComponent();
}
private async void Window_Loaded(object sender, RoutedEventArgs e) {
var assemblyQueue = JsonConvert.DeserializeObject<Queue<byte[]>>(await Globals.Client.RemoteCall<string>("GetCommon"));
var commonAssembly = AssemblyLoadContext.Default.LoadFromStream(
new MemoryStream(assemblyQueue.Dequeue()));
var botType = commonAssembly.GetExportedTypes().Single(t => t.Name.Equals("Bot"));
foreach (var assembly in assemblyQueue) {
var loadedAssembly = AssemblyLoadContext.Default.LoadFromStream(new MemoryStream(assembly));
foreach (var type in loadedAssembly.GetExportedTypes()
.Where(t => t.IsSubclassOf(botType))) {
var bot = (Bot)Activator.CreateInstance(type);
BotContext.BotTypes.Add(bot.BotType, type);
}
}
new MainWindow().Show();
Close();
}
}
}
<file_sep>/Common/Services/HttpHelper.cs
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Common.Types;
namespace Common.Services {
public class HttpHelper {
private const string UserAgent = "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36";
public static async Task<string> GetString(Uri url, HttpMethod method, CancellationToken cancelToken, int retries = 3) {
string str;
HttpMessageHandler handler;
try {
handler = new Http2WinHttpHandler {
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
}
catch (PlatformNotSupportedException) {
handler = new HttpClientHandler {
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
}
using (var client = new HttpClient(handler)) {
str = await GetString(url, method, client, cancelToken, retries);
}
return str;
}
public static async Task<string> GetString(Uri url, HttpMethod method, HttpClient client, CancellationToken cancelToken, int retries = 3, bool pushAllExceptions = false) {
string str = null;
using (var response = await GetResponse(url, method, client, cancelToken, retries, pushAllExceptions)) {
if (response != null) {
str = await response.Content.ReadAsStringAsync();
}
}
return str;
}
public static async Task<string> GetString(HttpRequestMessage request, HttpClient client, CancellationToken cancelToken) {
string str = null;
using (var response = await GetResponse(request, client, cancelToken)) {
if (response != null) {
str = await response.Content.ReadAsStringAsync();
}
}
return str;
}
public static async Task<string> GetString(HttpRequestMessage request, CancellationToken cancelToken) {
string str = null;
using (var response = await GetResponse(request, cancelToken)) {
if (response != null) {
str = await response.Content.ReadAsStringAsync();
}
}
return str;
}
public static async Task<string> GetString(Uri url, HttpMethod method, HttpContent content, CancellationToken cancelToken, int retries = 3) {
string str;
using (var request = new HttpRequestMessage() {
RequestUri = url,
Method = method,
Content = content,
Version = new Version(2, 0)
}) {
str = await GetString(request, cancelToken);
}
return str;
}
public static string GetStringSync(HttpRequestMessage request, HttpClient client, out HttpStatusCode? statusCode, CancellationToken cancelToken) {
string res = null;
try {
var httpTask = GetResponseSync(request, client, cancelToken);
httpTask.Wait(cancelToken);
var response = httpTask.Result;
var htmlTask = response.Content.ReadAsStringAsync();
htmlTask.Wait(cancelToken);
res = htmlTask.Result;
statusCode = response.StatusCode;
response.Dispose();
}
catch (Exception) {
statusCode = null;
}
return res;
}
public static async Task<Stream> GetStream(Uri url, HttpMethod method, CancellationToken cancelToken, int retries = 3) {
Stream stream = null;
using (var client = new HttpClient()) {
stream = await GetStream(url, method, client, cancelToken, retries);
}
return stream;
}
public static async Task<Stream> GetStream(Uri url, HttpMethod method, HttpClient client, CancellationToken cancelToken, int retries = 3) {
Stream ret = null;
using (var response = await GetResponse(url, method, client, cancelToken, retries)) {
if (response == null) return ret;
using (var stream = await response.Content.ReadAsStreamAsync()) {
if (stream is null) return null;
ret = new MemoryStream();
await stream.CopyToAsync(ret);
ret.Position = 0;
}
}
return ret;
}
public static async Task<HttpResponseMessage> GetResponse(Uri url, HttpMethod method, CancellationToken cancelToken, int retries = 3) {
HttpResponseMessage response = null;
HttpMessageHandler httpClientHandler;
try {
httpClientHandler = new Http2WinHttpHandler {
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
}
catch (PlatformNotSupportedException) {
httpClientHandler = new HttpClientHandler {
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
}
using (var client = new HttpClient(httpClientHandler)) {
response = await GetResponse(url, method, client, cancelToken, retries);
}
httpClientHandler.Dispose();
return response;
}
public static async Task<HttpResponseMessage> GetResponse(Uri url, HttpMethod method, HttpClient client, CancellationToken cancelToken, int retries = 3, bool pushAllExceptions = false) {
HttpResponseMessage response = null;
uint retriesCount = 0;
Exception exception = null;
while (retriesCount <= retries) {
try {
exception = null;
var request = new HttpRequestMessage() {
RequestUri = url,
Method = method
};
request.Headers.TryAddWithoutValidation("User-Agent", UserAgent);
request.Headers.TryAddWithoutValidation("Accept", "*/*");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
response = await client.SendAsync(request, cancelToken);
}
catch (Exception ex) {
exception = ex;
if (ex.GetType() == typeof(TaskCanceledException)) {
throw;
}
retriesCount++;
continue;
}
break;
}
if (exception != null && pushAllExceptions) {
throw exception;
}
return response;
}
public static async Task<HttpResponseMessage> GetResponse(HttpRequestMessage request, HttpClient client, CancellationToken cancelToken) {
HttpResponseMessage response = null;
try {
response = await client.SendAsync(request, cancelToken);
}
catch (Exception ex) {
if (ex.GetType() == typeof(TaskCanceledException)) {
throw;
}
}
return response;
}
public static async Task<HttpResponseMessage> GetResponseSync(HttpRequestMessage request, HttpClient client, CancellationToken cancelToken) {
HttpResponseMessage response = null;
try {
response = await client.SendAsync(request, cancelToken).ConfigureAwait(false);
}
catch (Exception ex) {
if (ex.GetType() == typeof(TaskCanceledException)) {
throw;
}
}
return response;
}
public static async Task<HttpResponseMessage> GetResponse(HttpRequestMessage request, CancellationToken cancelToken) {
HttpResponseMessage response = null;
using (var client = new HttpClient()) {
response = await GetResponse(request, client, cancelToken);
}
return response;
}
}
}<file_sep>/Common/Supreme/SupremeProduct.cs
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace Common.Supreme {
public partial class SupremeProduct {
[JsonProperty("styles")] public List<Style> Styles { get; set; }
[JsonProperty("description")] public string Description { get; set; }
[JsonProperty("can_add_styles")] public bool CanAddStyles { get; set; }
[JsonProperty("can_buy_multiple")] public bool CanBuyMultiple { get; set; }
[JsonProperty("ino")] public string Ino { get; set; }
[JsonProperty("cod_blocked")] public bool CodBlocked { get; set; }
[JsonProperty("canada_blocked")] public bool CanadaBlocked { get; set; }
[JsonProperty("purchasable_qty")] public long PurchasableQty { get; set; }
[JsonProperty("new_item")] public bool NewItem { get; set; }
[JsonProperty("apparel")] public bool Apparel { get; set; }
[JsonProperty("handling")] public long Handling { get; set; }
[JsonProperty("no_free_shipping")] public bool NoFreeShipping { get; set; }
[JsonProperty("can_buy_multiple_with_limit")]
public long CanBuyMultipleWithLimit { get; set; }
[JsonProperty("non_eu_blocked")] public bool NonEuBlocked { get; set; }
[JsonProperty("russia_blocked")] public bool RussiaBlocked { get; set; }
}
public partial class SupremeProduct {
public static SupremeProduct FromJson(string json) => JsonConvert.DeserializeObject<SupremeProduct>(json,
new JsonSerializerSettings {MissingMemberHandling = MissingMemberHandling.Ignore});
}
}
<file_sep>/ClownAIOClient/Pages/TasksPage.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using Common;
using Common.Supreme;
using Common.Types;
using Microsoft.Win32;
using Newtonsoft.Json;
using Supreme;
namespace ClownAIO.Pages {
/// <summary>
/// Interaction logic for TasksPage.xaml
/// </summary>
public partial class TasksPage : UserControl {
public TasksPage() {
InitializeComponent();
TaskPropertyGrid.DataContext = new TaskGridViewModel();
TaskListView.ItemsSource = BotContext.Bots;
BotContext.Bots.CollectionChanged += (sender, args) => { TaskListView.ItemsSource = BotContext.Bots; };
BillingCombo.ItemsSource = BotContext.Profiles;
BotContext.Profiles.CollectionChanged += (sender, args) => { BillingCombo.ItemsSource = BotContext.Profiles; };
BotType.ItemsSource = BotContext.BotTypes;
BotContext.BotTypes.CollectionChanged += (sender, args) => { BotType.ItemsSource = BotContext.BotTypes; };
}
private void AddTaskButton_OnClick(object sender, RoutedEventArgs e) {
if (string.IsNullOrWhiteSpace(ProductKeywords.Text)
|| BillingCombo.SelectedIndex.Equals(-1)) return;
if (string.IsNullOrWhiteSpace(ColorKeywords.Text) && SizeCombo.Text.Equals("Any")) {
BotContext.Bots.Add((Bot)Activator.CreateInstance(BotContext.BotTypes[Common.BotType.Supreme],
((KeyValuePair<string, BillingProfile>) BillingCombo.SelectedItem).Value,
new SearchProduct(CategoryCombo.Text, ProductKeywords.Text.Trim().Split(',').ToList())));
}
else if (string.IsNullOrWhiteSpace(ColorKeywords.Text)) {
BotContext.Bots.Add((Bot)Activator.CreateInstance(BotContext.BotTypes[Common.BotType.Supreme],
((KeyValuePair<string, BillingProfile>) BillingCombo.SelectedItem).Value,
new SearchProduct(CategoryCombo.Text, ProductKeywords.Text.Trim().Split(',').ToList(),
SizeCombo.Text)));
}
else if (SizeCombo.Text.Equals("Any")) {
BotContext.Bots.Add((Bot)Activator.CreateInstance(BotContext.BotTypes[Common.BotType.Supreme],
((KeyValuePair<string, BillingProfile>) BillingCombo.SelectedItem).Value,
new SearchProduct(CategoryCombo.Text, ProductKeywords.Text.Trim().Split(',').ToList(),
ColorKeywords.Text.Trim().Split(',').ToList())));
}
else {
BotContext.Bots.Add((Bot)Activator.CreateInstance(BotContext.BotTypes[Common.BotType.Supreme],
((KeyValuePair<string, BillingProfile>) BillingCombo.SelectedItem).Value,
new SearchProduct(CategoryCombo.Text, ProductKeywords.Text.Trim().Split(',').ToList(),
ColorKeywords.Text.Trim().Split(',').ToList(), SizeCombo.Text)));
}
BotContext.Bots.Last().Proxy = ProxyAddress.Text;
((Supreme.SupremeBot) BotContext.Bots.Last()).CheckoutDelay = CheckoutDelaySlider.Value;
((Supreme.SupremeBot) BotContext.Bots.Last()).CaptchaBypass = CaptchaBypassCheckbox.IsChecked.Equals(true);
}
private void TaskListView_OnSelectionChanged(object sender, SelectionChangedEventArgs e) {
((TaskGridViewModel) TaskPropertyGrid.DataContext).Bot = BotContext.Bots[TaskListView.SelectedIndex];
}
private void StartTaskButton_OnClick(object sender, RoutedEventArgs e) {
foreach (var task in TaskListView.SelectedItems) {
((Bot)task).Execute();
}
}
private void StopTaskButton_OnClick(object sender, RoutedEventArgs e) {
foreach (var task in TaskListView.SelectedItems) {
((Bot)task).Abort();
}
}
private void SaveTaskButton_OnClick(object sender, RoutedEventArgs e) {
if (TaskListView.SelectedItems.Count <= 0) return;
var sfd = new SaveFileDialog
{Title = "Choose file to export tasks to...", Filter = "JSON|*.json|All Files|*"};
var result = sfd.ShowDialog();
if (result != true) return;
try {
File.WriteAllText(sfd.FileName, JsonConvert.SerializeObject(TaskListView.SelectedItems));
}
catch (Exception) {
MessageBox.Show("Failed to save tasks.");
}
}
private void LoadTaskButton_OnClick(object sender, RoutedEventArgs e) {
var ofd = new OpenFileDialog
{Title = "Open exported tasks file...", Filter = "JSON|*.json|All Files|*"};
var result = ofd.ShowDialog();
if (result != true) return;
try {
var bots =
JsonConvert.DeserializeObject<Bot[]>(File.ReadAllText(ofd.FileName), new BotConverter());
foreach (var bot in bots) {
BotContext.Bots.Add(bot);
}
}
catch (Exception) {
MessageBox.Show("Failed to load tasks.");
}
}
private void BotType_OnSelectionChanged(object sender, SelectionChangedEventArgs e) {
switch (((KeyValuePair<BotType, Type>)BotType.SelectedItem).Key) {
case Common.BotType.Supreme: {
SupremeUs.Visibility = Visibility.Visible;
break;
}
default: {
SupremeUs.Visibility = Visibility.Hidden;
break;
}
}
}
}
public class TaskGridViewModel : INotifyPropertyChanged {
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private Bot _bot;
public Bot Bot {
get => _bot;
set {
_bot = value;
OnPropertyChanged();
}
}
}
}
<file_sep>/Common/Bot.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Common.Supreme;
using Common.Types;
using Newtonsoft.Json;
namespace Common {
public enum BotType {
Undefined,
Supreme,
Shopify
}
public abstract class Bot : INotifyPropertyChanged {
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private string _status = "Idle";
[Browsable(false), JsonIgnore] protected bool SerializeDebug { get; set; }
[DisplayName("Type"), Category("Information")]
public BotType BotType { get; }
[DisplayName("Billing Profile"), Category("Configuration"), TypeConverter(typeof(ExpandableObjectConverter))]
public BillingProfile BillingProfile { get; }
private Task Task { get; set; }
private CancellationTokenSource CancellationTokenSource { get; set; }
private HttpMessageHandler HttpMessageHandler { get; set; }
private SearchProduct _searchProduct;
private long _completedInMs = -1;
[ReadOnly(true), JsonIgnore]
[Category("Information")]
[DisplayName("Completed In")]
public long CompletedInMs {
get => _completedInMs;
set {
_completedInMs = value;
OnPropertyChanged();
}
}
[Category("Configuration")]
[DisplayName("Product Info")]
[TypeConverter(typeof(ExpandableObjectConverter))]
public SearchProduct SearchProduct {
get => _searchProduct;
set { _searchProduct = value; OnPropertyChanged(); }
}
[Browsable(false)]
public List<Tuple<HttpRequestMessage, string>> RequestsList { get; } =
new List<Tuple<HttpRequestMessage, string>>();
[Category("Configuration")]
public string Proxy {
get {
if (HttpMessageHandler.GetType() == typeof(Http2WinHttpHandler)) {
if (((Http2WinHttpHandler)HttpMessageHandler).Proxy is null) {
return "n/a";
}
var proxyAddress = ((WebProxy)((Http2WinHttpHandler)HttpMessageHandler).Proxy).Address.ToString();
var from = proxyAddress.IndexOf("://", StringComparison.Ordinal) + "://".Length;
var to = proxyAddress.LastIndexOf("/", StringComparison.Ordinal);
return proxyAddress.Substring(from, to - from);
}
if (((HttpClientHandler)HttpMessageHandler).Proxy is null) {
return "n/a";
}
var proxyAddress2 = ((WebProxy)((HttpClientHandler)HttpMessageHandler).Proxy).Address.ToString();
var from2 = proxyAddress2.IndexOf("://", StringComparison.Ordinal) + "://".Length;
var to2 = proxyAddress2.LastIndexOf("/", StringComparison.Ordinal);
return proxyAddress2.Substring(from2, to2 - from2);
}
set {
try {
const string proxyPattern = @"\d{1,3}(\.\d{1,3}){3}:\d{1,5}";
if (Regex.Match(value, proxyPattern).Success) {
WebProxy newProxy;
try {
newProxy = new WebProxy("http://" + value);
}
catch (Exception) {
return;
}
if (HttpMessageHandler.GetType() == typeof(Http2WinHttpHandler)) {
HttpMessageHandler = new Http2WinHttpHandler {
AutomaticRedirection = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.GZip,
WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy,
Proxy = newProxy
};
}
else {
HttpMessageHandler = new HttpClientHandler {
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.GZip,
Proxy = newProxy,
UseProxy = true
};
}
}
else {
if (HttpMessageHandler.GetType() == typeof(Http2WinHttpHandler)) {
HttpMessageHandler = new Http2WinHttpHandler {
AutomaticRedirection = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.GZip,
WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy
};
}
else {
HttpMessageHandler = new HttpClientHandler {
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.GZip,
UseProxy = false
};
}
}
}
catch (Exception) { }
OnPropertyChanged();
}
}
[ReadOnly(true), JsonIgnore]
[Category("Information")]
public string Status {
get => _status;
set {
_status = value;
OnPropertyChanged();
}
}
private readonly SortedSet<BotTask> _tasks =
new SortedSet<BotTask>(Comparer<BotTask>.Create((a, b) => a.Priority() - b.Priority()));
protected Bot() {
BotType = BotType.Undefined;
CancellationTokenSource = new CancellationTokenSource();
}
protected Bot(BotType botType, BillingProfile profile, SearchProduct searchProduct) {
BotType = botType;
BillingProfile = profile;
SearchProduct = searchProduct;
CancellationTokenSource = new CancellationTokenSource();
try {
HttpMessageHandler = new Http2WinHttpHandler {
AutomaticRedirection = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy
};
}
catch (PlatformNotSupportedException) {
HttpMessageHandler = new HttpClientHandler {
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
UseProxy = false
};
}
}
public void Execute() {
if (Task != null && Task.Status.Equals(TaskStatus.Running)) return;
Task = Task.Run(() => {
var stopwatch = Stopwatch.StartNew();
foreach (var task in _tasks.Where(task => task.Validate())) {
Status = task.Description();
task.Execute();
}
stopwatch.Stop();
CompletedInMs = stopwatch.ElapsedMilliseconds;
SerializeDebug = true;
Debug.WriteLine(JsonConvert.SerializeObject(this, Formatting.Indented));
SerializeDebug = false;
});
}
public void Abort() {
try {
CancellationTokenSource.Cancel();
Task = null;
CancellationTokenSource = new CancellationTokenSource();
Status = "Aborted";
CompletedInMs = -1;
}
catch (Exception) { }
}
/**
* Add tasks to our current BotTask.
*/
public void Append(params BotTask[] tasks) {
Array.ForEach(tasks, task => _tasks.Add(task));
}
public HttpClient GetNewHttpClient() {
return new HttpClient(HttpMessageHandler, false) {Timeout = TimeSpan.FromSeconds(2)};
}
public HttpMessageHandler GetClientHandler() {
return HttpMessageHandler;
}
public CancellationToken GetCancellationToken() {
return CancellationTokenSource.Token;
}
public bool ShouldSerializeRequestsList() {
return SerializeDebug;
}
}
} | f64c11c6e873fc5b2c28ba1039fc616fd46dee27 | [
"Markdown",
"C#"
] | 52 | C# | 67-6f-64/TheClownClub | 714d963bfe8de491732b66d35c60c959f63e2449 | cff501a05730695bea41215f0badc62e03510e95 |
refs/heads/master | <file_sep>package controller;
import dao.UserDao;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
@Controller
public class LoginController {
@RequestMapping(value = "/", method = RequestMethod.GET)//这里表示访问根目录的时候转到login.jsp页面的意思,同样会对该字符串进行路径解析
public String sayHello() {
return "login";
}
@RequestMapping(value = "login",method = RequestMethod.POST)//这个的意思是拦截到login的字样会加以判断来转移到哪个页面,当然也会加以处理
public String login(Model model, HttpServletRequest request)
{
String name=request.getParameter("name");
String password=request.getParameter("password");
if(UserDao.checkLogin(name,password)!=null)
{
model.addAttribute("name",name);
return "success";
}
else
{
return "login2";
}
}
}
<file_sep> package service;
import java.util.Date;
import entity.User;
import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class CodeHandle
{
@Autowired
private UserMapper userMapper;
@Autowired
@Transactional
public boolean CheckValid(User user)
{
User user1 = userMapper.findUser(user.getId());
if (user.equals(user1))
{
return true;
}
return false;
}
@Autowired
@Transactional
public boolean CheckRepeat(User user)
{
User user1 = userMapper.findUser(user.getId());
if (user1 == null)
return false;
Date d1 = new Date();
Date d2 = user1.getTime();
if (d1.getTime() - d2.getTime() >= 120000)
{
userMapper.deleteUser(user.getId());
return false;
}
return true;
}
}<file_sep>package entity;
import java.io.UnsupportedEncodingException;
public class inf {
int num;
String username;
String des;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDes() {
return des;
}
public void setDes(String des) throws UnsupportedEncodingException {
this.des =des;
}
}
<file_sep>package servlet;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class SessionBean {//用于获得session的类
private final static SqlSessionFactory sqlSessionFactory;
static {
String resource="config.xml";//mybatis的配置文件位置
InputStream inputStream=null;
try {
inputStream = Resources.getResourceAsStream(resource);//将xml的配置信息注入
}
catch (IOException e)
{
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//建一个session的工厂类
}
public static SqlSession getSession()
{
return sqlSessionFactory.openSession();
}//获得一个session
}
<file_sep>package service;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import com.gargoylesoftware.htmlunit.util.Cookie;
import org.springframework.stereotype.Service;
@Service
public class Admin
{
public void ChangePwd(String user_id, String new_pwd) throws java.io.IOException
{
WebClient webclient = new WebClient();
webclient.getOptions().setCssEnabled(false);
webclient.getOptions().setJavaScriptEnabled(false);
webclient.getOptions().setRedirectEnabled(true);
webclient.getCookieManager().setCookiesEnabled(true);
HtmlPage htmlpage = (HtmlPage)webclient.getPage("http://acm.wust.edu.cn/loginpage.php");
HtmlForm form = (HtmlForm)htmlpage.getForms().get(0);
HtmlElement button = (HtmlElement)htmlpage.getElementByName("submit");
HtmlTextInput nameField = (HtmlTextInput)form.getInputByName("user_id");
nameField.setValueAttribute("自己的账号");
HtmlPasswordInput pwdField = (HtmlPasswordInput)form.getInputByName("password");
pwdField.setValueAttribute("<PASSWORD>");
button.click();
java.util.Set<Cookie> cookies = webclient.getCookieManager().getCookies();
java.util.Map<String, String> responseCookies = new java.util.HashMap();
for (Cookie c : cookies) {
responseCookies.put(c.getName(), c.getValue());
}
HtmlPage nextPage = (HtmlPage)webclient.getPage("保密");//之后是分析页面获取按钮模拟修改密码
HtmlForm form1 = (HtmlForm)nextPage.getForms().get(0);
HtmlTextInput name = (HtmlTextInput)form1.getInputByName("user_id");
HtmlTextInput pwd = (HtmlTextInput)form1.getInputByName("passwd");
com.gargoylesoftware.htmlunit.html.HtmlInput btn = (HtmlInput)form1.getInputsByValue("xxxx").get(0);
name.setValueAttribute(user_id);
pwd.setValueAttribute(new_pwd);
String result = nextPage.asXml();
btn.click();
webclient.close();
}
public boolean checkExist(String id, String Mail) throws java.io.IOException
{
WebClient webclient = new WebClient();
webclient.getOptions().setCssEnabled(false);
webclient.getOptions().setJavaScriptEnabled(false);
webclient.getOptions().setRedirectEnabled(true);
webclient.getCookieManager().setCookiesEnabled(true);
HtmlPage htmlpage = (HtmlPage)webclient.getPage("http://acm.wust.edu.cn/loginpage.php");
HtmlForm form = (HtmlForm)htmlpage.getForms().get(0);
HtmlElement button = (HtmlElement)htmlpage.getElementByName("submit");
HtmlTextInput nameField = (HtmlTextInput)form.getInputByName("user_id");
nameField.setValueAttribute("自己的账号");
HtmlPasswordInput pwdField = (HtmlPasswordInput)form.getInputByName("password");
pwdField.setValueAttribute("<PASSWORD>");
button.click();
java.util.Set<Cookie> cookies = webclient.getCookieManager().getCookies();
java.util.Map<String, String> responseCookies = new java.util.HashMap();
for (Cookie c : cookies) {
responseCookies.put(c.getName(), c.getValue());
}
HtmlPage nextPage = (HtmlPage)webclient.getPage("http://acm.wust.edu.cn/userinfo.php?user=" + id);
if (nextPage.getByXPath("/html/body/div[@id='wrapper']/div[@id='main']/center/font[1]").size() == 0)//这里是xpath表达式获取页面元素
{
return false;
}
HtmlElement item = (HtmlElement)nextPage.getByXPath("/html/body/div[@id='wrapper']/div[@id='main']/center/font[1]").get(0);
String xml = item.asXml();
String mail = "";
String regex = "[a-zA-z\\.[0-9]]*@[a-zA-z[0-9]]*\\.com";
java.util.regex.Pattern p = java.util.regex.Pattern.compile(regex);
java.util.regex.Matcher m = p.matcher(xml);
int num = 0;
while (m.find()) {
mail = m.group().toString();
}
webclient.close();
if (Mail.equals(mail))
return true;
return false;
}
}<file_sep>package com.wust.servlet;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
@SpringBootApplication
@ComponentScan("controller")
@ComponentScan("entity")
@ComponentScan("service")
@ComponentScan("conf")
@MapperScan("mapper")
@EnableAutoConfiguration
public class ServletApplication {
public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}
}
<file_sep>package service;
import com.sun.mail.util.MailSSLSocketFactory;
import entity.User;
import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;
@Service
public class Mail
{
@Autowired
UserMapper userMapper;
@Transactional
public void sendCode(User user)
{
try
{
Properties prop = new Properties();
prop.setProperty("mail.debug", "true");//设置debug信息打印
prop.setProperty("mail.host", "smtp.qq.com");
prop.setProperty("mail.smtp.auth", "true");
prop.setProperty("mail.transport.protocol", "smtp");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(prop);
Transport ts = session.getTransport();
ts.connect("smtp.qq.com", "qq号", "这里填邮箱里的授权码(没有的要去qq邮箱那设置)");
Message message = createSimpleMail(user, session);
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
@Transactional
public MimeMessage createSimpleMail(User user, Session session) throws Exception
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("这里填发件人的邮箱"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getMail()));
message.setSubject("OJ账号找回");
Random rand = new Random();
Integer t = Integer.valueOf(rand.nextInt(90000) + 10000);//生成5位随机数
user.setCode(t.toString());
userMapper.insertUser(user);
message.setContent("本次的修改密码验证码为:" + t + ",2分钟内有效。若非本人操作,请尽快联系WUSTOJ管理员,qq:845723932 ", "text/html;charset=UTF-8");
return message;
}
}<file_sep>package com.smart.service;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.testng.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import com.smart.domain.User;
import static org.testng.Assert.*;
@ContextConfiguration("classpath*:/smart-context.xml")
public class UserServiceTest extends AbstractTransactionalTestNGSpringContextTests{
private UserService userService;
@Autowired
public void setUserService(UserService userService)
{
this.userService=userService;
}
@Test
public void hasMatchUser(){
boolean b1=userService.hasMatchUser("admin","123456");
boolean b2=userService.hasMatchUser("admin","1111");
assertEquals(b1,true);
//assertEquals(b2,true);
}
@Test
public void findUserByUserName() {
User user=userService.findUserByUserName("admin");
assertEquals(user.getUserName(),"admin");
}
} | 2cbe0d55e7ea27624cb28cf164b375f93d7c4655 | [
"Java"
] | 8 | Java | iunique/IdeaProject | 40db6f452569fc04956540e1c9a68e40ea1b6e63 | 1a58d0c26e9454628f6de5315641b5be6a2c1423 |
refs/heads/master | <repo_name>XiaoWenWenZhang/mockServer<file_sep>/.history/index_20210504221413.ts
import fs from 'fs';
import * as http from 'http'
http.createServer((req, res) => {
res.end('hello world');
}).listen(8082);<file_sep>/.history/index_20210504221824.ts
import * as fs from 'fs'
import * as http from 'http'
http.createServer((req, res) => {
const mockData = require('./mock');
if (req.url === '/task/list') {
return res.end(mockData.find(data => data.url === req.url).data)
}
}).listen(8082);<file_sep>/.history/index_20210504221326.ts
import fs from 'fs';
import http from 'http'
http.createServer((req, res) => {
res.end('hello world');
}).listen(8082);<file_sep>/.history/index_20210504231225.js
var fs = require('fs');
var path = require('path');
var http = require('http');
http.createServer(test).listen(8082);
var mockPath = path.resolve(__dirname, './mock.js');
function test(req, res) {
var mockData = getMockData();
res.setHeader('Content-Type', 'application/json;charset=UTF-8');
getRequestBody(req).then(function (data) {
if (req.url === '/task/delete') {
var list = mockData.find((function (item) { return item.url === '/task/list'; })).data;
var taskId = data.taskId;
var index = list.findIndex(function (item) { return item.taskId === taskId; });
if (index >= 0) {
list.splice(index, 1);
}
fs.writeFileSync(mockPath, 'module.exports=' + JSON.stringify(mockData));
}
res.end(JSON.stringify(mockData.find(function (data) {
return data.url === req.url;
})));
});
}
function getMockData() {
delete require.cache[require.resolve('./mock')];
return require('./mock');
}
function getRequestBody(req) {
return new Promise(function (resolve) {
var message = '';
req.on('data', function (chunk) {
message += (chunk || '').toString();
});
req.on('end', function (data) {
message += (data || '').toString();
console.log('adsfasdfasdfasdfasdfasdfa' + message);
resolve(JSON.parse(message.trim() || ''));
});
});
}
<file_sep>/.history/index_20210504234738.ts
import * as fs from 'fs'
import * as path from 'path'
import * as http from 'http'
const app = http.createServer(handle).listen(8082);
const mockPath = path.resolve(__dirname, './mock.js');
function handle(req, res) {
const mockData = getMockData();
res.setHeader('Content-Type', 'application/json;charset=UTF-8');
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "*");
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE")
getRequestBody(req).then(function (data) {
if (req.url === '/task/delete') {
const list = mockData.find((item => item.url === '/task/list')).data;
const taskId = data.taskId;
const index = list.findIndex(function (item) {return item.taskId === taskId});
if (index >= 0) {
list.splice(index, 1);
}
fs.writeFileSync(mockPath, 'module.exports=' + JSON.stringify(mockData));
}
if (req.url === '/task/create') {
const list = mockData.find((item => item.url === '/task/list')).data;
const id = 'id_' + Date.now();
const task = data;
task.id = id;
list.push(task);
fs.writeFileSync(mockPath, 'module.exports=' + JSON.stringify(mockData));
}
if(req.url === '/task/update') {
const list = mockData.find((item => item.url === '/task/list')).data;
const taskId = data.taskId;
const index = list.findIndex(function (item) {return item.taskId === taskId});
if(index >= 0) {
list.splice(index, 1, data);
}
fs.writeFileSync(mockPath, 'module.exports=' + JSON.stringify(mockData));
}
res.end(JSON.stringify(mockData.find(function(data) {
return data.url === req.url;
})));
});
}
function getMockData() {
delete require.cache[require.resolve('./mock')]
return require('./mock');
}
function getRequestBody(req: http.IncomingMessage) {
return new Promise<any>(function (resolve){
let message = '';
req.on('data', (chunk) => {
message += (chunk || '').toString();
})
req.on('end', (data) => {
message += (data || '').toString();
if (message.trim()) {
resolve(JSON.parse(message));
} else {
resolve({});
}
})
})
}<file_sep>/.history/index_20210504221715.ts
import * as fs from 'fs'
import * as http from 'http'
http.createServer((req, res) => {
const mockData = require('./mock');
}).listen(8082);<file_sep>/.history/index_20210504221114.ts
import fs from 'fs';
import http from 'http'
http.createServer('0.0.0.0', (req, res) => {
res.end('hello world');
}).listen(8082); | 4527de86a962340e285aba837a4ed8b6a1b5bf02 | [
"JavaScript",
"TypeScript"
] | 7 | TypeScript | XiaoWenWenZhang/mockServer | 8fd6c758d107dc501005d2c98ebdf13ed2c297e9 | 05fa878b94caeb172d3c1a864fa203b65ae9c642 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.