branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import './DisplayStyles.css';
import Button from '../ButtonComponents/Button';
import Results from '../ButtonComponents/Results';
import Clear from '../ButtonComponents/Clear';
import Zero from '../ButtonComponents/Zero';
class Display extends Component {
constructor(props) {
super(props);
this.state = {
result: '',
previousNumber: '',
currentNumber: '',
operator: ''
};
}
addToResults = value => {
this.setState({ result: this.state.result + value });
};
addZeroToResults = value => {
// if this.state.result is not empty then add zero
if (this.state.result !== '') {
this.setState({ result: this.state.result + value });
}
};
clearResult = () => {
this.setState({ result: '' });
};
divide = () => {
this.state.previousNumber = this.state.result;
this.setState({ result: '' });
this.state.operator = 'divide';
};
multiply = () => {
this.state.previousNumber = this.state.result;
this.setState({ result: '' });
this.state.operator = 'multiply';
};
subtract = () => {
this.state.previousNumber = this.state.result;
this.setState({ result: '' });
this.state.operator = 'subtract';
};
add = () => {
this.state.previousNumber = this.state.result;
this.setState({ result: '' });
this.state.operator = 'plus';
};
solved = () => {
this.state.currentNumber = this.state.result;
if (this.state.operator === 'plus') {
this.setState({
result:
parseInt(this.state.previousNumber) +
parseInt(this.state.currentNumber)
});
} else if (this.state.operator === 'subtract') {
this.setState({
result:
parseInt(this.state.previousNumber) -
parseInt(this.state.currentNumber)
});
} else if (this.state.operator === 'multiply') {
this.setState({
result:
parseInt(this.state.previousNumber) *
parseInt(this.state.currentNumber)
});
} else if (this.state.operator === 'divide') {
this.setState({
result:
parseInt(this.state.previousNumber) /
parseInt(this.state.currentNumber)
});
}
};
render() {
return (
<div className="Display">
<div className="col-sm-5 col-md-5 col-lg-5 m-auto">
<h3 class="text-center mb-3 fine-text">
Welcome To My React Calculator
</h3>
<div className="row">
<Results>{this.state.result}</Results>
</div>
<div className="row">
<Clear handleClear={this.clearResult}>clear</Clear>
<Button handleClick={this.divide}>/</Button>
</div>
<div className="row">
<Button handleClick={this.addToResults}>7</Button>
<Button handleClick={this.addToResults}>8</Button>
<Button handleClick={this.addToResults}>9</Button>
<Button handleClick={this.multiply}>X</Button>
</div>
<div className="row">
<Button handleClick={this.addToResults}>4</Button>
<Button handleClick={this.addToResults}>5</Button>
<Button handleClick={this.addToResults}>6</Button>
<Button handleClick={this.subtract}>-</Button>
</div>
<div className="row">
<Button handleClick={this.addToResults}>1</Button>
<Button handleClick={this.addToResults}>2</Button>
<Button handleClick={this.addToResults}>3</Button>
<Button handleClick={this.add}>+</Button>
</div>
<div className="row">
<Zero handleClick={this.addZeroToResults}>0</Zero>
<Button handleClick={this.solved}>=</Button>
</div>
</div>
</div>
);
}
}
export default Display;
<file_sep>import React, { Component } from 'react';
import './ButtonStyles.css';
class Zero extends Component {
render() {
return (
<div
className="col-9 d-flex justify-content-center align-items-center bg-my-color text-light border border-dark"
onClick={() => this.props.handleClick(this.props.children)}
>
{this.props.children}
</div>
);
}
}
export default Zero;
<file_sep>import React, { Component } from 'react';
import './ButtonStyles.css';
class Results extends Component {
render() {
return (
<div className="col-md-12 border border-dark rounded results">
{this.props.children}
</div>
);
}
}
export default Results;
|
b03a29bffbe05fbea44958f04fe2c9eb193b21ca
|
[
"JavaScript"
] | 3 |
JavaScript
|
meetnerdykat/React-Calculator
|
587fd623958c97baf05bf0f66b9fce00d6d4d5ea
|
c9bf4c7caf12f8a5f7b2d09b1d8045774eef148c
|
refs/heads/master
|
<file_sep># smart-vertical.js
Magical DOM rotation
Add the "vertical" class and run "generate_vertical_class();"
<file_sep>// Generated by CoffeeScript 1.3.3
(function() {
window.generate_vertical_class = function(dom_name) {
var el, rest, style, width;
if (dom_name == null) {
dom_name = 'vertical';
}
el = document.getElementsByClassName(dom_name)[0];
rest = el.clientHeight / 2;
width = el.clientWidth - rest;
style = document.createElement("style");
style.type = "text/css";
style.innerHTML = ".vertical {\n -webkit-transform: rotate(90deg);\n -webkit-transform-origin: 0px;\n margin-top: -" + rest + "px;\n margin-left: " + rest + "px;\n margin-right: -" + width + "px;\n margin-bottom: " + width + "px;\n}";
return document.getElementsByTagName("head")[0].appendChild(style);
};
}).call(this);
|
f73f762db20625e56ca6957263902223409ace44
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
grigio/smart-vertical.js
|
d3dce12efe50a0a5488785d34c62adf0be53c25c
|
287717d7f761b8263191f4a08a8bce71e019bb9d
|
refs/heads/master
|
<repo_name>iamneha/cgtk<file_sep>/window.c
#include<gtk/gtk.h>
static void activate(GtkApplication *app,
gpointer user_data)
{
GtkWidget *window;
window = gtk_application_window_new(app);
gtk_window_set_title(GTK_WINDOW(window), "window");
gtk_window_set_default_size(GTK_WINDOW(window),200, 200);
gtk_widget_show_all(window);
}
int main(int argc, char **argv)
{
GtkApplication *app;
int status;
app = gtk_application_new("or.gtk.example", G_APPLICATION_FLAGS_NONE);
g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
status = g_application_run(G_APPLICATION(app), argc, argv);
g_object_unref(app);
return status;
}
<file_sep>/packing.c
#include<gtk/gtk.h>
static void
print_hello(GtkWidget *widget,
gpointer data)
{
g_print("Hello world!");
}
static void
activate(GtkApplication *app,
gpointer user_data)
{
GtkWidget *window;
GtkWidget *grid;
GtkWidget *button;
//create new window and set title
window = gtk_application_window_new(app);
gtk_window_set_title(GTK_WINDOW(window), "window");
gtk_window_set_default_size(GTK_WINDOW(window), 200, 200);
gtk_container_set_border_width(GTK_CONTAINER(window), 10);
//construct container that is going to pack our widget
grid = gtk_grid_new();
//pack container in window
gtk_container_add(GTK_CONTAINER(window), grid);
button = gtk_button_new_with_label("Button1");
g_signal_connect(button, "clicked", G_CALLBACK(print_hello), NULL);
//place the first button in grid cell
gtk_grid_attach(GTK_GRID(grid), button, 0,0,1,1);
button = gtk_button_new_with_label("Button2");
g_signal_connect(button, "clicked", G_CALLBACK(print_hello), NULL);
//place second button in grid cell
gtk_grid_attach(GTK_GRID(grid), button, 1,0,1,1);
button = gtk_button_new_with_label("QUIT");
g_signal_connect_swapped(button, "clicked", G_CALLBACK(gtk_widget_destroy), window);
gtk_grid_attach(GTK_GRID(grid), button,0, 1,2,1);
gtk_widget_show_all(window);
}
int main(int argc, char **argv)
{
GtkApplication *app;
int status;
app = gtk_application_new("org.gtk.example", G_APPLICATION_FLAGS_NONE);
g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
status = g_application_run(G_APPLICATION(app), argc, argv);
g_object_unref(app);
return status;
}
|
c1d339573eeb66b3629a32740e84b26ccc836edb
|
[
"C"
] | 2 |
C
|
iamneha/cgtk
|
782230731e5cd67e4bf8e6a0ed895f3df6c558b8
|
0e71a9d309c2c334561ed7b0bbec4b72bd0aa1c0
|
refs/heads/master
|
<repo_name>JosephShering/bp<file_sep>/gulpfile.js
var gulp = require('gulp');
var stylus = require('gulp-stylus');
var rename = require('gulp-rename');
var browserify = require('gulp-browserify');
var nodemon = require('gulp-nodemon');
var server = require('./server.js');
gulp.task('styles', function() {
return gulp.src('./styles/main.styl')
.pipe(stylus())
.on('error', swallowError)
.pipe(rename('style.css'))
.pipe(gulp.dest('./client/'));
});
gulp.task('scripts', function() {
return gulp.src('./scripts/client.js')
.pipe(browserify({
transform : ['reactify'],
insertGlobals : true
}))
.on('error', swallowError)
.pipe(rename('bundle.js'))
.pipe(gulp.dest('./client/'));
});
gulp.task('watch', function() {
gulp.watch('./styles/**/*.styl', ['styles']);
gulp.watch('./scripts/**/*.js', ['scripts']);
nodemon({
script: 'server.js',
ext: 'js html',
env: { 'NODE_ENV': 'development' } ,
ignore: ['./scripts/**', './client/bundle.js'],
});
});
gulp.task('start', function() {
server.listen(5000);
console.log("Server running on port: 5000");
});
function swallowError(error) {
console.log(error.toString());
this.emit('end');
}
gulp.task('default', ['styles', 'scripts', 'watch']);
<file_sep>/server.js
var express = require('express');
var swig = require('swig');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var config = require('./config.json');
var app = express();
//Connect to the mongodb server
mongoose.connect(config.database);
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client'));
app.use('/', function(req, res) {
res.render('index.html', {});
});
//Add new controllers here
//Add new models here
if(process.env.NODE_ENV == 'development') {
app.listen(5000);
} else {
module.exports = app;
}
<file_sep>/readme.md
### Boilerplate Express Application
I created this so it's easier for me to get started with new clients. Instead of spending
40-50 minutes setting up the proper express application, I've installed all of these things
to save myself time
You can use it if you'd like, just:
`git clone ...`
`npm install`
`gulp`
and presto.
TODO
- [x] Create boilerplate repository
- [ ] Create Repository for reusable react components
|
10adaeb7e946ab0cc7fd179ff15d185af21fa81c
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
JosephShering/bp
|
8221091dc1ab5392e0989916abe014825d4cd815
|
c177df57848e2cf0e013680bd56f5cb7591b4ea8
|
refs/heads/master
|
<repo_name>kinansha/TriviaGame<file_sep>/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Added link to the jQuery Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Link to external javaScript -->
<script src="assets/javascript/app.js" type="text/javascript"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>"
crossorigin="anonymous" />
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Cinzel" rel="stylesheet" />
<!-- Link to external CSS -->
<link rel="stylesheet" href="assets/css/style.css" />
<title>Trivia Game</title>
</head>
<body>
<div class="container">
<br /><br />
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10 trivBox">
<br />
<h1 class="trivBoxHead">Fùtbol Trivia</h1>
<br /><br />
<button id="startGame" class="btn btn-primary btn-lg btn-block" type="submit">
Start
</button>
<div class="hideGame">
<div id="visibleGame">
<div id="timer">Time Remaining: 60</div>
<br />
<p>
Which of these players has never played for Manchester United?
</p>
<form>
<input type="radio" name="answer" value="wrong" /> <NAME>
<br />
<input type="radio" name="answer" value="right" id="correct1" />
<NAME> <br />
<input type="radio" name="answer" value="wrong" /> <NAME><br />
<input type="radio" name="answer" value="wrong" /> <NAME><br />
</form>
<br />
<p>
Which of these teams is not playing in the the EPL in the
2009-2010 season?
</p>
<form>
<input type="radio" name="answer" value="wrong" /> Birmingham
City <br />
<input type="radio" name="answer" value="wrong" /> Burnley FC
<br />
<input type="radio" name="answer" value="wrong" /> Wigan
Athletic <br />
<input type="radio" name="answer" value="right" id="correct2" />
Newcastle United <br />
</form>
<br />
<p>Who won the 1994 FIFA World Cup?</p>
<form>
<input type="radio" name="answer" value="wrong" /> Argentina
<br />
<input type="radio" name="answer" value="right" id="correct3" />
Brazil <br />
<input type="radio" name="answer" value="wrong" /> Germany
<br />
<input type="radio" name="answer" value="wrong" /> France <br />
</form>
<br />
<p>
According to the official FIFA rulebook, how long can a
goalkeeper hold onto the ball for?
</p>
<form>
<input type="radio" name="answer" value="right" id="correct4" />
5 Seconds <br />
<input type="radio" name="answer" value="wrong" /> 3 Seconds
<br />
<input type="radio" name="answer" value="wrong" /> 10 Seconds
<br />
<input type="radio" name="answer" value="wrong" /> 6 Seconds
<br />
</form>
<br />
<p>
Why did the Indian national team withdraw from the FIFA World
Cup competition in 1950?
</p>
<form>
<input type="radio" name="answer" value="wrong" /> As a
political protest <br />
<input type="radio" name="answer" value="wrong" /> Because they
did not have enough players to field a full squad <br />
<input type="radio" name="answer" value="wrong" /> Because
turbans were not allowed. <br />
<input type="radio" name="answer" value="right" id="correct5" />
Because they could not play barefoot <br />
</form>
<br />
<p>In the MLS in what city does the team Chivas USA play?</p>
<form>
<input type="radio" name="answer" value="wrong" /> Buffalo, New
York <br />
<input type="radio" name="answer" value="right" id="correct6" />
Carson, California <br />
<input type="radio" name="answer" value="wrong" /> Baltimore,
Maryland <br />
<input type="radio" name="answer" value="wrong" /> Miami,
Florida <br />
</form>
<br />
<p>
Back in the MLS, who is the all time leading goal scorer in the
league?
</p>
<form>
<input type="radio" name="answer" value="wrong" /> Landon
Donovan <br />
<input type="radio" name="answer" value="wrong" /> Preki <br />
<input type="radio" name="answer" value="wrong" /> <NAME>
<br />
<input type="radio" name="answer" value="right" id="correct7" />
<NAME> <br />
</form>
<br />
<p>
What are the home colors of the FC Barcelona soccer uniform?
</p>
<form>
<input type="radio" name="answer" value="wrong" /> Orange and
White <br />
<input type="radio" name="answer" value="right" id="correct8" />
Blue and Red<br />
<input type="radio" name="answer" value="wrong" /> Black and
White <br />
<input type="radio" name="answer" value="wrong" /> Yellow and
Blue <br />
</form>
<br /><br />
<button id="doneGame" class="btn btn-primary btn-lg btn-block" type="submit">
Done
</button>
</div>
<div id="visibleEndGame">
<h1 class="allDone">All Done!</h1>
<br />
<h1>Correct</h1>
<h2 id="correct"></h2>
<h1>Incorrect</h1>
<h2 id="incorrect"></h2>
</div>
</div>
<br /><br /><br /><br />
</div>
<a class="twitter-timeline" data-width="400" data-height="600" href="https://twitter.com/ChampionsLeague?ref_src=twsrc%5Etfw">Tweets
by ChampionsLeague</a>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<div class="col-md-1"></div>
</div>
<br /><br />
</div>
</body>
</html><file_sep>/assets/javascript/app.js
$(document).ready(function() {
// GLOBAL VARIABLES
// ===========================================================
var showGame = $("#visibleGame");
var showEndGame = $("#visibleEndGame");
var time = 60;
var intervalId;
// COUNTERS
// ===========================================================
var correct = 0;
var incorrect = 0;
// var unanswered = 0;
// BUTTON ACTIONS
// ===========================================================
$("#startGame").on("click", function() {
startGame();
})
$("#doneGame").on("click", function() {
doneGame();
})
// BEGIN GAME
// ===========================================================
function startGame() {
// Transition to questions element
$("#startGame").replaceWith(showGame);
// Start Timer
intervalId = setInterval(function() {
time--;
$("#timer").html("Time Remaining: " + time);
if (time == 0) {
doneGame();
}
}, 1000);
}
// END GAME
// ===========================================================
function doneGame() {
clearInterval(intervalId);
if ($("#correct1").prop("checked")) {
correct++;
} else {
incorrect++;
}
if ($("#correct2").prop("checked")) {
correct++;
} else {
incorrect++;
}
if ($("#correct3").prop("checked")) {
correct++;
} else {
incorrect++;
}
if ($("#correct4").prop("checked")) {
correct++;
} else {
incorrect++;
}
if ($("#correct5").prop("checked")) {
correct++;
} else {
incorrect++;
}
if ($("#correct6").prop("checked")) {
correct++;
} else {
incorrect++;
}
if ($("#correct7").prop("checked")) {
correct++;
} else {
incorrect++;
}
if ($("#correct8").prop("checked")) {
correct++;
} else {
incorrect++;
}
// Transition to correct/incorrect element
$("#visibleGame").replaceWith(showEndGame);
$("#correct").html(correct);
$("#incorrect").html(incorrect);
}
});
|
29c0c701a33b1f8e2d0bf944750fbfe4cdb2a4b9
|
[
"JavaScript",
"HTML"
] | 2 |
HTML
|
kinansha/TriviaGame
|
3ae4be094672069e0663ad92b388b97135217a9f
|
ebcf3ef8d69d3179ec826e476668a597e8b493c5
|
refs/heads/master
|
<repo_name>k4media/K4-Media<file_sep>/NewProject/footer.php
<div id='footer'>
<span> <center> All content © Forum Syd unless otherwise noted.</center></span>
</div><!-- /footer -->
</div><!-- /main-->
<?php wp_footer(); ?>
</body>
</html>
|
e17457a596c3ce59b6addf82062b873272e6b309
|
[
"PHP"
] | 1 |
PHP
|
k4media/K4-Media
|
1b77cb24ae8eb92b810e4f4b5ec8db7067e640fb
|
d78bbb8e9235922a71ad36582f4b6bfed640710b
|
refs/heads/master
|
<file_sep>package me.lihong.limedroid;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class LimeText extends FragmentActivity
implements SaveFileDialogFragment.SaveFileDialogListener{
private static final String TAG = "dialog";
// some state variables
private boolean autoComplete = true;
private boolean creatingFile = false;
private boolean savingFile = false;
private boolean openingFile = false;
private boolean openingError = false;
private boolean openingRecent = false;
private boolean sendingAttachment = false;
private static CharSequence temp_filename = "";
private boolean fromIntent = false;
private boolean openingIntent = false;
private Intent newIntent = null;
private boolean fromSearch = false;
private String queryString = "";
private CharSequence errorFname = "File";
private boolean errorSaving = false;
private int fileformat;
// some global variables
protected static EditText text = null;
protected static TextView title = null;
protected CharSequence filename = "";
protected long lastModified = 0;
protected boolean untitled = true;
// file format ids
private final static int FILEFORMAT_NL = 1;
private final static int FILEFORMAT_CR = 2;
private final static int FILEFORMAT_CRNL = 3;
// dialog ids
private final static int DIALOG_SAVE_FILE = 1;
private final static int DIALOG_OPEN_FILE = 2;
private final static int DIALOG_SHOULD_SAVE = 3;
private final static int DIALOG_OVERWRITE = 4;
private final static int DIALOG_SAVE_ERROR = 5;
private final static int DIALOG_SAVE_ERROR_PERMISSIONS = 6;
private final static int DIALOG_SAVE_ERROR_SDCARD = 7;
private final static int DIALOG_READ_ERROR = 8;
private final static int DIALOG_NOTFOUND_ERROR = 9;
private final static int DIALOG_SHOULD_SAVE_INTENT = 13;
private final static int DIALOG_MODIFIED = 14;
private final static int DIALOG_SAVE_FILE_AUTOCOMPLETE = 10;
private final static int DIALOG_OPEN_FILE_AUTOCOMPLETE = 11;
private final static int DIALOG_RECENT_FILE_DIALOG = 12;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lime_text);
//update optioons
updateOptions();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_lime_text, menu);
return true;
}
// @Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.save:
showSaveDialog();
return true;
case R.id.save_as:
saveAs();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void showSaveDialog(){
DialogFragment df = new SaveFileDialogFragment();
df.show(getSupportFragmentManager(), TAG);
}
/****************************************************************
* save(fname)
* What to do when saving note */
public void save(CharSequence fname)
{
errorSaving = false;
// actually save the file here
try {
File f = new File(fname.toString());
if ( (f.exists() && !f.canWrite()) || (!f.exists() && !f.getParentFile().canWrite()))
{
creatingFile = false;
openingFile = false;
errorSaving = true;
if (fname.toString().indexOf("/sdcard/") == 0) {
}else{
//showDialog(DIALOG_SAVE_ERROR_PERMISSIONS);
}
text.requestFocus();
f = null;
return;
}
f = null; // hopefully this gets garbage collected
// Create file
FileWriter fstream = new FileWriter(fname.toString());
BufferedWriter out = new BufferedWriter(fstream);
if (fileformat == FILEFORMAT_CR)
{
out.write(text.getText().toString().replace("\n", "\r"));
} else if (fileformat == FILEFORMAT_CRNL) {
out.write(text.getText().toString().replace("\n", "\r\n"));
} else {
out.write(text.getText().toString());
}
out.close();
// give a nice little message
Toast.makeText(this, R.string.onSaveMessage, Toast.LENGTH_SHORT).show();
// the filename is the new title
title.setText(fname);
filename = fname;
untitled = false;
lastModified = (new File(filename.toString())).lastModified();
temp_filename = "";
//addRecentFile(fname);
} catch (Exception e) { //Catch exception if any
creatingFile = false;
openingFile = false;
if (fname.toString().indexOf("/sdcard/") == 0) {
} else {
}
errorSaving = true;
}
text.requestFocus();
} // end saveNote()
private boolean saveAs() {
return true;
}
/****************************************************************
* updateOptions()
* start options app
**/
protected void updateOptions()
{
boolean value;
// load the preferences
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
autoComplete = sharedPref.getBoolean("autocomplete", false);
/********************************
* Auto correct and auto case */
boolean autocorrect = sharedPref.getBoolean("autocorrect", false);
boolean autocase = sharedPref.getBoolean("autocase", false);
/*
//TODO: need to seperate each layout, now just use edit instead
if (autocorrect && autocase)
{
setContentView(R.layout.edit_autotext_autocase);
} else if (autocorrect) {
setContentView(R.layout.edit_autotext);
} else if (autocase) {
setContentView(R.layout.edit_autocase);
} else {
setContentView(R.layout.edit);
}
*/
setContentView(R.layout.activity_lime_text);
text = (EditText) findViewById(R.id.file_content);
title = (TextView) findViewById(R.id.file_title);
text.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence one, int a, int b, int c) {
// put a little star in the title if the file is changed
if (!isTextChanged())
{
CharSequence temp = title.getText();
title.setText("* " + temp);
}
}
// complete the interface
public void afterTextChanged(Editable s) { }
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
});
/********************************
* links clickable */
boolean linksclickable = sharedPref.getBoolean("linksclickable", false);
if (linksclickable)
text.setAutoLinkMask(Linkify.ALL);
else
text.setAutoLinkMask(0);
/********************************
* show/hide filename */
value = sharedPref.getBoolean("hidefilename", false);
if (value)
title.setVisibility(View.GONE);
else
title.setVisibility(View.VISIBLE);
/********************************
* line wrap */
value = sharedPref.getBoolean("linewrap", true);
text.setHorizontallyScrolling(!value);
// setup the scroll view correctly
ScrollView scroll = (ScrollView) findViewById(R.id.scroll);
if (scroll != null)
{
scroll.setFillViewport(true);
scroll.setHorizontalScrollBarEnabled(!value);
}
/********************************
* font face */
String font = sharedPref.getString("font", "Monospace");
if (font.equals("Serif"))
text.setTypeface(Typeface.SERIF);
else if (font.equals("Sans Serif"))
text.setTypeface(Typeface.SANS_SERIF);
else
text.setTypeface(Typeface.MONOSPACE);
/********************************
* font size */
String fontsize = sharedPref.getString("fontsize", "Medium");
if (fontsize.equals("Extra Small"))
text.setTextSize(12.0f);
else if (fontsize.equals("Small"))
text.setTextSize(16.0f);
else if (fontsize.equals("Medium"))
text.setTextSize(20.0f);
else if (fontsize.equals("Large"))
text.setTextSize(24.0f);
else if (fontsize.equals("Huge"))
text.setTextSize(28.0f);
else
text.setTextSize(20.0f);
/********************************
* Colors */
int bgcolor = sharedPref.getInt("bgcolor", 0xFF000000);
text.setBackgroundColor(bgcolor);
int fontcolor = sharedPref.getInt("fontcolor", 0xFFCCCCCC);
text.setTextColor(fontcolor);
title.setTextColor(bgcolor);
title.setBackgroundColor(fontcolor);
text.setLinksClickable(true);
} // updateOptions()
public static boolean isTextChanged() // checks if the text has been changed
{
CharSequence temp = title.getText();
try { // was getting error on the developer site, so added this to "catch" it
if (temp.charAt(0) == '*')
{
return true;
}
} catch (Exception e) {
return false;
}
return false;
} // end isTextChanged()
@Override
public void onDialogPositiveClick(DialogFragment dialog) {
TextView v = (TextView)dialog.getView().findViewById(R.id.filename_view);
save(v.getText().toString());
}
@Override
public void onDialogNegtiveClick(DialogFragment dialog) {
}
}
<file_sep>limedroid
=========
most handy editor on Android
|
f529973639aec50d973c0d6d3b5d37f77dc148a8
|
[
"Markdown",
"Java"
] | 2 |
Java
|
qiulihong/LimeText
|
90377aaa66a17323287e48f6b5c438923ee7e076
|
92081e096dac36c7c8f0bdffaacb89452f0bfff4
|
refs/heads/master
|
<file_sep># Firestarter - A PyroCMS Base Theme
Base PyroCMS theme using Laravel Mix for a modern frontend development.
## Stack
* Bulma 0.4
* Vue 2.2
* jQuery 3.2
* Webpack using Laravel Mix
## Development
```shell
$ npm install
$ npm run dev // build for development
$ npm run watch // watches and builds dev automatically
$ npm run production // build for production
```
Refer to the Laravel Mix documentation for more information.
Tested on PyroCMS 3.3.
<file_sep><?php namespace Turnleft\FirestarterTheme;
use Anomaly\Streams\Platform\Addon\Theme\Theme;
class FirestarterTheme extends Theme
{
//
}
<file_sep><?php
return [
// General
'title' => 'Firestarter',
'name' => 'Firestarter Theme',
'description' => 'A PyroCMS Base Theme using Laravel Mix',
'copyright_notice' => 'All rights reserved.',
// Navigation
'home' => 'Home',
'posts' => 'Posts'
];
<file_sep>const { mix } = require('laravel-mix');
mix.disableNotifications();
mix.setPublicPath('resources/build');
mix.js('resources/js/app.js', 'assets/js')
.sass('resources/sass/app.scss', 'assets/css');
<file_sep><?php
namespace Turnleft\FirestarterTheme\Test\Feature;
class FirestarterThemeTest extends \TestCase
{
public function testHome()
{
// $this->visit('/');
}
}
|
143add9653d36e878bf6df60fce22cbc418c135b
|
[
"Markdown",
"JavaScript",
"PHP"
] | 5 |
Markdown
|
venstresving/firestarter-theme
|
b9f347b2d2da677cced54cde16031ddbac342af9
|
6fb5adf57cd1d219659835789c312ccffd800497
|
refs/heads/master
|
<file_sep><?php
namespace Integration\CommonOrders;
use Integration\CommonOrder;
use Integration\CommonOrder\CommonOrderStd;
use Integration\CommonOrders;
use PDO;
use Traversable;
/**
* Список заказов, находящихся в работе
*
* Список заказов, для которых необходимо обновлять статусы
*
* @author SergeChepikov
*/
class CommonOrdersInProgress implements CommonOrders
{
private $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
/**
* Список заказов
*
* @return Traversable|CommonOrder[]
*/
public function getIterator(): Traversable
{
$pkgs = $this->db->query("
SELECT td_id, gp_status, td_status_id, td_status_name
FROM orders
WHERE (gp_status NOT IN ('completed', 'returned', 'partly-completed', 'awaiting_return')
OR gp_status IS NULL) AND td_status_id NOT IN (12,20,22,17,19,18,16)
");
foreach ($pkgs as $pkg) {
yield new CommonOrderStd($pkg['td_id'], $this->db);
}
}
}
<file_sep>-- Adminer 4.7.1 MySQL dump
SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders`
(
`td_id` int(11) NOT NULL COMMENT 'Идентификатор в TD',
`sku` varchar(100) NOT NULL COMMENT 'Номер заказа',
`serv` varchar(100) NOT NULL DEFAULT 'выдача' COMMENT 'Услуга',
`gp_status` varchar(100) DEFAULT NULL COMMENT 'Статус в Главпункт',
`td_status_id` int(11) NOT NULL COMMENT 'Идентификатор статус ТД',
`td_status_name` varchar(255) NOT NULL COMMENT 'Название статуса ТД',
`shipment_id` int(11) NOT NULL COMMENT 'Номер отправки',
`return_shipment_id` int(11) DEFAULT NULL COMMENT 'Номер возвратной отправки',
`barcode` varchar(100) NOT NULL COMMENT 'Штрих-код заказа',
`price` float NOT NULL COMMENT 'Цена к оплате клиентом',
`td_status` int(11) DEFAULT NULL COMMENT '!deprecated Статус в ГП',
`payment_type` varchar(100) DEFAULT NULL COMMENT 'Тип оплаты',
`create_date` datetime DEFAULT NULL COMMENT 'Дата создания',
`modified_date` datetime DEFAULT NULL ON UPDATE current_timestamp() COMMENT 'Дата обновления',
`pkg_partial` varchar(100) DEFAULT NULL COMMENT 'sku заказа, при частичной выдаче',
`client_delivery_price` float NOT NULL DEFAULT 0 COMMENT 'Цена доставки для клиента',
`weight` float NOT NULL DEFAULT 0 COMMENT 'Вес (в кг)',
`buyer_fio` varchar(255) NOT NULL COMMENT 'Имя получателя',
`buyer_phone` varchar(255) NOT NULL COMMENT 'Телефон получателя',
`buyer_address` varchar(255) NOT NULL COMMENT 'Адрес получателя',
`delivery_date` date NOT NULL COMMENT 'Дата доставки',
`comment` varchar(255) NOT NULL COMMENT 'Комментарий',
`dst_punkt_id` varchar(255) NOT NULL COMMENT 'Пункт выдачи',
`items_count` varchar(255) NOT NULL COMMENT 'Кол-во мест',
`partial_giveout_enabled` tinyint(1) NOT NULL COMMENT 'Доступна ли частичная выдача',
`can_open_box` tinyint(1) NOT NULL COMMENT 'Можно ли открывать до оплаты',
UNIQUE KEY `td_id` (`td_id`),
KEY `shipment_id` (`shipment_id`),
KEY `return_shipment_id` (`return_shipment_id`),
CONSTRAINT `orders_ibfk_4` FOREIGN KEY (`shipment_id`) REFERENCES `shipments` (`id`) ON DELETE CASCADE
) ENGINE = InnoDB
DEFAULT CHARSET = utf8 COMMENT ='Заказы';
DROP TABLE IF EXISTS `orders_log`;
CREATE TABLE `orders_log`
(
`order_id` int(11) NOT NULL COMMENT 'Идентификатор заказа в TD',
`status` varchar(100) NOT NULL COMMENT 'Статус заказа',
`date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE current_timestamp() COMMENT 'Дата установления заказа',
KEY `order_id` (`order_id`),
CONSTRAINT `orders_log_ibfk_4` FOREIGN KEY (`order_id`) REFERENCES `orders` (`td_id`) ON DELETE CASCADE
) ENGINE = InnoDB
DEFAULT CHARSET = utf8 COMMENT ='Изменение статусов заказа';
DROP TABLE IF EXISTS `order_part`;
CREATE TABLE `order_part`
(
`order_id` int(11) NOT NULL COMMENT 'Идентификатор заказа',
`id` int(11) NOT NULL COMMENT 'Идентификатор в ТД',
`td_status_id` int(11) NOT NULL COMMENT 'ИД статуса в ТД',
`td_status_name` varchar(255) NOT NULL COMMENT 'Название статуса в ТД',
`name` varchar(255) NOT NULL COMMENT 'Имя товара',
`price` float NOT NULL COMMENT 'Цена товара',
`declared_price` float NOT NULL COMMENT 'Объявленная стоимость',
`barcode` varchar(255) NOT NULL COMMENT 'Штрих-код товара',
`num` int(11) NOT NULL COMMENT 'Кол-во',
`returning` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Идёт ли на возврат после частичной выдачи',
`article` varchar(255) NOT NULL COMMENT 'Артикул товара',
`weight` int(11) NOT NULL COMMENT 'Вес товара',
KEY `order_id` (`order_id`),
CONSTRAINT `order_part_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`td_id`) ON DELETE CASCADE
) ENGINE = InnoDB
DEFAULT CHARSET = utf8 COMMENT ='Номенклатура заказа';
DROP TABLE IF EXISTS `punkts`;
CREATE TABLE `punkts`
(
`tdId` int(11) NOT NULL COMMENT 'Идентификатор в TD',
`gpId` varchar(100) CHARACTER SET latin1 NOT NULL COMMENT 'Идентификатор в ГП',
`city` varchar(100) CHARACTER SET latin1 NOT NULL COMMENT 'Город нахождения',
`enabled` varchar(100) NOT NULL DEFAULT '1' COMMENT 'Включён пункт или нет',
UNIQUE KEY `id_key` (`tdId`, `gpId`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8 COMMENT ='Пункты выдачи';
DROP TABLE IF EXISTS `shipments`;
CREATE TABLE `shipments`
(
`id` int(11) NOT NULL COMMENT 'Идентификатор в TD',
`punkt_id` varchar(100) NOT NULL COMMENT 'Пункт получения',
`move_id` int(11) DEFAULT NULL COMMENT 'Накладная в ГП',
`created_date` datetime DEFAULT NULL COMMENT 'Дата создания',
`status` enum ('none','created','accepted','partly-accepted','pre-accepted') NOT NULL DEFAULT 'none' COMMENT 'Статус накладной',
UNIQUE KEY `id` (`id`),
UNIQUE KEY `move_id` (`move_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8 COMMENT ='Отправки';
DROP TABLE IF EXISTS `shipments_log`;
CREATE TABLE `shipments_log`
(
`shipment_id` int(11) NOT NULL COMMENT 'Идентификатор поставки',
`status` varchar(255) NOT NULL COMMENT 'Статус',
`date` datetime NOT NULL COMMENT 'Дата установки статуса',
KEY `shipment_id` (`shipment_id`),
CONSTRAINT `shipments_log_ibfk_1` FOREIGN KEY (`shipment_id`) REFERENCES `shipments` (`id`) ON DELETE CASCADE
) ENGINE = InnoDB
DEFAULT CHARSET = utf8 COMMENT ='Изменение статусов поставок';
<file_sep><?php
namespace Integration;
use IteratorAggregate;
use Traversable;
/**
* Поставки от ТопДеливери, находящиеся в БД интеграции
*
* @author SergeChepikov
*/
interface CommonShipments extends IteratorAggregate
{
/**
* @return Traversable|CommonShipment[]
*/
public function getIterator(): Traversable;
}
<file_sep><?php
namespace Integration\CommonCreatedRecord;
use Integration\CommonCreatedRecord;
use Integration\Punkt;
use Integration\Punkt\PunktStd;
use PDO;
use TopDelivery\TDOrder;
/**
* Новый заказ в интеграции
*
* @author SergeChepikov
*/
class CommonCreatedOrder implements CommonCreatedRecord
{
private $order;
private $db;
private $punkt;
private $shipmentId;
public function __construct(TDOrder $order, int $shipmentId, PDO $db, Punkt $punkt = null)
{
$this->order = $order;
$this->db = $db;
$this->shipmentId = $shipmentId;
$this->punkt = function ($id) use ($punkt, $db) {
return $punkt ?? new PunktStd($id, $db);
};
}
/**
* Создать новый заказ в интеграции
*
* @return int идентификатор созданного заказав
*/
public function create(): int
{
$order = $this->order->info();
$data = [
'td_id' => $order['tdId'],
'shipment_id' => $this->shipmentId,
'sku' => $order['sku'],
'barcode' => $order['barcode'],
'price' => $order['price'],
'td_status_id' => $order['tdStatusId'],
'td_status_name' => $order['tdStatusName'],
'client_delivery_price' => $order['client_delivery_price'],
'weight' => $order['weight'],
'buyer_fio' => $order['buyer_fio'],
'buyer_phone' => $order['buyer_phone'],
'comment' => $order['comment'],
'dst_punkt_id' => $this->punkt->call($this, $order['dst_punkt_id'])->gpId(),
'items_count' => $order['items_count'],
'partial_giveout_enabled' => $order['partial_giveout_enabled'],
'can_open_box' => $order['can_open_box']
];
$sql = "INSERT INTO `orders` (`td_id`, `shipment_id`, `sku`, `barcode`, `create_date`, `price`,
`td_status_id`, `td_status_name`, `client_delivery_price`, `weight`, `buyer_fio`, `buyer_phone`,
`comment`, `dst_punkt_id`, `items_count`, `partial_giveout_enabled`, `can_open_box`)
VALUES (:td_id, :shipment_id, :sku, :barcode, NOW(), :price, :td_status_id, :td_status_name,
:client_delivery_price, :weight, :buyer_fio, :buyer_phone, :comment, :dst_punkt_id, :items_count,
:partial_giveout_enabled, :can_open_box)
ON DUPLICATE KEY UPDATE shipment_id=" . $data["shipment_id"] . ", gp_status=NULL," .
" sku=" . $this->db->quote($data['sku']);
$query = $this->db->prepare($sql);
$query->execute($data);
foreach ($order['parts'] as $part) {
$sql = "SELECT * FROM `order_part` WHERE order_id = " . $this->db->quote($order['tdId']) .
" AND id = " . $this->db->quote($part['id']);
$parts = $this->db->query($sql)->fetchAll();
if (count($parts) != 0) {
continue;
}
$data = [
'order_id' => $order['tdId'],
'id' => $part['id'],
'td_status_id' => $part['tdStatusId'],
'td_status_name' => $part['tdStatusName'],
'name' => $part['name'],
'price' => $part['clientPrice'], // к оплате клиентом
'declared_price' => $part['declaredPrice'], // объявленная стоимость
'barcode' => $part['barcode'],
'num' => $part['num'],
'article' => $part['article'],
'weight' => $part['weight']
];
$sql = "INSERT INTO `order_part` (`order_id`, `id`, `td_status_id`, `td_status_name`, `name`,
`price`, `barcode`, `num`, `article`, `weight`, `declared_price`)
VALUES (:order_id, :id, :td_status_id, :td_status_name, :name, :price, :barcode, :num,
:article, :weight, :declared_price);";
$query = $this->db->prepare($sql);
$query->execute($data);
}
return $order['tdId'];
}
}
<file_sep><?php
namespace Integration;
use IteratorAggregate;
use Traversable;
/**
* Список заказов, находящихся в интеграции
*
* @author SergeChepikov
*/
interface CommonOrders extends IteratorAggregate
{
/**
* Список заказов
*
* @return Traversable|CommonOrder[]
*/
public function getIterator(): Traversable;
}
<file_sep><?php
namespace TopDelivery\TDChangeStatus;
use Api\TopDelivery\TopDeliveryApi;
use Exception;
use Integration\CommonOrder;
use Integration\CommonShipment;
use TopDelivery\TDChangeStatus;
/**
* Принятие поставки в системе ТопДеливери
*
* @author SergeChepikov
*/
class TDAcceptShipment implements TDChangeStatus
{
private $shipment;
private $orders;
private $api;
/**
* @param CommonShipment $shipment поставка, которую необходимо принять
* @param CommonOrder[] $orders заказы, которые нужно отметить как принятые
* @param TopDeliveryApi $api
*/
public function __construct(CommonShipment $shipment, array $orders, TopDeliveryApi $api)
{
$this->shipment = $shipment;
$this->orders = $orders;
$this->api = $api;
}
/**
* Выполнить изменение статуса
*/
public function do(): void
{
$shipmentInfo = $this->shipment->info();
// Если отправка имеет статус принятого, тогда ничего менять не нужно
if (in_array($shipmentInfo['status'], ['accepted', 'partly-accepted'])) {
return;
}
if (count($this->orders) === 0) {
throw new Exception("Для принятия поставки {$shipmentInfo['id']} не передан список заказов");
}
$acceptedOrder = [];
foreach ($this->orders as $order) {
$acceptedOrder[] = [
'orderId' => $order->info()['td_id']
];
}
$params = [
'orderIdentity' => $acceptedOrder,
'shipmentId' => $shipmentInfo['id']
];
$this->api->doRequest('saveScanningResults', $params);
}
}
<file_sep><?php
namespace Integration;
/***
* Измененная запись в таблице интеграции
*
* @author SergeChepikov
*/
interface CommonEditedRecord
{
/**
* @param array $params параметры для изменения
*/
public function edit(array $params): void;
}
<file_sep><?php
namespace Integration\CommonEditedStatus;
use Exception;
use Integration\CommonEditedRecord\CommonEditedOrder;
use Integration\CommonEditedStatus;
use Integration\CommonOrder;
use PDO;
/**
* Измененный статус заказа в интеграции
*
* @author SergeChepikov
*/
class CommonEditedOrderStatus implements CommonEditedStatus
{
private $order;
private $editedRecord;
private $db;
public function __construct(CommonOrder $order, PDO $db)
{
$this->editedRecord = new CommonEditedOrder($order, $db);
$this->db = $db;
$this->order = $order;
}
/**
* Изменение статуса
*
* @param string $status
*/
public function edit(string $status): void
{
$validStatuses = [
'not found', 'completed', 'awaiting_return', 'partly-completed', 'returned', 'transfering',
'pre-completed', 'pre-partly-completed', 'waiting', 'none'
];
if (!in_array($status, $validStatuses)) {
throw new Exception("Статус $status не является валидным статусом заказа");
}
if ($status !== $this->order->info()['gp_status']) {
$this->editedRecord->edit(['gp_status' => $status]);
$this->db->query("
INSERT INTO `orders_log` (`order_id`, `status`, `date`)
VALUES (
" . $this->db->quote($this->order->info()['td_id']) . ",
" . $this->db->quote($status) . ",
now()
);
");
}
}
}
<file_sep><?php
// Here you can initialize variables that will be available to your tests
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
// Подмена БД
$GLOBALS['config']['dbname'] = 'tdintegration_functional_tests';
$GLOBALS['config']['dbhost'] = 'dbhost';
$GLOBALS['config']['username'] = 'tdintegration';
$GLOBALS['config']['password'] = '<PASSWORD>';
<file_sep><?php
namespace Integration\CommonShipments;
use Integration\CommonShipment;
use Integration\CommonShipment\CommonShipmentStd;
use Integration\CommonShipments;
use PDO;
use Traversable;
/**
* Получение списка непринятых поставок
*
* @author SergeChepikov
*/
class CommonNotAcceptedShipments implements CommonShipments
{
private $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
/**
* @return Traversable|CommonShipment[]
*/
public function getIterator(): Traversable
{
$pkgs = $this->db->query("
SELECT *
FROM `shipments`
WHERE `status` NOT IN ('accepted','partly-accepted')");
foreach ($pkgs as $pkg) {
yield new CommonShipmentStd($pkg['id'], $this->db);
}
}
}
<file_sep><?php
namespace Integration\CommonShipment;
use Exception;
use Integration\CommonOrder;
use Integration\CommonOrder\CommonOrderStd;
use Integration\CommonShipment;
use PDO;
use Traversable;
/**
* Поставка от ТопДеливери, находящаяся в БД интеграции
*
* @author SergeChepikov
*/
class CommonShipmentStd implements CommonShipment
{
private $id;
private $db;
/**
* @param int $id
* @param PDO $db
*/
public function __construct(int $id, PDO $db)
{
$this->id = $id;
$this->db = $db;
}
/**
* Информация о поставке
*
* @return array
* [
* 'id' => '308789', // Идентификатор отправки в ТД
* 'punkt_id' => 'Sklad-SPB', // Пункт, где принимается отправка
* 'move_id' => '1085760', // Номер накладной в ГП
* 'status' => 'none', // Текущий статус отправки
* ]
*/
public function info(): array
{
$info = $this->db->query("
SELECT *
FROM `shipments`
WHERE `id` = " . $this->db->quote($this->id))->fetch();
if ($info === false) {
throw new Exception("Отправка с идентификатором {$this->id} не найдена.");
}
return $info;
}
/**
* Список заказов в поставке
*
* @return Traversable|CommonOrder[]
*/
public function orders(): Traversable
{
$orders = $this->db->query("
SELECT *
FROM `orders`
WHERE `shipment_id` = " . $this->db->quote($this->id));
foreach ($orders as $order) {
yield new CommonOrderStd($order['td_id'], $this->db);
}
}
}
<file_sep><?php
namespace Integration\Punkt;
use Exception;
use Integration\Punkt;
use PDO;
/**
* Пункт выдачи в таблице punkts
*
* Можем передавать как идентификатор ГП, так и идентификатор TD
*
* @author SergeChepikov
*/
class PunktStd implements Punkt
{
private $id;
private $db;
private $info;
/**
* @param int|string $id идентификатор пункта в ГП или в TD
* @param PDO $db
*/
public function __construct($id, PDO $db)
{
$this->id = $id;
$this->db = $db;
}
public function city(): string
{
return $this->info()['city'];
}
public function gpId(): string
{
return $this->info()['gpId'];
}
public function tdId(): int
{
return $this->info()['tdId'];
}
/**
* Включён пункт или нет
*
* @return bool
*/
public function enabled(): bool
{
return (bool)$this->info()['enabled'];
}
private function info(): array
{
if (!$this->info) {
$this->info = $this->db->query("
SELECT *
FROM `punkts`
WHERE `gpId` LIKE " . $this->db->quote($this->id) . "
OR `tdId` LIKE " . $this->db->quote($this->id)
)->fetch();
if ($this->info === false) {
throw new Exception("Пункт с идентификатором {$this->id} не найден.");
}
}
return $this->info;
}
}
<file_sep><?php
namespace Integration\Punkt;
use Integration\CommonShipment;
use Integration\Punkt;
use PDO;
/**
* Пункт получения по отправке
*
* @author SergeChepikov
*/
class PunktByShipment implements Punkt
{
/** @var Punkt */
private $orig;
public function __construct(CommonShipment $shipment, PDO $db, Punkt $punkt = null)
{
$this->orig = function () use ($shipment, $punkt, $db) {
return $punkt ?? new PunktStd($shipment->info()['punkt_id'], $db);
};
}
/**
* Идентификатор пункта в системе TD
*
* @return int
*/
public function tdId(): int
{
return $this->orig->call($this)->tdId();
}
/**
* Идентификатор пункта в системе ГП
*
* @return string
*/
public function gpId(): string
{
return $this->orig->call($this)->gpId();
}
/**
* Город нахождения пункта
*
* @return string
*/
public function city(): string
{
return $this->orig->call($this)->city();
}
/**
* Включён пункт или нет
*
* @return bool
*/
public function enabled(): bool
{
return $this->orig->call($this)->enabled();
}
}
<file_sep><?php
namespace Integration\CommonCreatedRecord;
use Integration\CommonCreatedRecord;
use Integration\Punkt;
use Integration\Punkt\PunktStd;
use PDO;
use TopDelivery\TDShipment;
/**
* Новая отправка из ТопДеливери в интеграции
*
* @author SergeChepikov
*/
class CommonCreatedShipment implements CommonCreatedRecord
{
private $shipment;
private $db;
private $punkt;
public function __construct(TDShipment $shipment, PDO $db, Punkt $punkt = null)
{
$this->shipment = $shipment;
$this->db = $db;
$this->punkt = function ($tdId) use ($punkt, $db) {
return $punkt ?? new PunktStd($tdId, $db);
};
}
/**
* Создать новую отправку в интеграции
*
* @return int идентификатор созданной отправки
*/
public function create(): int
{
$shipmentInfo = $this->shipment->info();
$data = [
'id' => $shipmentInfo['id'],
'punkt_id' => $this->punkt->call($this, $shipmentInfo['pickupAddressId'])->gpId()
];
$sql = "INSERT INTO `shipments` (`id`, `punkt_id`, `created_date`) VALUES (:id, :punkt_id, NOW())";
$query = $this->db->prepare($sql);
$query->execute($data);
return $shipmentInfo['id'];
}
}
<file_sep><?php
namespace Integration;
/**
* Новая запись в БД интеграции
*
* @author SergeChepikov
*/
interface CommonCreatedRecord
{
/**
* Создать новую запись в БД интеграции
*
* @return int идентификатор созданной записи
*/
public function create(): int;
}
<file_sep><?php
namespace Integration\Logger;
use Integration\Logger;
/**
* Не логировать ("заглушка")
*
* В случает отсутствия необходимости логировать результаты или ошибки, можно использовать данный класс
* вместо других реализаций интерфейса Logger.
*
* @author SergeChepikov
*/
class NotLogging implements Logger
{
/**
* Заносит сообщение в лог.
*
* @param string $message сообщение для логирования
* @param string $path путь для логирования
*/
public function log(string $message, string $path = null): void
{
return;
}
}
<file_sep><?php
namespace Glavpunkt;
/**
* Статус заказа в системе Главпункт
*
* @author SergeChepikov
*/
interface GpOrderStatus
{
/**
* Текущий статус заказа
*
* @return string
*/
public function status(): string;
/**
* Способ оплаты
*
* Метод доступен, если статус заказа completed или partly-completed
*
* @return string
*/
public function paymentType(): string;
/**
* Список выданных частей заказа, при частичной выдаче
*
* @return array
*/
public function parts(): array;
/**
* Сумма, полученная от покупателя за заказ
*
* @return float
*/
public function price(): float;
/**
* Номер возвратного заказа для частичной выдачи
*
* @return string
*/
public function pkgReturnSku(): string;
}
<file_sep><?php
namespace Integration\Logger;
use DateTime;
use Integration\Logger;
/**
* Логирование
*
* @author SergeChepikov
*/
class LoggerStd implements Logger
{
private $path;
/**
* @param string $path путь для логирования
*/
public function __construct(string $path)
{
$this->path = $path;
}
/**
* Заносит сообщение в лог.
*
* @param string $message сообщение для логирования
* @param string $path путь для логирования
*/
public function log(string $message, string $path = null): void
{
$date = (new DateTime)->format('d.m.Y H:i:s');
$logEntry = $date . ' ' . $message . "\n";
$logPath = 'logs/' . ($path ?? $this->path);
error_log($logEntry, 3, $logPath);
}
}
<file_sep><?php
namespace Integration;
/**
* Логирование
*
* @author SergeChepikov
*/
interface Logger
{
/**
* Заносит сообщение в лог.
*
* @param string $message сообщение для логирования
* @param string $path путь для логирование ошибок в другой журнал, нежели было задано изначально в конструкторе
*/
public function log(string $message, string $path = null): void;
}
<file_sep><?php
namespace Integration\CommonEditedStatus;
use Exception;
use Integration\CommonEditedRecord\CommonEditedShipment;
use Integration\CommonEditedStatus;
use Integration\CommonShipment;
use PDO;
/**
* Измененный статус отправки в интеграции
*
* @author SergeChepikov
*/
class CommonEditedShipmentStatus implements CommonEditedStatus
{
private $shipment;
private $editedRecord;
private $db;
public function __construct(CommonShipment $shipment, PDO $db)
{
$this->editedRecord = new CommonEditedShipment($shipment, $db);
$this->db = $db;
$this->shipment = $shipment;
}
/**
* Изменение статуса
*
* @param string $status
*/
public function edit(string $status): void
{
$validStatuses = ['none', 'created', 'accepted', 'partly-accepted', 'pre-accepted'];
if (!in_array($status, $validStatuses)) {
throw new Exception("Статус $status не является валидным статусом отправки");
}
$this->editedRecord->edit(['status' => $status]);
$this->db->query("
INSERT INTO `shipments_log` (`shipment_id`, `status`, `date`)
VALUES (
" . $this->db->quote($this->shipment->info()['id']) . ",
" . $this->db->quote($status) . ",
now()
);
");
}
}
<file_sep><?php
namespace TopDelivery\TDChangeStatus;
use Glavpunkt\GpOrderStatus;
use TopDelivery\TDChangeStatus;
use TopDelivery\TDOrder;
/**
* Сообщение об ошибке
*
* В случае возникновения рассинхронизации статусов, необходимо уведомить контактные лица в Главпункт и в ТопДеливери
*
* @author SergeChepikov
*/
class TDErrorStatusReport implements TDChangeStatus
{
private $orig;
private $mailTo;
private $gpOrderStatus;
private $tdOrder;
public function __construct(TDChangeStatus $orig, string $mailTo, GpOrderStatus $gpOrderStatus, TDOrder $tdOrder)
{
$this->orig = $orig;
$this->mailTo = $mailTo;
$this->gpOrderStatus = $gpOrderStatus;
$this->tdOrder = $tdOrder;
}
/**
* Выполнить изменение статуса
*/
public function do(): void
{
// @todo #35 описать ситуации, которые могут произойти в результате рассинхрона статусов
$this->orig->do();
}
}
<file_sep><?php
namespace Api\TopDelivery\TopDeliveryApi;
use Api\TopDelivery\TopDeliveryApi;
use Exception;
use stdClass;
/**
* Фейковый АПИ Топделивери
*
* Возвращает, то что мы просим и проверяет правильность запроса к нему
*
* @author <NAME>.
*/
class TopDeliveryFakeApi implements TopDeliveryApi
{
private $params;
private $answers;
public function __construct(array $params, array $answers)
{
$this->params = $params;
$this->answers = $answers;
}
/**
* Выполнение запроса по API
*
* @param string $method
* @param array $params
* @return stdClass
*/
public function doRequest(string $method, array $params = []): stdClass
{
return (object)$this->fakeAnswer($method, $params);
}
private function fakeAnswer(string $method, array $params = []): array
{
if (!isset($this->answers[$method])) {
throw new Exception("В TopDeliveryApi не определён вывод для метода $method");
}
if (testLibCompareArray($this->params[$method], $params)) {
return $this->answers[$method];
}
throw new Exception("Ошибка сравнения массивов.");
}
}
<file_sep><?php
namespace Integration;
use Traversable;
/**
* Поставка от ТопДеливери, находящаяся в БД интеграции
*
* @author SergeChepikov
*/
interface CommonShipment
{
/**
* Информация о поставке
*
* @return array
* [
* 'id' => '308789', // Идентификатор отправки в ТД
* 'punkt_id' => 'Sklad-SPB', // Пункт, где принимается отправка
* 'move_id' => '1085760', // Номер накладной в ГП
* 'status' => 'none', // Текущий статус отправки
* ]
*/
public function info(): array;
/**
* Список заказов в поставке
*
* @return Traversable|CommonOrder[]
*/
public function orders(): Traversable;
}
<file_sep># Оглавление
1. [Подключение библиотеки](#install)
2. [Описание](#description)
3. [Структура](#structure)
## Подключение библиотеки <a name="install"></a>
Для подключения библиотеки необходимо прописать в composer.json:
```
"require": {
"glavdev/tdlib": "master@dev"
},
"repositories": [
{
"type": "vcs",
"url": "<EMAIL>:glavdev/TDLib"
}
],
```
После необходимо выполнить команду
```
composer update
```
## Описание <a name="description"></a>
Библиотека предназначенная для создания интеграций, которые взаимодействуют с системами TopDelivery и Главпункт.
Задачами таких интеграций является получение информации об актуальных отправках из ТопДеливери и создание накладных
по этим отправкам в системе Главпункт. Интеграция может получать информацию об актуальных статусах заказов, как от
Главпункт, так и от ТопДеливери. Отмечает принятые поставки в системе ТопДеливери, а также выданные заказы, как
полностью выданные, так и частично.
## Структура <a name="structure"></a>
* Api - классы отвечающие за взаимодействие с API двух сервисов.
* Integration - классы отвечающие за процессы происходящие внутри интеграции
* TopDelivery - классы отвечающие за взаимодействие с системой TopDelivery<file_sep>-- Adminer 4.7.1 MySQL dump
SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
INSERT INTO `punkts` (`tdId`, `gpId`, `city`) VALUES
(0, 'Sklad-SPB', 'SPB'),
(1, 'Sklad-MSK', 'MSK'),
(727, 'Avtovo-S75', 'SPB'),
(728, 'Avtovo-MK1', 'SPB'),
(729, 'Akademicheskaya-N17k2', 'SPB'),
(730, 'SB-BaltiiskayaJemchujina-AT5', 'SPB'),
(731, 'Lyzhnyj-L3', 'SPB'),
(732, 'StarayaDerevnya-S118', 'SPB'),
(733, 'SB-Blagodatnaya-B50', 'SPB'),
(734, 'Bolshevikov-P4k1', 'SPB'),
(735, 'Vo-6l25', 'SPB'),
(736, 'Veteranov-N67k2', 'SPB'),
(737, 'Veteranov-V78k2', 'SPB'),
(738, 'Gavanskaya-G42-guk', 'SPB'),
(739, 'Gorkovskaya-K31', 'SPB'),
(740, 'Grazhdanskiy-P87', 'SPB'),
(742, 'Deviatkino-P3k1', 'SPB'),
(743, 'Dybenko-D27', 'SPB'),
(744, 'Elizarovskaya-N3', 'SPB'),
(745, 'Zvezdnaya-Z8', 'SPB'),
(746, 'Zvezdnaya-L70', 'SPB'),
(748, 'Kirovskiyzavod-St39-guk', 'SPB'),
(750, 'Komendantskiy-K9k1', 'SPB'),
(751, 'Kotina-K2-guk', 'SPB'),
(752, 'Kupchino-B5k0', 'SPB'),
(753, 'Kupchino-B94K41', 'SPB'),
(755, 'Ladozhskaya-E4k3', 'SPB'),
(756, 'Levashovskiy-L12', 'SPB'),
(757, 'Leninskiy-T17k2-ID', 'SPB'),
(759, 'Lomonosovskaya-P6', 'SPB'),
(760, 'Mezhdunarodnaia-B6k1', 'SPB'),
(761, 'Moskovskaya-A16', 'SPB'),
(762, 'SB-Narvskaya-S6LA', 'SPB'),
(763, 'Rabfakovskiy-R18', 'SPB'),
(764, 'Ozerki-E113k1', 'SPB'),
(765, 'OhtaMoll-B3', 'SPB'),
(766, 'ParkPobedy-M173', 'SPB'),
(767, 'Parnas-MD25k2-guk', 'SPB'),
(768, 'Matveeva-M5', 'SPB'),
(769, 'Petergofskoe-PSH45', 'SPB'),
(770, 'Petrogradskaya-K42b', 'SPB'),
(771, 'Pionerskaya-K15k2', 'SPB'),
(772, 'PLenina-K16', 'SPB'),
(773, 'Slavy-S4', 'SPB'),
(774, 'Primorskaya-O27', 'SPB'),
(775, 'Prosveshenia-E133', 'SPB'),
(776, 'Kulturi-P51', 'SPB'),
(777, 'Ribackoe-K24k1-guk', 'SPB'),
(778, 'Sennaya-M3', 'SPB'),
(779, 'Sklad-SPB', 'SPB'),
(780, 'Sofiyskaya-S33k1', 'SPB'),
(781, 'StarayaDerevnia-T2k1', 'SPB'),
(782, 'Tehnologicheskiy-Izm-12-guk', 'SPB'),
(783, 'SB-Udelnaya-S4LB', 'SPB'),
(784, 'Repischeva-13k1', 'SPB'),
(785, 'Moiseenko-25-24', 'SPB'),
(786, 'Germana-PG22', 'SPB'),
(787, 'MZaharova-MZ21', 'SPB'),
(788, 'Frunzenskaya-M65B', 'SPB'),
(789, 'Chernayarechka-S1', 'SPB'),
(790, 'Chernishevskaya-F25', 'SPB'),
(791, 'Revolucii-41-39', 'SPB'),
(792, 'Elektrosila-R12k2', 'SPB'),
(792, 'Energetikov-E64', 'SPB'),
(793, 'Energetikov-E64', 'SPB'),
(821, 'Sredneohtinskiy-S51-13', 'SPB'),
(822, 'Svetlanovskiy-S40', 'SPB'),
(830, 'SB-Avtozavodskaya-LS19', 'MSK'),
(831, 'Msk-DP-AkademikaYangelya-R3k1A', 'MSK'),
(833, 'Msk-DP-Bagrationovskaya-B8', 'MSK'),
(838, 'Msk-Barrikadnaya-K2', 'MSK'),
(839, 'Msk-DP-Belorusskaya-TZ3', 'MSK'),
(840, 'Msk-DP-Belyaevo-P96', 'MSK'),
(841, 'Msk-Bibirevo-B102', 'MSK'),
(842, 'DP-Bratislavskaya-B14', 'MSK'),
(843, 'Msk-DP-AdmiralaUshakova-Cp8', 'MSK'),
(844, 'Msk-DP-BulvarRokossovskogo-MR6', 'MSK'),
(845, 'Msk-DP-BuninskayaAlleya-AL63k1', 'MSK'),
(846, 'Msk-DP-VDNH-Z10c1', 'MSK'),
(847, 'DP-Veshnyakovskaya-V12g', 'MSK'),
(849, 'Msk-Voikovskaya-S1s2', 'MSK'),
(850, 'Msk-Vyhino-R991', 'MSK'),
(851, 'Msk-Dmitrovskaya-T23', 'MSK'),
(852, 'Msk-DP-Dubrovka-S13c2', 'MSK'),
(854, 'DP-Msk-Kahovskaya-A18', 'MSK'),
(855, 'Msk-DP-Kievskaya-B2', 'MSK'),
(856, 'Msk-DP-Kolomenskaya-A26', 'MSK'),
(858, 'Msk-Krilatskoe-Os12-1k1', 'MSK'),
(859, 'Msk-DP-Kuzminki-V117k2', 'MSK'),
(860, 'Msk-Marksistskaya-M3', 'MSK'),
(862, 'DP-Msk-Medvedkovo-Z10', 'MSK'),
(863, 'Msk-Mitino-D34', 'MSK'),
(864, 'Msk-DP-Mozhaiskoe-M30', 'MSK'),
(865, 'Msk-DP-Molodejnaya-T13k2', 'MSK'),
(866, 'Msk-Mytnaya-M48', 'MSK'),
(867, 'SB-Nagatinskaya-V26s5', 'MSK'),
(868, 'DP-Novogireevo-Z62a', 'MSK'),
(869, 'Msk-Novokosino-N5', 'MSK'),
(870, 'Msk-Novyecheremushki-P6466', 'MSK'),
(871, 'DP-Ozernaya-O29', 'MSK'),
(872, 'Msk-DP-Orehovo-S43k2', 'MSK'),
(873, 'Msk-Paveleckaya-K71', 'MSK'),
(874, 'Msk-DP-ParkKulturi-Z16', 'MSK'),
(879, 'Msk-Vernadskogo-V29', 'MSK'),
(880, 'Msk-DP-Prajskaya-K22G', 'MSK'),
(881, 'DP-Msk-Prazhskaya-K15', 'MSK'),
(882, 'Msk-DP-PreobrazhenskayaPl-PV1c1', 'MSK'),
(883, 'Msk-Mira-M40', 'MSK'),
(884, 'Msk-DP-Pushkinskaya-N8c2', 'MSK'),
(885, 'Msk-Rechnoyvokzal-F131', 'MSK'),
(886, 'Rizhskaya-M77', 'MSK'),
(887, 'Msk-SlavyanskiyBulvar-GK14k1a', 'MSK'),
(888, 'Msk-DP-Sokolniki-S4A', 'MSK'),
(890, 'Msk-Shodnenskaya-G81', 'MSK'),
(891, 'Msk-Taganskaja-N21-7c3', 'MSK'),
(892, 'Msk-DP-TeplyiStan-P146k1', 'MSK'),
(894, 'Msk-Tushinskaya-T17', 'MSK'),
(897, 'Msk-Frunzenskaya-K30', 'MSK'),
(898, 'Msk-DP-Hovrino-D36k4', 'MSK'),
(899, 'Msk-Tsaritsyno-L10', 'MSK'),
(900, 'DP-Chertanovskaya-B16', 'MSK'),
(901, 'Msk-Dp-Chkalovskaya-ZV36', 'MSK'),
(902, 'Msk-Shchelkovskaya-Shch68', 'MSK'),
(903, 'Msk-DP-Yugo-Zapadnaya-26B14', 'MSK'),
(905, 'Msk-Yasenevo-N7', 'MSK'),
(906, 'Msk-DP-RyazanskiiPr-N25', 'MSK'),
(920, 'Msk-DP-Begovaya-R4', 'MSK'),
(922, 'Msk-DP-ParkPobediP11c1', 'MSK'),
(923, 'Msk-DP-Kashirskaya-K24c7', 'MSK');
-- 2019-10-29 14:54:49<file_sep><?php
namespace Integration\CommonOrders;
use Integration\CommonOrder;
use Integration\CommonOrder\CommonOrderStd;
use Integration\CommonOrders;
use Integration\CommonShipment;
use PDO;
use Traversable;
/**
* Список заказов в интеграции, полученных по отправке ТД, в которой они находятся.
*
* @author SergeChepikov
*/
class CommonOrdersByShipment implements CommonOrders
{
private $shipment;
private $db;
public function __construct(CommonShipment $shipment, PDO $db)
{
$this->shipment = $shipment;
$this->db = $db;
}
/**
* Список заказов
*
* @return Traversable|CommonOrder[]
*/
public function getIterator(): Traversable
{
$orders = $this->db->query("
SELECT *
FROM `orders`
WHERE `shipment_id` = " . $this->db->quote($this->shipment->info()['id']));
foreach ($orders as $order) {
yield new CommonOrderStd($order['td_id'], $this->db);
}
}
}
<file_sep><?php
namespace TopDelivery;
/**
* Заказ в системе ТД
*
* @author SergeChepikov
*/
interface TDOrder
{
/**
* Информация о заказе
*
* @return array
* [
* [tdId] => 1944825
* [serv] => выдача
* [sku] => 219592
* [price] => 450
* [primerka] => 0
* [client_delivery_price] => 160
* [weight] => 59
* [barcode] => 1116*219592
* [is_prepaid] =>
* [buyer_fio] => Лариса
* [buyer_phone] => 89167766437
* [comment] =>
* [dst_punkt_id] => 507
* [items_count] => 1
* [partial_giveout_enabled] => 1
* [parts] => [
* [0] => [
* [name] => Сетевое зарядное устройство для Sony Ericsson Z530i
* [price] => 290
* [barcode] =>
* [num] => 1
* ]
* ]
* ]
*/
public function info(): array;
}
<file_sep><?php
namespace Codeception;
use Api\TopDelivery\TopDeliveryApi\TopDeliveryFakeApi;
use Codeception\Test\Unit;
use FunctionalTester;
use Integration\CommonCreatedRecord\CommonCreatedOrder;
use Integration\CommonCreatedRecord\CommonCreatedShipment;
use Integration\Punkt\PunktStd;
use TopDelivery\TDOrder\TDOrderStd;
use TopDelivery\TDShipment\TDShipmentStd;
/**
* Создание заказа
*
* @author <NAME>.
*/
class CommonCreatedOrderTest extends Unit
{
/**
* @var FunctionalTester
*/
protected $tester;
public function testCreate()
{
$pdo = getTestDB();
// Параметры для отправки API
$param['order']['orderId'] = 1488;
// order parts
$items = (object)[
'itemId' => 6699698,
'name' => 'Товар 1',
'article' => 'RU19OFZ11 - 112',
'count' => 1,
'declaredPrice' => 380,
'clientPrice' => 380,
'weight' => 1,
'push' => 1,
'status' => (object)[
'id' => 1,
'name' => 'Не обработан'
]
];
// Ожидаемый ответ
$answer['ordersInfo'] = (object)['orderInfo' => (object)[
'orderIdentity' => (object)['orderId' => 1488, 'webshopNumber' => 14556, 'barcode' => 'barcode'],
'status' => (object)['id' => 11, 'name' => 'namestatus'],
'clientFullCost' => 1500,
'clientDeliveryCost' => 150,
'deliveryWeight' => (object)['weight' => 1],
'clientInfo' => (object)['fio' => 'тест тестов', 'phone' => '79502210575', 'comment' => 'comment'],
'pickupAddress' => (object)['id' => 'Avtovo-S75'],
'services' => (object)['places' => 1, 'forChoise' => '0', 'notOpen' => 0],
'events' => [],
'items' => $items,
]];
// Отправка
$shipment = (object) [
'shipmentId' => 3,
'pickupAddress' => (object)['id' => 1562],
'status' => (object)['id' => 1488, 'name' => 'name']
];
// Новая отправка для того же заказа
$shipment2 = (object) [
'shipmentId' => 4,
'pickupAddress' => (object)['id' => 1562],
'status' => (object)['id' => 1488, 'name' => 'name']
];
$punkt = new PunktStd('Avtovo-S75', $pdo);
$tdOrder = new TDOrderStd(1488, new TopDeliveryFakeApi(['getOrdersInfo' => $param], ['getOrdersInfo' => $answer]));
// Создаем отправку
(new CommonCreatedShipment( new TDShipmentStd($shipment), $pdo, $punkt))->create();
// Создаем заказ
$tdId = (new CommonCreatedOrder($tdOrder, 3, $pdo, $punkt))->create();
// Проверяем, что order.shipment_id = shipment.id
$shipId = $this->tester->grabColumnFromDatabase('orders', 'shipment_id', ['td_id' => $tdId])[0];
$this->tester->assertEquals($shipId, 3);
// Создаем такой же заказ, но с новой отправкой
(new CommonCreatedShipment(new TDShipmentStd($shipment2), $pdo, $punkt))->create();
$tdId = (new CommonCreatedOrder($tdOrder, 4, $pdo, $punkt))->create();
// Проверяем, чтоб order.shipment_id обновилость на новую поставку
$shipId = $this->tester->grabColumnFromDatabase('orders', 'shipment_id', ['td_id' => $tdId])[0];
$this->tester->assertEquals($shipId, 4);
}
}
<file_sep><?php
namespace Api\Glavpunkt;
/**
* API Главпункт
*
* @author SergeChepikov
*/
interface GlapunktApi
{
/**
* POST запрос
*
* @param string $url
* @param array $params
* @return array
*/
public function postRequest(string $url, array $params): array;
/**
* GET запрос
*
* @param string $url
* @param array $params
* @return array
*/
public function getRequest(string $url, array $params = []): array;
}<file_sep><?php
namespace Integration\CommonShipments;
use Integration\CommonShipment\CommonShipmentStd;
use Integration\CommonShipments;
use PDO;
use Traversable;
/**
* Список поставок, находящиеся в БД интеграции, по статусу
*
* @author SergeChepikov
*/
class CommonShipmentsByStatus implements CommonShipments
{
private $status;
private $db;
public function __construct(string $status, PDO $db)
{
$this->db = $db;
$this->status = $status;
}
/**
* @return Traversable|CommonShipmentStd[]
*/
public function getIterator(): Traversable
{
$pkgs = $this->db->query("
SELECT *
FROM `shipments`
WHERE `status` = " . $this->db->quote($this->status));
foreach ($pkgs as $pkg) {
yield new CommonShipmentStd($pkg['id'], $this->db);
}
}
}
<file_sep><?php
namespace TopDelivery\TDChangeStatus;
use Api\TopDelivery\TopDeliveryApi;
use Integration\CommonEditedStatus;
use Integration\CommonShipment;
use Integration\Mailer;
use TopDelivery\TDChangeStatus;
/**
* Композер принятия поставки
*
* @author SergeChepikov
*/
class TDAcceptShipmentComposed implements TDChangeStatus
{
private $shipment;
private $partlyAccept;
private $accept;
private $orderList;
private $acceptedOrders;
private $editedStatus;
/**
* @param CommonShipment $shipment
* @param array $orderList полный список заказов в поставке
* @param array $acceptedOrders список принятых заказов в поставке
* @param TopDeliveryApi $api
* @param Mailer $mail почтовый ящик, куда необходимо отправлять письма о неполных поставках
* @param CommonEditedStatus $editedStatus измененный статус отправки
* @param TDChangeStatus $partlyAccept действие для частичного принятия поставки
* @param TDChangeStatus $accept действие для полного принятия поставки
*/
public function __construct(
CommonShipment $shipment,
array $orderList,
array $acceptedOrders,
TopDeliveryApi $api,
Mailer $mail,
CommonEditedStatus $editedStatus,
TDChangeStatus $partlyAccept = null,
TDChangeStatus $accept = null
) {
$this->shipment = $shipment;
$this->orderList = $orderList;
$this->acceptedOrders = $acceptedOrders;
$this->editedStatus = $editedStatus;
$this->partlyAccept = $partlyAccept
?? new TDPartlyAcceptShipment($shipment, $acceptedOrders, $orderList, $api, $mail);
$this->accept = $accept ?? new TDAcceptShipment($shipment, $acceptedOrders, $api);
}
/**
* Выполнить изменение статуса
*/
public function do(): void
{
$shipmentInfo = $this->shipment->info();
// Если отправка имеет статус принятого, тогда ничего менять не нужно
if (in_array($shipmentInfo['status'], ['accepted', 'partly-accepted'])) {
return;
}
if (count($this->acceptedOrders) === 0) {
// не принято ни одного заказа в поставке
return;
}
if (count($this->acceptedOrders) === count($this->orderList)) {
$this->accept->do();
$this->editedStatus->edit("accepted");
} else {
$this->partlyAccept->do();
$this->editedStatus->edit("partly-accepted");
}
}
}
<file_sep><?php
namespace TopDelivery;
/**
* Изменение статуса в системе ТопДеливери
*
* @author SergeChepikov
*/
interface TDChangeStatus
{
/**
* Выполнить изменение статуса
*/
public function do(): void;
}
<file_sep><?php /** @noinspection PhpUndefinedClassInspection */
// This is global bootstrap for autoloading
$siteRoot = (dirname(__DIR__));
require_once $siteRoot . '/vendor/autoload.php';<file_sep><?php
namespace TopDelivery;
/**
* Отправка ТопДеливери
*
* @author SergeChepikov
*/
interface TDShipment
{
/**
* Информация об отправке
*
* @return array
* [
* 'id' => '380363', // идентификатор отправки
* 'pickupAddressId' => 761, // код ПВЗ в системе ТопДеливери
* 'status' => [
* [id] => 3 // актуальный статус
* [name] => В пути
* ]
* ]
*/
public function info(): array;
}
<file_sep><?php
namespace Glavpunkt;
use IteratorAggregate;
use Traversable;
/**
* Подготовленные заказы к вгрузке в систему Главпункт
*
* @author SergeChepikov
*/
interface GpPreparedOrders extends IteratorAggregate
{
/**
* Список заказов для вгрузки в Главпункт
*
* @return Traversable|array[]
*/
public function getIterator(): Traversable;
}
<file_sep><?php
/**
* Возвращает соединение с БД
*
* @return PDO
*/
function getTestDB(): PDO
{
//подключение к БД
static $db;
if (isset($db)) {
return $db;
}
$db = new PDO(
"mysql:dbname={$GLOBALS['config']['dbname']};host={$GLOBALS['config']['dbhost']}",
$GLOBALS['config']['username'],
$GLOBALS['config']['password']
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//по умолчанию режим вборки - в виде ассоциативного массива
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->exec('SET NAMES utf8');
return $db;
}
/**
* Сравнение двух массивов
*
* @param array $expectedArray
* @param array $actualArray
*/
function testLibCompareArray(array $expectedArray, array $actualArray)
{
foreach ($expectedArray as $key => $value) {
if (is_array($value)) {
testLibCompareArray($value, $actualArray[$key]);
} elseif ($value != $actualArray[$key]) {
throw new Exception("Расхождение массивов по ключу $key: получили - " . $actualArray[$key] .
", ожидалось - $value");
}
}
return true;
}
<file_sep><?php
namespace Integration\CommonEditedRecord;
use Integration\CommonEditedRecord;
use Integration\CommonOrder;
use PDO;
/**
* Измененный в интеграции заказ
*
* @author SergeChepikov
*/
class CommonEditedOrder implements CommonEditedRecord
{
private $order;
private $db;
private $extraValidFields;
/**
* @param CommonOrder $order заказ в интеграции
* @param PDO $db база данных
* @param array $extraValidFields дополнительные поля, которые можно изменять в базе у заказа
*/
public function __construct(CommonOrder $order, PDO $db, array $extraValidFields = [])
{
$this->db = $db;
$this->order = $order;
$this->extraValidFields = $extraValidFields;
}
/**
* @param array $params параметры для изменения
*/
public function edit(array $params): void
{
$validFields = array_merge([
'gp_status', 'td_status_id', 'td_status_name', 'account_id',
'return_shipment_id', 'pkg_partial'
],
$this->extraValidFields
);
$sqlSetPart = [];
foreach ($params as $key => $value) {
if (in_array($key, $validFields)) {
$sqlSetPart[] = "`$key` = " . $this->db->quote($value);
}
}
if (count($sqlSetPart) > 0) {
$this->db->query("
UPDATE `orders` SET " .
implode(", ", $sqlSetPart) .
" WHERE `td_id` = " . $this->db->quote($this->order->info()['td_id']));
}
}
}
<file_sep><?php
namespace TopDelivery\TDChangeStatus;
use Glavpunkt\GpOrderStatus;
use Integration\CommonEditedStatus;
use Integration\CommonOrder;
use TopDelivery\TDChangeStatus;
/**
* Подушка безопасности
*
* Простановка дополнительных статусов с префиксом `pre` для безопасноти.
* необходимо для избежания случайных отметок
*
* @author SergeChepikov
*/
class TDSafeStatuses implements TDChangeStatus
{
private $orig;
private $order;
private $gpOrderStatus;
private $editedStatus;
/**
* @param TDChangeStatus $orig
* @param CommonOrder $order заказ в интеграции
* @param GpOrderStatus $gpOrderStatus статус заказа в системе Главпункт
* @param CommonEditedStatus $editedStatus измененный статус заказа в интеграции
*/
public function __construct(
TDChangeStatus $orig,
CommonOrder $order,
GpOrderStatus $gpOrderStatus,
CommonEditedStatus $editedStatus
) {
$this->orig = $orig;
$this->order = $order;
$this->gpOrderStatus = $gpOrderStatus;
$this->editedStatus = $editedStatus;
}
/**
* Выполнить изменение статуса
*/
public function do(): void
{
if ($this->order->info()['gp_status'] == $this->gpOrderStatus->status()) {
// Если заказ уже установлен, дальнейшая работа бесмысленна
return;
} elseif ($this->order->info()['gp_status'] !== 'pre-completed' &&
$this->gpOrderStatus->status() === 'completed'
) {
$this->editedStatus->edit('pre-completed');
} elseif ($this->order->info()['gp_status'] !== 'pre-partly-completed' &&
$this->gpOrderStatus->status() === 'partly-completed'
) {
$this->editedStatus->edit('pre-partly-completed');
} else {
$this->orig->do();
}
}
}
<file_sep><?php
namespace Integration;
/**
* Измененный статус в интеграции
*
* @author SergeChepikov
*/
interface CommonEditedStatus
{
/**
* Изменение статуса
*
* @param string $status
*/
public function edit(string $status): void;
}
<file_sep><?php
namespace TopDelivery\TDOrders;
use Api\TopDelivery\TopDeliveryApi;
use Exception;
use TopDelivery\TDOrder;
use TopDelivery\TDOrder\TDOrderStd;
use TopDelivery\TDOrders;
use TopDelivery\TDShipment;
use Traversable;
/**
* Список заказов находящихся в отправке
*
* @author SergeChepikov
*/
class TDOrdersByShipment implements TDOrders
{
private $api;
private $shipment;
public function __construct(TDShipment $shipment, TopDeliveryApi $api)
{
$this->api = $api;
$this->shipment = $shipment;
}
/**
* Список заказов
*
* @return Traversable|TDOrder[]
*/
public function getIterator(): Traversable
{
$shipmentInfo = $this->shipment->info();
$params = [
'currentShipment' => $shipmentInfo['id']
];
$orders = $this->api->doRequest('getOrdersByParams', $params);
if (!isset($orders->orderInfo)) {
throw new Exception("Не передан ни один заказ в отправке {$shipmentInfo['id']}");
}
$orders = $orders->orderInfo;
// Если в списке только один заказ
if (isset($orders->orderIdentity)) {
$orders = [$orders];
}
foreach ($orders as $order) {
yield new TDOrderStd($order->orderIdentity->orderId, $this->api);
}
}
}
<file_sep><?php
namespace TopDelivery\TDChangeStatus;
use Glavpunkt\GpOrderStatus;
use Integration\CommonEditedStatus;
use TopDelivery\TDChangeStatus;
/**
* Композер обновления статусов на стороне ТопДеливери
*
* @author SergeChepikov
*/
class TDChangeStatusComposed implements TDChangeStatus
{
private $origs;
private $orderStatus;
private $editedStatus;
/**
* @param TDChangeStatus[] $origs массив объектов для изменения статусов с ключами в виде статусов заказов
* @param GpOrderStatus $orderStatus текущий статус заказа в ГП
* @param CommonEditedStatus $editedStatus
*/
public function __construct(array $origs, GpOrderStatus $orderStatus, CommonEditedStatus $editedStatus)
{
$this->origs = $origs;
$this->orderStatus = $orderStatus;
$this->editedStatus = $editedStatus;
}
/**
* Выполнить изменение статуса
*
* Если у нас существует, какое-либо действие к этому статусу, его необходимо выполнить.
* Иначе просто поменять статус заказа в интеграции
*/
public function do(): void
{
if (isset($this->origs[$this->orderStatus->status()])) {
$this->origs[$this->orderStatus->status()]->do();
}
$this->editedStatus->edit($this->orderStatus->status());
}
}
<file_sep><?php
namespace Integration\Mailer;
use Exception;
use Integration\Mailer;
/**
* Отправка сообщения на email
*
* @author SergeChepikov
*/
class MailerStd implements Mailer
{
private $emails;
public function __construct(array $emails = [])
{
$this->emails = $emails;
}
/**
* @param string $theme Тема сообщения
* @param string $message Текст сообщения
* @param array $emails Дополнительные адреса доставки (кроме указанных в конструкторе)
*/
public function send(string $theme, string $message, array $emails = []): void
{
$emails = array_merge($this->emails, $emails);
if (empty($emails)) {
throw new Exception("Для отправки сообщений не указано ни одного адреса");
}
mail(implode(",", $emails), $theme, $message);
}
}
<file_sep><?php
namespace Glavpunkt\GpOrderStatus;
use Api\Glavpunkt\GlapunktApi;
use Exception;
use Glavpunkt\GpOrderStatus;
use Integration\CommonOrder;
/**
* Статус заказа в системе Главпункт
*
* @author SergeChepikov
*/
class GpOrderStatusStd implements GpOrderStatus
{
private $info;
private $order;
private $api;
public function __construct(CommonOrder $order, GlapunktApi $api)
{
$this->order = $order;
$this->api = $api;
}
/**
* Текущий статус заказа
*
* @return string
*/
public function status(): string
{
return $this->detailedStatus()['status'];
}
/**
* Способ оплаты
*
* Метод доступен, если статус заказа completed или partly-completed
*
* @return string
*/
public function paymentType(): string
{
if (in_array($this->status(), ['completed', 'partly-completed'])) {
return $this->detailedStatus()['paymentType'];
} else {
throw new Exception("Для статуса {$this->status()} заказа {$this->order->info()['sku']} " .
"невозможно получить способ оплаты. Статус должен быть 'completed' или 'partly-completed'");
}
}
/**
* Список выданных частей заказа, при частичной выдаче
*
* @return array
*/
public function parts(): array
{
if (in_array($this->status(), ['partly-completed'])) {
return $this->detailedStatus()['parts'];
} else {
throw new Exception("Для статуса {$this->status()} заказа {$this->order->info()['sku']} " .
"невозможно получить список выданных частей. Статус должен быть 'partly-completed'");
}
}
/**
* Сумма, полученная от покупателя за заказ
*
* @return float
*/
public function price(): float
{
if (in_array($this->status(), ['completed', 'partly-completed'])) {
return $this->detailedStatus()['price'];
} else {
throw new Exception("Для статуса {$this->status()} заказа {$this->order->info()['sku']} " .
"невозможно получить сумму, полученную от покупателя за заказа. " .
"Статус должен быть 'completed' или 'partly-completed'");
}
}
/**
* Номер возвратного заказа для частичной выдачи
*
* @return string
*/
public function pkgReturnSku(): string
{
if (in_array($this->status(), ['partly-completed'])) {
return $this->detailedStatus()['pkg-return'];
} else {
throw new Exception("Для статуса {$this->status()} заказа {$this->order->info()['sku']} " .
"невозможно получить номер возвратного заказа. Статус должен быть 'partly-completed'");
}
}
/**
* Детальный статус заказа, получаемый от системы Главпункт
*
* @return array
*/
private function detailedStatus(): array
{
if (!$this->info) {
$sku = $this->order->info()['sku'];
$pkgsStatuses = $this->api->getRequest('/api/pkg_status_detailed', ['sku' => [$sku]]);
if (isset($pkgsStatuses[$sku])) {
$this->info = $pkgsStatuses[$sku];
} else {
throw new Exception("При запросе статуса заказа $sku получен неправильный ответ: " .
print_r($pkgsStatuses, true));
}
}
return $this->info;
}
}
<file_sep><?php
namespace Integration;
use Traversable;
/**
* Заказ, находящийся в интеграции
*
* @author SergeChepikov
*/
interface CommonOrder
{
/**
* Информация о заказе
*
* @return array
*/
public function info(): array;
/**
* Номенклатура заказа
*
* @return Traversable|array[]
*/
public function parts(): Traversable;
}
<file_sep><?php
namespace Api\TopDelivery;
use stdClass;
/**
* API TopDelivery
*
* @author SergeChepikov
*/
interface TopDeliveryApi
{
/**
* Выполнение запроса по API
*
* @param string $method
* @param array $params
* @return stdClass
*/
public function doRequest(string $method, array $params = []): stdClass;
}
<file_sep><?php
namespace TopDelivery\TDShipments;
use Integration\CommonShipment\CommonShipmentStd;
use PDO;
use Throwable;
use TopDelivery\TDShipment;
use TopDelivery\TDShipments;
use Traversable;
/**
* Новые поставки от ТопДеливери
*
* Поставки, которые ещё не фигурировали в системе
*
* @author SergeChepikov
*/
class TDNewShipments implements TDShipments
{
private $shipments;
private $db;
public function __construct(TDShipments $shipments, PDO $db)
{
$this->shipments = $shipments;
$this->db = $db;
}
/**
* Список новых отправок
*
* @return Traversable|TDShipment[]
*/
public function getIterator(): Traversable
{
foreach ($this->shipments as $shipment) {
try {
(new CommonShipmentStd($shipment->info()['id'], $this->db))->info();
} catch (Throwable $t) {
yield $shipment;
}
}
}
}
<file_sep><?php
namespace Integration\CommonOrder;
use Exception;
use Integration\CommonOrder;
use PDO;
use Traversable;
/**
* Заказ в интеграции, полученный по идентификатору
*
* @author SergeChepikov
*/
class CommonOrderStd implements CommonOrder
{
private $id;
private $db;
/**
* @param int|string $id идентификатор заказа в ГП или в TD
* @param PDO $db
*/
public function __construct($id, PDO $db)
{
$this->id = $id;
$this->db = $db;
}
/**
* Информация о заказе
*
* @return array
*/
public function info(): array
{
$info = $this->db->query("
SELECT *
FROM `orders`
WHERE `sku` = " . $this->db->quote($this->id) . "
OR `td_id` = " . $this->db->quote($this->id))->fetch();
if ($info === false) {
throw new Exception("Пункт с идентификатором {$this->id} не найден.");
}
return $info;
}
/**
* Номенклатура заказа
*
* @return Traversable|array[]
*/
public function parts(): Traversable
{
$parts = $this->db->query("
SELECT *
FROM `order_part`
WHERE `order_id` = " . $this->db->quote($this->info()['td_id']));
foreach ($parts as $part) {
yield $part;
}
}
}
<file_sep><?php
namespace Glavpunkt\GpCreatedShipment;
use Api\Glavpunkt\GlapunktApi;
use Exception;
use Glavpunkt\GpPreparedOrders;
use Glavpunkt\GpCreatedShipment;
use Integration\Punkt;
/**
* Созданная накладная в системе ГП
*
* @author SergeChepikov
*/
class GpCreatedShipmentStd implements GpCreatedShipment
{
private $api;
private $orders;
public function __construct(GpPreparedOrders $orders, GlapunktApi $api)
{
$this->orders = $orders;
$this->api = $api;
}
/**
* Создание накладной
*
* @param Punkt $punkt пункт получения отправки
* @return int идентификатор созданной накладной
*/
public function create(Punkt $punkt): int
{
$invoice = [
'shipment_options' => [
'method' => 'self_delivery',
'punkt_id' => $punkt->gpId(),
'skip_existed' => '1'
],
'orders' => iterator_to_array($this->orders)
];
$result = $this->api->postRequest('/api/create_shipment', $invoice);
if ($result['result'] == "ok") {
return $result['docnum'];
} else {
throw new Exception("
Создание накладной не произошло из-за ошибки API
create_shipment вернул: " . print_r($result, true) .
" При запросе: " . print_r($invoice, true));
}
}
}
<file_sep><?php
namespace Api\Glavpunkt;
use Exception;
use Integration\Logger;
use Integration\Logger\LoggerStd;
/**
* API Главпункта
*
* @author SergeChepikov
*/
class GlavpunktApiStd implements GlapunktApi
{
private $login;
private $token;
private $basicUrl;
private $headers;
private $logger;
/**
* @param string $login логин пользователя
* @param string $token токен
* @param string $url адрес отправки запроса (напр. /api/take_pkgs)
* @param array $headers массив заголовков запроса
* @param Logger $logger логирование
*/
public function __construct(string $login, string $token, string $url, array $headers = [], Logger $logger = null)
{
$this->login = $login;
$this->token = $token;
$this->basicUrl = $url;
$this->headers = $headers;
$this->logger = $logger ?? new LoggerStd("gp_api.log");
}
/**
* POST запрос
*
* @param string $url
* @param array $params
* @return array
* @throws Exception
*/
public function postRequest(string $url, array $params): array
{
$params = array_merge(
$params,
[
'login' => $this->login,
'token' => $this->token
]
);
$requestJson = json_encode($params);
$headers = array_merge(
[
'Content-Type: application/json',
'Content-Length: ' . strlen($requestJson)
],
$this->headers
);
$url = $this->basicUrl . $url;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $requestJson);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERAGENT, 'top-delivery-integration');
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$answerJson = curl_exec($curl);
if ($answerJson === false) {
throw new Exception("POST запрос вернул ошибку (url=" . $url . ") " .
"\n запрос: " . print_r($params, true) . "\n" .
curl_error($curl));
}
curl_close($curl);
$this->logger->log("[POST to $url] REQUEST = " . $requestJson . PHP_EOL . "ANSWER = " . $answerJson);
$answer = json_decode($answerJson, true);
if (!is_array($answer)) {
throw new Exception("Запрос на url=$url вернул ответ в неправильном формате. Ответ: " . $answerJson);
}
return $answer;
}
/**
* GET запрос
*
* @param string $url
* @param array $params
* @return array
* @throws Exception
*/
public function getRequest(string $url, array $params = []): array
{
$params = array_merge(
$params,
[
'login' => $this->login,
'token' => $this->token
]
);
$url = $this->basicUrl . $url . "?" . http_build_query($params);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $this->headers,
]);
$answerJson = curl_exec($curl);
$this->logger->log("[GET to $url] " . $answerJson);
if ($answerJson === false) {
throw new Exception("GET запрос вернул ошибку (url=" . $url . ") " . curl_error($curl));
}
curl_close($curl);
$answer = json_decode($answerJson, true);
if (!is_array($answer)) {
throw new Exception("Запрос на url=$url вернул ответ в неправильном формате. Ответ: " . $answerJson);
}
return $answer;
}
}
<file_sep><?php
namespace TopDelivery\TDChangeStatus;
use Api\TopDelivery\TopDeliveryApi;
use Exception;
use Glavpunkt\GpOrderStatus;
use Integration\CommonOrder;
use TopDelivery\TDChangeStatus;
/**
* Отметка заказа в системе ТопДеливери как частично выданного
*
* @author SergeChepikov
*/
class TDPartlyCompeletedOrder implements TDChangeStatus
{
private $gpOrderStatus;
private $api;
private $order;
public function __construct(CommonOrder $order, GpOrderStatus $gpOrderStatus, TopDeliveryApi $api)
{
$this->gpOrderStatus = $gpOrderStatus;
$this->api = $api;
$this->order = $order;
}
/**
* Выполнить изменение статуса
*/
public function do(): void
{
$orderInfo = $this->order->info();
$items = [];
foreach ($this->order->parts() as $part) {
$count = 0;
// Просматриваем выданные заказы и ищем текущий
foreach ($this->gpOrderStatus->parts() as $returnPkg) {
if ($returnPkg['name'] === $part['name'] . " " . $part['id']) {
$count = $returnPkg['count'];
break;
}
}
// Если данный заказ выдан, отмечаем сколько данного заказа выдано было
if ($count) {
// Если выдано не всё кол-во, то статус должен быть выдано частично
$status = ($count == $part['num']) ? 3 : 4;
} else {
$status = 5;
}
$items[] = [
'itemId' => $part['id'],
'name' => $part['name'],
'article' => $part['article'],
'count' => $part['num'],
'deliveryCount' => $count,
'weight' => $part['weight'],
'push' => '1',
'clientPrice' => $part['price'],
'status' => [
'id' => $status
]
];
}
$params = [
'finalStatusParams' => [
'orderIdentity' => [
'orderId' => $orderInfo['td_id'],
'barcode' => $orderInfo['barcode']
],
'shipmentId' => $orderInfo['shipment_id'],
'accessCode' => md5("{$orderInfo['td_id']}+{$orderInfo['barcode']}"),
'workStatus' => [
'id' => 4 // выполнено частично
],
'items' => $items, // состав заказа
'dateFactDelivery' => date("Y-m-d"),
'clientPaid' => $this->gpOrderStatus->price(),
'deliveryPaid' => 1,
'paymentType' => $this->paymentType()
]
];
$this->api->doRequest('setOrdersFinalStatus', $params);
}
/**
* Способ оплаты заказа
*
* @return string
*/
private function paymentType(): string
{
switch ($this->gpOrderStatus->paymentType()) {
case "cash":
return "CASH";
case "credit":
return "CARD";
case "prepaid":
return "CASH";
default:
throw new Exception("В заказе {$this->order->info()['sku']} Способ оплаты " .
$this->gpOrderStatus->paymentType() . " неизвестен.");
}
}
}
<file_sep><?php
namespace Integration\CommonEditedRecord;
use Integration\CommonEditedRecord;
use Integration\CommonShipment;
use PDO;
/**
* Измененная в интеграции отправка
*
* @author SergeChepikov
*/
class CommonEditedShipment implements CommonEditedRecord
{
private $shipment;
private $db;
public function __construct(CommonShipment $shipment, PDO $db)
{
$this->db = $db;
$this->shipment = $shipment;
}
/**
* @param array $params параметры для изменения
*/
public function edit(array $params): void
{
$validFields = ['move_id', 'status', 'account_id'];
$sqlSetPart = [];
foreach ($params as $key => $value) {
if (in_array($key, $validFields)) {
$sqlSetPart[] = "`$key` = " . $this->db->quote($value);
}
}
if (count($sqlSetPart) > 0) {
$this->db->query("
UPDATE `shipments` SET " .
implode(", ", $sqlSetPart) .
" WHERE `id` = " . $this->db->quote($this->shipment->info()['id']));
}
}
}
<file_sep><?php
namespace TopDelivery\TDChangeStatus;
use Api\TopDelivery\TopDeliveryApi;
use Exception;
use Glavpunkt\GpOrderStatus;
use Integration\CommonOrder;
use TopDelivery\TDChangeStatus;
/**
* Отметка заказа в системе ТопДеливери как полностью выполненного
*
* @author SergeChepikov
*/
class TDCompletedOrder implements TDChangeStatus
{
private $gpOrderStatus;
private $api;
private $order;
public function __construct(CommonOrder $order, GpOrderStatus $gpOrderStatus, TopDeliveryApi $api)
{
$this->gpOrderStatus = $gpOrderStatus;
$this->api = $api;
$this->order = $order;
}
/**
* Выполнить изменение статуса
*/
public function do(): void
{
$orderInfo = $this->order->info();
$params = [
'finalStatusParams' => [
'orderIdentity' => [
'orderId' => $orderInfo['td_id'],
'barcode' => $orderInfo['barcode']
],
'shipmentId' => $orderInfo['shipment_id'],
'accessCode' => md5("{$orderInfo['td_id']}+{$orderInfo['barcode']}"),
'workStatus' => [
'id' => 3,
'name' => 'done'
],
'dateFactDelivery' => date("Y-m-d"),
'clientPaid' => $this->gpOrderStatus->price(),
'deliveryPaid' => 1,
'paymentType' => $this->paymentType()
]
];
$this->api->doRequest('setOrdersFinalStatus', $params);
}
/**
* Способ оплаты заказа
*
* @return string
*/
private function paymentType(): string
{
switch ($this->gpOrderStatus->paymentType()) {
case "cash":
return "CASH";
case "credit":
return "CARD";
case "prepaid":
return "CASH";
default:
throw new Exception("В заказе {$this->order->info()['sku']} Способ оплаты " .
$this->gpOrderStatus->paymentType() . " неизвестен.");
}
}
}
<file_sep><?php
namespace Integration;
/**
* Пункт выдачи в таблице punkts
*
* @author SergeChepikov
*/
interface Punkt
{
/**
* Идентификатор пункта в системе TD
*
* @return int
*/
public function tdId(): int;
/**
* Идентификатор пункта в системе ГП
*
* @return string
*/
public function gpId(): string;
/**
* Город нахождения пункта
*
* @return string
*/
public function city(): string;
/**
* Включён пункт или нет
*
* @return bool
*/
public function enabled(): bool;
}
<file_sep><?php
namespace TopDelivery;
use IteratorAggregate;
use Traversable;
/**
* Список заказов в ТопДеливери
*
* @author SergeChepikov
*/
interface TDOrders extends IteratorAggregate
{
/**
* Список заказов
*
* @return Traversable|TDOrder[]
*/
public function getIterator(): Traversable;
}
<file_sep><?php
namespace TopDelivery\TDOrder;
use Api\TopDelivery\TopDeliveryApi;
use stdClass;
use TopDelivery\TDOrder;
use Traversable;
/**
* Заказ в ТопДеливери
*
* Объектное представление ответа
*
* @author SergeChepikov
*/
class TDOrderStd implements TDOrder
{
private $id;
private $api;
public function __construct(int $id, TopDeliveryApi $api)
{
$this->id = $id;
$this->api = $api;
}
/**
* @link https://docs.topdelivery.ru/pages/soapapi/p/?v=2.0#method-getOrdersInfo
* @return array
*/
public function info(): array
{
$params = [
'order' => [
'orderId' => $this->id
]
];
$order = $this->api->doRequest('getOrdersInfo', $params)->ordersInfo;
return [
'tdId' => $order->orderInfo->orderIdentity->orderId,
'tdStatusId' => $order->orderInfo->status->id,
'tdStatusName' => $order->orderInfo->status->name,
'serv' => 'выдача',
'sku' => $order->orderInfo->orderIdentity->webshopNumber,
'price' => $order->orderInfo->clientFullCost,
'primerka' => 0,
'client_delivery_price' => $order->orderInfo->clientDeliveryCost,
'weight' => ceil((int)$order->orderInfo->deliveryWeight->weight / 1000),
'barcode' => $order->orderInfo->orderIdentity->barcode,
'is_prepaid' => '',
'events' => $order->orderInfo->events, // информация о событиях, которые произошли с заказом
'buyer_fio' => $order->orderInfo->clientInfo->fio,
'buyer_phone' => $order->orderInfo->clientInfo->phone,
'comment' => $order->orderInfo->clientInfo->comment,
'dst_punkt_id' => $order->orderInfo->pickupAddress->id, // Идентификатор к системе ТопДеливери
'items_count' => $order->orderInfo->services->places,
'partial_giveout_enabled' => $order->orderInfo->services->forChoise,
'can_open_box' => (int)!$order->orderInfo->services->notOpen,
'parts' => iterator_to_array($this->parts($order->orderInfo->items))
];
}
/**
* Номенклатура заказа
*
* @param $itemsFromTD
* @return Traversable
*/
private function parts($itemsFromTD): Traversable
{
// Мы можем получить только один товар
// и его нужно преобразовать в массив
$items = ($itemsFromTD instanceof stdClass)
? [$itemsFromTD]
: $itemsFromTD;
foreach ($items as $item) {
yield [
'id' => $item->itemId,
'tdStatusId' => $item->status->id,
'tdStatusName' => $item->status->name,
'name' => $item->name,
'clientPrice' => $item->clientPrice,
'declaredPrice' => $item->declaredPrice,
'article' => $item->article,
'weight' => $item->weight,
'barcode' => '',
'num' => $item->count
];
}
}
}
<file_sep><?php
namespace Integration;
/**
* Отправка сообщений на email
*
* @package Integration
*/
interface Mailer
{
/**
* @param string $theme Тема сообщения
* @param string $message Текст сообщения
* @param array $emails Дополнительные адреса доставки (кроме указанных в конструкторе)
*/
public function send(string $theme, string $message, array $emails = []): void;
}
<file_sep><?php
namespace TopDelivery;
use IteratorAggregate;
use Traversable;
/**
* Список отправок от ТопДеливери
*
* @author SergeChepikov
*/
interface TDShipments extends IteratorAggregate
{
/**
* Список отправок
*
* @return Traversable|TDShipment[]
*/
public function getIterator(): Traversable;
}
<file_sep><?php
namespace Glavpunkt;
use Integration\Punkt;
/**
* Созданная накладная в системе Главпункт
*
* @author SergeChepikov
*/
interface GpCreatedShipment
{
/**
* Создание накладной
*
* @param Punkt $punkt пункт получения отправки
* @return int идентификатор созданной накладной
*/
public function create(Punkt $punkt): int;
}
<file_sep><?php
namespace Glavpunkt\GpPreparedOrders;
use Glavpunkt\GpPreparedOrders;
use Integration\CommonOrder;
use Integration\CommonOrders;
use Traversable;
/**
* Заказы на выдачу, подготовленные к вгрузке в Главпункт
*
* @author SergeChepikov
*/
class GpPreparedOrdersVidacha implements GpPreparedOrders
{
private $orders;
public function __construct(CommonOrders $orders)
{
$this->orders = $orders;
}
/**
* Список заказов для вгрузки в Главпункт
*
* @return Traversable|array[]
*/
public function getIterator(): Traversable
{
foreach ($this->orders as $order) {
$pkgInfo = $order->info();
yield [
'serv' => "выдача",
'pvz_id' => $pkgInfo['dst_punkt_id'],
'sku' => $pkgInfo['sku'],
// Сумма к получению. Если передан 0, значит заказ предоплачен.
'price' => $pkgInfo['price'],
'insurance_val' => $this->insuranceVal($order), // Оценочная (страховая) стоимость заказа
'weight' => $pkgInfo['weight'], // Общий вес в кг.
'primerka' => 0,
'barcode' => $pkgInfo['barcode'],
'buyer_fio' => $pkgInfo['td_id'] . " " . $pkgInfo['buyer_fio'],
'buyer_phone' => $pkgInfo['buyer_phone'],
'comment' => $pkgInfo['comment'],
'items_count' => $pkgInfo['items_count'],
// если предоплачено, то запрещаем частичную выдачу
'partial_giveout_enabled' => ($pkgInfo['price'] == 0 ? 0 : $pkgInfo['partial_giveout_enabled']),
'can_open_box' => $pkgInfo['can_open_box'],
'parts' => $this->parts($order), // Номенклатура заказа
];
}
}
/**
* Номенклатура создаваемого заказа
*
* @param CommonOrder $order
* @return array
*/
private function parts(CommonOrder $order): array
{
$orderInfo = $order->info();
$parts = [];
foreach ($order->parts() as $part) {
$insVal = $part['declared_price'] != 0 ? $part['declared_price'] : 0.01;
$parts[] = [
'name' => $part['name'] . " " . $part['id'],
'price' => $part['price'],
'insurance_val' => $insVal,
'num' => $part['num'],
'weight' => $part['weight'] / 1000
];
}
if ($orderInfo['client_delivery_price'] > 0) {
$parts[] = [
'name' => "Стоимость доставки",
'price' => $orderInfo['client_delivery_price'],
'insurance_val' => 0
];
}
return $parts;
}
/**
* Оценочная (страховая) стоимость заказа
*
* @param CommonOrder $order
* @return float
*/
private function insuranceVal(CommonOrder $order): float
{
$insuranceVal = 0;
foreach ($order->parts() as $part) {
$insVal = $part['declared_price'] != 0 ? $part['declared_price'] : 0.01;
$insuranceVal += $insVal * $part['num'];
}
return $insuranceVal;
}
}
<file_sep><?php
namespace TopDelivery\TDChangeStatus;
use Api\TopDelivery\TopDeliveryApi;
use DateTime;
use Integration\CommonOrder;
use Integration\CommonShipment;
use Integration\Mailer;
use TopDelivery\TDChangeStatus;
/**
* Частичное принятие поставки от ТопДеливери
*
* @author SergeChepikov
*/
class TDPartlyAcceptShipment implements TDChangeStatus
{
private $accept;
private $shipment;
private $acceptedOrders;
private $orderList;
private $mail;
/**
* @param CommonShipment $shipment поставка в интеграции
* @param CommonOrder[] $acceptedOrders принятые заказы в поставке с ключом в виде идентификатора
* @param CommonOrder[] $orderList полный список заказов в поставке
* @param TopDeliveryApi $api
* @param Mailer $mail почтовый ящик, куда необходимо отправлять письма о неполных поставках
* @param TDChangeStatus $accept действие по принятию поставки
*/
public function __construct(
CommonShipment $shipment,
array $acceptedOrders,
array $orderList,
TopDeliveryApi $api,
Mailer $mail,
TDChangeStatus $accept = null
) {
$this->shipment = $shipment;
$this->acceptedOrders = $acceptedOrders;
$this->orderList = $orderList;
$this->mail = $mail;
$this->accept = $accept ?? new TDAcceptShipment($shipment, $acceptedOrders, $api);
}
/**
* Выполнить изменение статуса
*/
public function do(): void
{
$shipmentInfo = $this->shipment->info();
$mailTheme = "Поставка от ТопДеливери {$shipmentInfo['id']} принята не полностью";
$mailText = (new DateTime())->format("H:i d.m.Y") . "\n" .
"Поставка от ТопДеливери {$shipmentInfo['id']} принята не полностью. \n" .
"Идентификатор пункта поступления: {$shipmentInfo['punkt_id']} \n";
foreach ($this->orderList as $order) {
$orderInfo = $order->info();
$mailText .= "Заказ №{$orderInfo['sku']} с идентификатором ТД {$orderInfo['td_id']}: ";
$mailText .= isset($this->acceptedOrders[$orderInfo['td_id']]) ? "<b>принят</b>\n" : "<b>не принят</b>\n";
}
$this->mail->send($mailTheme, $mailText);
$this->accept->do();
}
}
<file_sep><?php
namespace Api\TopDelivery;
use Exception;
use Integration\Logger;
use Integration\Logger\LoggerStd;
use SoapClient;
use stdClass;
/**
* API TopDelivery (SOAP Based)
*
* @link https://docs.topdelivery.ru/pages/soapapi/p/?v=2.0
* @author SergeChepikov
*/
class TopDeliveryApiStd implements TopDeliveryApi
{
private $login;
private $password;
private $soapClient;
private $logger;
/**
* @param string $login
* @param string $password
* @param SoapClient $soapClient
* @param Logger $logger
*/
public function __construct(
string $login,
string $password,
SoapClient $soapClient,
Logger $logger = null
) {
$this->login = $login;
$this->password = $<PASSWORD>;
$this->soapClient = $soapClient;
$this->logger = $logger ?? new LoggerStd("tdi_api.log");
}
/**
* Выполнение запроса
*
* @param string $method
* @param array $params
* @return mixed
*/
public function doRequest(string $method, array $params = []): stdClass
{
$auth = [
'auth' => [
'login' => $this->login,
'password' => $<PASSWORD>-><PASSWORD>
]
];
$params = array_merge($auth, $params);
$this->logger->log("[REQUEST to $method] " . print_r($params, true));
$result = $this->soapClient->$method($params);
$this->logger->log("[ANSWER from $method] " . print_r($result, true));
if ($result->requestResult->status !== 0) {
$this->logger->log("[REQUEST from $method] " . print_r($params, true), "tdi_api_error.log");
$this->logger->log("[ANSWER from $method] " . print_r($result, true), "tdi_api_error.log");
throw new Exception("Запрос {$method} окончился ошибкой {$result->requestResult->message}. " .
"Отправлен запрос: " . print_r($params, true) . "\n" .
"Получен ответ: " . print_r($result, true));
}
return $result;
}
}
<file_sep><?php
namespace TopDelivery\TDShipments;
use Api\TopDelivery\TopDeliveryApi;
use TopDelivery\TDShipment\TDShipmentStd;
use TopDelivery\TDShipments;
use Traversable;
/**
* Список отправок ТопДеливери по параметрам
*
* @author SergeChepikov
*/
class TDShipmentsByParams implements TDShipments
{
private $api;
private $params;
/**
* @param array $params параметры запроса на получение списка отправок
* [
* 'shipmentStatus' => [
* 'id' => 3
* ],
* 'shipmentDirection' => [
* 'receiverId' => 361 // идентификатор клиента в TD
* ]
* ]
* @param TopDeliveryApi $api АПИ по которому необходимо получить список отправок
*/
public function __construct(array $params, TopDeliveryApi $api)
{
$this->params = $params;
$this->api = $api;
}
/**
* Список отправок
*
* @link https://docs.topdelivery.ru/pages/soapapi/p/?v=2.0#complexType-getShipmentsByParams
* @return Traversable|TDShipmentStd[]
*/
public function getIterator(): Traversable
{
$shipmentList = $this->api->doRequest('getShipmentsByParams', $this->params)->shipments;
if (is_null($shipmentList)) {
return;
}
// Если в списке только одна поставка
if (isset($shipmentList->shipmentId)) {
$shipmentList = [$shipmentList];
}
foreach ($shipmentList as $shipment) {
yield new TDShipmentStd($shipment);
}
}
}
<file_sep><?php
namespace TopDelivery\TDShipment;
use stdClass;
use TopDelivery\TDShipment;
/**
* Отправка ТопДеливери
*
* Объектное представление ответа ТопДеливери
*
* @author SergeChepikov
*/
class TDShipmentStd implements TDShipment
{
private $shipment;
/**
* @param stdClass $shipment
* (
* [shipmentId] => 380363 // идентификатор отправки
* [weight] => 1
* [placesCount] => 1
* [ordersCount] => 1
* [dateCreate] => 2019-06-03 10:00:35
* [sorted] =>
* [pickupAddress] => stdClass Object
* (
* [id] => 761 // код ПВЗ в системе ТопДеливери
* [address] =>
* [name] =>
* )
* [status] => stdClass Object
* (
* [id] => 3 // актуальный статус
* [name] => В пути
* )
* [intakeParams] => stdClass Object
* (
* [need] => 1
* [address] => Нижегородская
* [contacts] => 84956603683
* [intakeDate] => stdClass Object
* (
* [date] => 2019-06-05
* [timeInterval] => stdClass Object
* (
* [bTime] => 09:00:00
* [eTime] => 18:00:00
* )
* )
* )
* [shipmentDirection] => stdClass Object
* (
* [type] => PARTNER_PICKUP
* [receiverId] => 361
* [senderId] => 95
* [directionName] => PARTNER_PICKUP@361
* )
* )
*/
public function __construct($shipment)
{
$this->shipment = $shipment;
}
/**
* Информация об отправке
*
* @return array
* [
* 'id' => '380363', // идентификатор отправки
* 'pickupAddressId' => 761, // код ПВЗ в системе ТопДеливери
* 'status' => [
* 'id' => 3 // актуальный статус
* 'name' => В пути
* ]
* ]
*/
public function info(): array
{
return [
'id' => $this->shipment->shipmentId, // идентификатор отправки
'pickupAddressId' => $this->shipment->pickupAddress->id, // код ПВЗ в системе ТопДеливери
'status' => [
'id' => $this->shipment->status->id, // актуальный статус
'name' => $this->shipment->status->name
]
];
}
}
|
d4f291d26d07b4e12c89e3778b1fd05e6d7cc0db
|
[
"Markdown",
"SQL",
"PHP"
] | 63 |
PHP
|
glavdev/TDLib
|
fc5c9a6ee4c999a00f7a064f0865f5f7b7288b91
|
384581072b7d26c6067ad3feb1840204149e6da5
|
refs/heads/master
|
<file_sep>const request = require('request');
const cheerio = require('cheerio');
const fs = require('fs');
const dir = './memes';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
const download = function(uri, filename, callback) {
request.head(uri, function(err, res, body) {
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri)
.pipe(fs.createWriteStream(filename))
.on('close', callback);
});
};
request(
{
url: 'https://memegen.link/examples',
},
function(error, response, body) {
const $ = cheerio.load(body);
const imgSrcs = $('img')
.map(function() {
return 'https://memegen.link' + $(this).attr('src');
})
.get();
const firstTenImgs = imgSrcs.slice(0, 10);
firstTenImgs.forEach(function(value, index) {
download(value, './memes/image' + index + '.png', function() {
console.log('done');
});
});
},
);
|
185c92bc09d0a13041a23aab4d55ff567a0f6c0d
|
[
"JavaScript"
] | 1 |
JavaScript
|
SaraBurgin/memescraper
|
c1ef5ad9b4740be840ddab14a918d7a1d491ab9d
|
4fc87d24e25af195b820dcace8b7b8dadccfdcda
|
refs/heads/master
|
<repo_name>marl/bandhub<file_sep>/bash_scripts/DownloadAudio.sh
#!/bin/bash
#SBATCH --job-name=DL
#SBATCH --nodes=1
#SBATCH --cpus-per-task=2
#SBATCH --mem=20GB
#SBATCH --time=48:00:00
#SBATCH --output=slurm-%j.out
module purge
module load python3/intel/3.5.3
SRCDIR=$HOME
source activate bandhub
chmod +x $SRCDIR/BandhubAudioDownload.py
python3 $SRCDIR/BandhubAudioDownload.py '/scratch/work/marl/bandhub/BandhubDataset.h5' '/scratch/work/marl/bandhub/unprocessedAudio' '/scratch/work/marl/bandhub/processedAudio' '/scratch/work/marl/bandhub/tempFiles' 0 100 True<file_sep>/BandhubInfo.md
#### Written by <NAME>
#### This .md file contains the documentation for python scripts, batch scripts, HDF file fields, and miscellaneous observations with respect to the Bandhub dataset.
#### For more information or clarification with respect to any of the below content, please contact <NAME> at the following email: <EMAIL>
# Bandhub Documentation:
## 1. HDF File creation
#### python script: BandhubFileCreation.py
#### batch script: FileCreation.sh
#### batch script arguments:
portNum : int
Name of the hdf5 file
databaseName : str
Name of the mongdb database that contains all of the bandhub collections
outputFileName : str
Name of the HDF file to be written out
startIndex : int
Start index in the song collection (public songs only) that iterated over to
generate the HDF file. There were approximately 420000 "public songs" (aka mixes or collaborations) in the database
documentLimit : int
Total number of songs in the song collection to be looked through
#### description:
These scripts will incrementally iterate through the Bandhub monogodb database (specifically the songsStream) and generate an HDF file with name outputFileName containing relevant information. This process took a very long time and so multiple copies of BandhubFileCreation.py and BandhubBatch.sh were used to generate partitions of the dataset which were then combined using the CombineDatasetPartitions.ipynb
#### misc: CombineDatasetPartitions.ipynb
## 2. HDF Effects Append
#### python script: BandhubAppend.py
#### batch script: Append.sh
#### batch script arguments:
hdfName : str
Name of the old hdf5 file whose information is to be appended
portNum : int
Port number of the mongo process run in the batch script
outputFileName : str
Name of the new hdf5 file to be written
startIndex : int
First row of the data to be grabbed (0 is the first row)
documentLimit : int
Total number of rows of the old dataset to be processed and written out
#### description:
These scripts take the original HDF file created using the scripts in section 1 (BandhubFileCreation.py and BandhubBatch.sh) and appends on extra audio effects information. In the original, some of the audio effects were mixed together. In the version created using these scripts, the audio effects are split into two categories based on where they are located in the songs collection. In the songs collection field "settings," a specific tracks settings can be located using the track ID as a keyword. The audio effects settings are located either within those individual track settings or further nested inside the field audioChannels[0]. These two different settings (which for some settings appear to have different ranges) are denoted as x2 and x1, respectively, where x is the type of track setting (volume, mute, solo, reverb, eq etc. ). The effects appending goes much faster than the previous set of scripts and can be run on the whole dataset or split into partitions and once again combined using the Jupyter notebook script CombineDatasetPartitions.ipynb. In addition, the subTitle field was added and the processedAudioURL field was altered.
#### misc: CombineDatasetPartitions.ipynb
## 3. Audio Download
#### python script: BandhubAudioDownload.py
#### batch script: DownloadAudio.sh
#### batch script arguments:
hdfFile : str
Name of the old hdf5 file whose information is to be appended
outputPathUnprocessed : str
Path to the directory where the unprocessed audio will be written
(ie: /scratch/netID/unprocessedAudio)
outputPathProcessed : str
Path to the diretory where the processed audio will be written
(ie: /scratch/netID/processedAudio)
tempPath : str
Path to the directory where the compressed .ogg files will be written
(ie: /scratch/netID/tempFiles)
startIndex : int
First row of the data to be grabbed (0 is the first row)
rowLimit : int
Total number of rows to be processed/downloaded (soft cap)
publishedTracks : bool
True if you want only the tracks that are considered published, false it you want
to download all files in the HDF file.
#### description:
These scripts download unprocessed (audioURL) and processed (processedAudioURL).ogg audio files (there is a small subset that are .m4a that were not able to be downloaded using pysoundfile), zeropad all files such that all tracks within a mix are of uniform length, and write out the resulting file as .flac. The raw .ogg files are also downloaded to the tempPath directory and need to be manually deleted by user (rm -r tempPath) after the script has been run. Multiple copies of these scripts were also created and used to download different sections of the dataset simultaneously to reduce the time it took to download.
#### misc:
## 4. Video Download
#### python script: BandhubVideoDownload.py
#### batch script: DownloadVideo.sh
#### batch script arguments:
hdfFile : str
Name of the old hdf5 file whose information is to be appended
outputPath : str
Path to the directory where the video files will be stored
(ie: /scratch/netID/video)
startIndex : int
First row of the data to be grabbed (0 is the first row)
rowLimit : int
Total number of rows to be processed/downloaded (soft cap)
publishedTracks : bool
Name of the new hdf5 file to be written
#### description:
These scripts download .mp4 track video (trackVideoURL). This procedure is much faster than the scripts in section 3, so multiple copies were not run. Note that YouTube videos were not downloaded.
## 5. File Transfer
#### batch script: FileTransfer.sh
#### description:
This script simply uses the rsync command to copy over files to the /scratch/work/marl/bandhub/ folder. Because the audio was originally downloaded to my scratch folder (/scratch/gjr286/) there was a need to copy over the files.
#### misc:
## 6. Graveyard
#### Contains old .py and .sh download scripts that can be ignored
## Not Completed:
1. Convert HDF from Pandas to H5py
2. Validate the downloaded audio and append information to the HDF file
a. Also handle the 48000 SR material and correct some zero padding if necessary.
b. Fields to add - audioSampleRate, unprocessedAudioFilename, processedAudioFilename, songDuration
3. YouTube video downloads
4. Mixed Audio?
## HDF File Fields:
#### The most updated version of the HDF file is located in the /scratch/work/marl/bandhub folder and its titled BandhubDataset.h5. The dataset within the HDF file is entitled "bandhub".
#### The dataset contains the following fields:
* trackId - str
* Unique trackId which can be used to locate a track in the tracksStream of the Bandhub database
* songId - str
* Uniquely identifies a song or "mix" which might include a single track or a collection of tracks
* masterOwner - str
* The username of the individual who began the mix
* trackOwner - str
* The username of the individual who created the track
* artist - str
* The artist of the song
* title - str
* The title of the song
* subTitle - str
* Contains some additional information regarding the song, such as lyrics or cover style, or describes additional instruments the masterOwner is interested in adding to the current mix
* views - int
* How many times the mix has been viewed by others on Bandhub
* instrument - str
* Track-level instrument label (most are blank, see statistics section below)
* contentTags - str (json)
* Style/genre single-word annotations (most are blank, see statistics section below)
* audioURL - str
* Raw unprocessed track URL
* processedAudioURL - str
* Processed track URL (with added audio effects)
* trackVideoURL - str
* The track video (which does not include any audio)
* startTime - int
* Start time of the track in the mix (in samples)
* trackDuration - float
* Length of the track (in seconds)
* audioSampleRate - int
* Sample rate (this is currently filled with zeros and should be rewritten in the next HDF version)
* fromYouTube - bool
* Is the track imported from YouTube?
* isFinished - bool
* Is the mix marked as completed by the masterOwner (see statistics section below)
* isPublished - bool
* Is the track part of the final mix (or is a draft track)
* hasPublishedTracks - bool
* Does the song/mix contain at least one published track?
* mixedAudioURL - str
* Audio URL of the final mixed audio (most are blank)
* mixedVideoURL - str
* Video URL (which includes audio) of the final mix
* musicBrainzID - str
* Initial music brainz ID
* newMusicBrainzID - str
* Music brainz ID after the server was migrated
* publicSongCollectionIndex - int
* Index in the mongodb song collection after restricting the find function to public tracks (access : 1) (please see the BandhubFileCreation.py)
* volume1 - float
* volume2 - float
* Track volumes
* mute1 - bool
* mute2 - bool
* Is the track muted?
* solo1 - bool
* solo2 - bool
* Is the track solo'ed?
* compressorValue1 - float
* compressorValue2 - float
* Track compressors
* panValue1 - float
* panValue2 - float
* Track pan
* echoValue1 - float
* echoValue2 - float
* Track echo
* noiseGateValue1 - float
* noiseGateValue2 - float
* Track noise gate?
* reverbValue1 - float
* reverbValue2 - float
* Track reverb
* eqValue1 - str (json)
* eqValue2 - str (json)
* Track EQ Values vary in length, therefore they are encoded as json strings
## Dataset Creation Procedure
#### Steps
1. Use FileCreation.sh to create generate the initial HDF file. This was originally done in groupings of 30,000 songs. That is, multiple copies of FileCreation.sh and the associated python script were used to generate the HDF file. The startIndex was set to increments of 30,000 (0, 30,000, 60,000, etc.) and the documentLimit was set to 30,010 (for some overlap to guarantee all songs were looked through). After all 420,000 “public” access songs were looked through, the individual dataset partitions were combined using CombineDatasetPartitions.ipynb. In this .ipynb, duplicate trackIds are removed and any overlap by virtue of the creation procedure was accounted for.
2. Use the Append.sh to add the additional field names that were not included in the initial HDF creation. This script is much faster than the previous and can be done in chunks or all together. To generate the current version of the HDF file, 60,000 row chunks were used, followed by combining the HDF partitions using CombineDatasetPartitions.ipynb. Once again some overlap was included (by making the documentLimit slightly above the length of each chunk, 60,000 in this case) and removed using CombineDatasetPartitions.ipynb. This current HDF version still uses Pandas, NOT h5py.
3. The next steps were to download the data. Use DownloadAudio.sh to download the processed and unprocessed audio data. The downloading was once again down in chunks using multiple copies of the shell and python script. The files were initially downloaded to my scratch folder and the shell script TransferFiles.sh was used to move all the data to /scratch/work/marl/bandhub, where the data currently exists. The audio download stores the .ogg files in a directory that must be removed by the user after downloading. The main output paths contain only .flac files. The name of each file was generated from the unique ends of the url used to download the file (see the .py script). There are a few caveats with respect to the current audio download. First, the rowLimit is a soft cap. That is, the script does not break until all tracks associated with the last song have been looked through to ensure that all tracks within a song are of uniform length. However, this does not hold for the startIndex. That is, if one sets the startIndex at 20,000, if there are associated tracks before that value, all tracks within a song might not be of uniform length. This was handled by adding sufficient overlap between chunks of audio downloads and taking the file that had the most recent timestamp. Thus it is important for perform the audio download in sequential order (or when you validate that all audio is accurate and handle the 48,000 sr material and the few songs that are .m4a, redownload all tracks within a song if that set of tracks does not have uniform length.
4. Use DownloadVideo.sh to download the video material. The video data downloads much faster than the audio data because it only needs to be read in once and is not converted. This download was done without multiple copies of the .py and .sh scripts and is straight-forward. The only video data missing are YouTube videos, which might have copyright issues anyway.
## Bandhub Basic Statistics
#### Please see BandhubStats.ipynb
<file_sep>/graveyard/DownloadBatch.sh
#!/bin/bash
#SBATCH --job-name=DL
#SBATCH --nodes=1
#SBATCH --cpus-per-task=2
#SBATCH --mem=20GB
#SBATCH --time=48:00:00
#SBATCH --output=slurm-%j.out
module purge
module load python3/intel/3.5.3
SRCDIR=$HOME
RUNDIR=$SCRATCH/run-${SLURM_JOB_ID/.*}
mkdir -p $RUNDIR
source activate bandhub
cd $RUNDIR
chmod +x $SRCDIR/BandhubDownload.py
python3 $SRCDIR/BandhubDownload.py '/home/gjr286/BandhubDatasetTemp.h5' '/scratch/gjr286/TestUnprocessed' '/scratch/gjr286/TestProcessed' '/scratch/gjr286/tempFiles' 0 100 True<file_sep>/python_scripts/BandhubAppend.py
'''
Written by <NAME> - Music and Audio Research Lab (MARL)
This function reads in the dataset created using the function BandhubFileCreation.py
and appends new fields (namely additional audio effects) from the bandhub mongodb
database. The old fields and the additional fields are then written out as a new
HDF file.
Running this code directly perform the appending and writes out a new HDF file
Please use the associated script Append.sh to run this script
'''
import argparse
import pymongo
import pandas as pd
import numpy as np
from bson.objectid import ObjectId
import os
import json
import time
import sys
# IMPORTS
def initialize(mongoPortNum):
'''
This function intializes the songs collection in the bandhub mongodb database and
returns the collection.
Parameters
----------
mongoPortNum : int
Port number of the mongod process.
Returns
-------
songsCollection : object
The collection of songs in the bandhub mongodb database
'''
client = pymongo.MongoClient('localhost',mongoPortNum) #connection to MongoDB instance
db = client.get_database('b=bandhub') #grab database
songsCollection = db.get_collection('songsStream')
print('Setup Complete, collections grabbed')
return songsCollection
def check_for_null(string_data):
'''
This function checks if an input string is null.
Parameters
----------
string_data : str
Any string grabbed from the HDF file
Returns
-------
string_data : str
None if the string is null else the string is returned.
'''
if pd.isnull(string_data):
string_data = None
return string_data
def unicode_truncate(s, length, encoding = 'utf-8'):
'''
This function checks if an input string as encoded with utf-8 is greater than length.
If so, the string is truncated.
Parameters
----------
s : str
Input str to be checked for necessary truncation before storage in HDF5
length : int
Max length of the input string
encoding : str
Encoding used by the HDF file for storage (for Pandas this is utf-8)
Returns
-------
trunacted_string : str
A truncated string for storage in HDF file
'''
encoded = s.encode(encoding)[:length]
return encoded.decode(encoding, 'ignore')
def fill_blank_settings():
'''
This functions returns default/blank settings if no track settings are found in the
associated song collection
Parameters
----------
None
Returns
-------
18 track settings variables with default values (types: bool, str, and int)
'''
volume1 = -1
volume2 = -1
mute1 = False
mute2 = False
solo1 = False
solo2 = False
compressorValue1 = -1000
compressorValue2 = -1000
echoValue1 = -1000
echoValue2 = -1000
noiseGateValue1 = -1000
noiseGateValue2 = -1000
panValue1 = -1000
panValue2 = -1000
reverbValue1 = -1000
reverbValue2 = -1000
eqValue1 = -1000
eqValue2 = -1000
return (volume1, volume2, mute1, mute2, solo1, solo2, compressorValue1, compressorValue2,
echoValue1, echoValue2, noiseGateValue1, noiseGateValue2, panValue1, panValue2,
reverbValue1, reverbValue2, eqValue1, eqValue2)
def grab_audio_effects_settings(trackSettings):
'''
This functions grabs the audio effects settings for an associated track
Note: Track settings are located in the songs collection, NOT the track collection.
Also, there are two possible locations of the audio effects. First, in the
audioChannels field. Second, outside the audioChannels field in the track settings
Parameters
----------
trackSettings : dictionary
The settings of a track which is located in the songs collection
Returns
-------
18 track settings variables (types : bool, str, int, and float )
'''
volume1 = None
volume2 = None
mute1 = None
mute2 = None
compressorState1 = None
compressorState2 = None
compressorValue1 = None
compressorValue2 = None
echoState1 = None
echoState2 = None
echoValue1 = None
echoValue2 = None
noiseGateState1 = None
noiseGaeState2 = None
noiseGateValue1 = None
noiseGateValue2 = None
panState1 = None
panState2 = None
panValue1 = None
panValue2 = None
reverbState1 = None
reverbState2 = None
reverbValue1 = None
reverbValue2 = None
solo1 = None
solo2 = None
eqState1 = None
eqState2 = None
eqValue1 = None
eqValue2 = None
#reset these variables
audioChannel = trackSettings.get('audioChannels')
#to be used to grab track settings in the audioChannels
if audioChannel is not None:
volume1 = audioChannel[0].get('volume')
mute1 = audioChannel[0].get('mute')
solo1 = audioChannel[0].get('solo')
if mute1 is None:
mute1 = False
if solo1 is None:
solo1 = False
if volume1 is None:
volume1 = -1
compressorState1 = audioChannel[0].get('compressorState')
compressorValue1 = audioChannel[0].get('compressorValue')
if (compressorState1 == 0) or (compressorValue1 is None):
compressorValue1 = -1000
echoState1 = audioChannel[0].get('echoState')
echoValue1 = audioChannel[0].get('echoValue')
if (echoState1 == 0) or (echoValue1 is None):
echoValue1 = -1000
noiseGateState1 = audioChannel[0].get('noiseGateState')
noiseGateValue1 = audioChannel[0].get('noiseGateValue')
if (noiseGateState1 == 0) or (noiseGateValue1 is None):
noiseGateValue1 = -1000
panState1 = audioChannel[0].get('panState')
panValue1 = audioChannel[0].get('panValue')
if (panState1 == 0) or (panValue1 is None):
panValue1 = -1000
reverbState1 = audioChannel[0].get('reverbState')
reverbValue1 = audioChannel[0].get('reverbValue')
if (reverbState1 == 0) or (reverbValue1 is None):
reverbValue1 = -1000
eqState1 = audioChannel[0].get('visualEQState')
eqValue1 = audioChannel[0].get('visualEQValues')
if (eqState1 ==0) or (eqValue1 is None):
eqValue1 = []
eqValue1.append(-1000)
else:
volume1 = -1
solo1 = False
mute1 = False
compressorValue1 = -1000
echoValue1 = -1000
noiseGateValue1 = -1000
panValue1 = -1000
reverbValue1 = -1000
eqValue1 = []
eqValue1.append(-1000)
volume2 = trackSettings.get('volume')
mute2 = trackSettings.get('mute')
solo2 = trackSettings.get('solo')
if mute2 is None:
mute2 = False
if solo2 is None:
solo2 = False
if volume2 is None:
volume2 = -1
compressorState2 = trackSettings.get('compressorState')
compressorValue2 = trackSettings.get('compressorValue')
if (compressorState2 == 0) or (compressorValue2 is None):
compressorValue2 = -1000
echoState2 = trackSettings.get('echoState')
echoValue2 = trackSettings.get('echoValue')
if (echoState2 == 0) or (echoValue2 is None):
echoValue2 = -1000
noiseGateState2 = trackSettings.get('noiseGateState')
noiseGateValue2 = trackSettings.get('noiseGateValue')
if (noiseGateState2 == 0) or (noiseGateValue2 is None):
noiseGateValue2 = -1000
panState2 = trackSettings.get('panState')
panValue2 = trackSettings.get('panValue')
if (panState2 == 0) or (panValue2 is None):
panValue2 = -1000
reverbState2 = trackSettings.get('reverbState')
reverbValue2 = trackSettings.get('reverbValue')
if (reverbState2 == 0) or (reverbValue2 is None):
reverbValue2 = -1000
eqState2 = trackSettings.get('visualEQState')
eqValue2 = trackSettings.get('visualEQValues')
if (eqState2 ==0) or (eqValue2 is None):
eqValue2 = []
eqValue2.append(-1000)
if eqValue1 is not None:
eqValue1 = [ round(elem,2) if elem is not None else elem for elem in eqValue1]
eqValue1 = json.dumps(eqValue1)
if eqValue2 is not None:
eqValue2 = [round(elem,2) if elem is not None else elem for elem in eqValue2]
eqValue2 = json.dumps(eqValue2)
return (volume1, volume2, mute1, mute2, solo1, solo2, compressorValue1, compressorValue2,
echoValue1, echoValue2, noiseGateValue1, noiseGateValue2, panValue1, panValue2,
reverbValue1, reverbValue2, eqValue1, eqValue2)
def grab_old_data(row):
'''
This functions grabs a row of data from the original HDF file for writing to a new
HDF file.
Parameters
----------
row : dictionary
dictionary containing of row of data from the original HDF file
Returns
-------
24 different fields of varying types for storage in new HDF file
'''
trackId = row.trackId
songId = row.songId
masterOwner = check_for_null(row.masterOwner)
trackOwner = check_for_null(row.trackOwner)
artist = check_for_null(row.artist)
title= check_for_null(row.title)
views = row.views
instrument = check_for_null(row.instrument)
contentTags = row.contentTags
audioURL = check_for_null(row.audioURL)
processedAudioURL = check_for_null(row.cleanProcessedAudioURL)
startTime = row.startTime
trackDuration = row.trackDuration
audioSampleRate = row.audioSampleRate
trackVideo = check_for_null(row.trackVideo)
fromYouTube = row.fromYouTube
isFinished = row.isFinished
isPublished = row.isPublished
hasPublishedTracks = row.hasPublishedTracks
mixedAudio = check_for_null(row.mixedAudio)
mixedVideo = check_for_null(row.mixedVideo)
musicBrainzID = check_for_null(row.musicBrainzID)
newMusicBrainzID = check_for_null(row.newMusicBrainzID)
publicSongCollectionIndex = row.publicSongCollectionIndex
return (trackId, songId, masterOwner, trackOwner, artist, title, views, instrument,
contentTags, audioURL, processedAudioURL, startTime, trackDuration, audioSampleRate,
trackVideo, fromYouTube, isFinished, isPublished, hasPublishedTracks, mixedAudio,
mixedVideo, musicBrainzID, newMusicBrainzID, publicSongCollectionIndex)
def write_data(hdfName, songsCol, fileName, startIdx, documentLimit):
'''
This functions writes data to the new hdf5 file. Grabs all of the data of interest
from the old dataset and puts it into a pandas Dataframe and stores in new HDF file
Parameters
----------
hdfName : str
Name of original hdf5 file to which new fields must be added
songsCol : object
Bandhub mongodb songs collections which contains relevant audio effects to be
added as new fields
fileName : str
Name of new hdf file to be created
startIdx : int
Row index from which to grab from the old dataset
documentLimit : int
Total number of rows to be grabbed from the old dataset.
Returns
-------
None
'''
currData = pd.read_hdf(hdfName, "bandhub") # Read in HDF file.
currData = currData.iloc[startIndex:startIndex + documentLimit]
groupedData = currData.groupby("songId")
#Open the hdf file for storage.
hdf = pd.HDFStore(fileName)
print('HDF opened')
#Define the columns of the h5 file.
cols = ['trackId', 'songId', 'masterOwner','trackOwner', 'artist', 'title', 'subTitle',
'views', 'instrument', 'contentTags', 'audioURL', 'processedAudioURL','trackVideoURL',
'startTime','trackDuration', 'audioSampleRate', 'fromYouTube', 'isFinished',
'isPublished', 'hasPublishedTracks','mixedAudioURL','mixedVideoURL', 'musicBrainzID',
'newMusicBrainzID', 'publicSongCollectionIndex', 'volume1', 'volume2', 'mute1', 'mute2',
'solo1', 'solo2','compressorValue1' , 'compressorValue2', 'panValue1', 'panValue2',
'echoValue1','echoValue2', 'noiseGateValue1', 'noiseGateValue2', 'reverbValue1',
'reverbValue2', 'eqValue1', 'eqValue2']
# Fields needed in the song collection, used for projecting to improve performance
songFields = {'settings':1, 'subTitle':1}
rowCount = startIdx
frameCount = 0;
frameCountLimit = 199; #how many rows of data are accumulated before writing to file
for name,group in groupedData:
songId = pd.unique(group.songId)[0]
try:
songDoc = songsCol.find({'_id' : ObjectId(songId)}, songFields)
trackIds = group.trackId
for doc in songDoc:
songSettings = doc.get('settings')
subTitle = doc.get('subTitle')
# truncate subtitle if longer than 800 characters (when encoded with UTF-8)
if len(subTitle.encode('utf-8')) > 800:
print('subtitle above length 800')
subTitle = unicode_truncate(subTitle, 800)
#print(len(subTitle.encode('utf-8')))
trackCount = 0 #used for indexing into the grouped data
for track in trackIds:
trackSettings = songSettings.get(track)
if trackSettings is not None:
(volume1, volume2, mute1, mute2, solo1, solo2, compressorValue1,
compressorValue2, echoValue1, echoValue2, noiseGateValue1,
noiseGateValue2, panValue1, panValue2, reverbValue1, reverbValue2,
eqValue1, eqValue2) = grab_audio_effects_settings(trackSettings)
else:
(volume1, volume2, mute1, mute2, solo1, solo2, compressorValue1,
compressorValue2, echoValue1, echoValue2, noiseGateValue1,
noiseGateValue2, panValue1, panValue2, reverbValue1, reverbValue2,
eqValue1, eqValue2) = fill_blank_settings()
currRow = group.iloc[trackCount]
(trackId, songId, masterOwner, trackOwner, artist, title, views,
instrument, contentTags, audioURL, processedAudioURL, startTime,
trackDuration, audioSampleRate, trackVideo, fromYouTube, isFinished,
isPublished, hasPublishedTracks, mixedAudio, mixedVideo, musicBrainzID,
newMusicBrainzID, publicSongCollectionIndex) = grab_old_data(currRow)
data = [] #to hold a row of data
data.append([str(trackId), str(songId), masterOwner, trackOwner,
artist, title, subTitle, int(views), instrument, contentTags, audioURL,
processedAudioURL, trackVideo, startTime, float(trackDuration),
int(audioSampleRate),fromYouTube, isFinished, isPublished, hasPublishedTracks,
mixedAudio, mixedVideo, str(musicBrainzID), str(newMusicBrainzID),
publicSongCollectionIndex, float(volume1), float(volume2), mute1, mute2,
solo1, solo2, float(compressorValue1), float(compressorValue2),
float(panValue1), float(panValue2), float(echoValue1), float(echoValue2),
float(noiseGateValue1), float(noiseGateValue2), float(reverbValue1),
float(reverbValue2), eqValue1, eqValue2])
if frameCount == 0:
df = pd.DataFrame(data, columns = cols)
else:
currDf = pd.DataFrame(data,columns = cols)
df = df.append(currDf, ignore_index=True)
#store a row of data and convert to dataframe
frameCount += 1
if (frameCount > frameCountLimit):
df.index = pd.Series(df.index) + (rowCount - frameCountLimit)
hdf.append('bandhub', df, format = 'table', min_itemsize = 800, data_columns = True, compression = 'zlib')
df = pd.DataFrame(columns = cols)
frameCount = 0;
print('Data rows appended', rowCount)
sys.stdout.flush()
#append data to file
trackCount += 1
rowCount += 1
except pymongo.errors.AutoReconnect:
print('AutoReconnect error')
hdf.close()
#catch reconnect error and close file
df.index = pd.Series(df.index) + (rowCount - frameCount)
hdf.append('bandhub', df, format = 'table', min_itemsize = 800, data_columns = True, compression = 'zlib')
hdf.close()
print('Appending Complete, HDF file closed')
if __name__ == '__main__':
'''
This functions is called if this .py script is run directly and parses the arugments
and passes them to the functions which perform the new dataset creation.
Parameters (in the accompanying .sh script)
----------
hdfName : str
Name of the old hdf5 file whose information is to be appended
portNum : int
Port number of the mongo process run in the batch script
outputFileName : str
Name of the new hdf5 file to be written
startIndex : int
First row of the data to be grabbed (0 is the first row)
documentLimit : int
Total number of rows of the old dataset to be processed and written out
Returns
-------
None
'''
parser = argparse.ArgumentParser()
parser.add_argument("hdfFile", help='Name of HDF File to be rewritten', type=str)
parser.add_argument("portNum", help='Port Number of Mongo Instance', type=int)
parser.add_argument("outputFileName", help = 'Name of hdf file to be output (ie: bandhub.h5)', type=str)
parser.add_argument("startIndex", help = 'Index in the songs collection from which to begin file creation', type=int)
parser.add_argument("documentLimit", help = 'Total number of rows to be looked through', type=int)
#arguments to parse
args = parser.parse_args()
hdfName = args.hdfFile
port = args.portNum
outputFN = args.outputFileName
startIndex = args.startIndex
documentLimit = args.documentLimit
#parse args and store values
print('Arugments parsed, ready to begin writing')
songsCollection = initialize(port) #call the initialize function
write_data(hdfName, songsCollection, outputFN, startIndex, documentLimit) #perform the file creation<file_sep>/README.md
# bandhub
Bandhub dataset curation and analysis
<file_sep>/bash_scripts/TransferFiles.sh
#!/bin/bash
#SBATCH --job-name=Transfer
#SBATCH --nodes=1
#SBATCH --cpus-per-task=2
#SBATCH --mem=20GB
#SBATCH --time=48:00:00
#SBATCH --output=slurm-%j.out
rsync -rthv --progress /scratch/gjr286/UnprocessedAudio/ /scratch/work/marl/bandhub/unprocessedAudio <file_sep>/python_scripts/BandhubFileCreation.py
'''
Written by <NAME> - Music and Audio Research Lab (MARL)
This function creates an hdf5 dataset containing relevant information contained in the
bandhub mongodb database.
Running this code directly writes out a new HDF file
Please use the associated script FileCreation.sh to run this script
'''
import argparse
import pymongo
import pandas as pd
import numpy as np
from bson.objectid import ObjectId
import os
import json
import time
# IMPORTS
def initialize(mongoPortNum, database):
'''
This functions connects to the mongo client and returns all the database collections
Parameters
----------
mongoPortNum : int
Port number of the mongod process.
database : str
Name of the bandhub mongodb database
Returns
-------
songsCollection : object
The songsStream collection of the bandhub mongodb database
postsCollection : object
The posts collection of the bandhub mongodb database
videosCollection : object
The mergedVideos collection of the bandhub mongodb database
tracksCollection : object
The tracksStream collection of the bandhub mongodb database
'''
client = pymongo.MongoClient('localhost',mongoPortNum) #connection to MongoDB instance
db = client.get_database(database) #grab database
#grab collections. These should be named as seen below.
postsCollection = db.get_collection('posts')
videosCollection = db.get_collection('mergedVideos')
songsCollection = db.get_collection('songsStream')
tracksCollection = db.get_collection('tracksStream')
print('Setup Complete, collections grabbed')
return songsCollection, postsCollection, videosCollection, tracksCollection
def songInformation(songDocument):
'''
This functions grabs the information of interest from the passed in songDocument
Parameters
----------
songDocument : dictionary
A document from the songsCollection from which information will be grabbed
Returns
-------
7 different fields from the songDocument
'''
songId = songDocument['_id']
#grab songId which is unique for each collaboration
musicBrainzID = songDocument.get('musicbrainzMetadataId')
newMusicBrainzID = songDocument.get('newMusicbrainzMetadataId')
#music brainz IDs
contentTags = json.dumps(songDocument.get('channels'))
#encode any content tags as JSON strings
songMixedVideo = songDocument.get('mp4MergedVideoUrl')
#mixed video link located in the songs document (used in cases where the 'correct' video can't be located)
views = songDocument.get('numberOfViews')
allTracks = songDocument.get('trackIDs')
return songId, musicBrainzID, newMusicBrainzID, contentTags, songMixedVideo, views, allTracks
def postInformation(postDocument):
'''
This functions grabs the information of interest from the passed in postDocument
Parameters
----------
postDocuments : dictionary
A document from the postsCollection from which information will be grabbed
Returns
-------
5 different fields from the postsDocument
'''
artist = postDocument.get('mb_artist')
title = postDocument.get('title')
masterOwner = postDocument.get('owner') #masterOwner is owner of individual who starts the collaboration
publishedTracks = postDocument['participantsInfo']['publishedTracks']
collabSettings = postDocument.get('collabSettings')
if collabSettings is None:
isFinished = False
else:
isFinished = collabSettings['finished']
#set bool for whether collaboration is finished. What about completed?
return artist, title, masterOwner, publishedTracks, isFinished
def videoInformation(videoDocuments, sortedTracks, songMixedVideo):
'''
This functions grabs all the mixed video and audio from a set of matching video documents
Pass in a set of video documents, determine which video is final version by
matching a sorted version of the published tracks (located in the post document)
to the track IDs in the video document. If no match is found. the mixed video URL in
the song collection is used.
Parameters
----------
videoDocuments : cursor
Cursor which points to all video documents associated with a specific songID
sortedTracks : list
Sorted list of published track IDs located in the post document (see above function).
Used for matching to the list of track IDs located in the video document
songMixedVideo : str
URL to the mixed video which is located in the song document. Note: The mixed
video URL can also be found in the video document.
Returns
-------
mixedVideo: str
URL of the mixed video for a collaboration.
mixedAudio: str
URL of the mixed audio for a collaboration
'''
mixedVideo = None
mixedAudio = None
for videoDocs in videoDocuments:
#print('Iterate through the videos')
toCompare = []
for ids in videoDocs['trackIds']:
toCompare.append(str(ids))
sortedToCompare = sorted(toCompare)
#create list to compare list of published tracks to
if (sortedToCompare == sortedTracks):
mixedVideo = videoDocs['mp4MergedVideoUrl']
mixedAudio = videoDocs.get('mp3AudioUrl')
break
#if the lists are equal grab the mixed video and mixed audio
if mixedVideo is None:
mixedVideo = songMixedVideo
#if no matches in the video collection then just grab from the songs collection
return mixedVideo, mixedAudio
def trackInformation(trackDocument, trackSettings, isPublished):
'''
This functions grabs the information of interest from the passed in songDocument.
Parameters
----------
trackDocument : dictionary
Document from the track collection
trackSettings : dictionary
A dictionary containing settings for a specific track which are located in the
corresponding song document
isPublished :
Returns
-------
10 different fields
'''
audioURL = trackDocument['audioChannels'][0].get('fileUrl')
if audioURL is None:
audioURL = trackDocument.get('audioFileUrl')
if isPublished:
print('published track but no audio URL in the expected location')
print(trackDocument['_id'])
startTime = trackDocument['startTimeValue']
#grab unprocessed audio and its start time
cleanProcessedAudioURL = trackSettings.get('effectsAudioUrl')
processedAudioURL = None
#if there is a processedAudioURL grab it
audioChannel = trackSettings.get('audioChannels')
#If no effectsAudioUrl, try these two locations.
#Also check to make sure its not a duplicate of the URL in the track stream
if cleanProcessedAudioURL is None:
if audioChannel is not None:
dummyURL = audioChannel[0].get('audioFileUrl')
if dummyURL != audioURL:
processedAudioURL = dummyURL
if cleanProcessedAudioURL is None:
dummyURL = trackSettings.get('audioFileUrl')
if dummyURL != audioURL:
processedAudioURL = dummyURL
# *** NOTE ***
#The processedAudioURL was later removed from the dataset only leaving
#the cleanProcessedAudioURL, but renamed as processedAudioURL
trackVideo = trackDocument.get('videoFileUrl')
trackVideo2 = trackDocument.get('sourceVideoURL')
if (trackVideo is None) and (trackVideo2 is not None):
trackVideo = trackVideo2
if trackVideo2 is not None:
fromYouTube = True
else:
fromYouTube = False
#grab video files. Set fromYouTube bool
trackOwner = trackDocument['owner']
#grab the owner of the track
audioSampleRate = trackDocument['audioChannels'][0].get('audioSampleRate')
if audioSampleRate is None:
audioSampleRate = 0
#get sample rate
trackDuration = trackDocument.get('durationInSeconds') #track duration
if trackDuration is None:
totalFrames = trackDocument['audioChannels'][0].get('audioTotalFrames')
if totalFrames is not None and audioSampleRate is not 0:
trackDuration = totalFrames/audioSampleRate
# if not track duration field them compute the track duration
instrument = trackDocument.get('instrumentAssignedBySongOwner') #track instrument
return (audioURL, cleanProcessedAudioURL, processedAudioURL, trackVideo, startTime,
trackOwner, trackDuration, audioSampleRate, instrument, fromYouTube)
def createSortedTrackList(publishedTracks):
'''
This functions takes a list of track IDs and creates a sorted list for comparison
with the list of trackIDs in the video document
Parameters
----------
publishedTracks : list of str
List of published track IDs
Returns
-------
sortedTrackList : list of str
Sorted list of published track ids
publishedTrackList : list of str
Unsorted list of publishd track ids (after removing invalid/missing list entries)
'''
publishedTrackList = []
for track in publishedTracks:
try:
publishedTrackList.append(str(track['_id']))
except KeyError:
print('skipped song')
sortedTrackList = sorted(publishedTrackList)
#print('Created published tracks array to compare tracks in the videos to')
#grab the array of published tracks for this collaboration and create a list to hold those tracks
#the track list will be used to compare against trackIds in the video document to determine which
#video document holds the final mix.
return sortedTrackList, publishedTrackList
def grabAudioEffectsSettings(trackSettings):
'''
This functions grabs all of the audio effects settings for a specific track. Track
settings are located in the song document inside a dictionary whose keys are the track
IDs.
NOTE : These audio effects were later removed and replaced by the full set of audio
effects in the script BandhubAppend.py. Please see that script for the
final audio effects fields (and the most recent dataset fields)
Parameters
----------
trackSettings : dictionary
Dictionary holding the audio effects added to a particular track
Returns
-------
8 different audio effects fields
'''
trackVolume = None
mute = None
compressorState = None
compressorValue = None
echoState = None
echoValue = None
noiseGateState = None
noiseGateValue = None
panState = None
panValue = None
reverbState = None
reverbValue = None
#eqState = None
#eqValue = None
solo = None
#reset these variables if we move to a new published track
audioChannel = trackSettings.get('audioChannels')
#to be used to grab track settings
### AUDIO EFFECTS SETTINGS ###
#conflicting values of some effects (including track volume)
#inside and outside of audioChannels.
#if the settings are located in settings.audioChannel[0] grab them there
if audioChannel is not None:
trackVolume = audioChannel[0].get('volume')
mute = audioChannel[0].get('mute')
compressorState = audioChannel[0].get('compressorState')
compressorValue = audioChannel[0].get('compressorValue')
echoState = audioChannel[0].get('echoState')
echoValue = audioChannel[0].get('echoValue')
noiseGateState = audioChannel[0].get('noiseGateState')
noiseGateValue = audioChannel[0].get('noiseGateValue')
panState = audioChannel[0].get('panState')
panValue = audioChannel[0].get('panValue')
reverbState = audioChannel[0].get('reverbState')
reverbValue = audioChannel[0].get('reverbValue')
#eqState = audioChannel[0].get('visualEQState')
#eqValue = audioChannel[0].get('visualEQValues')
solo = audioChannel[0].get('solo')
#if not then try to grab from settings('field')
if trackVolume is None:
trackVolume = trackSettings.get('volume')
if mute is None:
mute = trackSettings.get('mute')
if(mute == True):
trackVolume = 0
elif trackVolume is None:
trackVolume = -1
#compressor
if compressorValue is None:
compressorState = trackSettings.get('compressorState')
compressorValue = trackSettings.get('compressorValue')
if (compressorState == 0) or (compressorValue is None):
compressorValue = 0
#echo
if echoValue is None:
echoState = trackSettings.get('echoState')
echoValue = trackSettings.get('echoValue')
if (echoState == 0) or (echoValue is None):
echoValue = 0
#noise gate?
if noiseGateValue is None:
noiseGateState = trackSettings.get('noiseGateState')
noiseGateValue = trackSettings.get('noiseGateValue')
if (noiseGateState == 0) or (noiseGateValue is None):
noiseGateValue = 0
#pan
if panValue is None:
panState = trackSettings.get('panState')
panValue = trackSettings.get('panValue')
if (panState == 0) or (panValue is None):
panValue = 0
#reverb
if reverbValue is None:
reverbState = trackSettings.get('reverbState')
reverbValue = trackSettings.get('reverbValue')
if (reverbState == 0) or (reverbValue is None):
reverbValue = 0
#is solo'ed. I don't think this is ever true, but grab it anyway
if solo is None:
solo = trackSettings.get('solo')
#eq
#if eqValue is None:
# eqState = trackSettings.get('visualEQState')
# eqValue = trackSettings.get('visualEQValues')
#if (eqState == 0):
# eqValue is None
#eqValue = json.dumps(eqValue)
#print(eqValue)
return trackVolume, mute, compressorValue, echoValue, noiseGateValue, panValue, reverbValue, solo
def writeData(songsCol, postsCol, videosCol, tracksCol, fileName, ind, documentLimit):
'''
This functions calls the above functions, gathers all relevant information for a given
track into a single row of data. This row of data is converted to a pandas dataframe
and then written to the HDF file.
NOTE : Later, it was found that writing to the HDF for each row is extremely inefficient
and may explain while it took exorbitant amounts of time to write out the
original HDF file. Please see BandhubAppend.py for how this script can be
modified to potentially improve its performance (if one is looking to recreate
the dataset). In BandhubAppend.py, data is gathered in 200 row chunks and then
written to the file.
Parameters
----------
songsCol : object?
Mongodb collection of songsStream
postsCol : object?
Mongodb collection of posts
videosCol : object?
Mongodb collection of mergedVideos
tracksCol : object?
Mongodb collection of tracksStream
fileName : str
Name of the HDF file that will be written out
ind : int
Song collection index to begin at
documentLimit : int
Total number of songs to be looked through
Returns
-------
None
'''
#open the hdf file for storage.
hdf = pd.HDFStore(fileName)
print('HdF opened')
#define the columns of the h5 file
cols = ['trackId', 'songId', 'masterOwner','trackOwner', 'artist', 'title', 'views', 'instrument', 'contentTags', 'audioURL', 'cleanProcessedAudioURL', 'processedAudioURL', 'startTime', 'trackDuration', 'audioSampleRate', 'trackVolume', 'compressorValue', 'panValue', 'echoValue', 'noiseGateValue', 'reverbValue', 'solo', 'trackVideo', 'fromYouTube', 'isFinished', 'isPublished', 'hasPublishedTracks', 'mixedAudio','mixedVideo', 'musicBrainzID', 'newMusicBrainzID', 'publicSongCollectionIndex']
max_i = 418465 #hard coded the total number of public songs to be looked through (only used for print statement)
songsFields = {'musicbrainzMetadataId':1,'newMusicbrainzMetadataId':1, 'channels':1,'mp4MergedVideoUrl':1,'numberOfViews':1, 'settings':1, 'trackIDs':1, 'hasPublishedTracks':1}
postsFields = {'mb_artist':1,'title':1,'owner':1,'participantsInfo':1,'collabSettings':1}
videoFields = {'mp4MergedVideoUrl':1, 'mp3AudioUrl':1, 'trackIds':1}
trackFields = {'audioChannels':1, 'audioFileUrl':1, 'startTimeValue':1,'videoFileUrl':1,'sourceVideoURL':1,'owner':1,'durationInSeconds':1,'instrumentAssignedBySongOwner':1}
#fields needed in each collection, used for projecting to improve performance
cursor = songsCol.find({'access' : 1}, songsFields).skip(ind).batch_size(15).limit(documentLimit)
#grab public song collaborations.
#1. Skip how many indices we want (ind)
#2. limit files grabbed from database at one time to 15.
#3. Limit the number of files to be looked through to documentLimit
i = ind
try:
for songDoc in cursor:
if (i%10 == 0):
percent = i / max_i
print('Creating File: %f%%' % percent)
#print percentage of total documents iterated through
songId, musicBrainzID, newMusicBrainzID, contentTags, songMixedVideo, views, allTracks = songInformation(songDoc)
#grab information from song document
if not allTracks:
print('No tracks in trackIDs field of song document')
print(songId)
i = i+1
continue
#if no trackIDs for a song then immediately move to next song.
post = postsCol.find({'objectId' : songId}, postsFields).limit(1)
#grab the corresponding post document
for postDoc in post:
#iterate through corresponding post document and grab relevant information
artist, title, masterOwner, publishedTracks, isFinished = postInformation(postDoc)
#grab and store post document information
#find the corresponding video documents.
#Note: there are multiple videos docs for the same collaboration as
#instruments are added and tracks are swapped out
if not publishedTracks:
print('No published tracks')
#print(i)
print(postDoc['_id'])
print(songId)
hasPublishedTracks = False
mixedVideo = None
mixedAudio = None
else:
hasPublishedTracks = True
videoDocuments = videosCol.find({'songId': songId}, videoFields)
sortedTrackList, publishedTrackList = createSortedTrackList(publishedTracks)
mixedVideo, mixedAudio = videoInformation(videoDocuments, sortedTrackList, songMixedVideo)
#create a sorted list of published tracks if there are tracks that are published
crossHasPublishedTracks = songDoc.get('hasPublishedTracks')
if crossHasPublishedTracks is not None:
if not (hasPublishedTracks == crossHasPublishedTracks):
print('hasPublishedTracks does not match crossHasPublishedTracks')
print(songId)
#error check if the field hasPublishedTracks in the songs document matches
#what the post document reports
for track in allTracks:
#for all tracks grab the information from the songs collection
trackId = track
isPublished = False
if hasPublishedTracks is True:
for pubTrackId in publishedTrackList:
if str(trackId) == pubTrackId:
isPublished = True
#print('Published Track Match')
break
# check to see if published
trackSettings = songDoc['settings'].get(str(trackId))
#grab trackId and settings of published track.
if trackSettings is None:
if isPublished:
print('Track settings not found for publishedTrack')
print(songId)
print(trackId)
continue
#if no track settings move to next track
trackVolume, mute, compressorValue, echoValue, noiseGateValue, panValue, reverbValue, solo = grabAudioEffectsSettings(trackSettings)
#grab all the audio effects for a track from the songs collection
trackDocument = tracksCol.find({'_id' : trackId}, trackFields).limit(1)
#grab the corresponding track document
for trackDoc in trackDocument:
#look through corresponding track document
if trackDoc['audioChannels']:
audioURL, cleanProcessedAudioURL, processedAudioURL, trackVideo, startTime, trackOwner, trackDuration, audioSampleRate, instrument, fromYouTube = trackInformation(trackDoc, trackSettings, isPublished)
else:
if isPublished:
print('track is published but no audioChannels in track doc')
print(songId)
print(trackId)
continue
data = [] #to hold a row of data
data.append([str(trackId), str(songId), masterOwner, trackOwner, artist, title, views, instrument, contentTags, audioURL, cleanProcessedAudioURL, processedAudioURL, startTime, float(trackDuration), int(audioSampleRate), float(trackVolume), float(compressorValue), float(panValue), float(echoValue), float(noiseGateValue), float(reverbValue), solo, trackVideo, fromYouTube, isFinished, isPublished, hasPublishedTracks, mixedAudio, mixedVideo, str(musicBrainzID), str(newMusicBrainzID), i])
df = pd.DataFrame(data, columns = cols)
#store a row of data and convert to dataframe
hdf.append('bandhub', df, format = 'table', min_itemsize = 500, data_columns = True, compression = 'zlib')
print('Data row appended')
#append data to file
# Note: the min_itemsize is changed to 800 in BandhubAppend.py
i = i + 1 #increment index counter
except pymongo.errors.AutoReconnect:
print('AutoReconnect error')
hdf.close()
#catch reconnect error and close file
try:
cursor.next()
#check if you can continue to iterate through the cursor
except StopIteration:
print('Done')
hdf.close()
#catch raised exception for cursor.next and close file
hdf.close()
#this line of code shouldn't be reached, but included to be safe.
if __name__ == '__main__':
'''
This functions is called when the script is run directly. It will iterate through the
bandhub song collection (limited to songs that are considered public) starting at
startIndex and ending at startIndex+documentLimit and generate an HDF file with the
fields of interest located in all the bandhub collections (songs, tracks, posts,
and mergedVideos)
Parameters (in the accompanying .sh script)
----------
portNum : int
Name of the hdf5 file
databaseName : str
Name of the mongdb database that contains all of the bandhub collections
outputFileName : str
Name of the HDF file to be written out
startIndex : int
Start index in the song collection (public songs only) that iterated over to
generate the HDF file
documentLimit : int
Total number of songs in the song collection to be looked through
Returns
-------
None
'''
parser = argparse.ArgumentParser()
parser.add_argument("portNum", help='Port Number of Mongo Instance', type=int)
parser.add_argument("databaseName", help='Name of bandhub dataset in MongoDB', type=str)
parser.add_argument("outputFileName", help = 'Name of hdf file to be output (ie: bandhub.h5)', type=str)
parser.add_argument("startIndex", help = 'Index in the songs collection from which to begin file creation', type=int)
parser.add_argument("documentLimit", help = 'Total number of songs or collaborations to be looked through', type=int)
#arguments to parse
args = parser.parse_args()
port = args.portNum
db = args.databaseName
outputFN = args.outputFileName
startIndex = args.startIndex
documentLimit = args.documentLimit
#parse args and store values
print('Arugments parsed, ready to begin writing')
songsCollection, postsCollection, videosCollection, tracksCollection = initialize(port,db)
writeData(songsCollection, postsCollection, videosCollection, tracksCollection, outputFN, startIndex, documentLimit)<file_sep>/python_scripts/BandhubAudioDownload.py
'''
Written by <NAME> - Music and Audio Research Lab (MARL)
This script downloads unprocessed and processed audio files of the bandhub dataset
and writes them out as .flac files after zeropadding the individual tracks such that all
tracks within one collaboration are of uniform length
Running this code directly performs the downloading
Please use the associated script DownloadAudio.sh to run this script
'''
import argparse
import pandas as pd
import numpy as np
import os
import urllib
import requests
import soundfile as sf
import errno
import sys
# IMPORTS
def make_dir(directory):
'''
This functions creates a new directory for storing files if that directory does not
already exist.
Parameters
----------
directory : str
Name of the directory to be created
Returns
-------
None
'''
try:
os.mkdir(directory)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
pass
def temp_write_url(url, tempPath):
'''
This functions writes the .ogg url to a temporary file path which needs to be later
be deleted manually by the user
Parameters
----------
url : str
URL of the .ogg file to be downloaded from the internet
tempPath : str
Prepend for the path to the temporary files where the .ogg files are stored
Returns
-------
baseFilename : str
unique filename for a .ogg track grabbed from the URL
tempOutputFN : str
full path of the .ogg file
'''
baseFilename = url.rpartition('/')[2] #partition the URL into unique filename
tempOutputFN = tempPath + '/' + baseFilename #construct an output filename
try:
r = requests.get(url)
with open(tempOutputFN, 'wb') as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
except requests.exceptions.RequestException as e:
print(e)
return baseFilename, tempOutputFN
def write_file(filename, tempPath, outputPath, maxLength, startTime):
'''
This functions reads in a .ogg temporary file and writes out a .flac file after
zeropadding such that all published tracks in a mix are of uniform length
Parameters
----------
filename : str
Unique name of the audio file
tempPath : str
Prepend for the path of the temporary .ogg file which needs to be zeropadded and converted
outputPath : str
Prepend for the path of the final output .flac file
maxLength : int
Maximum length of all published tracks in a mix so be used to generate files with
uniform length
startTime : int
Start time of the track in samples
Returns
-------
None
'''
tempFN = tempPath + '/' + filename
outputFN = outputPath + '/' + filename[:-4] + '.flac'
audioData,samplerate = sf.read(tempFN)
if samplerate != 44100:
print("SR is not 44100")
#print(audioData.shape)
nChan = audioData.ndim
lengthInSamples = max(audioData.shape)
#if startTime > 0 :
if nChan > 1:
ch1 = np.pad(audioData[:,0], ((startTime, maxLength- (startTime+lengthInSamples)),),'constant')
ch2 = np.pad(audioData[:,1], ((startTime, maxLength- (startTime+lengthInSamples)),),'constant')
audioData = np.stack((ch1,ch2),axis = 1)
else:
audioData = np.pad(audioData, ((startTime, maxLength- (startTime+lengthInSamples)),),'constant')
#print(audioData.shape)
sf.write(outputFN, audioData, samplerate)
def download(HDFName, outputPathUnprocessed,outputPathProcessed, tempPath, startIndex, rowLimit, publishedOnly):
'''
This functions performs the file downloading after reading in an HDF file and grouping
the data rows by the songIDs (so that all tracks within a mix are grabbed together).
These files are then written out as .flac files in two separate directory, one for
unprocessed raw audio (without audio effects) and a second for processed audio (with)
audio effects.
Parameters
----------
HDFName : str
Name of the hdf5 file
outputPathUnprocessed : str
Path to the directory where the unprocessed audio is stored
outputPathProcessed : str
Path to the directory where the processed audio is stored
tempPath : str
Path to the directory where the .ogg files downloaded when the web are stored
startIndex : int
Row index where the downloading will begin
rowLimit : int
Total number of rows to be processed
This cap is soft as all tracks in a mix will be processed even if the rowLimit
has been reached
publishedOnly : bool
If true, only the tracks that are published will be downloaded
Returns
-------
None
'''
data = pd.read_hdf(HDFName, "bandhub") # read in HDF file
#dataClean= data.loc[data[columnName].notnull()] #grab unique URLs that are not null
if publishedOnly is True:
data = data.loc[data.isPublished == True] #grab published tracks
data = data[["songId","trackId","audioURL","cleanProcessedAudioURL","startTime","trackDuration"]]
data = data.iloc[startIndex:startIndex+rowLimit+100]
groupedData = data.groupby("songId")
make_dir(outputPathUnprocessed)
make_dir(outputPathProcessed)
make_dir(tempPath)
# try to make new directory, if user has not created it already
rowCounter = startIndex;
for name,group in groupedData:
currRawTracks = group.audioURL
currProcessedTracks = group.cleanProcessedAudioURL
startTimes = group.startTime
validStartTimes = []
currRawTracksFNs = []
currProcessedTracksFNs = []
count = 0;
maxLength = 0;
#writes out the .ogg files and reads them back in to determine max length of all
#tracks within a mix
for url in currRawTracks:
if url[-4:] == '.ogg':
baseFilename, tempFilename = temp_write_url(url, tempPath)
try:
audioData,samplerate = sf.read(tempFilename)
currLength = max(audioData.shape) + startTimes.iloc[count]
currRawTracksFNs.append(baseFilename)
validStartTimes.append(startTimes.iloc[count])
if currLength > maxLength:
maxLength = currLength
except RuntimeError:
print('Unknown data format (unprocessedAudioURL) in row', rowCounter)
count+=1
rowCounter +=1
#writes out the .ogg files and reads them back in to determine max length of all
#tracks within a mix
for url in currProcessedTracks:
if pd.notnull(url):
if url[-4:] == '.ogg':
baseFilename, tempFilename = temp_write_url(url,tempPath)
try:
audioData,samplerate = sf.read(tempFilename)
currLength = max(audioData.shape)
currProcessedTracksFNs.append(baseFilename)
if currLength > maxLength:
maxLength = currLength
except RuntimeError:
print('Unknown data format (processedAudioURL) in row', rowCounter-1)
#elif currLength != maxLength:
#print("Processed Audio Length is not same",url)
# write out the unprocessed and processed audio as .flac files
count = 0;
for fn in currRawTracksFNs:
write_file(fn, tempPath, outputPathUnprocessed, maxLength, validStartTimes[count])
count +=1
if currProcessedTracksFNs:
for fn in currProcessedTracksFNs:
write_file(fn, tempPath, outputPathProcessed, maxLength, 0)
print(rowCounter)
sys.stdout.flush()
if rowCounter > rowLimit+startIndex-1:
print("Final Row Processed", rowCounter - 1)
break
if __name__ == '__main__':
'''
This functions is called if this .py script is run directly and parses the arugments
and passes them to the functions which perform the dataset download. It will download
unprocessed audio to the outputPathUnprocessed and processed audio to the
outputPathProcessed, starting at the startIndex and ending at startIndex + rowLimit.
Parameters (in the accompanying .sh script)
----------
hdfFile : str
Name of the old hdf5 file whose information is to be appended
outputPathUnprocessed : str
Path to the directory where the unprocessed audio will be written
(ie: /scratch/netID/unprocessedAudio)
outputPathProcessed : str
Path to the diretory where the processed audio will be written
(ie: /scratch/netID/processedAudio)
tempPath : str
Path to the directory where the compressed .ogg files will be written
(ie: /scratch/netID/tempFiles)
startIndex : int
First row of the data to be grabbed (0 is the first row)
rowLimit : int
Total number of rows to be processed/downloaded (soft cap)
publishedTracks : bool
True if you want only the tracks that are considered published, false it you want
to download all files in the HDF file.
Returns
-------
None
'''
parser = argparse.ArgumentParser()
parser.add_argument("hdfFile", help='Port Number of Mongo Instance', type=str)
parser.add_argument("outputPathUnprocessed", help = 'Name of folder to download files to (ie: /scratch/netID/TrackAudioU)', type=str)
parser.add_argument("outputPathProcessed", help = 'Name of folder to download files to (ie: /scratch/netID/TrackAudioP)', type=str)
parser.add_argument("tempPath", help = 'Name of folder to store temporary files (ie: /scratch/netID/Temp)', type=str)
parser.add_argument("startIndex", help = 'Index in the dataset to start data download', type=int)
parser.add_argument("rowLimit", help = 'The total number of files to be downloaded', type=int)
parser.add_argument("publishedTracks", help = 'True if you want only published tracks, False if you want the complete set', type=bool)
args = parser.parse_args()
hdfName = args.hdfFile
outputPathUnprocessed = args.outputPathUnprocessed
outputPathProcessed = args.outputPathProcessed
tempPath = args.tempPath
startIndex = args.startIndex
rowLimit = args.rowLimit
publishedOnly = args.publishedTracks
#parse args and store values
print('Arugments parsed, ready to begin downloading')
download(hdfName, outputPathUnprocessed, outputPathProcessed, tempPath, startIndex, rowLimit, publishedOnly)<file_sep>/bash_scripts/FileCreation.sh
#!/bin/bash
#SBATCH --job-name=Create
#SBATCH --nodes=1
#SBATCH --cpus-per-task=2
#SBATCH --mem=40GB
#SBATCH --time=48:00:00
#SBATCH --output=slurm-%j.out
module purge
module load python3/intel/3.5.3
SRCDIR=$HOME
RUNDIR=$SCRATCH/run-${SLURM_JOB_ID/.*}
mkdir -p $RUNDIR
source activate bandhub
module load mongodb/3.4.10
mongod --dbpath /scratch/gjr286/mongodb --fork --logpath mongo.log --port 27017
cd $RUNDIR
chmod +x $SRCDIR/BandhubFileCreation.py
python3 $SRCDIR/BandhubFileCreation.py 27017 'b=bandhub' 'bandhub.h5' 0 30000<file_sep>/python_scripts/BandhubVideoDownload.py
'''
Written by <NAME> - Music and Audio Research Lab (MARL)
This script downloads the track videos of the bandhub dataset
Running this code directly performs the downloading
Please use the associated script DownloadVideo.sh to run this script
'''
import argparse
import pandas as pd
import requests
import errno
import os
import sys
# IMPORTS
def make_dir(directory):
'''
This functions creates a new directory for storing files if that directory does not
already exist.
Parameters
----------
directory : str
Name of the directory to be created
Returns
-------
None
'''
try:
os.mkdir(directory)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
pass
def write_url(url, outputPath):
'''
This functions writes the .ogg url to a temporary file path which needs to be later
be deleted manually by the user
Parameters
----------
url : str
URL of the .mp4 file to be downloaded from the internet
outputPath : str
Path where the .mp4 files will be downloaded to.
Returns
-------
None
'''
baseFilename = url.rpartition('/')[2] #partition the URL into unique filename
outputFilename = outputPath + '/' + baseFilename #construct an output filename
try:
r = requests.get(url)
with open(outputFilename, 'wb') as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
except requests.exceptions.RequestException as e:
print(e)
def download(hdfName, outputPath, startIndex, rowLimit, publishedOnly):
'''
This functions performs the track video downloading after reading in an HDF file.
Parameters
----------
hdfName : str
Name of the hdf5 file
outputPath : str
Path to the directory where the unprocessed audio is stored
startIndex : int
Row index where the downloading will begin
rowLimit : int
Total number of rows to be processed
This cap is soft as all tracks in a mix will be processed even if the rowLimit
has been reached
publishedOnly : bool
If true, only the tracks that are published will be downloaded
Returns
-------
None
'''
data = pd.read_hdf(hdfName, 'bandhub') # read in HDF file
if publishedOnly is True:
data = data.loc[data.isPublished == True] #grab published tracks
data = data.iloc[startIndex:startIndex+rowLimit+100]
dataColumn = data["trackVideoURL"] #grab only the column of interest
make_dir(outputPath)
rowCounter = startIndex
for url in dataColumn:
if pd.notnull(url):
if url[-4:] == '.mp4':
write_url(url, outputPath)
print('Row Processed', rowCounter)
sys.stdout.flush()
rowCounter += 1
if rowCounter > rowLimit+startIndex - 1:
break
print("Final Row Processed", rowCounter-1)
if __name__ == '__main__':
'''
This functions is called when the script is run directly. It will download the track
videos to the outputPath, starting at the startIndex and ending at
startIndex + fileLimit.
Parameters (in the accompanying .sh script)
----------
hdfFile : str
Name of the old hdf5 file whose information is to be appended
outputPath : str
Path to the directory where the video files will be stored
(ie: /scratch/netID/video)
startIndex : int
First row of the data to be grabbed (0 is the first row)
rowLimit : int
Total number of rows to be processed/downloaded (soft cap)
publishedTracks : bool
True if you want only the tracks that are considered published, false it you want
to download all files in the HDF file.
Returns
-------
None
'''
parser = argparse.ArgumentParser()
parser.add_argument("hdfFile", help='Full path to HDF file', type=str)
parser.add_argument("outputPath", help = 'Full path of folder to download video files to', type=str)
parser.add_argument("startIndex", help = 'Index in the dataset to start data download', type=int)
parser.add_argument("fileLimit", help = 'The total number of files to be downloaded', type=int)
parser.add_argument("publishedOnly", help = 'True if you want only published tracks, False if you want the complete set', type=bool)
args = parser.parse_args()
HDFName = args.hdfFile
outputPath = args.outputPath
startIndex = args.startIndex
fileLimit = args.fileLimit
publishedOnly = args.publishedOnly
#parse args and store values
print('Arugments parsed, ready to begin downloading')
download(HDFName, outputPath, startIndex, fileLimit, publishedOnly)<file_sep>/graveyard/BandhubDownload.py
# Written by <NAME> - Music and Audio Research Lab (MARL)
# Download Dataset
# Running this code directly will download the dataset.
# ========================================================================================
import argparse
import pymongo
import pandas as pd
import numpy as np
from bson.objectid import ObjectId
import os
import json
import os
import urllib
import requests
import soundfile as sf
# IMPORTS
# ========================================================================================
#UNCOMPRESSED = False
def Download(filename, columnName, outputPath, startIndex, fileLimit):
data = pd.read_hdf(filename, 'bandhub') # read in HDF file
dataClean= data.loc[data[columnName].notnull()] #grab unique URLs that are not null
if publishedOnly is True:
dataClean = dataClean.loc[dataClean.isPublished == True] #grab published tracks
dataColumn = pd.unique(dataClean[columnName]) #grab only the column of interest
try:
os.mkdir(outputPath)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
pass
# try to make new directory, if user has not created it already
for url in dataColumn[startIndex:startIndex+fileLimit]:
filename = url.rpartition('/')[2] #partition the URL into unique filename
tempOutputFN = outputPath + '/' + filename #construct an output filename
r = requests.get(url)
with open(tempOutputFN, 'wb') as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
#grab the data and write
#if UNCOMPRESSED:
# fullpath = path + '/' + filename
# audioData, samplerate = sf.read(fullpath)
# MAIN FUNCTION
# ========================================================================================
#if running the file directly perform the following
if __name__ == '__main__':
# ========================================================================================
parser = argparse.ArgumentParser()
parser.add_argument("HDFFile", help='Port Number of Mongo Instance', type=str)
parser.add_argument("OutputPath", help = 'Name of folder to download files to (ie: bandhub.h5)', type=str)
parser.add_argument("DataType", help = 'Type of data to be downloaded (ie: Tracks, Videos, MixedAudio, ProcessedAudio,etc.)', type=str)
parser.add_argument("StartIndex", help = 'Index in the dataset to start data download', type=int)
parser.add_argument("FileLimit", help = 'The total number of files to be downloaded', type=int)
parser.add_argument("PublishedTracks", help = 'True if you want only published tracks, False if you want the complete set', type=bool)
#arguments to parse
#The various types are 'Tracks', 'Videos', 'ProcessedAudio', 'MixedAudio'
args = parser.parse_args()
HDFName = args.HDFFile
outputPath = args.OutputPath
dataType = args.DataType
startIndex = args.StartIndex
fileLimit = args.FileLimit
publishedOnly = args.PublishedTracks
#parse args and store values
if dataType == "Tracks":
columnName = "audioURL"
elif dataType == "Videos":
columnName = "trackVideo"
elif dataType == "ProcessedAudio":
columnName = "cleanProcessedAudioURL"
elif dataType == "MixedAudio":
columnName = "mixedVideo"
#mixed audio is created by stripping the mixed video
print('Arugments parsed, ready to begin downloading')
Download(HDFName, columnName, outputPath, startIndex, fileLimit)
#songsCollection, postsCollection, videosCollection, tracksCollection = initialize(port,db) #call the initialize function
#writeData(songsCollection, postsCollection, videosCollection, tracksCollection, outputFN, startIndex, documentLimit) #perform the file creation
# ========================================================================================<file_sep>/bash_scripts/DownloadVideo.sh
#!/bin/bash
#SBATCH --job-name=VideoDL
#SBATCH --nodes=1
#SBATCH --cpus-per-task=2
#SBATCH --mem=20GB
#SBATCH --time=48:00:00
#SBATCH --output=slurm-%j.out
module purge
module load python3/intel/3.5.3
SRCDIR=$HOME
source activate bandhub
chmod +x $SRCDIR/BandhubVideoDownload.py
python3 $SRCDIR/BandhubVideoDownload.py '/scratch/work/marl/bandhub/BandhubDataset.h5' '/scratch/work/marl/bandhub/video' 0 300000 True<file_sep>/bash_scripts/Append.sh
#!/bin/bash
#SBATCH --job-name=Append
#SBATCH --nodes=1
#SBATCH --cpus-per-task=2
#SBATCH --mem=40GB
#SBATCH --time=48:00:00
#SBATCH --output=slurm-%j.out
module purge
module load python3/intel/3.5.3
SRCDIR=$HOME
RUNDIR=$SCRATCH/run-${SLURM_JOB_ID/.*}
mkdir -p $RUNDIR
source activate bandhub
module load mongodb/3.4.10
mongod --dbpath /scratch/gjr286/mongodb2 --fork --logpath mongo.log --port 27017
cd $RUNDIR
chmod +x $SRCDIR/BandhubAppend.py
python3 $SRCDIR/BandhubAppend.py '/scratch/gjr286/NewBandhubDataset.h5' 27017 'BandhubNewAudioEffects.h5' 0
|
60be7ef500ddd1b8f90ac84c08071823f16d5d32
|
[
"Markdown",
"Python",
"Shell"
] | 13 |
Shell
|
marl/bandhub
|
aa90572a607973d3245b70972c6cbe7b6acd9a83
|
b4e4836b7c27aba42798b26d9549b68c8369ead2
|
refs/heads/master
|
<repo_name>PetyaDjanovska/RVroute<file_sep>/app/controllers/favorites_controller.rb
class FavoritesController < ApplicationController
def index
@favorites = current_user.favorites
render 'index'
end
def create
@campsite = Campsite.find_by(id: params[:campsite_id])
@favorite = Favorite.new
@favorite.campsite_id = @campsite.id
@favorite.user_id = current_user.id
@favorite.note = params[:note]
if @favorite.save
redirect_to favorites_path
else
flash[:message] = @favorite.errors.messages[:favorite].first
redirect_to campsites_path
end
end
def most_favorite
@best = Favorite.most_favorite
end
end<file_sep>/app/models/campsite.rb
class Campsite < ApplicationRecord
validates :name, :uniqueness => true
validates :name, :presence => true
has_many :favorites
has_many :users, through: :favorites
has_many :comments
def self.find_by_location(location)
where("address LIKE ?", location).order(:name)
end
end
<file_sep>/app/controllers/campsites_controller.rb
class CampsitesController < ApplicationController
def index
@campsites = Campsite.all
end
def new
@campsite = Campsite.new
end
def create
@campsite = Campsite.find_by(name: params[:campsite][:name])
if @campsite
flash[:message] = "A campsite with that name already exists!"
redirect_to new_campsite_path
else
@campsite = Campsite.create(campsite_args)
redirect_to campsite_path(@campsite)
end
end
def show
@campsite = Campsite.find_by(id: params[:id])
@comment = @campsite.comments.build
end
def edit
@campsite = Campsite.find_by(id: params[:id])
end
def update
@campsite = Campsite.find_by(id: params[:id])
@campsite.update(address: params[:campsite][:address], description: params[:campsite][:description])
redirect_to campsite_path(@campsite)
end
def search
@list = Campsite.find_by_location(params[:location])
end
private
def campsite_args
params.require(:campsite).permit(:name, :address, :description)
end
end
<file_sep>/app/models/favorite.rb
class Favorite < ApplicationRecord
validate :no_repeat_favorites
belongs_to :user
belongs_to :campsite
scope :with_notes, -> { where(note: true) }
def no_repeat_favorites
existing_favorites = Favorite.where(campsite_id: campsite_id, user_id: user_id)
if existing_favorites.exists?
errors.add :favorite, 'already added to Favorites'
end
end
def self.most_favorite
best_id = Favorite.all.group(:campsite_id).count.max_by{|k,v| v}[0]
Campsite.find(best_id)
end
end<file_sep>/README.md
# RVroute
This app allows users to add location and description of a new campsite, thus enabling other users to see
and add it to their favorite places if they wish.
Users are able to add comments about the campsites they visit and check which place is the Favorite for most users.
# Tech/framework used
The app was built using Rails 5.2.0
# Installation
To use the application locally, fork and clone the repo. Then run bundle install, run rake db:migrate to load the databases.
Then, run rails s and navigate to localhost:3000 in your browser.
# Contribute
You are most welcome to contribute if interested.
# Submitting a Pull Request
1. Fork it.
2. Create a branch
3. Commit your changes
4. Push to the branch
5. Open a Pull Request
# License
Copyright (c) 2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<file_sep>/config/routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get '/users/:id', to: 'users#show', as: 'user'
get '/', to: 'application#home'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
get '/logout',to: 'sessions#destroy'
get '/auth/:provider/callback', to: 'sessions#create'
# campsite routes
resources :campsites, only: [:index, :show, :new, :create, :edit, :update] do
resources :comments
end
get '/favorites', to: 'favorites#index'
post '/favorites', to: 'favorites#create'
get '/best_campsite', to: 'favorites#most_favorite'
get '/favorites_with_notes', to: 'favorites#fav_with_notes'
get '/search', to: 'campsites#search'
get '/list', to: 'comments#list'
end
<file_sep>/app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def new
@campsite = Campsite.find_by(id: params[:campsite_id])
@comment = @campsite.comments.build
end
def create
@campsite = Campsite.find_by(id: params[:campsite_id])
@comment = @campsite.comments.build(comment_params)
@comment.user_id = current_user.id
@comment.save
redirect_to campsite_comments_path(@campsite)
end
def index
@campsite = Campsite.find_by(id: params[:campsite_id])
@comments = @campsite.comments
end
def list
@user = current_user
@comments = @user.comments
end
private
def comment_params
params.require(:comment).permit(:title, :text)
end
end<file_sep>/app/models/comment.rb
class Comment < ApplicationRecord
validates :title, :uniqueness => true
belongs_to :campsite
belongs_to :user
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :require_login, except: [:home]
helper_method :current_user
helper_method :logged_in?
protect_from_forgery
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def logged_in?
!!current_user
end
def home
render :layout => "no_nav"
end
private
def require_login
unless logged_in?
flash[:error] = "You must be logged in to access this section"
redirect_to "/"
end
end
end
<file_sep>/app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
skip_before_action :require_login
def new
@user= User.new
render :layout => "no_nav"
end
def create
if auth_hash = request.env['omniauth.auth']
# Existing user
if @user = User.find_by(uid: auth_hash['uid'])
session[:user_id] = @user.id
redirect_to user_path(@user)
else
# New user
@user = User.new(uid: auth_hash['uid'], name: auth_hash['info']['first_name'], password: <PASSWORD>)
if @user.save
session[:user_id] = @user.id
redirect_to user_path(@user)
end
end
else
@user = User.find_by(name: params[:user][:name])
if @user && @user.authenticate(params[:user][:password])
session[:user_id] = @user.id
redirect_to user_path(@user)
else
flash[:message] = "Wrong credentials"
redirect_to '/'
end
end
end
def destroy
session.delete :user_id
redirect_to "/"
end
end<file_sep>/app/models/user.rb
class User < ApplicationRecord
has_secure_password
validates_uniqueness_of :name, :message => "has been taken"
validates_presence_of :name, :message => "can't be blank"
validates :password, :confirmation => true
validates :password_confirmation, :presence => true
has_many :favorites
has_many :campsites, through: :favorites
has_many :comments
end
|
63c74c80fb207ac5526b33be97c64c5c6b54d598
|
[
"Markdown",
"Ruby"
] | 11 |
Ruby
|
PetyaDjanovska/RVroute
|
44bc55b527477722d007502f2866f6c4526c61db
|
50dfee8b617efcc84f4db599bc368c568d061dc5
|
refs/heads/master
|
<file_sep>package secrets
import (
"errors"
"fmt"
"github.com/libopenstorage/openstorage/api"
osecrets "github.com/libopenstorage/secrets"
"github.com/libopenstorage/secrets/k8s"
)
const (
// SecretNameKey is a label on the openstorage.Volume object
// which corresponds to the name of the secret which holds the
// token information. Used for all secret providers
SecretNameKey = "openstorage.io/auth-secret-name"
// SecretNamespaceKey is a label on the openstorage.Volume object
// which corresponds to the namespace of the secret which holds the
// token information. Used for all secret providers
SecretNamespaceKey = "openstorage.io/auth-secret-namespace"
// SecretTokenKey corresponds to the key at which the auth token is stored
// in the secret. Used when secrets endpoint is kubernetes secrets
SecretTokenKey = "auth-token"
)
var (
// ErrSecretsNotInitialized is returned when the auth secret provider is not initialized
ErrSecretsNotInitialized = errors.New("auth token secret instance not initialized")
// ErrAuthTokenNotFound is returned when the auth token was not found in the secret
ErrAuthTokenNotFound = errors.New("auth token was not found in the configured secret")
)
// Auth interface provides helper routines to fetch authorization tokens
// from a secrets store
type Auth struct {
ProviderClient osecrets.Secrets
ProviderType AuthTokenProviders
}
// AuthTokenProviders is an enum indicating the type of secret store that is storing
// the auth token
type AuthTokenProviders int
const (
TypeNone AuthTokenProviders = iota
TypeK8s
TypeDCOS
TypeVault
TypeKVDB
TypeDocker
)
// NewAuth returns a new instance of Auth implementation
func NewAuth(
p AuthTokenProviders,
s osecrets.Secrets,
) (*Auth, error) {
if s == nil {
return nil, ErrSecretsNotInitialized
}
switch p {
case TypeK8s:
return &Auth{s, p}, nil
case TypeDCOS:
return &Auth{s, p}, nil
case TypeVault:
return &Auth{s, p}, nil
case TypeKVDB:
return &Auth{s, p}, nil
case TypeDocker:
return &Auth{s, p}, nil
}
return nil, fmt.Errorf("secrets type %v not supported", p)
}
// GetToken returns the token for a given secret name and context
// based on the configured auth secrets provider.
func (a *Auth) GetToken(tokenSecretContext *api.TokenSecretContext) (string, error) {
var inputSecretKey string
var outputSecretKey string
secretName := tokenSecretContext.SecretName
// Handle edge cases for different providers.
switch a.ProviderType {
case TypeDCOS:
inputSecretKey = tokenSecretContext.SecretName
namespace := tokenSecretContext.SecretNamespace
if namespace != "" {
inputSecretKey = namespace + "/" + secretName
}
outputSecretKey = inputSecretKey
case TypeK8s:
inputSecretKey = tokenSecretContext.SecretName
outputSecretKey = SecretTokenKey
default:
inputSecretKey = tokenSecretContext.SecretName
outputSecretKey = SecretNameKey
}
// Get secret value with standardized interface
secretValue, err := a.ProviderClient.GetSecret(inputSecretKey, a.requestToContext(tokenSecretContext))
if err != nil {
return "", err
}
// Retrieve auth token
authToken, exists := secretValue[outputSecretKey]
if !exists {
return "", ErrAuthTokenNotFound
}
return authToken.(string), nil
}
func (a *Auth) requestToContext(request *api.TokenSecretContext) map[string]string {
context := make(map[string]string)
// Add namespace for providers that support it.
switch a.ProviderType {
case TypeK8s:
context[k8s.SecretNamespace] = request.SecretNamespace
}
return context
}
func (a *Auth) Type() AuthTokenProviders {
return a.ProviderType
}
|
781e1ab29a4a2ffcf645b65f0222001da0553c8a
|
[
"Go"
] | 1 |
Go
|
cleytonocan/openstorage
|
eb0c0cf331cd241ce7b1cb3d3cb3638bc9faec62
|
40eeac5a975e646d94e74723f6629435efb731d9
|
refs/heads/master
|
<file_sep>package core;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by s.sergienko on 16.12.2016.
*/
public class CoreTest {
@Test
public void testIsDependencyFromDaoIsWork() throws Exception {
Assert.assertThat(new Core().getHiFromDao(), Is.is("Hi, I am Dao)"));
}
}<file_sep>package core;
import dao.Dao;
/**
* Created by s.sergienko on 16.12.2016.
*/
public class Core {
public String getHi() {
return "Hi, I am Core)";
}
public String getHiFromDao() {
return new Dao().getHi();
}
}
|
f8872370dc3f110362c593c9c5c398f8cd3ed920
|
[
"Java"
] | 2 |
Java
|
Sergiyenkosa/WebAppModel
|
b084ba81db0bc8c9f427cfdf2e65b7647a005738
|
83814140f951646a5014dc8cdf591751c56b56c0
|
refs/heads/master
|
<repo_name>LaurieOu/PianoGame<file_sep>/frontend/components/Organ.jsx
var React = require('react');
var Key = require('./Key');
var KeyListener = require('../util/KeyListener');
var Recorder = require('./Recorder');
var Instructions = require('./instructions');
var keys = [
'A3','A3S','B3',
'C4','C4S','D4','D4S','E4','F4','F4S','G4','G4S','A4','A4S','B4',
'C5','C5S','D5','D5S','E5','F5','F5S','G5','G5S','A5','A5S','B5',
'C6', 'C6S', 'D6'];
var Organ = React.createClass({
getInitialState: function() {
return {render: false};
},
componentWillMount: function () {
KeyListener.keyStart();
KeyListener.keyEnd();
},
homeClick: function() {
this.setState({render: true});
},
reloadPage: function(e){
e.preventDefault();
location.reload();
},
render: function() {
var organKeys = this.keys();
return (
<div className="main-page">
<div className="falling-notes-container">
<label className="piano-type-label">PianoType</label>
<Recorder />
<button className="home-button" onClick={this.reloadPage}>Home</button>
<Instructions />
</div>
<div className="octave">
{organKeys}
</div>
</div>
);
},
keys: function() {
return keys.map(function(key, idx) {
return <Key key={idx} id={key} />;
});
}
});
module.exports = Organ;
<file_sep>/frontend/components/FightSong.jsx
var React = require('react');
var Note = require('./note');
// 'Q B4', 'Q C5', 'Q D5', 'Q D5', 'Q D5', 'A D5', 'Q D5', 'Q E5', 'Q D5', 'A C5', 'F BN',
// 'Q A4', 'Q C5', 'H C5', 'Q C5', 'Q C5', 'H E5', 'Q D5', 'T B4', 'H BN',
// 'Q D5', 'H G5', 'Q G5', 'A G5', 'Q E5', 'Q F5S', 'Q G5', 'Q A5', 'Q A5', 'A A5', 'Q BN',
// 'Q E5', 'Q G5', 'H A5', 'Q A5', 'Q B5', 'Q C6', 'H B5', 'Q G5', 'T A5', 'Q BN'
var Melody = [
'F F4S', 'H E4', 'F G4', 'H F4S', 'F D4', 'T A3', 'H BN',
'F F4S', 'H E4', 'F G4', 'H F4S', 'F D4', 'T F4S', 'T E4',
'F E4', 'H D4S', 'F F4S', 'H E4', 'F C4S', 'F E4', 'F D4',
'F C4S', 'F D4', 'H B3', 'F C4S', 'F E4', 'F D4', 'H A3', 'H BN',
'F F4S', 'H E4', 'F G4', 'H F4S', 'F D4', 'T A3', 'H BN',
'F F4S', 'H E4', 'F G4', 'H F4S', 'F D4', 'T F4S', 'T E4',
'F E4', 'H D4S', 'F F4S', 'H E4', 'F C4S', 'F E4', 'F D4',
'F C4S', 'F D4', 'H B3', 'F C4S', 'F E4', 'F D4', 'T F4S', 'H BN',
'F F4S', 'F G4', 'F B4', 'T A4',
'H F4S', 'F G4', 'F B4','H A4', 'F E4', 'H G4', 'H BN', 'F F4S', 'H F4S', 'H BN',
'H F4S', 'F G4', 'H A4', 'F C5S', 'F B4', 'F A4', 'H D4', 'H BN', 'F C5S', 'F B4', 'F A4', 'H BN',
'H D4', 'H D4', 'H F4S', 'F E4', 'H D4', 'H A4', 'H B4', 'F D4', 'T E4',
'F F4S', 'F G4', 'F B4', 'T A4',
'H F4S', 'F G4', 'F B4','H A4', 'F E4', 'H G4', 'H BN', 'F F4S', 'H F4S', 'H BN',
'H F4S', 'F G4', 'H A4','F C5S', 'F B4', 'F A4', 'H D4', 'H D4', 'F C5S', 'F D5', 'F A4',
'H D4', 'H D4', 'F F4S','F E4', 'F D4', 'F E4', 'F G4', 'F F4S', 'F D4', 'F C4S', 'H D4'
];
var FightSong = React.createClass({
notes: function() {
return Melody.reverse().map(function(note,idx) {
return <Note note={note} key={idx}/>;
});
},
render: function(){
var notes = this.notes();
return (
<div>
<label className="tip-label">Tip: Focus on typing the letters :)</label>
{notes}
</div>
);
}
});
module.exports = FightSong;
<file_sep>/frontend/util/Track.js
//attrHash = {name, roll: recipe}
// var keyStore = require('../stores/key_store');
var KeyActions = require('../actions/KeyActions');
var Track = function (attrHash) {
this.name = "";
this.roll = [];
if (attrHash !== undefined) {
this.name = attrHash.name;
this.roll = attrHash.roll;
}
}
Track.prototype = {
startRecording: function() {
this.roll = [];
this.start = Date.now();
},
addNotes: function(notes) {
var timeDiff = Date.now() - this.start;
this.roll.push({"timeDiff": timeDiff, "notes": notes});
},
stopRecording: function() {
this.addNotes([]);
},
isBlank: function() {
return this.roll.length === 0;
},
play: function() {
if (this.interval) {return;}
var playbackStartTime = Date.now();
var currentNote = 0;
this.interval = setInterval(function() {
if (currentNote < this.roll.length) {
if (Date.now() - playbackStartTime >= this.roll[currentNote].timeDiff) {
var notes = this.roll[currentNote].notes || [] ;
KeyActions.updateNotes(notes);
currentNote++;
}
} else {
clearInterval(this.interval);
delete this.interval
}
}.bind(this), 1);
}
};
module.exports = Track;
<file_sep>/frontend/components/instructions.jsx
var React = require('react');
var FightSong = require('./FightSong');
var Instructions = React.createClass({
getInitialState: function() {
return {show: true, showFightSong: false };
},
individualPractice: function() {
this.setState({show: false});
},
playSong: function() {
this.setState({show: false});
this.setState({showFightSong: true});
},
render: function() {
var instructions = "";
if (this.state.show) {
instructions = (
<div className="instructions-container">
<img src="http://www.streathamchoral.com/communities/6/004/012/793/646//images/4613017096.gif" className="notes-picture" />
<div className="whole-new-world-instructions">
<label className="instructions-text2">
Welcome! You can play "A Whole New World" from Aladdin! Type the letters inside the falling rectangles.
</label><br/>
<button onClick={this.playSong} className="play-song-button">Play A Whole New World!</button>
</div>
<div className="whole-new-world-instructions">
<label className="instructions-text1">
OR you can practice independently and record yourself on the piano.
</label><br/>
<button onClick={this.individualPractice} className="practice-on-own-button">Practice On Your Own</button>
</div>
</div>
)
};
var fightSong = "";
if(this.state.showFightSong) {
fightSong = (
<FightSong />
)
};
return (
<div>
{instructions}
{fightSong}
</div>
);
}
});
module.exports = Instructions;
<file_sep>/frontend/components/Key.jsx
var React = require('react');
var keyStore = require('../stores/key_store');
var Tones = require('../constants/Tones');
var Note = require('../util/Note');
Mapping = {
'A3': 'Z',
'A3S': 'S',
'B3': 'X',
'C4': 'C',
'C4S': 'F',
'D4': 'V',
'D4S': 'G',
'E4': 'B',
'F4': 'N',
'F4S': 'J',
'G4': 'M',
'G4S': 'K',
'A4': '<',
'A4S': 'L',
'B4': '>',
'C5': '?',
'C5': 'Q',
'C5S': '2',
'D5': 'W',
'D5S': '3',
'E5': 'E',
'F5': 'R',
'F5S': '5',
'G5': 'T',
'G5S': '6',
'A5': 'Y',
'A5S': '7',
'B5': 'U',
'C6': 'I',
'C6S': '9',
'D6': 'O'
};
var Key = React.createClass({
getInitialState: function() {
return {KeyStore: keyStore.all(), keyNote: undefined, playing: false};
},
_keysChanged: function () {
this.setState({KeyStore: keyStore.all()});
},
componentDidMount: function() {
this.state.keyNote = new Note(Tones[this.props.id]);
keyStore.addListener(this._keysChanged);
},
playNote: function (id) {
if (this.state.keyNote) {
if (this.state.KeyStore.includes(id)) {
this.state.keyNote.start();
this.state.playing = true;
} else {
this.state.keyNote.stop();
this.state.playing = false;
}
}
},
render: function() {
var id = this.props.id;
var letter = Mapping[id];
var type = '';
var notesLabel = "notes-label";
this.playNote(id);
if (id.includes('S')) {
type += ' sharp';
notesLabel += "-S"
}
if (this.state.playing) {
type += ' playing';
}
return (
<div >
<h1 id={id} className={type}><span className={notesLabel}>{letter}</span></h1>
</div>
);
}
});
module.exports = Key;
<file_sep>/README.md
# PianoGame
![alt tag] (http://res.cloudinary.com/ddefvho7g/image/upload/v1458106937/Screen_Shot_2016-03-15_at_10.37.32_PM_kbhvls.png)
##Summary
PianoType is an educational game that teaches one how to type as well as play
the piano simultaneously. The back end utilizes Ruby on Rails while the front end
uses Flux/React architecture. The app allows users to:
- use their keyboard as a piano to make music
- record their songs by pressing 'Start Recording'
- play back the song they recorded by pressing 'Play Recording'
- play a predesigned song by pressing 'Play A Whole New World!'
- see what note they are pressing because the notes highlight
- record their own original songs by pressing 'Practice On Your Own'
##Overall Structure
###Back end
The Back end was built using Ruby on Rails. There weren't any database requests.
###Front end
The front end utilized React.js and Javascript. The piano, notes, and recorder
are re-rendered without sending requests to the server constantly. This is done
through React's virtual DOM which update elements that have changed state. CSS
animations and transforms are used to make the notes slide down the screen by
translating each note and setting the duration of the whole song.
###Libraries
- React.js
- Flux
##Primary Components
###Piano
Used window.AudioContext to support sound inputs and produces a sound using the
Web Audio API. It creates a sound sources and connects them to the AudioContext
sound destinations.
var ctx = new (window.AudioContext || window.webkitAudioContext)();
gainNode.connect(ctx.destination);
###Recorder
The recorder is made using the React/Flux architecture. In the recorder
component, a Listener adds all the notes a user presses to the Track Util.
When 'Play Recording' is pressed, we throttle through an iteration of all the
notes that's been added to the track by using setInterval. Inside the setInterval,
the keyStore is called every 1ms to update the keys in the store.
![alt tag] (http://res.cloudinary.com/ddefvho7g/image/upload/v1458108881/Screen_Shot_2016-03-15_at_11.14.16_PM_tpkqhf.png)
###Sliding notes
Used mixins so that the app will be supported in different browsers. The code I
used to make the notes slide from top to bottom:
.music-note {
text-align: center;
@include animation("falling-keys linear");
@include animation-duration(160s);
margin-top: 3px;
}
@include keyframes(falling-keys) {
0% {
@include transform(translateY(-14700px))
}
100% {
@include transform(translateY(15000px))
}
}
![alt tag] (http://res.cloudinary.com/ddefvho7g/image/upload/v1458106945/Screen_Shot_2016-03-15_at_10.39.01_PM_febdr7.png)
<file_sep>/frontend/actions/KeyActions.js
var Dispatcher = require('../dispatcher/Dispatcher');
var KeyActions = {
addNote: function(key) {
Dispatcher.dispatch({
actionType: "ADD_NOTE",
note: key
});
},
removeNote: function(key) {
Dispatcher.dispatch({
actionType: "REMOVE_NOTE",
note: key
});
},
updateNotes: function(notes) {
Dispatcher.dispatch ({
actionType: "UPDATE_NOTES",
notes: notes
});
}
};
module.exports = KeyActions;
|
4a6ef466520d350cb717b728caae31b091f00130
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
LaurieOu/PianoGame
|
d23ee24458f51cc12bda18f2b6a7b6bc6d2be556
|
ab9b6aabee2b7282a07aeb4f4fb55b11ca13ef54
|
refs/heads/master
|
<file_sep>using adviceMe.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
namespace adviceMe.Api
{
class API
{
public static String URL = "http://advisemeapp.herokuapp.com/api";
/*public static String URL = "http://192.168.1.37:3000/api";*/
public static String requestURL(String path)
{
return URL + path;
}
/* public async static void doRequest(){
using (var client = new HttpClient())
{
User user = new User("login", "email", "<PASSWORD>");
var data = new Dictionary<String, String>();
DataContractJsonSerializer serialer = new DataContractJsonSerializer(typeof(User));
using (MemoryStream stream = new MemoryStream())
{
serialer.WriteObject(stream, user);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
String param = sr.ReadToEnd();
data["user"] = param;
}
HttpResponseMessage result = await client.PostAsync(requestURL("/users.json"), new FormUrlEncodedContent(data));
string resultContent = result.Content.ReadAsStringAsync().Result;
}
}*/
public async static Task<HttpResponseMessage> doPost(string path, String param)
{
using (var client = new HttpClient())
{
StringContent theContent = new StringContent(param, System.Text.Encoding.UTF8, "application/json");
return await client.PostAsync(requestURL(path),theContent);
}
}
public async static Task<HttpResponseMessage> doGet(string path, String param)
{
using (var client = new HttpClient())
{
StringContent theContent = new StringContent(param, System.Text.Encoding.UTF8, "application/json");
return await client.GetAsync(requestURL(path));
}
}
public static string serialize(Object obj, System.Type type)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, obj);
stream.Position = 0;
string json = Encoding.UTF8.GetString(stream.ToArray(), 0, stream.ToArray().Length);
/*StreamReader sr = new StreamReader(stream);*/
return json ;
}
}
}
}
<file_sep>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace adviceMe.Model
{
[DataContract]
class UserInfo
{
public UserInfo()
{
}
[DataMember]
public String id;
[DataMember]
public String email;
[DataMember]
public String name;
public static UserInfo desirialize(String json)
{
return JsonConvert.DeserializeObject<UserInfo>(json.Substring(8, json.Length - 9));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.UI.Xaml.Media.Imaging;
// Документацию по шаблону элемента пустой страницы см. по адресу http://go.microsoft.com/fwlink/?LinkID=390556
namespace adviceMe
{
/// <summary>
/// Пустая страница, которую можно использовать саму по себе или для перехода внутри фрейма.
/// </summary>
///
public sealed partial class CameraPage : Page
{
Windows.Media.Capture.MediaCapture captureManager;
string uri;
public CameraPage()
{
this.InitializeComponent();
}
/// <summary>
/// Вызывается перед отображением этой страницы во фрейме.
/// </summary>
/// <param name="e">Данные события, описывающие, каким образом была достигнута эта страница.
/// Этот параметр обычно используется для настройки страницы.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
InitCamera_Click();
}
async protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
await captureManager.StopPreviewAsync();
}
async private void InitCamera_Click()
{
captureManager = new MediaCapture();
await captureManager.InitializeAsync();
capturePreview.Source = captureManager;
capturePreview.UpdateLayout();
await captureManager.StartPreviewAsync();
}
async private void Button_Click(object sender, RoutedEventArgs e)
{
ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
//await captureManager.StopPreviewAsync();
// create storage file in local app storage
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"TestPhoto.jpg",
CreationCollisionOption.GenerateUniqueName);
// take photo
await captureManager.CapturePhotoToStorageFileAsync(imgFormat, file);
// Get photo as a BitmapImage
uri = file.Path;
// imagePreivew is a <Image> object defined in XAML
//capturePreivew.Source = bmpImage;
Frame.Navigate(typeof(PhotoPreviewPage), uri);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media.Imaging;
// Документацию по шаблону элемента пустой страницы см. по адресу http://go.microsoft.com/fwlink/?LinkID=390556
namespace adviceMe
{
/// <summary>
/// Пустая страница, которую можно использовать саму по себе или для перехода внутри фрейма.
/// </summary>
public sealed partial class PhotoPreviewPage : Page
{
public PhotoPreviewPage()
{
this.InitializeComponent();
}
/// <summary>
/// Вызывается перед отображением этой страницы во фрейме.
/// </summary>
/// <param name="e">Данные события, описывающие, каким образом была достигнута эта страница.
/// Этот параметр обычно используется для настройки страницы.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var uri = e.Parameter as string;
BitmapImage bmpImage = new BitmapImage(new Uri(uri));
previewPhoto.Source = bmpImage;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(CameraPage));
}
}
}
<file_sep>using adviceMe.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Phone.UI.Input;
using System.Threading.Tasks;
using System.Net.Http;
// Документацию по шаблону элемента "Пустая страница" см. по адресу http://go.microsoft.com/fwlink/?LinkId=391641
namespace adviceMe
{
/// <summary>
/// Пустая страница, которую можно использовать саму по себе или для перехода внутри фрейма.
/// </summary>
public sealed partial class LoginPage : Page
{
public LoginPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Вызывается перед отображением этой страницы во фрейме.
/// </summary>
/// <param name="e">Данные события, описывающие, каким образом была достигнута эта страница.
/// Этот параметр обычно используется для настройки страницы.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Подготовьте здесь страницу для отображения.
// TODO: Если приложение содержит несколько страниц, обеспечьте
// обработку нажатия аппаратной кнопки "Назад", выполнив регистрацию на
// событие Windows.Phone.UI.Input.HardwareButtons.BackPressed.
// Если вы используете NavigationHelper, предоставляемый некоторыми шаблонами,
// данное событие обрабатывается для вас.
}
private void TextBlock_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void TextBlock_SelectionChanged_1(object sender, RoutedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
User user = new User("login", "<EMAIL>", "<PASSWORD>");
//сериализовать в json
String param = Api.API.serialize(user, typeof(User));
/*changes - это callback*/
//Api.API.doPost("/users.json", param).ContinueWith((requestTask) => changes(requestTask.Result));
Frame.Navigate(typeof(CategoryPage));
}
private object changes(HttpResponseMessage httpResponseMessage)
{
var json = httpResponseMessage.Content.ReadAsStringAsync().Result;
UserInfo user = UserInfo.desirialize(json as string);
return user;
}
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
Frame frame = Window.Current.Content as Frame;
if (frame == null)
{
return;
}
if (frame.CanGoBack)
{
frame.GoBack();
e.Handled = true;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Devices.Geolocation;
// Документацию по шаблону элемента пустой страницы см. по адресу http://go.microsoft.com/fwlink/?LinkID=390556
namespace adviceMe
{
/// <summary>
/// Пустая страница, которую можно использовать саму по себе или для перехода внутри фрейма.
/// </summary>
public sealed partial class CategoryPage : Page
{
public CategoryPage()
{
this.InitializeComponent();
}
/// <summary>
/// Вызывается перед отображением этой страницы во фрейме.
/// </summary>
/// <param name="e">Данные события, описывающие, каким образом была достигнута эта страница.
/// Этот параметр обычно используется для настройки страницы.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private void TextBlock_SelectionChanged(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(restaurantsTop));
}
private void TextBlock_Tapped(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(restaurantsTop));
}
private void TextBlock_Tapped_1(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(allRestaurants));
}
private void TextBlock_Tapped_2(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(PhotoRate));
}
private void TextBlock_Tapped_3(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(CameraPage));
}
async private void TextBlock_SelectionChanged_1(object sender, RoutedEventArgs e)
{
}
async private void TextBlock_Tapped_4(object sender, TappedRoutedEventArgs e)
{
//gps
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracyInMeters = 50;
try
{
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(5),
timeout: TimeSpan.FromSeconds(10)
);
string latitude = geoposition.Coordinate.Latitude.ToString("0.000000");
string longitude = geoposition.Coordinate.Longitude.ToString("0.000000");
}
//If an error is catch 2 are the main causes: the first is that you forgot to include ID_CAP_LOCATION in your app manifest.
//The second is that the user doesn't turned on the Location Services
catch (Exception ex)
{
//exception
}
}
}
}
|
70312fb98988fa4473e69dc2040683ae0e6bb8a9
|
[
"C#"
] | 6 |
C#
|
kas1906/AdviceMeWindowsPhoneApp
|
ad36e770f3bb65fc5182fc0ef8d91606cc20f1d3
|
c5393fb8b23bb262522bacaa48d83d889d65449f
|
refs/heads/master
|
<file_sep>package loops;
public class ForLooo {
public static void main(String[] args) {
for (int i =100; i<120; i++){
System.out.println(i);
}
}
}
<file_sep>package superKeyword_Constructor;
public class CarStructure {
public CarStructure (){
System.out.println("Car structure is created");
}
}
<file_sep>package StaticVariableAndMethod;
public class TestVariable {
public static void main(String[] args) {
MakeStaticVariable.age = 30;
System.out.println(MakeStaticVariable.age);
MakeStaticVariable.age = 50;
System.out.println(MakeStaticVariable.age);
// MakeStaticVariable uzzal = new MakeStaticVariable();
// uzzal.age = 38;
// System.out.println("Age of Uzzal: " +uzzal.age);
// MakeStaticVariable riffat = new MakeStaticVariable();
// riffat.age = 28;
// System.out.println("Age of Riffat: "+riffat.age);
}
}<file_sep>package StaticVariableAndMethod;
public class TestStaticClass {
public static void main(String[] args) {
MakeStaticClass.studentName();
MakeStaticClass.studentAddress();
MakeStaticClass msc = new MakeStaticClass();
msc.display();
msc.getRoomSize();
System.out.println("Room Size: "+ msc.getRoomSize());
}
}
<file_sep>package StaticVariableAndMethod;
public class MakeStaticVariable {
static int age;
public int getAge(){
return age;
}
}
<file_sep>package superKeyWord;
public class TestAge {
public static void main(String[] args) {
SonAge sa = new SonAge();
sa.displayAge();
}
}
<file_sep>package stringClass;
public class StringClass {public static void main(String[] args) {
String s = "My name is Uzzal";
System.out.println(s); // will show s value
System.out.println(s.charAt(8)); // Returns the char value at the specified index.
System.out.println(s.length()); // will show length of s value
System.out.println(s.concat(" Palma")); // will add after s value
System.out.println(s.trim());
System.out.println(s.substring(0, 10)); // will show between 0-10 all character
System.out.println(s.codePointAt(6));
System.out.println(s.codePointBefore(7));
System.out.println(s.compareToIgnoreCase(s));
System.out.println(s.toLowerCase());
System.out.println(s.toUpperCase());
System.out.println(" ");
String str = "Learning Team";
String str1 = new String ("learning team");
String str2 = new String ("Java Team");
System.out.println(str.compareToIgnoreCase(str1));
System.out.println(str1.compareTo(str2)); //
System.out.println(s.endsWith(str2));
System.out.println(str.indexOf(2, 5));
}
}
<file_sep>package NestedClass;
public class NestedClassChild {
Father father = new Father();
public void Son(){
System.out.println("Outer Method :Son is doing a nice job");
father.fatherBusiness();
father.fatherBankBalance();
Mother.motherIndustry();
Mother.motherJewelery();
}
public void Daughter(){
System.out.println("Outer Method :Daughter is studying in NYU");
father.fatherBusiness();
father.fatherBankBalance();
Mother.motherIndustry();
Mother.motherJewelery();
}
public class Father{
private void fatherBusiness(){
System.out.println("Inner Method: Father is a businessman");
}
private void fatherBankBalance(){
System.out.println("Inner Method: Father is a Bilinear");
}
}
public static class Mother{
private static void motherIndustry(){
System.out.println("Inner Method: Father is a businessman");
}
private static void motherJewelery (){
System.out.println("Inner Method: Father is a Bilinear");
}
}
}
<file_sep>package HashMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MakingHashMap {
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(1, "USA, UK");
hashMap.put(2, "Australia");
hashMap.put(3, "Natherland");
hashMap.put(4, "France");
for(Map.Entry <Integer, String> map:hashMap.entrySet()) {
System.out.println(map.getKey()+ " -- "+ map.getValue());
}
}
}
<file_sep>package linkListAndArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class MakeLinkList {
public static void main(String[] args) {
List<String> list = new LinkedList<String>();
list.add("Dhaka");
list.add("Chittagong");
list.add("Rajshahi");
list.add("Khulna");
list.add("Sylhet");
for (String st: list)
System.out.println(st);
System.out.println(" ");
list.size();
System.out.println("size of list: "+ list.size());
System.out.println(" ");
list.remove(3);
Iterator it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
<file_sep>package thisKeyWord;
public class ThisData {
int a;
int b;
int c;
public void setData(int a, int b){
this.a = a;
this.b = b;
}
public void displahyData(){
System.out.println("Value of A= : " + a);
System.out.println("Value of A= : " + a);
}
public void plusData(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
System.out.println("Value of a+b+c total= " +(a+b+c));
}
public static void main(String[] args) {
ThisData td = new ThisData();
td.setData(34, 78);
td.displahyData();
td.plusData(12, 13, 18);
}
}
|
03530916ef4ab5b86c1bb2308df360e8668e8682
|
[
"Java"
] | 11 |
Java
|
upalma/HomeWorkPartA
|
432b67912d50d5a99b05ff6b85663fc08ffcc8fe
|
b71d3d442b84e24a29ad6edf747ed68f2bddd129
|
refs/heads/master
|
<repo_name>yovienug1106/user-reporting-vr<file_sep>/Assets/Editor/BugReporting/DevLogWindow.cs
using System;
using Unity.Cloud.UserReporting;
using Unity.Cloud.UserReporting.Plugin;
using UnityEditor;
using UnityEngine;
namespace Assets.Editor.UserReporting
{
public class DevLogWindow : EditorWindow
{
#region Static Methods
[MenuItem("Dev Log/Dev Log Window")]
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(DevLogWindow));
}
#endregion
#region Constructors
public DevLogWindow()
{
this.titleContent = new GUIContent("Dev Log");
this.summary = string.Empty;
this.description = string.Empty;
}
#endregion
#region Fields
private UserReport userReport;
private bool creating;
private string description;
private bool submitting;
private string summary;
private Texture thumbnailTexture;
#endregion
#region Methods
private void Create()
{
this.creating = false;
if (Application.isPlaying)
{
if (UnityUserReporting.CurrentClient != null)
{
UnityUserReporting.CurrentClient.TakeScreenshot(2048, 2048, s => { });
UnityUserReporting.CurrentClient.TakeScreenshot(512, 512, s => { });
UnityUserReporting.CurrentClient.CreateUserReport((br) =>
{
this.SetThumbnail(br);
this.summary = string.Empty;
this.description = string.Empty;
this.userReport = br;
});
}
else
{
EditorUtility.DisplayDialog("Dev Log", "Bug Reporting is not configured. Bug Reporting is required for dev logs. Call UnityUserReporting.Configure() to configure Bug Reporting or add the UserReportingPrefab to your scene.", "OK");
}
}
else
{
EditorUtility.DisplayDialog("Dev Log", "Dev logs can only be sent in play mode.", "OK");
}
}
private void CreatePropertyField(string propertyName)
{
SerializedObject serializedObject = new SerializedObject(this);
SerializedProperty stringsProperty = serializedObject.FindProperty(propertyName);
EditorGUILayout.PropertyField(stringsProperty, true);
serializedObject.ApplyModifiedProperties();
}
private void OnGUI()
{
float spacing = 16;
if (Application.isPlaying)
{
GUIStyle buttonStyle = new GUIStyle(GUI.skin.button);
buttonStyle.margin = new RectOffset(8, 8, 4, 4);
buttonStyle.padding = new RectOffset(8, 8, 4, 4);
GUIStyle textAreaStyle = new GUIStyle(GUI.skin.textArea);
textAreaStyle.wordWrap = true;
GUILayout.Space(spacing);
this.creating = GUILayout.Button("New Dev Log", buttonStyle, GUILayout.ExpandWidth(false));
if (this.userReport != null)
{
GUILayout.Space(spacing);
Rect lastRect = GUILayoutUtility.GetLastRect();
float imageHeight = Mathf.Min(this.position.width, 256);
EditorGUI.DrawPreviewTexture(new Rect(0, lastRect.yMax, this.position.width, imageHeight), this.thumbnailTexture, null, ScaleMode.ScaleToFit);
GUILayout.Space(imageHeight);
GUILayout.Space(spacing);
GUILayout.Label("Summary");
this.summary = EditorGUILayout.TextField(this.summary, textAreaStyle);
GUILayout.Label("Notes");
this.description = EditorGUILayout.TextArea(this.description, textAreaStyle, GUILayout.MinHeight(128));
GUILayout.Space(spacing);
EditorGUILayout.BeginHorizontal();
this.submitting = GUILayout.Button("Submit Dev Log", buttonStyle, GUILayout.ExpandWidth(false));
GUILayout.Space(spacing);
EditorGUILayout.EndHorizontal();
}
}
else
{
GUIStyle labelStyle = new GUIStyle(GUI.skin.label);
labelStyle.alignment = TextAnchor.UpperCenter;
labelStyle.margin = new RectOffset(8, 8, 8, 8);
labelStyle.wordWrap = true;
GUILayout.Space(spacing);
EditorGUILayout.HelpBox("Dev logs can only be sent in play mode.", MessageType.Info);
GUILayout.Space(spacing);
}
}
public void OnInspectorUpdate()
{
this.Repaint();
}
private void SetThumbnail(UserReport userReport)
{
if (userReport != null)
{
byte[] data = Convert.FromBase64String(userReport.Thumbnail.DataBase64);
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(data);
this.thumbnailTexture = texture;
}
}
private void Submit()
{
this.submitting = false;
if (Application.isPlaying)
{
if (UnityUserReporting.CurrentClient != null)
{
this.userReport.Summary = this.summary;
this.userReport.Fields.Add(new UserReportNamedValue("Notes", this.description));
this.userReport.Dimensions.Add(new UserReportNamedValue("DevLog", "True"));
this.userReport.IsHiddenWithoutDimension = true;
// Send
UnityUserReporting.CurrentClient.SendUserReport(this.userReport, (success, br2) =>
{
this.userReport = null;
if (EditorUtility.DisplayDialog("Dev Log", "Dev log submitted. Would you like to view it?", "View", "Don't View"))
{
string url = string.Format("https://developer.cloud.unity3d.com/userreporting/direct/projects/{0}/reports/{1}", br2.ProjectIdentifier, br2.Identifier);
Application.OpenURL(url);
}
});
}
else
{
EditorUtility.DisplayDialog("Dev Log", "Bug Reporting is not configured. Bug Reporting is required for dev logs. Call UnityUserReporting.Configure() to configure In-Game Bug Reporting or add the UserReportingPrefab to your scene.", "OK");
}
}
else
{
EditorUtility.DisplayDialog("Dev Log", "Dev logs can only be sent in play mode.", "OK");
}
}
private void Update()
{
if (this.creating)
{
this.Create();
}
if (this.submitting)
{
this.Submit();
}
}
#endregion
}
}<file_sep>/README.md
# Unity Cloud Diagnostics: User Reporting VR Sample
This is a VR Unity project that uses the User Reporting feature of Unity Cloud Diagnostics.
<file_sep>/Assets/DeviceScript.cs
using System.Collections.Generic;
using Unity.Cloud.UserReporting.Plugin;
using UnityEngine;
public class DeviceScript : MonoBehaviour
{
#region Constructors
public DeviceScript()
{
this.summaries = new List<string>();
this.summaries.Add("Audio Issue");
this.summaries.Add("Graphics Issue");
this.summaries.Add("Physics Issue");
}
#endregion
#region Fields
private bool isSubmitting;
public RenderTexture RenderTexture;
public TextMesh StatusText;
private List<string> summaries;
private int summaryIndex;
public TextMesh SummaryText;
#endregion
#region Methods
public void OnSubmit()
{
if (this.isSubmitting)
{
return;
}
this.isSubmitting = true;
UnityUserReporting.CurrentClient.TakeScreenshotFromSource(2048, 2048, this.RenderTexture, s => { });
UnityUserReporting.CurrentClient.TakeScreenshotFromSource(512, 512, this.RenderTexture, s => { });
UnityUserReporting.CurrentClient.CreateUserReport((br) =>
{
UnityUserReporting.CurrentClient.SendUserReport(br, (success, br2) =>
{
this.isSubmitting = false;
});
});
}
public void OnSummaryChange()
{
this.summaryIndex++;
if (this.summaryIndex >= this.summaries.Count)
{
this.summaryIndex = 0;
}
}
private void Update()
{
if (this.SummaryText != null)
{
this.SummaryText.text = this.summaries[this.summaryIndex];
}
if (this.StatusText != null)
{
this.StatusText.text = this.isSubmitting ? "Sending" : "Ready";
}
}
#endregion
}<file_sep>/Assets/Spawner.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Unity.Cloud.UserReporting;
using Unity.Cloud.UserReporting.Plugin;
using UnityEngine;
using Random = UnityEngine.Random;
public class Spawner : MonoBehaviour
{
#region Fields
private int cubeCount;
public Material material;
public Camera CameraSource;
private float duration;
private Queue<GameObject> spawnedCubes;
#endregion
#region Methods
private void SpawnCube()
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
Vector2 positionInCirle = Random.insideUnitCircle;
positionInCirle *= 100;
cube.transform.position = new Vector3(positionInCirle.x, 100, positionInCirle.y);
Renderer cubeRenderer = cube.GetComponent<Renderer>();
cubeRenderer.material = this.material;
Rigidbody rigidBody = cube.AddComponent<Rigidbody>();
rigidBody.velocity = new Vector3((Random.value - 0.5F) * 10, 0, (Random.value - 0.5F) * 10);
rigidBody.angularVelocity = new Vector3((Random.value - 0.5F) * Mathf.PI * 10, (Random.value - 0.5F) * Mathf.PI * 10, (Random.value - 0.5F) * Mathf.PI * 10);
this.cubeCount++;
this.spawnedCubes.Enqueue(cube);
if (this.spawnedCubes.Count > 300)
{
GameObject spawnedCube = this.spawnedCubes.Dequeue();
Destroy(spawnedCube);
}
}
private void Start()
{
this.spawnedCubes = new Queue<GameObject>();
}
private void Update()
{
this.duration += Time.deltaTime;
if (this.duration > 0.1F)
{
this.duration = 0;
this.SpawnCube();
}
}
#endregion
}
|
4f5ec4a22a831b0a93ecd79e1bdfd724f1ac9649
|
[
"Markdown",
"C#"
] | 4 |
C#
|
yovienug1106/user-reporting-vr
|
9992894439c3ab1866cec2cc8f36b843924bfd5e
|
dcc0355556a4c38b8aa1a2cbd1b740d3381a46bb
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
'''
1. 输入框,支持鼠标点击及键盘混合输入
2. 输入框,支持鼠标点击退格及键盘退格
3. 自自定义,字符串连接操作
4. 有待完善功能, +/-/*//数据类型验证
'''
from Tkinter import *
class CalButton:
def __init__(self, frame, n, fn):
self.frame = frame
self.value = n
self.fn = fn
self.button = Button(frame, text=n, command=self.get_value)
def get_value(self):
self.fn(self.value)
def key(event):
print "pressed", repr(event.char)
class Calculator(Frame):
def __init__(self, master, **kw):
self.frame = Frame(master, height=480, width=320)
self.frame.pack_propagate(0)
self.frame.pack()
self.cal_init()
def cal_init(self):
self.op_label = Label(self.frame, text="Op")
self.op_label.grid(row=1)
Label(self.frame, text="result").grid(row=3)
self.entry3 = Entry(self.frame)
op = Label(self.frame, text="", height=2) #占位用
op.grid(row=5, column=1)
self.entry3.grid(row=3, column=1)
self.entry1_init()
self.op_init()
self.entry2_init()
self.button_init()
# 计算,清除按钮
cal_button = Button(self.frame, text='计算', command=self.cal_fun)
clear_button = Button(self.frame, text='清除', command=self.clear_fun)
zw_button = Button(self.frame, text='C', command=self.clear_step)
cal_button.grid(row=10, column=0)
clear_button.grid(row=10, column=1)
zw_button.grid(row=10, column=2)
def entry1_init(self):
Label(self.frame, text="Num1").grid(row=0)
self.entry1 = Entry(self.frame)
self.entry1.grid(row=0, column=1)
self.entry1.focus_set()
self.entry1.bind('<FocusIn>', self.entry1_focusin)
def entry1_focusin(self, event):
self.entry = '1'
def entry2_init(self):
Label(self.frame, text="Num2").grid(row=2)
self.entry2 = Entry(self.frame)
self.entry2.grid(row=2, column=1)
self.entry2.bind('<FocusIn>', self.entry2_focusin)
def entry2_focusin(self, event):
self.entry = '2'
def op_init(self):
self.op_list = Listbox(self.frame, height=2)
# self.op_list.configure(height=5)
for item in ['+', '-', '*', '/', '字符串连接']:
self.op_list.insert(END, item)
self.op_list.grid(row=1, column=1)
# self.op_list.bind("<Key>", self.key_press)
# self.op_list.bind("<Button-1>", self.set_focus)
# self.op_list.activate(0)
def button_init(self):
num1 = self.create_button(1)
num2 = self.create_button(2)
num3 = self.create_button(3)
num4 = self.create_button(4)
num5 = self.create_button(5)
num5 = self.create_button(6)
num5 = self.create_button(7)
num5 = self.create_button(8)
num5 = self.create_button(9)
def create_button(self, n):
num = CalButton(self.frame, n, self.get_button_value)
if(1 <= n <= 3 ):
row = 6
column = n - 1
if(4 <= n <= 6):
row = 7
column = n - 4
if( 7 <= n <= 9):
row = 8
column = n - 7
num.button.grid(row=row, column=column)
return num.button
def get_button_value(self, value):
if self.entry == '1':
self.entry1.insert(END, value)
if self.entry == '2':
self.entry2.insert(END, value)
print value
def select_op(self):
print 1111
def cal_fun(self):
self.op = self.op_list.get(ACTIVE)
entry1 = self.entry1.get()
entry2 = self.entry2.get()
if not entry2:
return False
if self.op == '+':
res = self.plus(entry1, entry2)
if self.op == '-':
res = self.sub(entry1, entry2)
if self.op == '*':
res = self.mult(entry1, entry2)
if self.op == '/':
res = self.div(entry1, entry2)
if self.op.encode('utf-8') == '字符串连接':
res = self.str_plus(entry1, entry2)
else:
pass
self.entry3.delete(0, END) # 先清空
self.entry3.insert(END, res)
# print self.op_list.curselection()
# self.op_list.see(2)
def plus(self, a, b):
return float(a) + float(b)
def sub(self, a, b):
return float(a) - float(b)
def mult(self, a, b):
return float(a) * float(b)
def div(self, a, b):
return round(float(a) / float(b))
def str_plus(self, a, b):
return a + b
def clear_fun(self):
self.entry1.delete(0, END)
self.entry2.delete(0, END)
self.entry3.delete(0, END)
self.op = '+'
self.op_list.see(0)
self.op_list.activate(0)
self.entry1.focus_set()
def clear_step(self):
if self.entry == '1':
value_len = len(self.entry1.get())
self.entry1.delete(value_len - 1, END)
if self.entry == '2':
value_len = len(self.entry2.get())
self.entry2.delete(value_len - 1, END)
def key_press(self, event):
print repr(event.char)
def set_focus(self, event):
self.frame.focus_set()
print self.op_list.get(ACTIVE)
print self.op_list.curselection()
self.op_label.configure(text='Op('+self.op_list.get(ACTIVE)+')')
root = Tk()
app = Calculator(root)
root.mainloop()
root.destroy()
<file_sep># python2.7-learning
python2.7-learning
<file_sep># -*- coding: utf-8 -*-
from Tkinter import *
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
def callback():
print e.get()
b = Button(master, text="get", width=10, command=callback)
b.pack()
mainloop()
e = Entry(master, width=50)
e.pack()
text = e.get()
def makeentry(parent, caption, width=None, **options):
Label(parent, text=caption).pack(side=LEFT)
entry = Entry(parent, **options)
if width:
entry.config(width=width)
entry.pack(side=LEFT)
return entry
user = makeentry(master, "User name:", 10)
password = makeentry(master, "Password:", 10, show="*")
content = StringVar()
entry = Entry(master, text=caption, textvariable=content)
text = content.get()
content.set(text)
# root = Tk()
# def key(event):
# print "pressed", repr(event.char)
#
# def callback(event):
# frame.focus_set()
# print "clicked at", event.x, event.y
#
# frame = Frame(root, width=100, height=100)
# frame.bind("<Key>", key)
# frame.bind("<Button-1>", callback)
# frame.pack()
#
# root.mainloop()
#-------------------二输入规则计算器--------------------
#Author:哈士奇说喵(第一次署名有点怕)
# from Tkinter import *
# import difflib
# #主框架部分
# root = Tk()
# root.title('乞丐版规则器0.0')
# root.geometry()
# Label_root=Label(root,text='规则运算(根框架)',font=('宋体',15))
#
# #-----------------------定义规则------------------------
#
# def Plus(a,b):
# return round(a+b, 2)
#
# def Sub(a,b):
# return round(a-b,2)
#
# def Mult(a,b):
# return round(a*b, 2)
#
# def Div(a,b):
# return round(a/b, 2)
#
# def P_str(a,b):
# return a+b
#
# def Rep(a,b):
# return difflib.SequenceMatcher(None,a,b).ratio()
# #difflib可以看看其中的定义,计算匹配率的
#
# #还可以继续增加规则函数,只要是两输入的参数都可以
# #----------------------触发函数-----------------------
#
# def Answ():#规则函数
#
# if lb.get(lb.curselection()).encode('utf-8') == '加':
# Ans.insert(END,'规则:+ ->'+str(Plus(float(var_first.get()),float(var_second.get()))))
# if lb.get(lb.curselection()).encode('utf-8')=='减':
# Ans.insert(END,'规则:- ->'+str(Sub(float(var_first.get()),float(var_second.get()))))
# if lb.get(lb.curselection()).encode('utf-8')=='乘':
# Ans.insert(END,'规则:x ->'+str(Mult(float(var_first.get()),float(var_second.get()))))
# if lb.get(lb.curselection()).encode('utf-8')=='除':
# Ans.insert(END,'规则:/ ->'+str(Div(float(var_first.get()),float(var_second.get()))))
# if lb.get(lb.curselection()).encode('utf-8')=='字符串连接':
# Ans.insert(END,'规则:字符串连接 ->' +P_str(var_first.get(),var_second.get()).encode('utf-8'))
# if lb.get(lb.curselection()).encode('utf-8')=='字符串相似度':
# Ans.insert(END,'规则:字符串相似度 ->'+str(Rep(var_first.get(),var_second.get())))
#
# #添加规则后定义规则函数
#
# def Clea():#清空函数
# input_num_first.delete(0,END)#这里entry的delect用0
# input_num_second.delete(0,END)
# Ans.delete(0,END)#text中的用0.0
#
#
# #----------------------输入选择框架--------------------
# frame_input = Frame(root)
# Label_input=Label(frame_input, text='(输入和选择框架)', font=('',15))
# var_first = StringVar()
# var_second = StringVar()
# input_num_first = Entry(frame_input, textvariable=var_first)
# input_num_second = Entry(frame_input, textvariable=var_second)
#
# #---------------------选择运算规则---------------------
# #还可以添加其他规则
#
# lb = Listbox(frame_input,height=4)
# list_item=['加', '减', '乘', '除','字符串连接','字符串相似度']
# for i in list_item:
# lb.insert(END,i)
#
# #---------------------计算结果框架---------------------
# frame_output = Frame(root)
# Label_output=Label(frame_output, text='(计算结果框架)', font=('',15))
# Ans = Listbox(frame_output, height=1,width=30)#text也可以,Listbox好处在于换行
#
#
# #-----------------------Button-----------------------
#
# calc = Button(frame_output,text='计算', command=Answ)
# cle = Button(frame_output,text='清除', command=Clea)
#
#
# #---------------------滑动Scrollbar-------------------
# scr1 = Scrollbar(frame_input)
# lb.configure(yscrollcommand = scr1.set)
# scr1['command']=lb.yview
#
# scr2 = Scrollbar(frame_output)
# Ans.configure(yscrollcommand = scr2.set)
# scr2['command']=Ans.yview
#
#
# #-------------------------布局------------------------
# #布局写在一块容易排版,可能我low了吧
# Label_root.pack(side=TOP)
# frame_input.pack(side=TOP)
# Label_input.pack(side=LEFT)
#
# input_num_first.pack(side=LEFT)
# lb.pack(side=LEFT)
# scr1.pack(side=LEFT,fill=Y)
# input_num_second.pack(side=RIGHT)
#
# frame_output.pack(side=TOP)
# Label_output.pack(side=LEFT)
# calc.pack(side=LEFT)
# cle.pack(side=LEFT)
# Ans.pack(side=LEFT)
# scr2.pack(side=LEFT,fill=Y)
#
# #-------------------root.mainloop()------------------
#
# root.mainloop()
#
# label1 = Label(master, text="First").grid(row=0, sticky=W)
# label2 = Label(master, text="Second").grid(row=1, sticky=W)
#
# e1 = Entry(master)
# e2 = Entry(master)
#
# e1.grid(row=0, column=1)
# e2.grid(row=1, column=1)
# master.mainloop()
# root = Tk()
#
# def callback():
# print "called the callback!"
# create a toolbar
# toolbar = Frame(root)
#
# b = Button(toolbar, text="new", width=6, command=callback)
# b.pack(side=LEFT, padx=2, pady=2)
#
# b = Button(toolbar, text="open", width=6, command=callback)
# b.pack(side=LEFT, padx=2, pady=2)
#
# toolbar.pack(side=TOP, fill=X)
# status = Label(toolbar, text="", bd=1, relief=SUNKEN, anchor=W)
# status.pack(side=BOTTOM, fill=X)
#
# mainloop()
# def callback():
# print "called the callback!"
#
# root = Tk()
#
# # create a menu
# menu = Menu(root)
# root.config(menu=menu)
#
# filemenu = Menu(menu)
# menu.add_cascade(label="File", menu=filemenu)
# filemenu.add_command(label="New", command=callback)
# filemenu.add_command(label="Open...", command=callback)
# filemenu.add_separator()
# filemenu.add_command(label="Exit", command=callback)
#
# helpmenu = Menu(menu)
# menu.add_cascade(label="Help", menu=helpmenu)
# helpmenu.add_command(label="About...", command=callback)
#
# mainloop()
# root = Tk()
#
# def key(event):
# print "pressed", repr(event.char)
#
# def callback(event):
# frame.focus_set()
# print "clicked at", event.x, event.y
#
# frame = Frame(root, width=100, height=100)
# frame.bind("<Key>", key)
# frame.bind("<Button-2>", callback)
# frame.pack()
#
# root.mainloop()
# root = Tk()
# w = Label(root, text='hello, world')
# w.pack()
# root.mainloop()
# class App(Frame):
# def __init__(self, master, **kw):
# self.frame = Frame(master, height=320, width=320)
# self.frame.pack_propagate(0)
# self.frame.pack()
# # Frame.__init__(self, master)
# # self.config(height=320, width=320)
# # self.grid_propagate(0)
# # self.pack()
#
# self.button = Button(self.frame, text='QUIT', fg='red', command=self.frame.quit)
# self.button.pack( expand=1, side=LEFT)
# self.hi_there = Button(self.frame, text='Hello', command=self.say_hi)
# self.hi_there.pack(side=LEFT)
#
# def say_hi(self):
# print 'hi there, everyone'
# self.frame.configure(height=640, width=320)
# self.hi_there.configure(text='red')
#
#
# root = Tk()
# app = App(root)
# root.mainloop()
# root.destroy()
# class Application(Frame):
# def __init__(self, master=None):
# Frame.__init__(self, master)
# self.pack()
# self.create_widgets()
#
# def say_hi(self):
# print 'hi there, everyone'
#
# def create_widgets(self):
# self.QUIT = Button(self)
# self.QUIT['text'] = 'QUIT'
# self.QUIT['fg'] = 'red'
# self.QUIT['command'] = self.quit
#
# self.QUIT.pack({'side': 'left'})
# #
# self.hi_there = Button(self)
# self.hi_there['text'] = 'Hello'
# self.hi_there['command'] = self.say_hi
# #
# self.hi_there.pack({'side': 'left'})
#
#
#
#
# root = Tk()
# app = Application(master=root)
# app.mainloop()
# root.destroy()
|
84d3dbe6792383029f9b1b4a147ab23d9b8049ec
|
[
"Markdown",
"Python"
] | 3 |
Python
|
twolun/python2.7-learning
|
51b26d79f3e8da96a3876dc2849577a7e391ba8d
|
b7a9c9b1b0882559bd4bee4b2fa8031e91a7f78b
|
refs/heads/master
|
<repo_name>wolf-tian/MVP-MVVM<file_sep>/src/main/java/cn/compal/feeling/di/component/FragmentComponent.java
package cn.compal.feeling.di.component;
import android.app.Activity;
import cn.compal.feeling.di.module.FragmentModule;
import cn.compal.feeling.di.scope.FragmentScope;
import dagger.Component;
/**
* Created by wolf on 2017/9/2.
*/
@FragmentScope
@Component(dependencies = AppComponent.class, modules = FragmentModule.class)
public interface FragmentComponent
{
Activity getActivity();
//void inject(FirstFragmentPage firstFragmentPage);
}
<file_sep>/src/main/java/cn/compal/feeling/module/DataManager.java
package cn.compal.feeling.module;
import cn.compal.feeling.module.http.IHttpHelper;
import cn.compal.feeling.module.http.api.BaseApi;
import cn.compal.feeling.module.prefs.IPreferencesHelper;
import io.reactivex.Flowable;
/**
* Created by wolf on 2017/11/17.
*/
public class DataManager implements IHttpHelper, IPreferencesHelper
{
IHttpHelper mHttpHelper;
IPreferencesHelper mPreferencesHelper;
public DataManager(IHttpHelper httpHelper, IPreferencesHelper preferencesHelper)
{
mHttpHelper = httpHelper;
mPreferencesHelper = preferencesHelper;
}
/* @Override
public Flowable<ZqzhHttpResponse<List<InstructionBooksBean>>> getZqzhHttpResponse(BaseApi api)
{
return mHttpHelper.getZqzhHttpResponse(api);
}*/
@Override
public Flowable<Object> getZqzhHttpStringResponse(BaseApi api)
{
return mHttpHelper.getZqzhHttpStringResponse(api);
}
}
<file_sep>/src/main/java/cn/compal/feeling/module/http/interceptor/CommonInterceptor.java
package cn.compal.feeling.module.http.interceptor;
import java.io.IOException;
import cn.compal.feeling.app.App;
import cn.compal.feeling.util.PhonePackageUtil;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by wolf on 2016/12/13.
*/
public class CommonInterceptor implements Interceptor
{
public Response intercept(Chain chain) throws IOException
{
Request oldRequest = chain.request();
// 添加新的参数
HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
.newBuilder()
.scheme(oldRequest.url().scheme())
.host(oldRequest.url().host())
.addQueryParameter("tType", "android")
.addQueryParameter("sType", "Android")
.addQueryParameter("sysVersion", App.version)
.addQueryParameter("terminalType", "android")
.addQueryParameter("mType", PhonePackageUtil.getMmtyp())
.addQueryParameter("terminalType", "android");
// 新的请求
Request newRequest = oldRequest.newBuilder()
.method(oldRequest.method(), oldRequest.body())
.url(authorizedUrlBuilder.build())
.build();
return chain.proceed(newRequest);
}
}
<file_sep>/src/main/java/cn/compal/feeling/module/http/IHttpHelper.java
package cn.compal.feeling.module.http;
import cn.compal.feeling.module.http.api.BaseApi;
import io.reactivex.Flowable;
/**
* Created by wolf on 2017/11/16.
*/
public interface IHttpHelper
{
//Flowable<ZqzhHttpResponse<List<InstructionBooksBean>>> getZqzhHttpResponse(BaseApi api);
Flowable<Object> getZqzhHttpStringResponse(BaseApi api);
}
<file_sep>/src/main/java/cn/compal/feeling/util/PhonePackageUtil.java
package cn.compal.feeling.util;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
/**
* @author wolf
* @version 1.0
* @Description 安卓手机或应用信息工具类
* @date 2016-8-11 上午10:23:39
*/
public class PhonePackageUtil
{
/**
* 获取手机信息-手机品牌
*/
public static String getMtyb()
{
return android.os.Build.BRAND;// 手机品牌
}
/**
* 获取手机信息-手机型号
*/
public static String getMmtyp()
{
return android.os.Build.MODEL; // 手机型号
}
/**
* 获取手机信息-手机Imei
*/
public static String getImei(Activity activity)
{
TelephonyManager tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getDeviceId();
}
/**
* 获取手机信息-手机Imsi
*/
public static String getImsi(Activity activity)
{
TelephonyManager tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getSubscriberId();
}
/**
* 获取手机信息-手机号码
*/
public static String getNumer(Activity activity)
{
TelephonyManager tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getLine1Number();
}
/**
* 获取手机信息-手机运营商
*/
public static String getServiceName(Activity activity)
{
TelephonyManager tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getSimOperatorName();
}
/**
* 获取手机信息
*/
public static void getPhoneInfo()
{
// tvPhoneInfo.setText("品牌: " + mtyb + "\n" + "型号: " + mtype + "\n" +
// "版本: Android " + android.os.Build.VERSION.RELEASE + "\n" + "IMEI: " +
// imei
// + "\n" + "IMSI: " + imsi + "\n" + "手机号码: " + numer + "\n" + "运营�? " +
// serviceName + "\n");
}
/**
* 获取手机内存大小
*
* @return
*/
private String getTotalMemory(Activity activity)
{
String str1 = "/proc/meminfo";// 系统内存信息文件
String str2;
String[] arrayOfString;
long initial_memory = 0;
try
{
FileReader localFileReader = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(
localFileReader, 8192);
str2 = localBufferedReader.readLine();// 读取meminfo第一行,系统总内存大�?
arrayOfString = str2.split("\\s+");
for (String num : arrayOfString)
{
Log.i(str2, num + "\t");
}
initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存,单位是KB,乘�?024转换为Byte
localBufferedReader.close();
} catch (IOException e)
{
}
return Formatter.formatFileSize(activity.getBaseContext(),
initial_memory);// Byte转换为KB或�?MB,内存大小规格化
}
/**
* 获取当前可用内存大小
*
* @return
*/
public static String getAvailMemory(Activity activity)
{
ActivityManager am = (ActivityManager) activity
.getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo mi = new MemoryInfo();
am.getMemoryInfo(mi);
return Formatter.formatFileSize(activity.getBaseContext(), mi.availMem);
}
/**
* 获取手机CPU信息
*
* @return
*/
public static String[] getCpuInfo()
{
String str1 = "/proc/cpuinfo";
String str2 = "";
String[] cpuInfo = {"", ""};
String[] arrayOfString;
try
{
FileReader fr = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
str2 = localBufferedReader.readLine();
arrayOfString = str2.split("\\s+");
for (int i = 2; i < arrayOfString.length; i++)
{
cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
}
str2 = localBufferedReader.readLine();
arrayOfString = str2.split("\\s+");
cpuInfo[1] += arrayOfString[2];
localBufferedReader.close();
} catch (IOException e)
{
}
// tvHardwareInfo.append("CPU型号 " + cpuInfo[0] + "\n" + "CPU频率: "+
// cpuInfo[1] + "\n");
return cpuInfo;
}
/**
* 获取CPU核数
*
* @return
*/
private int getNumCores()
{
// Private Class to display only CPU devices in the directory listing
class CpuFilter implements FileFilter
{
@Override
public boolean accept(File pathname)
{
// Check if filename is "cpu", followed by a single digit number
if (Pattern.matches("cpu[0-9]", pathname.getName()))
{
return true;
}
return false;
}
}
try
{
// Get directory containing CPU info
File dir = new File("/sys/devices/system/cpu/");
// Filter to only list the devices we care about
File[] files = dir.listFiles(new CpuFilter());
// Return the number of cores (virtual CPU devices)
return files.length;
} catch (Exception e)
{
e.printStackTrace();
// Default to return 1 core
return 1;
}
}
/**
* 获取当前安装应用列表
*
* @return
*/
public List<PackageInfo> getPackageInfo(Activity activity)
{
PackageManager pm = activity.getPackageManager();
List<PackageInfo> packageInfos = pm.getInstalledPackages(0);
/*
* for(PackageInfo pi:packageInfos) {
* if("com.gis".equals(pi.packageName)) { flag = true;
* System.out.println("@:"+flag); } }
*/
return packageInfos;
}
/**
* 获取当前应用版本信息
*
* @return
*/
public static String getVersionName(Activity activity)
{
PackageManager pm = activity.getPackageManager();
PackageInfo packageInfo;
try
{
packageInfo = pm.getPackageInfo(activity.getPackageName(), 0);
return packageInfo.versionName;
} catch (NameNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
/**
* 检查sim卡状态
* @param context
* @return
*/
public static boolean checkSimState(Context context)
{
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| tm.getSimState() == TelephonyManager.SIM_STATE_UNKNOWN)
{
return false;
}
return true;
}
}
<file_sep>/src/main/java/cn/compal/feeling/module/http/subscriber/CommonSubscriber.java
package cn.compal.feeling.module.http.subscriber;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;
import cn.compal.feeling.base.BaseView;
import cn.compal.feeling.module.http.exception.HttpTimeException;
import io.reactivex.subscribers.ResourceSubscriber;
import retrofit2.HttpException;
/**
* Created by wolf on 2017/2/23.
*/
public abstract class CommonSubscriber<T> extends ResourceSubscriber<T>
{
private BaseView mView;
private String mErrorMsg;
private boolean isShowErrorState = true;
private static final String RedirectException_MSG = "服务器重定向错误";
private static final String NetWorkUnknownException_MSG = "网络未知类型错误";
private static final String ServerUnknownException_MSG = "服务器未知类型错误";
private static final String HttpException_MSG = "Http请求4xx错误";
private static final String ConnectException_MSG = "Http链接失败";
private static final String JSONException_MSG = "Json解析失败";
private static final String UnknownHostException_MSG = "无法解析该域名";
protected CommonSubscriber(BaseView view)
{
this.mView = view;
}
protected CommonSubscriber(BaseView view, String errorMsg)
{
this.mView = view;
this.mErrorMsg = errorMsg;
}
protected CommonSubscriber(BaseView view, boolean isShowErrorState)
{
this.mView = view;
this.isShowErrorState = isShowErrorState;
}
protected CommonSubscriber(BaseView view, String errorMsg, boolean isShowErrorState)
{
this.mView = view;
this.mErrorMsg = errorMsg;
this.isShowErrorState = isShowErrorState;
}
@Override
public void onComplete()
{
}
@Override
public void onError(Throwable e)
{
if (mView == null)
{
return;
}
if (mErrorMsg != null && !TextUtils.isEmpty(mErrorMsg))
{
mView.showErrorMsg(mErrorMsg);
} else if (e instanceof HttpException)
{
/*网络异常*/
int code = ((HttpException) e).code();
if (300 <= code && code < 400)
{
mView.showErrorMsg(RedirectException_MSG);
} else if (400 <= code && code < 500)
{
mView.showErrorMsg(HttpException_MSG);
} else if (500 <= code && code < 600)
{
mView.showErrorMsg(ServerUnknownException_MSG);
} else
{
mView.showErrorMsg(NetWorkUnknownException_MSG);
}
} else if (e instanceof HttpTimeException)
{
/*自定义运行时异常*/
mView.showErrorMsg(e.getMessage());
} else if (e instanceof ConnectException || e instanceof SocketTimeoutException)
{
/*链接异常*/
mView.showErrorMsg(ConnectException_MSG);
} else if (e instanceof JSONException || e instanceof ParseException)
{
/*json解析异常*/
mView.showErrorMsg(JSONException_MSG);
} else if (e instanceof UnknownHostException)
{
/*无法解析该域名异常*/
mView.showErrorMsg(UnknownHostException_MSG);
} else
{
mView.showErrorMsg("未知错误ヽ(≧Д≦)ノ");
Log.d("--->", e.toString());
}
if (isShowErrorState)
{
mView.stateError();
}
}
}
<file_sep>/src/main/java/cn/compal/feeling/di/module/AppModule.java
package cn.compal.feeling.di.module;
import javax.inject.Singleton;
import cn.compal.feeling.app.App;
import cn.compal.feeling.module.DataManager;
import cn.compal.feeling.module.http.IHttpHelper;
import cn.compal.feeling.module.http.RetrofitHelper;
import cn.compal.feeling.module.prefs.IPreferencesHelper;
import cn.compal.feeling.module.prefs.impl.PreferencesHelperImpl;
import dagger.Module;
import dagger.Provides;
/**
* Created by wolf on 2017/9/2.
*/
@Module
public class AppModule
{
private final App application;
public AppModule(App application)
{
this.application = application;
}
@Provides
@Singleton
App provideApplicationContext()
{
return application;
}
@Provides
@Singleton
IPreferencesHelper providePreferencesHelper(PreferencesHelperImpl preferencesHelper)
{
return preferencesHelper;
}
@Provides
@Singleton
IHttpHelper provideHttpHelper(RetrofitHelper retrofitHelper)
{
return retrofitHelper;
}
@Provides
@Singleton
DataManager provideDataManager(IHttpHelper httpHelper, IPreferencesHelper preferencesHelper)
{
return new DataManager(httpHelper, preferencesHelper);
}
}
<file_sep>/src/main/java/cn/compal/feeling/module/http/api/BaseApi.java
package cn.compal.feeling.module.http.api;
import java.util.Map;
import cn.compal.feeling.app.Constants;
import cn.compal.feeling.util.StringUtil;
/**
* 请求数据统一封装类
* Created by wolf on 2017/3/7.
*/
public class BaseApi
{
/*基础url*/
private String baseUrl = Constants.baseUrl;
/*是否需要缓存处理*/
private boolean cache = false;
/*方法名*/
private String mothed;
/*超时时间-默认6秒*/
private int connectionTime = 6;
/*有网情况下的本地缓存时间默认60秒*/
private int cookieNetWorkTime = 60;
/*无网络的情况下本地缓存时间默认30天*/
private int cookieNoNetWorkTime = 24 * 60 * 60 * 30;
/*是否强制刷新处理*/
private boolean forceRefresh = true;
private Map<String, String> parameters;
/*是否显示加载框*/
private boolean showProgress = true;
/*方法模块*/
private String module;
public int getCookieNoNetWorkTime()
{
return cookieNoNetWorkTime;
}
public void setCookieNoNetWorkTime(int cookieNoNetWorkTime)
{
this.cookieNoNetWorkTime = cookieNoNetWorkTime;
}
public int getCookieNetWorkTime()
{
return cookieNetWorkTime;
}
public void setCookieNetWorkTime(int cookieNetWorkTime)
{
this.cookieNetWorkTime = cookieNetWorkTime;
}
public String getMothed()
{
return mothed;
}
public int getConnectionTime()
{
return connectionTime;
}
public void setConnectionTime(int connectionTime)
{
this.connectionTime = connectionTime;
}
public void setMothed(String mothed)
{
this.mothed = mothed;
}
public String getBaseUrl()
{
return baseUrl;
}
public void setBaseUrl(String baseUrl)
{
this.baseUrl = baseUrl;
}
public String getUrl()
{
if (StringUtil.isEmpty(mothed))
{
return baseUrl;
} else
{
if (null == getParameters())
{
return baseUrl + mothed;
} else
{
return baseUrl + mothed + StringUtil.transMapToString(getParameters());
}
}
}
public boolean isCache()
{
return cache;
}
public void setCache(boolean cache)
{
this.cache = cache;
}
public boolean isForceRefresh()
{
return forceRefresh;
}
public void setForceRefresh(boolean forceRefresh)
{
this.forceRefresh = forceRefresh;
}
public Map<String, String> getParameters()
{
return parameters;
}
public void setParameters(Map<String, String> parameters)
{
this.parameters = parameters;
}
public boolean isShowProgress()
{
return showProgress;
}
public void setShowProgress(boolean showProgress)
{
this.showProgress = showProgress;
}
public String getModule()
{
return module;
}
public void setModule(String module)
{
this.module = module;
}
}
<file_sep>/src/main/java/cn/compal/feeling/base/BaseMVVMActivity.java
package cn.compal.feeling.base;
import android.content.SharedPreferences;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.app.AppCompatDelegate;
import android.view.ViewGroup;
import javax.inject.Inject;
import cn.compal.feeling.app.App;
import cn.compal.feeling.di.component.ActivityComponent;
import cn.compal.feeling.di.component.DaggerActivityComponent;
import cn.compal.feeling.di.module.ActivityModule;
import cn.compal.feeling.util.SnackbarUtil;
/**
* Created by wolf on 2017/12/6.
*/
public abstract class BaseMVVMActivity<T extends BasePresenter,D extends ViewDataBinding> extends SimpleMVVMActivity implements BaseView
{
@Inject
protected T mViewModel;
protected D mBinding;
public static SharedPreferences guestureSp, settingsApp,settings;
protected ActivityComponent getActivityComponent()
{
return DaggerActivityComponent.builder()
.appComponent(App.getAppComponent())
.activityModule(getActivityModule())
.build();
}
protected ActivityModule getActivityModule()
{
return new ActivityModule(this);
}
protected void initDataBinding() {
int layoutId = getLayoutRes();
mBinding = DataBindingUtil.setContentView(this, layoutId);
}
@Override
protected void onViewCreated()
{
super.onViewCreated();
settings = this.getSharedPreferences("WADE_MOBILE_STORAGE", 0);
guestureSp=getSharedPreferences("GuestureLockSP",0);
settingsApp = this.getSharedPreferences("WADE_MOBILE_STORAGE_APP", 0);
initDataBinding();
initInject();
if (mViewModel != null)
mViewModel.attachView(this);
}
@Override
protected void onDestroy()
{
if (mBinding != null)
mBinding.unbind();
if (mViewModel != null)
mViewModel.detachView();
super.onDestroy();
}
@Override
public void showErrorMsg(String msg)
{
SnackbarUtil.show(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0), msg);
}
@Override
public void useNightMode(boolean isNight)
{
if (isNight)
{
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
} else
{
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_NO);
}
recreate();
}
@Override
public void stateError()
{
}
@Override
public void stateEmpty()
{
}
@Override
public void stateLoading()
{
}
@Override
public void stateMain()
{
}
protected abstract void initInject();
}<file_sep>/src/main/java/cn/compal/feeling/module/http/service/ZqzhHttpService.java
package cn.compal.feeling.module.http.service;
import java.util.List;
import java.util.Map;
import cn.compal.feeling.module.http.response.ZqzhHttpResponse;
import io.reactivex.Flowable;
import okhttp3.MultipartBody;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Path;
/**
* Created by wolf on 2017/11/17.
*/
public interface ZqzhHttpService
{
String HOST = "http://css.telecomjs.com/mcssAppService-web/";
/**
* 上传图片文件单个
*/
@Multipart
@POST("{qModle}")
Flowable<String> uploadImageFile(@Path("qModle") String qModle, @Part MultipartBody.Part file);
/**
* 上传图片文件数组
*/
@Multipart
@POST("{qModle}")
Flowable<String> uploadImageFiles(@Path("qModle") String qModle, @Part() List<MultipartBody.Part> parts);
/**
* 根据方法名和方法模块获取服务器数据
**/
@FormUrlEncoded
@POST("{qModle}/{qType}")
<T> Flowable<ZqzhHttpResponse<List<T>>> getRepoDataByModeAndQtype(@Path("qModle") String qModle, @Path("qType") String qType, @FieldMap Map<String, String> options);
/**
* 根据方法名和方法模块获取服务器数据
**/
//@POST("{qModle}/{qType}")
//Flowable<ZqzhHttpResponse<List<InstructionBooksBean>>> getRepoDataByModeAndQtype(@Path("qModle") String qModle, @Path("qType") String qType);
/**
* 根据方法名和方法模块获取服务器数据
**/
@POST("{qModle}/{qType}")
Flowable<Object> getStringRepoDataByModeAndQtype(@Path("qModle") String qModle, @Path("qType") String qType);
/**
* 根据方法名和方法模块获取服务器数据
**/
@POST("{qModle}/{qType}")
Flowable<Object> getStringRepoDataByModeAndQtype(@Path("qModle") String qModle, @Path("qType") String qType, @FieldMap Map<String, String> options);
}
<file_sep>/src/main/java/cn/compal/feeling/di/component/AppComponent.java
package cn.compal.feeling.di.component;
import javax.inject.Singleton;
import cn.compal.feeling.app.App;
import cn.compal.feeling.di.module.AppModule;
import cn.compal.feeling.di.module.HttpModule;
import cn.compal.feeling.module.DataManager;
import cn.compal.feeling.module.http.RetrofitHelper;
import cn.compal.feeling.module.prefs.impl.PreferencesHelperImpl;
import dagger.Component;
/**
* Created by wolf on 2017/8/2.
*/
@Singleton
@Component(modules = {AppModule.class, HttpModule.class})
public interface AppComponent
{
App getContext(); // 提供App的Context
DataManager getDataManager(); //数据中心
RetrofitHelper retrofitHelper(); //提供http的帮助类
PreferencesHelperImpl preferencesHelper(); //提供sp帮助类
}
<file_sep>/src/main/java/cn/compal/feeling/util/NetWorkUtils.java
package cn.compal.feeling.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.text.DecimalFormat;
import cn.compal.feeling.app.App;
/**
* 网络工具类
* Created by wolf on 2016/12/27.
*/
public class NetWorkUtils
{
/**
* 判断某一个Activity页面是否有网络连接
*
* @param context 判断的Activity
* @return
*/
public static boolean isNetworkConnected(Context context)
{
try
{
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected())
{
if (info.getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
} catch (Exception e)
{
e.printStackTrace();
return false;
}
return false;
}
/**
* 判断是否有网络连接
*
* @return
*/
public static boolean isNetworkConnected()
{
try
{
ConnectivityManager connectivityManager = (ConnectivityManager) App.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info != null && info.isConnected())
{
if (info.getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
} catch (Exception e)
{
e.printStackTrace();
return false;
}
return false;
}
/**
* 判断WIFI网络是否可用
*
* @param context
* @return
*/
public static boolean isWifiConnected(Context context)
{
if (context != null)
{
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWiFiNetworkInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWiFiNetworkInfo != null)
{
return mWiFiNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 判断MOBILE网络是否可用
*
* @param context
* @return
*/
public static boolean isMobileConnected(Context context)
{
if (context != null)
{
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mMobileNetworkInfo = mConnectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mMobileNetworkInfo != null)
{
return mMobileNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 获取当前网络连接的类型信息
*
* @param context
* @return 没有网络-1 移动网络 0 wifi 1
*/
public static int getConnectedType(Context context)
{
if (context != null)
{
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isAvailable())
{
return mNetworkInfo.getType();
}
}
return -1;
}
private static final int NETWORK_TYPE_UNAVAILABLE = -1;
// private static final int NETWORK_TYPE_MOBILE = -100;
private static final int NETWORK_TYPE_WIFI = -101;
private static final int NETWORK_CLASS_WIFI = -101;
private static final int NETWORK_CLASS_UNAVAILABLE = -1;
/**
* Unknown network class.
*/
private static final int NETWORK_CLASS_UNKNOWN = 0;
/**
* Class of broadly defined "2G" networks.
*/
private static final int NETWORK_CLASS_2_G = 1;
/**
* Class of broadly defined "3G" networks.
*/
private static final int NETWORK_CLASS_3_G = 2;
/**
* Class of broadly defined "4G" networks.
*/
private static final int NETWORK_CLASS_4_G = 3;
private static DecimalFormat df = new DecimalFormat("#.##");
// 适配低版本手机
/**
* Network type is unknown
*/
public static final int NETWORK_TYPE_UNKNOWN = 0;
/**
* Current network is GPRS
*/
public static final int NETWORK_TYPE_GPRS = 1;
/**
* Current network is EDGE
*/
public static final int NETWORK_TYPE_EDGE = 2;
/**
* Current network is UMTS
*/
public static final int NETWORK_TYPE_UMTS = 3;
/**
* Current network is CDMA: Either IS95A or IS95B
*/
public static final int NETWORK_TYPE_CDMA = 4;
/**
* Current network is EVDO revision 0
*/
public static final int NETWORK_TYPE_EVDO_0 = 5;
/**
* Current network is EVDO revision A
*/
public static final int NETWORK_TYPE_EVDO_A = 6;
/**
* Current network is 1xRTT
*/
public static final int NETWORK_TYPE_1xRTT = 7;
/**
* Current network is HSDPA
*/
public static final int NETWORK_TYPE_HSDPA = 8;
/**
* Current network is HSUPA
*/
public static final int NETWORK_TYPE_HSUPA = 9;
/**
* Current network is HSPA
*/
public static final int NETWORK_TYPE_HSPA = 10;
/**
* Current network is iDen
*/
public static final int NETWORK_TYPE_IDEN = 11;
/**
* Current network is EVDO revision B
*/
public static final int NETWORK_TYPE_EVDO_B = 12;
/**
* Current network is LTE
*/
public static final int NETWORK_TYPE_LTE = 13;
/**
* Current network is eHRPD
*/
public static final int NETWORK_TYPE_EHRPD = 14;
/**
* Current network is HSPA+
*/
public static final int NETWORK_TYPE_HSPAP = 15;
/**
* 格式化大小
*
* @param size
* @return
*/
public static String formatSize(long size)
{
String unit = "B";
float len = size;
if (len > 900)
{
len /= 1024f;
unit = "KB";
}
if (len > 900)
{
len /= 1024f;
unit = "MB";
}
if (len > 900)
{
len /= 1024f;
unit = "GB";
}
if (len > 900)
{
len /= 1024f;
unit = "TB";
}
return df.format(len) + unit;
}
public static String formatSizeBySecond(long size)
{
String unit = "B";
float len = size;
if (len > 900)
{
len /= 1024f;
unit = "KB";
}
if (len > 900)
{
len /= 1024f;
unit = "MB";
}
if (len > 900)
{
len /= 1024f;
unit = "GB";
}
if (len > 900)
{
len /= 1024f;
unit = "TB";
}
return df.format(len) + unit + "/s";
}
public static String format(long size)
{
String unit = "B";
float len = size;
if (len > 1000)
{
len /= 1024f;
unit = "KB";
if (len > 1000)
{
len /= 1024f;
unit = "MB";
if (len > 1000)
{
len /= 1024f;
unit = "GB";
}
}
}
return df.format(len) + "\n" + unit + "/s";
}
/**
* 获取运营商
*
* @return
*/
public static String getProvider(Context context)
{
String provider = "未知";
try
{
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String IMSI = telephonyManager.getSubscriberId();
Log.v("tag", "getProvider.IMSI:" + IMSI);
if (IMSI == null)
{
if (TelephonyManager.SIM_STATE_READY == telephonyManager
.getSimState())
{
String operator = telephonyManager.getSimOperator();
Log.v("tag", "getProvider.operator:" + operator);
if (operator != null)
{
if (operator.equals("46000")
|| operator.equals("46002")
|| operator.equals("46007"))
{
provider = "中国移动";
} else if (operator.equals("46001"))
{
provider = "中国联通";
} else if (operator.equals("46003"))
{
provider = "中国电信";
}
}
}
} else
{
if (IMSI.startsWith("46000") || IMSI.startsWith("46002")
|| IMSI.startsWith("46007"))
{
provider = "中国移动";
} else if (IMSI.startsWith("46001"))
{
provider = "中国联通";
} else if (IMSI.startsWith("46003"))
{
provider = "中国电信";
}
}
} catch (Exception e)
{
e.printStackTrace();
}
return provider;
}
/**
* 获取当前的网络类型 :没有网络-1 2G网络2 3G网络3 4G网络4 WIFI网络6
*
* @param context
* @return
*/
public static int getCurrentNetworkType(Context context)
{
int networkClass = getNetworkClass(context);
int type = -1;
switch (networkClass)
{
case NETWORK_CLASS_UNAVAILABLE:
type = -1;
break;
case NETWORK_CLASS_WIFI:
type = 6;
break;
case NETWORK_CLASS_2_G:
type = 2;
break;
case NETWORK_CLASS_3_G:
type = 3;
break;
case NETWORK_CLASS_4_G:
type = 4;
break;
case NETWORK_CLASS_UNKNOWN:
type = -1;
break;
}
return type;
}
/**
* 获取当前的网络状态
*
* @param context
* @return
*/
public static String getCurrentNetworkStatus(Context context)
{
int type = getCurrentNetworkType(context);
String status = "未知网络";
//没有网络-1 2G网络2 3G网络3 4G网络4 WIFI网络6
switch (type)
{
case -1:
status = "没有网络";
break;
case 2:
status = "2G网络";
break;
case 3:
status = "3G网络";
break;
case 4:
status = "4G网络";
break;
case 6:
status = "wifi 网络";
break;
default:
status = "未知网络";
break;
}
return status;
}
private static int getNetworkClassByType(int networkType)
{
switch (networkType)
{
case NETWORK_TYPE_UNAVAILABLE:
return NETWORK_CLASS_UNAVAILABLE;
case NETWORK_TYPE_WIFI:
return NETWORK_CLASS_WIFI;
case NETWORK_TYPE_GPRS:
case NETWORK_TYPE_EDGE:
case NETWORK_TYPE_CDMA:
case NETWORK_TYPE_1xRTT:
case NETWORK_TYPE_IDEN:
return NETWORK_CLASS_2_G;
case NETWORK_TYPE_UMTS:
case NETWORK_TYPE_EVDO_0:
case NETWORK_TYPE_EVDO_A:
case NETWORK_TYPE_HSDPA:
case NETWORK_TYPE_HSUPA:
case NETWORK_TYPE_HSPA:
case NETWORK_TYPE_EVDO_B:
case NETWORK_TYPE_EHRPD:
case NETWORK_TYPE_HSPAP:
return NETWORK_CLASS_3_G;
case NETWORK_TYPE_LTE:
return NETWORK_CLASS_4_G;
default:
return NETWORK_CLASS_UNKNOWN;
}
}
private static int getNetworkClass(Context context)
{
int networkType = NETWORK_TYPE_UNKNOWN;
try
{
final NetworkInfo network = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (network != null && network.isAvailable()
&& network.isConnected())
{
int type = network.getType();
if (type == ConnectivityManager.TYPE_WIFI)
{
networkType = NETWORK_TYPE_WIFI;
} else if (type == ConnectivityManager.TYPE_MOBILE)
{
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
networkType = telephonyManager.getNetworkType();
}
} else
{
networkType = NETWORK_TYPE_UNAVAILABLE;
}
} catch (Exception ex)
{
ex.printStackTrace();
}
return getNetworkClassByType(networkType);
}
}
<file_sep>/src/main/java/cn/compal/feeling/module/prefs/IPreferencesHelper.java
package cn.compal.feeling.module.prefs;
/**
* Created by wolf on 2016/9/30.
*/
public interface IPreferencesHelper
{
}
<file_sep>/README.md
# MVP-MVVM
<file_sep>/src/main/java/cn/compal/feeling/adapter/MvvmCommonAdapter.java
package cn.compal.feeling.adapter;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
/**
* Created by wolf on 2017/11/7.
*/
public class MvvmCommonAdapter extends RecyclerView.Adapter<MvvmCommonAdapter.CommonHolder>
{
protected Context mContext;
//所有 item 的数据集合
protected List mDatas;
//item 布局文件 id
protected int mLayoutId;
protected LayoutInflater mInflater;
// mvvm绑定的viewModel引用
private int mVariableId;
private OnItemClickListener mOnItemClickListener;
//构造方法
public MvvmCommonAdapter(List datas, int variableId, Context context, int layoutId)
{
mContext = context;
mDatas = datas;
mLayoutId = layoutId;
mInflater = LayoutInflater.from(mContext);
mVariableId = variableId;
}
public List getmDatas()
{
return mDatas;
}
public void setmDatas(List mDatas)
{
this.mDatas = mDatas;
}
@Override
public CommonHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), mLayoutId, parent, false);
CommonHolder myHolder = new CommonHolder(binding.getRoot());
myHolder.setBinding(binding);
myHolder.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(@NonNull View view, int adapterPosition)
{
if (mOnItemClickListener != null)
{
mOnItemClickListener.onItemClick(view, adapterPosition);
}
}
});
return myHolder;
}
@Override
public void onBindViewHolder(CommonHolder holder, int position)
{
holder.binding.setVariable(mVariableId, mDatas.get(position));
holder.binding.executePendingBindings();
}
public void setOnItemClickListener(@Nullable OnItemClickListener onItemClickListener)
{
this.mOnItemClickListener = onItemClickListener;
}
@Override
public int getItemCount()
{
return null == mDatas ? 0 : mDatas.size();
}
class CommonHolder extends RecyclerView.ViewHolder
{
private ViewDataBinding binding;
public CommonHolder(View itemView)
{
super(itemView);
}
public ViewDataBinding getBinding()
{
return binding;
}
public void setBinding(ViewDataBinding binding)
{
this.binding = binding;
}
private OnItemClickListener mOnItemClickListener;
private final View.OnClickListener mOnClickListener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (mOnItemClickListener != null)
{
mOnItemClickListener.onItemClick(v, getAdapterPosition());
}
}
};
void setOnItemClickListener(OnItemClickListener onItemClickListener)
{
this.mOnItemClickListener = onItemClickListener;
if (onItemClickListener != null)
{
this.itemView.setOnClickListener(mOnClickListener);
}
}
}
}
|
77c7494d39297512f2463f5efce1acb1bebc6e25
|
[
"Markdown",
"Java"
] | 15 |
Java
|
wolf-tian/MVP-MVVM
|
1eae5bb2b8b31421bf8ed707382a52f6b6f7645e
|
d28dd6efa549c1850c0e2195f44085dbba561f78
|
refs/heads/master
|
<repo_name>localytest/elevator<file_sep>/README.md
# elevator
First there is an elevator class.
It has a direction (up, down, stand, maintenance),
a current floor and a list of floor requests sorted in the direction.
Each elevator has a set of signals: Alarm, Door open, Door close
The scheduling will be like:
if available pick a standing elevator for this floor.
else pick an elevator moving to this floor.
else pick a standing elevator on an other floor.
Sample data:
- Elevator standing in first floor
- Request from 6th floor go down to ground(first floor).
- Request from 5th floor go up to 7th floor
- Reuqest from 3rd floor go down to ground
- Request from ground go up to 7th floor.
- Floor 2 and 4 are in maintenance.
Plus: Making an API to send/receive requests to elevator and write log file.
<file_sep>/index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Elevator</title>
</head>
<body>
<?php
require_once 'elevator_class.php';
$elevator = new my_elevator;
$elevator->current_floor = 1;
$elevator->request_floor = array(5, 2, 6);
$elevator->maintenance(array(1, 3));
$elevator->call_evelator();
?>
</body>
</html>
<file_sep>/elevator_api.php
<?php
/**
*
* @param int current_floor
* @param int request_floor
* @param int maintenance
*
* current_floor=1&request_floor=0,6,5,7,3,2,4&maintenance=2,4
*/
if (isset($_GET['current_floor']) && isset($_GET['request_floor'])) {
require_once 'elevator_class.php';
$elevator = new my_elevator;
$current_floor = (int) $_GET['current_floor'];
$request_floor = explode(',', $_GET['request_floor']);
$maintenance = isset($_GET['maintenance']) ? explode(',', $_GET['maintenance']) : array();
$elevator->floors = array(-1, 0, 1, 2, 3, 4, 5, 6, 7, 8);
$elevator->current_floor = $current_floor;
$elevator->request_floor = $request_floor;
$elevator->maintenance($maintenance);
$elevator->call_evelator();
echo 'Please check log.';
} else {
die('try again');
}
<file_sep>/nbproject/private/private.properties
index.file=index.php
url=http://localhost/elevator/
|
1c2fa21a4dfbde1168640faa4374a180226004a9
|
[
"Markdown",
"PHP",
"INI"
] | 4 |
Markdown
|
localytest/elevator
|
4c40041bd3ec5c46c915cf6ea75c96c0e003e09a
|
20a77574f7c47264f16075381096e5c8be095265
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ScriptedEvent
{
/// <summary>
/// The type of event : spike in, out, ...
/// </summary>
public TypeScriptedEvent typeOfEvent;
/// <summary>
/// The time to launch the event
/// </summary>
public float timeToLaunchEvent = 0;
/// <summary>
/// The id of the spike or the text
/// </summary>
public int id = 0;
/// <summary>
/// Constructor
/// </summary>
/// <param name="__type"></param>
/// <param name="__time"></param>
/// <param name="__id"></param>
public ScriptedEvent(TypeScriptedEvent __type, float __time, int __id)
{
this.typeOfEvent = __type;
this.timeToLaunchEvent = __time;
this.id = __id;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TextManager : MonoBehaviour {
/// <summary>
/// The text with the score in it
/// </summary>
public GameObject textScore;
/// <summary>
/// The text with the instruction : Go, jump...
/// </summary>
public GameObject textInstructions;
/// <summary>
/// The score of the player
/// </summary>
private int score = 0;
/// <summary>
/// Has the game started ?
/// </summary>
bool gameStarted = false;
/// <summary>
/// Is the player alive ?
/// </summary>
bool playerAlive = true;
/// <summary>
/// Number of points gained per frame
/// </summary>
[SerializeField]
private int pointsPerFrame = 1;
// Use this for initialization
void Start ()
{
textScore.GetComponent<Text>().text = "";
textInstructions.GetComponent<Text>().text = "";
gameStarted = false;
playerAlive = true;
EventManager.addActionToEvent<int>(MyEventTypes.SCOREADD, addScore);
EventManager.addActionToEvent<int>(MyEventTypes.TEXTCHANGE, textChange);
EventManager.addActionToEvent(MyEventTypes.ONLOSE, playerLost);
}
void Update()
{
if(playerAlive && gameStarted)
{
addScore(pointsPerFrame);
}
}
void playerLost()
{
playerAlive = false;
}
/// <summary>
/// Add and print the score
/// </summary>
/// <param name="scoreToAdd"></param>
void addScore(int scoreToAdd)
{
if (playerAlive)
{
score += scoreToAdd;
textScore.GetComponent<Text>().text = score.ToString("n0");
}
}
/// <summary>
/// Change the text with some IDs
/// </summary>
/// <param name="idText"></param>
void textChange(int idText)
{
if(playerAlive)
{
switch (idText)
{
case 1:
textInstructions.GetComponent<Text>().text = "3";
break;
case 2:
textInstructions.GetComponent<Text>().text = "2";
break;
case 3:
textInstructions.GetComponent<Text>().text = "1";
break;
case 4:
textInstructions.GetComponent<Text>().text = "GO !";
playerAlive = true;
gameStarted = true;
break;
case 5:
textInstructions.GetComponent<Text>().text = "Attention...";
break;
case 6:
textInstructions.GetComponent<Text>().text = "Bon courage !";
break;
case 7:
textInstructions.GetComponent<Text>().text = "You lose !";
break;
default:
textInstructions.GetComponent<Text>().text = "";
break;
}
}
else
textInstructions.GetComponent<Text>().text = "You lose !";
}
}
<file_sep>using UnityEngine;
using System.Collections.Generic;
public enum TypeScriptedEvent
{
SPIKEIN,
GROUPSPIKEIN,
SPIKEOUT,
GROUPSPIKEOUT,
TEXT
}
public class LevelManager : MonoBehaviour
{
/// <summary>
/// The player to destroy if game over
/// </summary>
public GameObject player;
/// <summary>
/// List of the events that we'll raise during runtime
/// </summary>
public List<ScriptedEvent> listEvents = new List<ScriptedEvent>();
/// <summary>
/// Time at the beginning of the events
/// </summary>
private float timeBeginning = 0;
/// <summary>
/// Cooldown between the spikes
/// </summary>
private float cooldown = 2;
/// <summary>
/// The total number of group of spikes
/// </summary>
private int nbGroupSpikes = 4;
/// <summary>
/// The total number of spikes
/// </summary>
private int nbSpikes = 4;
/// <summary>
/// The creator of the spikes
/// </summary>
public GameObject spikeFactory;
/// <summary>
/// Number of spikes that will go out
/// </summary>
private int nbSpikeToOut = 0;
/// <summary>
/// Number of spikes that can go Out at the same time (increase with difficulty)
/// </summary>
private float nbSpikeSameTime = 1;
// Use this for initialization
void Start ()
{
EventManager.addActionToEvent(MyEventTypes.ONLOSE, onLose);
createListEventsScripted();
nbSpikes = (spikeFactory.GetComponent<SpikeFactory>().nbSpikesGround + 2*spikeFactory.GetComponent<SpikeFactory>().nbSpikesWall);
nbGroupSpikes = (spikeFactory.GetComponent<SpikeFactory>().nbGroupGround + 2 * spikeFactory.GetComponent<SpikeFactory>().nbGroupWall);
nbSpikeSameTime = 1;
}
// Update is called once per frame
void Update ()
{
// initialisation of the time
if (timeBeginning == 0)
timeBeginning = Time.time;
// we check the events
for (int i = (listEvents.Count - 1); i >= 0; --i)
{
if ((Time.time - timeBeginning) >= listEvents[i].timeToLaunchEvent)
{
int id = listEvents[i].id;
switch (listEvents[i].typeOfEvent)
{
case TypeScriptedEvent.SPIKEIN:
EventManager.raise<int>(MyEventTypes.SPIKEIN, id);
nbSpikeToOut--;
break;
case TypeScriptedEvent.SPIKEOUT:
EventManager.raise<int>(MyEventTypes.SPIKEOUT, id);
break;
case TypeScriptedEvent.GROUPSPIKEIN:
EventManager.raise<int>(MyEventTypes.GROUPSPIKEIN, id);
nbSpikeToOut--;
break;
case TypeScriptedEvent.GROUPSPIKEOUT:
EventManager.raise<int>(MyEventTypes.GROUPSPIKEOUT, id);
break;
case TypeScriptedEvent.TEXT:
EventManager.raise<int>(MyEventTypes.TEXTCHANGE, id);
break;
default:
break;
}
listEvents.Remove(listEvents[i]);
}
}
// If we don't have any more spikes to lever
if (nbSpikeToOut < (int)nbSpikeSameTime)
{
float nextTime = ((Time.time - timeBeginning) + cooldown);
int randomId = 0;
if (Random.Range(0, 100) < 80)
{
randomId = Random.Range(0, nbGroupSpikes);
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.GROUPSPIKEOUT, nextTime, randomId));
nbSpikeToOut++;
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.GROUPSPIKEIN, nextTime + 4, randomId));
}
else
{
randomId = (int)Random.Range(0, nbSpikes);
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.SPIKEOUT, nextTime, randomId));
nbSpikeToOut++;
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.SPIKEIN, nextTime + 4, randomId));
}
cooldown = Mathf.Max(2, cooldown * 0.98f);
if (nbSpikeSameTime < nbGroupSpikes + nbSpikes)
nbSpikeSameTime += 0.34f;
}
}
void createListEventsScripted()
{
// Text "3,2,1, go"
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.TEXT, 1, 1));
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.TEXT, 2, 2));
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.TEXT, 3, 3));
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.TEXT, 4, 4));
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.TEXT, 6, 5));
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.GROUPSPIKEOUT, 6, 0));
nbSpikeToOut++;
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.GROUPSPIKEIN, 10, 0));
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.GROUPSPIKEOUT, 9, 5));
nbSpikeToOut++;
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.GROUPSPIKEIN, 13, 5));
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.TEXT, 12, 6));
listEvents.Add(new ScriptedEvent(TypeScriptedEvent.TEXT, 15, 42));
}
void onLose()
{
EventManager.raise<int>(MyEventTypes.TEXTCHANGE, 7);
Destroy(player);
}
}
<file_sep>using UnityEngine;
using System.Collections.Generic;
public class SpikeFactory : MonoBehaviour
{
/// <summary>
/// The prefab to build the spikes
/// </summary>
public GameObject spikePrefab;
/// <summary>
/// List of the position of the spikes
/// Position : betweeen 0 and 1
/// </summary>
///
private List<Vector3> posSpike;
/// <summary>
/// List of the scale of the spikes
/// Scale : whatever you want
/// </summary>
private List<Vector3> scaleSpikes;
/// <summary>
/// List of the orientations of the spikes
/// </summary>
private List<Vector3> orientationsSpikes;
/// <summary>
/// List of the groups of spikes
/// </summary>
private List<int> idGroupSpikes;
/// <summary>
/// The number of spikes on the ground
/// </summary>
public int nbSpikesGround = 1;
/// <summary>
/// The number of spikes on the walls
/// </summary>
public int nbSpikesWall = 1;
/// <summary>
/// The number of group of spikes on the ground
/// </summary>
public int nbGroupGround = 4;
/// <summary>
/// The number of group of spikes on the wall
/// </summary>
public int nbGroupWall = 4;
/// <summary>
/// Working resolution
/// </summary>
public Vector2 normalResolution;
// Use this for initialization
void Start ()
{
Debug.Assert(nbSpikesGround % nbGroupGround == 0);
Debug.Assert(nbSpikesWall % nbGroupWall == 0);
// XML read of the spikes ?
posSpike = new List<Vector3>();
scaleSpikes = new List<Vector3>();
orientationsSpikes = new List<Vector3>();
idGroupSpikes = new List<int>();
// We calculate the position of the wall spikes
float scaleY = 0;
float ratioSpikeInScreen = ((float)Screen.width / (float)Screen.height);
// Sur un echantillon representatif
scaleY = 2.0f*ratioSpikeInScreen + 0.4f;
for (int i = 0; i < nbSpikesGround; i++)
{
float delta =(float)( 1.0f / (float)(nbSpikesGround + 1));
float posX = delta + i * delta;
posSpike.Add(new Vector3(posX, -0.185f, 0));
scaleSpikes.Add(new Vector3(0.5f, 4, 1));
orientationsSpikes.Add(new Vector3(0,0,0));
int idGroup = (int)(i / (nbSpikesGround / nbGroupGround)) + 1;
idGroupSpikes.Add(idGroup);
}
for (int i = 0; i < nbSpikesWall; ++i)
{
float delta = (float)(1.0f / (float)(nbSpikesWall + 1));
float posY = delta + i * delta;
posSpike.Add(new Vector3(-0.105f, posY, 0));
scaleSpikes.Add(new Vector3(0.5f, scaleY, 1));
orientationsSpikes.Add(new Vector3(0, 0, 90));
int idGroup = (int)(i / (nbSpikesWall / nbGroupWall)) + 1 + nbGroupGround;
idGroupSpikes.Add(idGroup);
}
for (int i = 0; i < nbSpikesWall; i++)
{
float delta = (float)(1.0f / (float)(nbSpikesWall + 1));
float posY = delta + i * delta;
posSpike.Add(new Vector3(1.105f, posY, 0));
scaleSpikes.Add(new Vector3(0.5f, scaleY, 1));
orientationsSpikes.Add(new Vector3(0, 0, -90));
int idGroup = (int)(i / (nbSpikesWall / nbGroupWall)) + 1 + nbGroupGround + nbGroupWall;
idGroupSpikes.Add(idGroup);
}
initSpikes();
}
/// <summary>
/// Initialize the walls, ground, and roof
/// </summary>
void initSpikes()
{
//We create all the spikes
for (int i = 0; i < posSpike.Count; i ++)
{
GameObject spike = Instantiate(spikePrefab);
int id = i;
spike.GetComponent<SpikeScript>().idSpike = id;
spike.GetComponent<SpikeScript>().idGroupSpike = idGroupSpikes[i] - 1;
spike.transform.parent = this.transform;
Vector3 posSpikeWorld = Camera.main.ViewportToWorldPoint(posSpike[i]);
spike.transform.position = new Vector3(posSpikeWorld.x, posSpikeWorld.y, -1);
spike.transform.Rotate(orientationsSpikes[i]);
spike.transform.localScale = scaleSpikes[i];
spike.GetComponent<SpikeScript>().translateInCamera = 0.05f;
spike.gameObject.name = "Spike "+id;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class SpikeScript : MonoBehaviour
{
/// <summary>
/// ID of the spike
/// </summary>
public int idSpike = 0;
/// <summary>
/// ID of the group of spikes to raise
/// </summary>
public int idGroupSpike = 0;
/// <summary>
/// Must be the spike in mouvement to out ?
/// </summary>
private bool mustBeInMovementOut = false;
/// <summary>
/// Must be the spike in mouvement to in ?
/// </summary>
private bool mustBeInMovementIn = false;
/// <summary>
/// % of the camera that can see the spike, when out
/// </summary>
public float translateInCamera = 0.05f;
/// <summary>
/// Original translation speed of the spikes
/// </summary>
private float speed = 0.1f;
/// <summary>
/// The original number of seconds before the spike go up
/// </summary>
public float secondsBeforeUp = 2.5f;
/// <summary>
/// Time when the spike begin to go up
/// </summary>
private float timeBeginningUp = 0;
/// <summary>
/// Position of the spike when in the ground
/// </summary>
private float posWhenIn = 0;
/// <summary>
/// The speed of the spike
/// </summary>
private float actualSpeed = 0;
/// <summary>
/// The number of seconds before the spike go up
/// </summary>
private float actualTimeToGoUp = 0;
/// <summary>
/// True if it can kill the player, false otherwise
/// </summary>
public bool canKillPlayer = false;
// Use this for initialization
void Start()
{
this.gameObject.GetComponent<Renderer>().material.color = Color.green;
float rotation = this.transform.rotation.z;
Vector3 posSpikeCam = Camera.main.WorldToViewportPoint(this.transform.position);
if (rotation > 0 || rotation < 0)
posWhenIn = posSpikeCam.x;
else if (rotation == 0)
posWhenIn = posSpikeCam.y;
actualTimeToGoUp = secondsBeforeUp;
actualSpeed = speed;
canKillPlayer = false;
subscribeEvent<int>();
}
void Update()
{
//We increase the speed and decrease the cooldown
actualTimeToGoUp = secondsBeforeUp * Mathf.Max(0.1f, 1 - Time.timeSinceLevelLoad / 300);
actualSpeed = speed * Mathf.Min(5, 1 + Time.timeSinceLevelLoad / 60);
// We apply translation to the spikes
// Then we check for the ending position of the spike
//Go out has priority vs go in
if (mustBeInMovementOut && Time.time > (timeBeginningUp + actualTimeToGoUp))
{
this.gameObject.GetComponent<Renderer>().material.color = Color.red;
canKillPlayer = true;
float rotation = this.transform.rotation.z;
Vector3 posSpikeCam = Camera.main.WorldToViewportPoint(this.transform.position);
Vector3 perfectPosition = new Vector3(this.transform.position.x,
Camera.main.ViewportToWorldPoint(new Vector3(posSpikeCam.x,
translateInCamera,
posSpikeCam.z)).y,
this.transform.position.z);
if (rotation > 0 && posSpikeCam.x <= translateInCamera)
{
this.transform.Translate(new Vector3(0, -actualSpeed, 0));
Vector3 newPos = Camera.main.WorldToViewportPoint(this.transform.position);
if (newPos.x >= translateInCamera)
{
perfectPosition = new Vector3(
Camera.main.ViewportToWorldPoint(new Vector3(translateInCamera,
posSpikeCam.y,
posSpikeCam.z)).x,
this.transform.position.y,
this.transform.position.z);
this.transform.position = perfectPosition;
mustBeInMovementOut = false;
}
}
else if (rotation < 0 && posSpikeCam.x >= (1 - translateInCamera))
{
this.transform.Translate(new Vector3(0, -actualSpeed, 0));
Vector3 newPos = Camera.main.WorldToViewportPoint(this.transform.position);
if (newPos.x <= (1 - translateInCamera))
{
perfectPosition = new Vector3(
Camera.main.ViewportToWorldPoint(new Vector3((1 - translateInCamera),
posSpikeCam.y,
posSpikeCam.z)).x,
this.transform.position.y,
this.transform.position.z);
this.transform.position = perfectPosition;
mustBeInMovementOut = false;
}
}
else if (rotation == 0 && posSpikeCam.y <= translateInCamera)
{
this.transform.Translate(new Vector3(0, actualSpeed, 0));
Vector3 newPos = Camera.main.WorldToViewportPoint(this.transform.position);
if (newPos.y >= translateInCamera)
{
this.transform.position = perfectPosition;
mustBeInMovementOut = false;
}
}
}
else if(mustBeInMovementOut)
{
this.gameObject.GetComponent<Renderer>().material.color = Color.red;
canKillPlayer = true;
}
else if (mustBeInMovementIn)
{
this.gameObject.GetComponent<Renderer>().material.color = Color.green;
canKillPlayer = false;
float rotation = this.transform.rotation.z;
Vector3 posSpikeCam = Camera.main.WorldToViewportPoint(this.transform.position);
Vector3 perfectPosition = new Vector3( this.transform.position.x,
Camera.main.ViewportToWorldPoint(new Vector3(posSpikeCam.x,
posWhenIn,
posSpikeCam.z)).y,
this.transform.position.z);
if (rotation > 0 && posSpikeCam.x >= posWhenIn)
{
this.transform.Translate(new Vector3(0, actualSpeed, 0));
Vector3 newPos = Camera.main.WorldToViewportPoint(this.transform.position);
if (newPos.x <= posWhenIn)
{
perfectPosition = new Vector3(
Camera.main.ViewportToWorldPoint(new Vector3(posWhenIn,
posSpikeCam.y,
posSpikeCam.z)).x,
this.transform.position.y,
this.transform.position.z);
this.transform.position = perfectPosition;
mustBeInMovementIn = false;
}
}
else if (rotation < 0 && posSpikeCam.x <= posWhenIn)
{
this.transform.Translate(new Vector3(0, actualSpeed, 0));
Vector3 newPos = Camera.main.WorldToViewportPoint(this.transform.position);
if (newPos.x >= posWhenIn)
{
perfectPosition = new Vector3(
Camera.main.ViewportToWorldPoint(new Vector3(posWhenIn,
posSpikeCam.y,
posSpikeCam.z)).x,
this.transform.position.y,
this.transform.position.z);
this.transform.position = perfectPosition;
mustBeInMovementIn = false;
}
}
else if (rotation == 0 && posSpikeCam.y >= posWhenIn)
{
this.transform.Translate(new Vector3(0, -actualSpeed, 0));
Vector3 newPos = Camera.main.WorldToViewportPoint(this.transform.position);
if (newPos.y <= posWhenIn)
{
this.transform.position = perfectPosition;
mustBeInMovementIn = false;
}
}
}
}
private void subscribeEvent<T>()
{
EventManager.addActionToEvent<int>(MyEventTypes.SPIKEOUT, raiseSpike);
EventManager.addActionToEvent<int>(MyEventTypes.SPIKEIN, retractSpike);
EventManager.addActionToEvent<int>(MyEventTypes.GROUPSPIKEOUT, raiseGroupSpike);
EventManager.addActionToEvent<int>(MyEventTypes.GROUPSPIKEIN, retractGroupSpike);
}
public void raiseSpike(int i)
{
if (i == idSpike)
{
raiseSpike();
}
}
public void raiseGroupSpike(int i)
{
if (i == idGroupSpike)
{
raiseSpike();
}
}
private void raiseSpike()
{
timeBeginningUp = Time.time;
mustBeInMovementOut = true;
}
public void retractSpike(int i)
{
if (i == idSpike)
retractThisSpike();
}
public void retractGroupSpike(int i)
{
if (i == idGroupSpike)
retractThisSpike();
}
private void retractThisSpike()
{
mustBeInMovementIn = true;
}
}
<file_sep>using System.Collections.Generic;
using UnityEngine;
public class MyPhysics : MonoBehaviour
{
/// <summary>
/// acceleration donnee par le joueur
/// </summary>
public Vector2 playerGivenAcceleration;
/// <summary>
/// acceleration reelle
/// </summary>
private Vector2 acceleration;
/// <summary>
/// la vitesse effective du joueur
/// </summary>
private Vector2 speed;
/// <summary>
/// la position calculee du joueur
/// </summary>
public Vector2 position { get; private set; }
/// <summary>
/// la scale du joueur calculee
/// </summary>
public Vector3 scale { get; private set; }
private static List<BoxCollider> colliderList;
/// <summary>
/// le joueur sur qui le gravite joue
/// </summary>
private MovePlayer move;
public bool isInContactWithLeftWall;
public bool isInContactWithRightWall;
public bool isInContactWithPlateform;
public bool isInContactWithRoof;
/// <summary>
/// The gravity of the world
/// </summary>
[SerializeField]
private float gravity=9;
/// <summary>
/// la vitesse max du joueur
/// </summary>
[SerializeField]
private float maxSpeed=10;
/// <summary>
/// coefficient de frottement au sol
/// </summary>
[SerializeField]
private float groundDragCoeff=10;
/// <summary>
/// coefficient de frottement en l'air
/// </summary>
[SerializeField]
private float airDragCoeff=1;
// Use this for initialization
void Start ()
{
speed = new Vector2(0,0);
scale = new Vector3(1, 1, 1);
isInContactWithLeftWall = false;
isInContactWithRightWall = false;
isInContactWithPlateform = false;
isInContactWithRoof = false;
move = this.gameObject.GetComponent<MovePlayer>();
}
private void drag(float coeff)
{
if (speed.x > 0)
{
if(playerGivenAcceleration.x<=0)
speed.x -= coeff;
if (speed.x < 0)
speed.x = 0;
if (speed.x > maxSpeed)
speed.x = maxSpeed;
}
else if (speed.x < 0)
{
if(playerGivenAcceleration.x>=0)
speed.x += coeff;
if (speed.x > 0)
speed.x = 0;
if (speed.x < -maxSpeed)
speed.x = -maxSpeed;
}
}
/// <summary>
/// calcul de la nouvelle acceleration en prenant compte de la gravité
/// </summary>
private void gravityCalculator()
{
acceleration.y -= gravity;
}
/// <summary>
/// check if the player is out of the given walls
/// reset his position accordingly and set the booleans
/// </summary>
// potential problem if distance between wall are smaller than the player
private void checkOutOfWall()
{
Debug.Assert(colliderList != null);
foreach(BoxCollider collider in colliderList)
{
if ( position.x < collider.transform.position.x && collider.CompareTag(StringEnum.GetStringValue(Tags.LEFT_WALL))
|| position.x > collider.transform.position.x && collider.CompareTag(StringEnum.GetStringValue(Tags.RIGHT_WALL))
|| position.y < collider.transform.position.y && collider.CompareTag(StringEnum.GetStringValue(Tags.PLATFORM))
|| position.y > collider.transform.position.y && collider.CompareTag(StringEnum.GetStringValue(Tags.ROOF))
)
{
playerHasCollided(collider);
playerHasExitCollider(collider);
}
}
}
// Update is called once per frame
void Update ()
{
scale = new Vector3(1, 1, 1);
acceleration = playerGivenAcceleration;
//le coefficient de friction correspondant pour l'etat du player
float coeff = groundDragCoeff;
bool isGravityEnabled = true;
// if the player is in contact with something calculate his new position
// set isGravityEnabled and the dragCoeff
// rescale the player if Delta speed != 0
if (isInContactWithLeftWall || isInContactWithPlateform || isInContactWithRightWall || isInContactWithRoof)
{
if (isInContactWithRoof)
{
coeff = airDragCoeff;
if (acceleration.y > 0)
acceleration.y = 0;
if (speed.y > 0)
{
speed.y = 0;
}
}
else if (isInContactWithPlateform)
{
isGravityEnabled = false;
if (acceleration.y < 0)
acceleration.y = 0;
if (speed.y < 0)
{
speed.y = 0;
}
}
if (isInContactWithLeftWall)
{
if (acceleration.x < 0)
acceleration.x = 0;
if (speed.x < 0)
{
speed.x = 0;
}
}
else if (isInContactWithRightWall)
{
if (acceleration.x > 0)
acceleration.x = 0;
if (speed.x > 0)
{
speed.x = 0;
}
}
}
else//no contact
{
coeff = airDragCoeff;
isGravityEnabled = true;
}
if(isGravityEnabled)
gravityCalculator();
//update position
if (playerGivenAcceleration.Equals(new Vector2(0, 0)))
speed = speed + (acceleration * Time.deltaTime);
else
speed = speed + (0.02f * acceleration);
scale = new Vector3(1, scale.y+(speed.y/(2*maxSpeed)), 1);
drag(coeff);
position = position + (speed * Time.deltaTime);
checkOutOfWall();
}
public void playerHasCollided(BoxCollider collider)
{
Debug.Log(collider.gameObject + " entered");
if (collider.CompareTag(StringEnum.GetStringValue(Tags.LEFT_WALL)))
{
float distanceX = ((collider.bounds.size.x + move.GetComponent<Collider>().bounds.size.x) / 2);
float wallPosition = collider.transform.position.x + collider.center.x;
speed.x = 0;
position = new Vector2(wallPosition + distanceX, position.y);
Debug.Log("leftWall");
isInContactWithLeftWall = true;
}
else if (collider.CompareTag(StringEnum.GetStringValue(Tags.RIGHT_WALL)))
{
float distanceX = ((collider.bounds.size.x + move.GetComponent<Collider>().bounds.size.x) / 2);
float wallPosition = collider.transform.position.x + collider.center.x;
speed.x = 0;
position = new Vector2(wallPosition - distanceX, position.y);
Debug.Log("RightWall");
isInContactWithRightWall = true;
}
else if (collider.CompareTag(StringEnum.GetStringValue(Tags.PLATFORM)))
{
float distanceY = ((collider.bounds.size.y + move.GetComponent<Collider>().bounds.size.y) / 2);
//la position du collider par rapport a l'object
float center = collider.center.y;
//la position de l'object portant le collider
float positionCollider = collider.transform.position.y;
//position du collider
float platformPosition = center + positionCollider;
speed.y = 0;
position = new Vector2(position.x, platformPosition + distanceY);
Debug.Log("plat");
isInContactWithPlateform = true;
}
else if(collider.CompareTag(StringEnum.GetStringValue(Tags.ROOF)))
{
float distanceY = ((collider.bounds.size.y + move.GetComponent<Collider>().bounds.size.y) / 2);
//la position du collider par rapport a l'object
float center = collider.center.y;
//la position de l'object portant le collider
float positionCollider = collider.transform.position.y;
//position du collider
float platformPosition = center + positionCollider;
speed.y = 0;
position = new Vector2(position.x, platformPosition - distanceY);
Debug.Log("roof");
isInContactWithRoof = true;
}
}
public void playerHasExitCollider(BoxCollider collider)
{
Debug.Log(collider.gameObject + " exited");
if (collider.CompareTag(StringEnum.GetStringValue(Tags.LEFT_WALL)))
{
isInContactWithLeftWall = false;
}
else if(collider.CompareTag(StringEnum.GetStringValue(Tags.RIGHT_WALL)))
{
isInContactWithRightWall = false;
}
else if (collider.CompareTag(StringEnum.GetStringValue(Tags.PLATFORM)))
{
isInContactWithPlateform = false;
}
else if(collider.CompareTag(StringEnum.GetStringValue(Tags.ROOF)))
{
isInContactWithRoof = false;
}
}
public static void newWall(BoxCollider collider)
{
if (colliderList == null)
colliderList = new List<BoxCollider>();
colliderList.Add(collider);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class Particles : MonoBehaviour {
public bool isInContactWithWall;
private ParticleSystem.EmissionModule emission;
// Use this for initialization
void Start () {
emission = this.gameObject.GetComponent<ParticleSystem>().emission;
}
// Update is called once per frame
void Update ()
{
Debug.Log(emission.enabled);
if (isInContactWithWall)
{
emission.enabled = true;
}
else
{
emission.enabled = false;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class PlatformScript : MonoBehaviour {
/// <summary>
/// Number of seconds before respawn of the platform
/// </summary>
public float cooldownRespawn = 5;
/// <summary>
/// Last time.time when the platform was desactivated
/// </summary>
private float lastTimeDesactivated = 0;
/// <summary>
/// Number of seconds before the desapear of the platform
/// </summary>
public float timeBeforeDisapear = 3;
// Use this for initialization
void Start ()
{
this.transform.parent.gameObject.GetComponent<Renderer>().material.color = new Color(0, 0, 10);
}
void Update()
{
if (lastTimeDesactivated != 0)
{
if (Time.time - lastTimeDesactivated > timeBeforeDisapear + cooldownRespawn)
{
respawnPlatform();
}
else if (Time.time - lastTimeDesactivated > timeBeforeDisapear)
{
hidePlatform();
}
}
}
public void platformTouched()
{
if(lastTimeDesactivated == 0)
{
lastTimeDesactivated = Time.time;
this.transform.parent.gameObject.GetComponent<Renderer>().material.color = new Color(100, 0, 0);
}
}
/// <summary>
/// Hide the platform
/// </summary>
public void hidePlatform()
{
if(this.gameObject.GetComponent<BoxCollider>().enabled)
{
EventManager.raise(MyEventTypes.PLATFORMHIDEN);
this.gameObject.GetComponent<BoxCollider>().enabled = false;
this.transform.parent.GetComponent<Renderer>().enabled = false;
}
}
/// <summary>
/// Print the platform, and enable the collider
/// </summary>
public void respawnPlatform()
{
lastTimeDesactivated = 0;
this.transform.parent.GetComponent<Renderer>().enabled = true;
this.gameObject.GetComponent<BoxCollider>().enabled = true;
this.transform.parent.gameObject.GetComponent<Renderer>().material.color = new Color(0, 0, 10);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class MovePlayer : MonoBehaviour
{
/// <summary>
/// The multiplicator of the speed
/// </summary>
public float speedX;
/// <summary>
/// The height of the jump
/// </summary>
public float speedJumpY;
// Is the player in contact wiith a plateform ?
public bool isInContactWithPlatform;
// Is the player in contact wiith a wall ?
public bool isInContactWithWall;
// Has the player already used his double jump ?
private bool doubleJumpedUsed = false;
// Lats platform collided
private BoxCollider lastCollider;
/// <summary>
/// Single jump
/// </summary>
private bool singleJumpUsed = false;
// Use this for initialization
void Start()
{
this.gameObject.GetComponent<Renderer>().material.color = Color.white;
}
// Update is called once per frame
void Update()
{
if (isInContactWithPlatform || isInContactWithWall)
{
doubleJumpedUsed = false;
singleJumpUsed = false;
}
controls();
movePlayerFromPhysics();
}
private void movePlayerFromPhysics()
{
this.gameObject.transform.position = this.gameObject.GetComponent<MyPhysics>().position;
this.gameObject.transform.localScale = this.gameObject.GetComponent<MyPhysics>().scale;
Vector3 cameraLimits = Camera.main.WorldToViewportPoint(this.gameObject.transform.position);
if (cameraLimits.x < 0 || cameraLimits.x > 1f ||
cameraLimits.y < 0 || cameraLimits.y > 1f)
{
EventManager.raise(MyEventTypes.ONLOSE);
}
}
void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.tag == StringEnum.GetStringValue(Tags.SPIKE))
{
if(collision.gameObject.GetComponent<SpikeScript>() != null && collision.gameObject.GetComponent<SpikeScript>().canKillPlayer)
{
EventManager.raise(MyEventTypes.ONLOSE);
}
}
else
{
if (collision.gameObject.tag == StringEnum.GetStringValue(Tags.PLATFORM))
{
// If it's a platform and not the ground
if (collision.gameObject.GetComponent<PlatformScript>() != null)
{
if (collision.GetType() == typeof(BoxCollider))
lastCollider = (BoxCollider)collision;
collision.gameObject.GetComponent<PlatformScript>().platformTouched();
EventManager.addActionToEvent(MyEventTypes.PLATFORMHIDEN, platformExited);
}
isInContactWithPlatform = true;
doubleJumpedUsed = false;
singleJumpUsed = false;
}
else if (collision.gameObject.tag == StringEnum.GetStringValue(Tags.RIGHT_WALL)
|| collision.gameObject.tag == StringEnum.GetStringValue(Tags.LEFT_WALL))
{
isInContactWithWall = true;
doubleJumpedUsed = false;
singleJumpUsed = false;
if (this.transform.GetChild(0).gameObject.GetComponent<Particles>() != null)
this.transform.GetChild(0).gameObject.GetComponent<Particles>().isInContactWithWall = this.isInContactWithWall;
}
if (collision.GetType() == typeof(BoxCollider))
this.GetComponent<MyPhysics>().playerHasCollided((BoxCollider)collision);
else
Debug.Log("CRITICAL " + collision.gameObject + " PLATFORM NOT BOXCOLLIDER");
}
}
/// <summary>
/// Called when the platform disapear
/// </summary>
void platformExited()
{
isInContactWithPlatform = false;
if(this.GetComponent<MyPhysics>() != null)
this.GetComponent<MyPhysics>().playerHasExitCollider((BoxCollider)lastCollider);
}
void OnTriggerExit(Collider collision)
{
// If we exited normally the platform
if (lastCollider == collision)
EventManager.removeActionFromEvent(MyEventTypes.PLATFORMHIDEN, platformExited);
if (collision.gameObject.tag == StringEnum.GetStringValue(Tags.PLATFORM))
{
isInContactWithPlatform = false;
}
else if (collision.gameObject.tag == StringEnum.GetStringValue(Tags.RIGHT_WALL)
|| collision.gameObject.tag == StringEnum.GetStringValue(Tags.LEFT_WALL))
{
isInContactWithWall = false;
if (this.transform.GetChild(0).gameObject.GetComponent<Particles>() != null)
this.transform.GetChild(0).gameObject.GetComponent<Particles>().isInContactWithWall = this.isInContactWithWall;
}
if (collision.gameObject.tag != StringEnum.GetStringValue(Tags.SPIKE))
{
if (collision.GetType() == typeof(BoxCollider))
this.GetComponent<MyPhysics>().playerHasExitCollider((BoxCollider)collision);
else
Debug.Log("CRITICAL " + collision.gameObject + " PLATFORM NOT BOXCOLLIDER");
}
}
/// <summary>
/// Get the inputs of the player, and apply it to the player
/// </summary>
void controls()
{
float xAxis = Input.GetAxis("XAxis");
this.gameObject.GetComponent<MyPhysics>().playerGivenAcceleration = new Vector3(xAxis * speedX, this.gameObject.GetComponent<MyPhysics>().playerGivenAcceleration.y, 0);
if (this.gameObject.GetComponent<MyPhysics>() != null)
if (Input.GetButtonDown("Jump"))
{
if(!singleJumpUsed)
{
this.gameObject.GetComponent<MyPhysics>().playerGivenAcceleration = new Vector3(this.gameObject.GetComponent<MyPhysics>().playerGivenAcceleration.x, speedJumpY, 0);
singleJumpUsed = true;
if(this.gameObject.GetComponent<AudioSource>() != null)
{
AudioSource audio = this.gameObject.GetComponent<AudioSource>();
audio.Play();
}
}
else if (!doubleJumpedUsed && singleJumpUsed)
{
this.gameObject.GetComponent<MyPhysics>().playerGivenAcceleration = new Vector3(this.gameObject.GetComponent<MyPhysics>().playerGivenAcceleration.x, speedJumpY, 0);
doubleJumpedUsed = true;
if (this.gameObject.GetComponent<AudioSource>() != null)
{
AudioSource audio = this.gameObject.GetComponent<AudioSource>();
audio.Play();
}
}
}
else
{
GetComponent<MyPhysics>().playerGivenAcceleration = new Vector3(GetComponent<MyPhysics>().playerGivenAcceleration.x, 0, 0);
}
}
void OnDestroy()
{
EventManager.removeActionFromEvent(MyEventTypes.PLATFORMHIDEN, platformExited);
}
}
<file_sep>using UnityEngine;
using System.Collections.Generic;
public class LevelFactory : MonoBehaviour
{
/// <summary>
/// The prefab to build the plateforms
/// </summary>
public GameObject platformPrefab;
/// <summary>
/// List of the position of the platforms
/// Position : betweeen 0 and 1
/// </summary>
///
public List<Vector3> posPlatforms;
/// <summary>
/// List of the position of the walls
/// Position : betweeen 0 and 1
/// </summary>
///
public List<Vector3> posWalls;
/// <summary>
/// List of the scale of the platforms
/// Scale : whatever you want
/// </summary>
public List<Vector3> scalePlatforms;
/// <summary>
/// List of the scale of the walls
/// Scale : whatever you want
/// </summary>
public List<Vector3> scaleWalls;
// Use this for initialization
void Start ()
{
// XML read of the platforms ?
Debug.Assert(posWalls.Count == scaleWalls.Count);
Debug.Assert(posPlatforms.Count == scalePlatforms.Count);
initWalls();
initPlatforms();
initPlatformsWalls();
}
/// <summary>
/// Initialize the walls, ground, and roof
/// </summary>
void initWalls()
{
GameObject ground = Instantiate(platformPrefab);
ground.transform.parent = this.transform;
ground.transform.localScale = new Vector3(120, 1, 1);
Vector3 posGround = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, 0));
ground.transform.position = new Vector3(0, posGround.y + ground.GetComponent<Collider>().bounds.size.y / 2, 0);
ground.gameObject.name = "Ground";
foreach(Transform child in ground.transform)
{
if (child.gameObject.tag != StringEnum.GetStringValue(Tags.PLATFORM))
{
Destroy(child.gameObject);
}
else
{
Destroy(child.gameObject.GetComponent<PlatformScript>());
MyPhysics.newWall(child.gameObject.GetComponent<BoxCollider>());
}
}
GameObject roof = Instantiate(platformPrefab);
roof.transform.parent = this.transform;
roof.transform.localScale = new Vector3(120, 1, 1);
Vector3 posRoof = Camera.main.ViewportToWorldPoint(new Vector3(0, 1, 0));
roof.transform.position = new Vector3(0, posRoof.y - roof.GetComponent<Collider>().bounds.size.y / 2, 0);
roof.gameObject.name = "Roof";
foreach (Transform child in roof.transform)
{
if (child.gameObject.tag != StringEnum.GetStringValue(Tags.ROOF))
{
Destroy(child.gameObject);
}
else
MyPhysics.newWall(child.gameObject.GetComponent<BoxCollider>());
}
GameObject leftWall = Instantiate(platformPrefab);
leftWall.transform.parent = this.transform;
leftWall.transform.localScale = new Vector3(1, 120, 1);
Vector3 posLeftWall = Camera.main.ViewportToWorldPoint(new Vector3(0, 0.5f, 0));
leftWall.transform.position = new Vector3(posLeftWall.x + leftWall.GetComponent<Collider>().bounds.size.x / 2, 0 , 0);
leftWall.gameObject.name = "LeftWall";
foreach (Transform child in leftWall.transform)
{
if (child.gameObject.tag != StringEnum.GetStringValue(Tags.LEFT_WALL))
{
Destroy(child.gameObject);
}
else
MyPhysics.newWall(child.gameObject.GetComponent<BoxCollider>());
}
GameObject rightWall = Instantiate(platformPrefab);
rightWall.transform.parent = this.transform;
rightWall.transform.localScale = new Vector3(1, 120, 1);
Vector3 posRightWall = Camera.main.ViewportToWorldPoint(new Vector3(1f, 0.5f, 0));
rightWall.transform.position = new Vector3(posRightWall.x - rightWall.GetComponent<Collider>().bounds.size.x / 2, 0, 0);
rightWall.gameObject.name = "RightWall";
foreach (Transform child in rightWall.transform)
{
if (child.gameObject.tag != StringEnum.GetStringValue(Tags.RIGHT_WALL))
{
Destroy(child.gameObject);
}
else
MyPhysics.newWall(child.gameObject.GetComponent<BoxCollider>());
}
}
/// <summary>
/// Initialize the platforms : scale and positions
/// </summary>
void initPlatforms()
{
for(int i = 0; i< posPlatforms.Count; i++)
{
Vector3 pos = posPlatforms[i];
Vector3 scale = scalePlatforms[i];
GameObject platform = Instantiate(platformPrefab);
platform.transform.parent = this.transform;
platform.gameObject.name = "Platform";
Vector3 posPlatform = Camera.main.ViewportToWorldPoint(pos);
platform.transform.position = new Vector3(posPlatform.x, posPlatform.y, 0);
platform.transform.localScale = scale;
foreach (Transform child in platform.transform)
{
if (child.gameObject.tag != StringEnum.GetStringValue(Tags.PLATFORM))
{
Destroy(child.gameObject);
}
}
}
}
/// <summary>
/// Init some little walls
/// </summary>
void initPlatformsWalls()
{
for (int i = 0; i < posWalls.Count; i++)
{
Vector3 pos = posWalls[i];
Vector3 scale = scaleWalls[i];
GameObject platform = Instantiate(platformPrefab);
platform.transform.parent = this.transform;
platform.gameObject.name = "PlatformWall";
Vector3 posPlatform = Camera.main.ViewportToWorldPoint(pos);
platform.transform.position = new Vector3(posPlatform.x, posPlatform.y, 0);
platform.transform.localScale = scale;
foreach (Transform child in platform.transform)
{
if (child.gameObject.tag != StringEnum.GetStringValue(Tags.LEFT_WALL) &&
child.gameObject.tag != StringEnum.GetStringValue(Tags.RIGHT_WALL))
{
Destroy(child.gameObject);
}
}
}
}
}
|
860729b3f01eef614ec31d33c636d03546dd68f0
|
[
"C#"
] | 10 |
C#
|
pingu111/Controler
|
ce070db699c954ada3a84299f6af640951757c0e
|
3cbf8c92b17b35eab78ac82b5d8f403c1028f561
|
refs/heads/master
|
<file_sep>import React from 'react'
import useForm from '../hooks/form-hook'
import validate from '../utils/validate'
import './Login.css'
const Login = () =>{
const {handleChange, values, handleSubmit} = useForm();
return(
<div className="main__form">
<form onSubmit={handleSubmit}>
<label>Email</label>
<input
id="email"
type="text"
name="email"
placeholder="Enter email"
value={values.email}
onChange={handleChange}
/>
<label>Password</label>
<input
id="password"
type="password"
name="password"
placeholder="Enter Password"
value={values.password}
onChange={handleChange}
/>
<button type="submit">Login</button>
</form>
</div>
)
}
export default Login<file_sep># auth-react-hooks
<file_sep>import React from 'react'
import { useForm } from 'react-hook-form'
import './Register.css';
const Register=()=>{
const {register, handleSubmit, formState:{errors, isDirty, isValid},} = useForm({mode: "onChange"});
console.log("error object:" ,errors);
const onSubmit=(data)=>{
console.log(data)
}
return (
<div className="main__form">
<form onSubmit={handleSubmit(onSubmit)}>
<h1>Register</h1>
<label className="label">Email</label> {errors.email && (<p className="danger"> {errors.email.message}</p> )}
<input
type="text"
placeholder="Enter Email"
{...register("email", {
required: "Email is required",
pattern: {
value: /^[^@ ]+@[^@ ]+\.[^@ .]{2,}$/,
message: "Email format not valid"
}})}/>
<label>Username</label>
<input
type="text"
name="username"
placeholder="Enter an Username"
{...register('username', {
required: "Username is required",
minLength: 6,
maxLength: 12,
pattern:{
value: /^[A-Za-z0-9]+$/i,
message: "Username contain uppercase , lowercase and number"
}
})}/>
{errors.username && (<p className="danger"> {errors.username.message}</p> )}
<label>Password</label>
<input
type="<PASSWORD>"
name="password"
placeholder="Enter password"
{...register('password',
{required: "Password is required",
minLength: 6,
pattern: {
value: /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/ ,
message: "Password should contain at least one uppercase letter, lowercase letter, digit, and special symbol."
}
})}/>
{errors.password && (<p className="danger"> {errors.password.message}</p> )}
<button type="submit" disabled={!isDirty || !isValid}>Register</button>
</form>
</div>
)
}
export default Register
|
eb09bb4bf1c4b5bd3b38b4b8ecb5d97e7600826c
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
grlara9/auth-react-hooks
|
33bb72652e6d2e20b7dd6477104b06d6258b6f42
|
948ca1817ff6292bf61308284805af38cb77aa7c
|
refs/heads/master
|
<file_sep>
# Orangered!
This small application is designed to sit up in your Mac OS X menu bar and poll every 60 seconds to see if you have any reddit.com messages awaiting your feverent attention.
This is for testing a PR, do not merge.
For the reddit obsessed.
# UFO Colors
* Outline : Not logged in
* Filled : Logged in, no messages
* Orange Canopy: You have a message! Make with the clicking!
* Magenta Canopy: Mod mail, look at you, Mr. Importante!
# Special Thanks to the following redditors:
* Traviscat
* ashleyw
* Condawg
* dawnerd
* despideme
* derekaw
* EthicalReasoning
* giftedmunchkin
* kevinhoagland
* loggedout
* polyGone
* RamenStein
* shinratdr
* sporadicmonster
* pkamb
* sammcj
# Features
This application is deliberately as featureless as possible, if you are looking for a commercially supported expierence, you may look at <NAME>'s excellent Orangered notifier for Reddit: https://itunes.apple.com/us/app/orangered-notifier-for-reddit/id468366517?mt=12
<file_sep>//
// UserDefaults+Orangered.swift
// Orangered
//
// Created by <NAME> on 6/13/16.
// Copyright © 2016 Rockwood Software. All rights reserved.
//
import Foundation
import Cocoa
private let kUserNameKey = "username"
private let kLoggedInKey = "logged in"
private let kUseAltImagesKey = "use alt images"
private let kMailCountKey = "unread inbox count"
private let kServiceName = "Orangered!"
extension UserDefaults {
var username:String? {
get {
return string(forKey: kUserNameKey)
}
set {
set(newValue, forKey: kUserNameKey)
}
}
var password:String? {
get {
let pass = getPassword()
UserDefaults.keychainItem = nil
return pass
}
set {
setPassword(newValue!)
}
}
var loggedIn:Bool {
get {
return bool(forKey: kLoggedInKey)
}
set {
set(newValue, forKey: kLoggedInKey)
}
}
var useAltImages:Bool {
get {
return bool(forKey: kUseAltImagesKey)
}
set {
set(newValue, forKey: kUseAltImagesKey)
}
}
var mailCount:Int {
get {
return integer(forKey: kMailCountKey)
}
set {
set(newValue, forKey: kMailCountKey)
}
}
// C APIs are *the worst*
static fileprivate var keychainItem:SecKeychainItem? = nil
fileprivate func getPassword() -> String? {
guard let uname = username else {
print("no user name set")
return nil
}
var passwordLength:UInt32 = 0
var passwordData:UnsafeMutableRawPointer? = nil
let err = SecKeychainFindGenericPassword(nil,
UInt32(kServiceName.count),
kServiceName,
UInt32(uname.count),
uname,
&passwordLength,
&passwordData,
&UserDefaults.keychainItem)
if let pass = passwordData, err == errSecSuccess {
let password = String(bytesNoCopy: pass, length: Int(passwordLength), encoding: String.Encoding.utf8, freeWhenDone: true)
return password
}
else {
print("Error grabbing password: \(err)")
}
return nil
}
fileprivate func setPassword(_ pass:String) {
guard let uname = username else {
print("No username")
return
}
if let _ = getPassword() {
// have to update instead of setting
updatePassword(pass)
return
}
let result = SecKeychainAddGenericPassword(nil,
UInt32(kServiceName.count),
kServiceName,
UInt32(uname.count),
uname,
UInt32(pass.count),
pass,
nil)
if result != errSecSuccess {
print("error setting key: \(result)")
}
}
fileprivate func updatePassword(_ password:String) {
guard let itemActual = UserDefaults.keychainItem else {
print("Must grab a password to init the item before updatint it, bleah")
return
}
let result = SecKeychainItemModifyAttributesAndData(itemActual,
nil,
UInt32(password.count),
password)
if result != errSecSuccess {
print("error updating the keychain: \(result)")
}
UserDefaults.keychainItem = nil
}
}
<file_sep>//
// PrefViewController.swift
// Orangered
//
// Created by <NAME> on 6/17/16.
// Copyright © 2016 Rockwood Software. All rights reserved.
//
import Cocoa
import ServiceManagement
class PrefViewController: NSViewController {
let startAtLogin = NSButton(cbWithTitle: "Start at Login", target: nil, action: #selector(salClicked))
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func loadView() {
// Don't call into super, as we don't want it to try to load from a nib
view = NSView()
view.translatesAutoresizingMaskIntoConstraints = false
}
fileprivate func setup() {
startAtLogin.target = self
startAtLogin.translatesAutoresizingMaskIntoConstraints = false
title = "Orangered! Preferences"
view.addSubview(startAtLogin)
NSLayoutConstraint.activate([
startAtLogin.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10),
startAtLogin.topAnchor.constraint(equalTo: view.topAnchor, constant: 10),
view.bottomAnchor.constraint(equalTo: startAtLogin.bottomAnchor, constant: 10),
view.widthAnchor.constraint(equalTo: startAtLogin.widthAnchor, constant: 20)
])
}
@objc fileprivate func salClicked() {
print(SMLoginItemSetEnabled("com.rockwood.Orangered" as CFString, true))
}
}
extension NSButton {
convenience init(cbWithTitle title: String, target: NSObject?, action: Selector) {
if #available(OSX 10.12, *) {
self.init(checkboxWithTitle: title, target: target, action: action)
} else {
self.init()
setButtonType(.switch)
self.title = title
self.target = target
self.action = action
}
}
}
<file_sep>//
// AppDelegate.swift
// Orangered-Swift
//
// Created by <NAME> on 5/29/16.
// Copyright © 2016 Rockwood Software. All rights reserved.
//
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var controller:StatusItemController!
func applicationDidFinishLaunching(_ aNotification: Notification) {
controller = StatusItemController()
}
}
<file_sep>//
// StatusItemController.swift
// Orangered
//
// Created by <NAME> on 6/13/16.
// Copyright © 2016 Rockwood Software. All rights reserved.
//
import Foundation
import Cocoa
import UserNotifications
private let kUpdateURL = URL(string: "http://voidref.com/orangered/version")
private let kRedditCookieURL = URL(string: "https://reddit.com")
private let kLoginMenuTitle = NSLocalizedString("Login…", comment: "Menu item title for bringing up the login window")
private let kLogoutMenuTitle = NSLocalizedString("Log Out", comment: "Menu item title for logging out")
private let kAttemptingLoginTitle = NSLocalizedString("Attempting Login…", comment: "Title of the login menu item while it's attemping to log in")
private let kOpenMailboxRecheckDelay = 5.0
class StatusItemController: NSObject, UNUserNotificationCenterDelegate {
enum State {
case loggedout
case invalidcredentials
case disconnected
case mailfree
case orangered
case modmail
case update
fileprivate static let urlMap = [
loggedout: nil,
invalidcredentials: nil,
disconnected: nil,
mailfree: URL(string: "https://www.reddit.com/message/inbox/"),
orangered: URL(string: "https://www.reddit.com/message/unread/"),
modmail: URL(string: "https://www.reddit.com/message/moderator/"),
update: nil
]
func image(forAppearance appearanceName: String, useAlt:Bool = false) -> NSImage {
let imageMap = [
State.loggedout: "not-connected",
State.invalidcredentials: "not-connected",
State.disconnected: "not-connected",
State.mailfree: "logged-in",
State.orangered: "message",
State.modmail: "mod",
State.update: "BlueEnvelope" // TODO: Sort this out
]
guard let basename = imageMap[self] else {
fatalError("you really messed up this time, missing case: imageMap for \(self)")
}
var name = basename
if useAlt {
name = "alt-\(basename)"
}
if appearanceName == NSAppearance.Name.vibrantDark.rawValue {
name = "\(name)-dark"
}
guard let image = NSImage(named: name) else {
fatalError("fix yo assets, missing image: \(name)")
}
return image
}
func mailboxUrl() -> URL? {
return State.urlMap[self]!
}
}
fileprivate var state = State.disconnected {
willSet {
if newValue != state {
// In order to avoid having to set flags for handling values set that were already set, we check `willSet`. This, however, necessitates we reschedule handling until the value is actually set as there doesn't seem to be a way to let it set and then call a method synchronously
DispatchQueue.main.async(execute: {
self.handleStateChanged()
})
}
}
}
fileprivate let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
fileprivate var statusPoller:Timer?
fileprivate let prefs = UserDefaults.standard
fileprivate var statusConnection:URLSession?
fileprivate let session = URLSession.shared
fileprivate var loginWindowController:NSWindowController?
fileprivate var prefWindowController:NSWindowController?
fileprivate var mailboxItem:NSMenuItem?
fileprivate var loginItem:NSMenuItem?
fileprivate var mailCount:Int {
get {
return prefs.mailCount
}
set {
prefs.mailCount = newValue
}
}
override init() {
super.init()
prefs.useAltImages = false
setup()
if prefs.loggedIn {
login()
}
}
fileprivate func setup() {
UNUserNotificationCenter.current().delegate = self
setupMenu()
}
private func setupMenu() {
let menu = Menu()
let mailbox = NSMenuItem(title: NSLocalizedString("Mailbox…", comment:"Menu item for opening the reddit mailbox"),
action: #selector(handleMailboxItemSelected), keyEquivalent: "")
mailbox.isEnabled = false
menu.addItem(mailbox)
mailboxItem = mailbox
menu.addItem(NSMenuItem.separator())
let login = NSMenuItem(title: kLoginMenuTitle,
action: #selector(handleLoginItemSelected), keyEquivalent: "")
menu.addItem(login)
loginItem = login
#if PrefsDone
let prefsItem = NSMenuItem(title: NSLocalizedString("Preferences…", comment:"Menu item title for opening the preferences window"),
action: #selector(handlePrefItemSelected), keyEquivalent: "")
menu.addItem(prefsItem)
#endif
let quitItem = NSMenuItem(title: NSLocalizedString("Quit", comment:"Quit menu item title"),
action: #selector(quit), keyEquivalent: "")
menu.addItem(quitItem)
menu.items.forEach { (item) in
item.target = self
}
statusItem.menu = menu
var altImageName = "active"
if prefs.useAltImages {
altImageName = "alt-\(altImageName)"
}
statusItem.button?.alternateImage = NSImage(named: altImageName)
updateIcon()
}
private func login() {
guard let url = URL(string: "https://ssl.reddit.com/api/login") else {
print("Error bad url, wat?")
return
}
guard let uname = prefs.username, let password = prefs.password else {
showLoginWindow()
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "user=\(uname)&passwd=\(password)".data(using: String.Encoding.utf8)
loginItem?.title = kAttemptingLoginTitle
let task = session.dataTask(with: request) { (data, response, error) in
self.handleLogin(response: response, data:data, error: error)
}
task.resume()
}
fileprivate func handleLogin(response:URLResponse?, data:Data?, error:Error?) {
if let dataActual = data, let
dataString = String(data:dataActual, encoding:String.Encoding.utf8) {
if dataString.contains("wrong password") {
DispatchQueue.main.async {
// There seems to be a problem with showing another window while this one has just been dismissed, rescheduling on the main thread solves this.
// TODO: wrong password error
self.state = .invalidcredentials
let alert = NSAlert()
alert.messageText = NSLocalizedString("Username and password do not match any recognized by Reddit", comment: "username/password mismatch error")
alert.addButton(withTitle: NSLocalizedString("Lemme fix that...", comment:"Wrong password dialog acknowledgement button"))
alert.runModal()
self.showLoginWindow()
}
return
}
}
guard let responseActual = response as? HTTPURLResponse else {
print("Response is not an HTTPURLResponse, somehow: \(String(describing: response))")
return
}
guard let headers = responseActual.allHeaderFields as NSDictionary? as! [String:String]? else {
print("wrong headers ... or so: \(responseActual.allHeaderFields)")
return
}
guard let url = responseActual.url else {
print("missing url from response: \(responseActual)")
return
}
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: url)
if cookies.count < 1 {
print("Login error: \(String(describing: response))")
state = .disconnected
}
else {
HTTPCookieStorage.shared.setCookies(cookies, for: kRedditCookieURL, mainDocumentURL: nil)
prefs.loggedIn = true
state = .mailfree
setupStatusPoller()
}
}
private func setupStatusPoller() {
statusPoller?.invalidate()
let interval:TimeInterval = 60
statusPoller = Timer(timeInterval: interval, target: self, selector: #selector(checkReddit), userInfo: nil, repeats: true)
RunLoop.main.add(statusPoller!, forMode: .default)
statusPoller?.fire()
}
private func showLoginWindow() {
let login = LoginViewController { [weak self] (name, password) in
self?.loginWindowController?.close()
self?.prefs.username = name
self?.prefs.password = <PASSWORD>
self?.login()
}
let window = NSPanel(contentViewController: login)
window.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark)
loginWindowController = NSWindowController(window: window)
NSApp.activate(ignoringOtherApps: true)
loginWindowController?.showWindow(self)
}
private func showPrefWindow() {
let pref = NSWindowController(window: NSPanel(contentViewController: PrefViewController()))
prefWindowController = pref
NSApp.activate(ignoringOtherApps: true)
pref.showWindow(self)
}
private func interpretResponse(json: Any) {
// Crude, but remarkably immune to data restructuring as long as the key value pairs don't change.
// WTF Swift 3...
guard let jsonDict = json as AnyObject? else {
return
}
guard let jsonActual = jsonDict["data"] as? [String:AnyObject] else {
print("response json unexpected format: \(json)")
return
}
if let newMailCount = jsonActual["inbox_count"] as? Int {
if newMailCount != mailCount {
mailCount = newMailCount
if mailCount > 0 {
notifyMail()
}
else {
// We had mail, and now we don't. Safe to assume it's all been read.
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
}
}
if let modMailState = jsonActual["has_mod_mail"] as? Bool, modMailState == true {
state = .modmail
return
}
if let mailState = jsonActual["has_mail"] as? Bool {
if mailState {
state = .orangered
}
else {
state = .mailfree
}
}
else {
// probably login error
state = .disconnected
}
}
private func handleStateChanged() {
updateIcon()
mailboxItem?.isEnabled = true
loginItem?.title = prefs.loggedIn ? kLogoutMenuTitle : kLoginMenuTitle
switch state {
case .disconnected:
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10, execute: {
self.login()
})
fallthrough
case .loggedout, .invalidcredentials:
mailboxItem?.isEnabled = false
case .orangered, .modmail, .mailfree, .update:
break
}
}
private func updateIcon() {
statusItem.button?.image = state.image(forAppearance: statusItem.button!.effectiveAppearance.name.rawValue, useAlt: prefs.useAltImages)
}
private func notifyMail() {
let note = UNMutableNotificationContent()
note.title = "Orangered!"
note.body = NSLocalizedString("You have a new message on reddit!", comment: "new message notification text")
// note.actionButtonTitle = NSLocalizedString("Read", comment: "notification call to action button")
if mailCount > 1 {
note.body = String
.localizedStringWithFormat(NSLocalizedString("You have %i unread messages on reddit",
comment: "plural message notification text"),
mailCount)
}
UNUserNotificationCenter
.current()
.add(UNNotificationRequest(identifier: "Orangered!", content: note, trigger: nil))
}
private func openMailbox() {
if let url = state.mailboxUrl() {
NSWorkspace.shared.open(url)
}
// There's no reasonable way to know when reddit has cleared the unread flag, so we just wait a bit and check again.
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + kOpenMailboxRecheckDelay) {
self.checkReddit()
}
}
private func logout() {
prefs.loggedIn = false
statusPoller?.invalidate()
let storage = HTTPCookieStorage.shared
storage.cookies(for: kRedditCookieURL!)?.forEach { storage.deleteCookie($0) }
state = .loggedout
}
@objc private func checkReddit() {
guard let uname = prefs.username,
let url = URL(string: "http://www.reddit.com/user/\(uname)/about.json") else {
print("User name empty")
return
}
let task = session.dataTask(with: url) { (data, response, error) in
if let dataActual = data {
do {
try self.interpretResponse(json: JSONSerialization.jsonObject(with: dataActual, options: .allowFragments))
} catch let error {
print("Error reading response json: \(error)")
}
}
else {
print("Failure: \(String(describing: response))")
}
}
task.resume()
}
@objc private func quit() {
NSApplication.shared.stop(nil)
}
@objc func handleLoginItemSelected() {
if prefs.loggedIn {
logout()
}
else {
showLoginWindow()
}
}
@objc func handlePrefItemSelected() {
showPrefWindow()
}
@objc func handleMailboxItemSelected() {
openMailbox()
}
// MARK: User Notification Center
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
openMailbox()
}
// @objc func userNotificationCenter(did) {
// openMailbox()
// }
}
<file_sep>//
// LoginViewController.swift
// Orangered
//
// Created by <NAME> on 6/13/16.
// Copyright © 2016 Rockwood Software. All rights reserved.
//
import Cocoa
let kHelpURL = URL(string: "https://www.github.com/voidref/orangered")
typealias LoginAction = (_:String, _ password:String) -> Void
class LoginViewController: NSViewController {
fileprivate let nameLabel = NSTextField()
fileprivate let passwordLabel = NSTextField()
fileprivate let nameField = NSTextField()
fileprivate let passwordField = NSSecureTextField()
fileprivate let loginButton = NSButton()
fileprivate let helpButton = NSButton()
fileprivate let loginAction:LoginAction
init(_ action: @escaping LoginAction) {
loginAction = action
super.init(nibName: nil, bundle: nil)
title = NSLocalizedString("Orangered! Login", comment: "The login window title")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func loadView() {
// Don't call into super, as we don't want it to try to load from a nib
view = NSVisualEffectView()
view.translatesAutoresizingMaskIntoConstraints = false
}
fileprivate func setup() {
[nameLabel,
nameField,
passwordLabel,
passwordField,
loginButton,
helpButton].forEach { add($0) }
func confgure(label:NSTextField, text:String) {
label.stringValue = text
label.isEditable = false
label.backgroundColor = #colorLiteral(red: 0.6470588235, green: 0.631372549, blue: 0.7725490196, alpha: 0)
label.drawsBackground = false
label.sizeToFit()
label.isBezeled = false
}
confgure(label: nameLabel,
text: NSLocalizedString("User Name:", comment: "reddit user name field label"))
confgure(label: passwordLabel,
text: NSLocalizedString("Password:", comment: "password field label"))
let pref = UserDefaults.standard
nameField.stringValue = pref.username ?? ""
passwordField.stringValue = pref.password ?? ""
loginButton.title = NSLocalizedString("Login", comment: "login button title on the login window")
loginButton.bezelStyle = .rounded
loginButton.keyEquivalent = "\r"
loginButton.target = self
loginButton.action = #selector(loginClicked)
helpButton.bezelStyle = .helpButton
helpButton.title = ""
helpButton.target = self
helpButton.action = #selector(helpClicked)
let space:CGFloat = 16
let fieldWidth:CGFloat = 160
let fieldGuide = NSLayoutGuide()
view.addLayoutGuide(fieldGuide)
NSLayoutConstraint.activate([
fieldGuide.topAnchor.constraint(equalTo: nameLabel.topAnchor),
fieldGuide.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor),
fieldGuide.trailingAnchor.constraint(equalTo: nameField.trailingAnchor),
fieldGuide.centerXAnchor.constraint(equalTo: view.centerXAnchor),
fieldGuide.bottomAnchor.constraint(equalTo: passwordLabel.bottomAnchor),
nameLabel.trailingAnchor.constraint(equalTo: nameField.leadingAnchor, constant: -space / 2),
nameField.firstBaselineAnchor.constraint(equalTo: nameLabel.firstBaselineAnchor),
nameField.widthAnchor.constraint(equalToConstant: fieldWidth),
passwordLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: space / 2),
passwordLabel.trailingAnchor.constraint(equalTo: nameLabel.trailingAnchor),
passwordField.firstBaselineAnchor.constraint(equalTo: passwordLabel.firstBaselineAnchor),
passwordField.leadingAnchor.constraint(equalTo: nameField.leadingAnchor),
passwordField.trailingAnchor.constraint(equalTo: nameField.trailingAnchor),
loginButton.topAnchor.constraint(equalTo: fieldGuide.bottomAnchor, constant: space),
loginButton.trailingAnchor.constraint(equalTo: fieldGuide.trailingAnchor),
helpButton.leadingAnchor.constraint(equalTo: fieldGuide.leadingAnchor),
helpButton.centerYAnchor.constraint(equalTo: loginButton.centerYAnchor),
view.topAnchor.constraint(equalTo: nameLabel.topAnchor, constant: -space),
view.bottomAnchor.constraint(equalTo: loginButton.bottomAnchor, constant: space),
view.widthAnchor.constraint(equalTo: fieldGuide.widthAnchor, constant: space * 2)
])
}
fileprivate func add(_ sub:NSView) {
sub.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(sub)
}
@objc private func loginClicked() {
loginAction(nameField.stringValue, passwordField.stringValue)
}
@objc fileprivate func helpClicked() {
if let urlActual = kHelpURL {
NSWorkspace.shared.open(urlActual)
}
else {
print("Umm, fix your url?")
}
}
}
<file_sep>//
// main.swift
// Orangered
//
// Created by <NAME> on 5/29/16.
// Copyright © 2016 Rockwood Software. All rights reserved.
//
import AppKit
autoreleasepool { () -> () in
let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
app.run()
}
<file_sep>//
// Menu.swift
// Orangered
//
// Created by <NAME> on 6/13/16.
// Copyright © 2016 Rockwood Software. All rights reserved.
//
import Foundation
import Cocoa
class Menu: NSMenu {
init() {
super.init(title: "Orangered!")
setup()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setup() {
autoenablesItems = false
}
}
|
b39378e5c2c47243dbcdd111187be754b8f433e2
|
[
"Markdown",
"Swift"
] | 8 |
Markdown
|
voidref/orangered
|
cece595bc9ab8316db7159b5e23cea7d9468b0ef
|
e2473219d02e1b09f428e19fcb04594103e9f024
|
refs/heads/main
|
<file_sep>import { gql } from '@apollo/client';
import { Post } from '../../types';
export const POST_QUERY = gql`
query($id: ID!) {
post(id: $id) {
id
title
description
}
}
`;
export interface PostData {
post: Post;
}<file_sep>import { gql } from '@apollo/client';
export const TOGGLE_LIST_HIDDEN = gql`
mutation {
toggleListHidden @client
}
`;
export interface ToggleListHiddenData {
listHidden: boolean;
}<file_sep>import { gql } from '@apollo/client';
import { Post } from '../../types';
export const UPDATE_POST = gql`
mutation($post: UpdatePostInput!) {
updatePost(input: $post) {
post {
id
title
description
}
}
}
`;
export interface UpdatePostData {
post: Post;
}
export interface PostInputType {
post: {
id: number;
title?: string;
description?: string;
}
}<file_sep>import { gql } from '@apollo/client';
export const LIST_HIDDEN_QUERY = gql`
{
listHidden @client
}
`;
export interface ListHiddenData {
listHidden: boolean;
}
<file_sep>import { gql, InMemoryCache, Resolvers } from '@apollo/client';
import { LIST_HIDDEN_QUERY, ListHiddenData } from './queries/list-hidden.query';
export const typeDefs = gql`
extend type Mutation {
ToggleListHidden: Boolean!
}
`;
export const resolvers: Resolvers = {
Mutation: {
toggleListHidden: (_root, _args, ctx, _info) => {
const cache: InMemoryCache = ctx.cache;
const { listHidden } = cache.readQuery<ListHiddenData, null>({
query: LIST_HIDDEN_QUERY,
});
cache.writeQuery<ListHiddenData, null>({
query: LIST_HIDDEN_QUERY,
data: { listHidden: !listHidden },
});
return !listHidden;
},
},
};
|
5dd78d0744302cfeec9273c6932ab2db01ecdef6
|
[
"TypeScript"
] | 5 |
TypeScript
|
aokabin/next-apollo-training
|
bb1ade7507885e3f3c2c7c6ee24b827160a0904f
|
74995ee3147e35f3bc271987155ffac17ce4de1a
|
refs/heads/master
|
<repo_name>dab80/js_additional_challenges<file_sep>/19_Challenges.js
(function() {
'use strict';
function sum(num1, num2) {
return num1 + num2;
}
function avg(num1, num2, num3) {
return (num1 + num2 + num3) / 3;
}
function greaterThan(num1, num2) {
return num2 > num1;
}
function secondLargest(an_array) {
an_array.sort();
return an_array[an_array.length - 2];
}
function containsVowel(a_string) {
let vowels = /^[aeiouAEIOU]+$/;
for (let i = 0; i < a_string.length - 1; i++) {
if (a_string.charAt(i).match(vowels) !== null) {
return true;
}
} //end of for loop
return false; //therefore, no vowels
}
function pigLatin(a_string) {
//convert a string to an array
let vowels = /^[aeiouAEIOU]+$/;
let my_array = a_string.split(" ");
let my_string = "";
let rtn_string = "";
//for each word in the array
for (let i = 0; i < my_array.length; i++) {
//add a space after the first word
if (i > 0) {
rtn_string = rtn_string + " ";
}
my_string = my_array[i];
//find the location of the first vowel
for (let j = 0; j < my_string.length; j++) {
if (my_string.charAt(j).match(vowels) !== null) {
//new word = (vowel to end) + (leading chars + ay)
rtn_string = rtn_string + my_string.slice(j) + my_string.slice(0, j) + "ay";
break;
} //end of if
} //end of string for loop
} //end of array for loop
return rtn_string;
} //end of piglatin function
function longestWord(a_string) {
let my_array = a_string.split(" ");
let index = 0;
for (let i = 0; i < my_array.length; i++) {
if (my_array[i].length > my_array[index].length) {
console.log(my_array[i] + " length = " + my_array[i].length);
index = i;
}
} //end for loop
return "The longest word is --> " + my_array[index];
} //end of longestWord
// -----------------------------------------------
// Hard mode
// -----------------------------------------------
// 08 | weave
// Write a function called weave that accepts an input string and number.
// The function should return the string with every xth character replaced with an 'x'.
function weave(a_string, a_num) {
let new_string = "";
for (let i = 0; i < a_string.length; i++) {
//take into account zero index and treat as one index
if ((i + 1) % a_num === 0) {
new_string = new_string + 'x';
} else {
new_string = new_string + a_string.charAt(i);
}
} //end of for loop
return new_string;
}
// 09 | bonus
// Jeb eats out at restaurants all the time but is horrible at math.
// He decides to write a function called bonus that accepts a single parameter
// (the cost of the meal), and should return the tip Jeb should give his waiter.
// Jeb uses two rules to calculate tips:
// First he always tips 20% on the original bill.
// He then rounds up to the nearest dollar. For example,
// if the total with tip is $22.78, he'd round up to $23.00.
//
function bonus(meal_cost) {
return Math.floor(meal_cost * .2) + 1;
}
// 10 | multiples
// Write a function called multiples that accepts two numbers and returns
// an array of all numbers from 1 - 100 that are evenly divisible by both.
function multiples(num1, num2) {
let new_array = [];
for (let i = 1; i <= 100; i++) {
if (i % num1 === 0 && i % num2 === 0) {
new_array.push(i);
}
} //end of for
return new_array;
} //end of multiples
// 11 | blackjack
// Write a function called blackjack that accepts an array containing a
// hand of cards represented by the digits 2 - 9 and the values J, Q, K, and A.
// Return true if the hand busts (the value of the cards is > 21) or false if it hasn't busted.
//
// According to the rules of blackjack, an ace can be worth either 1 or 11.
// You should make it 11 unless that causes the hand to bust, in which case
// it should be 1 (just like if you play in person).
function blackjack(card_array) {
let card_count = 0;
let numAces = 0;
let s = "";
for (let i = 0; i < card_array.length; i++) {
s = card_array[i].toString().toUpperCase();
// console.log("Card is " + s);
if (s === "J" || s === "Q" || s === "K" || s === "10") {
card_count = card_count + 10;
} else if (s === "2" || s === "3" || s === "4" || s === "5" || s === "6" || s === "7" || s === "8" || s === "9") {
card_count = card_count + card_array[i];
} else if (s === "A" && card_count <= 10) {
card_count = card_count + 11;
numAces = numAces++;
} else if (s === "A" && numAces === 1) {
card_count = card_count - 11 + 1;
} else if (s === "A") {
card_count = card_count + 1;
} else {
// console.log("Invalid Input");
}
// console.log("Card Count = " + card_count);
} //end of for loop
if (card_count > 21) {
return true;
} else {
return false;
}
} //end of blackjack
// 12 | divisors
//Write a function called divisors that accepts a number
//and returns an array of all of the numbers that divide evnely into it.
function divisors(some_num) {
let some_array = [];
for (let i = 1; i <= some_num; i++) {
if (some_num % i === 0 && some_array.indexOf(i) < 0) {
some_array.push(i);
}
} //end of for loop
return some_array.sort(function(a, b) {
return a - b
});
}
// 13 | hamming
//Write a function called hamming that accepts two strings.
//If the lengths of the strings are not equal, the function should return zero.
//Otherwise, return the number of letters that are in the same position in both words.
function hamming(string_1, string_2) {
if (string_1.length !== string_2.length) {
return 0;
} else {
let num_common = 0;
for (let i = 0; i < string_1.length; i++) {
if (string_1.charAt(i) === string_2.charAt(i)) {
num_common++;
}
} //end of for loop
return num_common;
} //end of else
} //end of hamming
// 14 | pokemon
//Write a function called pokemon that accepts an array of numbers.
//Each element in the array represents a day, and the number represents the
//number of Pokemon caught on that day. i
//Return an array of the same length that contains the number of total Pokemon caught up to that day.
function pokemon(num_array) {
let num_pokemon = 0;
let array_pokemon = [];
for (let i = 0; i < num_array.length; i++) {
num_pokemon = num_pokemon + num_array[i];
array_pokemon.push(num_pokemon);
}
return array_pokemon;
}
// 15 | find
//Write a function called find that accepts two parameters:
//the first is an array of numbers and the second is a single number. i
//Return the index of the first time you find the second parameter in the first parameter.
function find(num_array, a_num) {
return num_array.indexOf(a_num);
}
// -----------------------------------------------------
// Nightmare mode
// -----------------------------------------------------
// 16 | map
// Write a function called map that accepts an array and a function as arguments.
// You should return an array containing the values of the array after the function has been applied to each one.
// Note: there is a built-in function called map. You can't use that ;-)
function map(an_array, a_function) {
return a_function(an_array);
}
function squareIt(an_array) {
for (let i = 0; i < an_array.length; i++) {
an_array[i] = an_array[i] * an_array[i];
}
return an_array;
}
// 17 | filter
// Write a function called filter that accepts an array and a function as arguments.
// You should return an array containing the values of the array that return true after the function is applied.
function filter(an_array, a_function) {
return a_function(an_array);
}
function r_u_a_square(an_array) {
let a_true_array = [];
for (let i = 0; i < an_array.length; i++) {
if (Math.sqrt(an_array[i]) === Math.floor(Math.sqrt(an_array[i]))) {
a_true_array.push(an_array[i]);
}
} //end of for loop
return a_true_array;
}
// 18 | sprint
// Write a function called sprint that accepts a single array of objects
// representing Olympic sprinters, each which has a name (string) and
// time (in seconds, so a number). Return the name of the athlete with the fastest time.
function sprint(an_array_of_objects) {
let index_num = 0;
for (let i = 1; i < an_array_of_objects.length; i++) {
if (an_array_of_objects[i].time < an_array_of_objects[index_num].time) {
index_num = i;
}
} //end of for loop
return an_array_of_objects[index_num].name;
}
//http://www.rankings.com/sports-track-sprinters/
// 19 | scrabble
// Write a function called scrabble that accepts a string and an object containing
// a property for each letter and a value representing the number of scrabble points its worth.
// Return the number of points that the whole word is worth.
// Hint: strings have a split() function that might be useful.
function scrabble(a_string, obj_values) {
let word_value = 0;
a_string = a_string.toUpperCase();
// let lookup = "";
for (let i = 0; i < a_string.length; i++) {
word_value = word_value + eval("obj_values." + a_string.charAt(i));
// console.log(a_string.charAt(i) + " is worth " + obj_values.a_string.charAt(i));
// console.log(obj_values.eval(a_string.charAt(i)));
// lookup = "obj_values." + a_string.charAt(i);
// console.log(eval(lookup));
// console.log(eval("obj_values." + a_string.charAt(i)));
// console.log(a_char);
} // end of for loop
return word_value;
}
// console.log("------------------------------");
// console.log("sum(3,5) = " + sum(3,5));
// console.log("------------------------------");
// console.log("avg(3,4,5) = " + avg(3,4,5));
// console.log("------------------------------");
// console.log("greaterThan(9,5) = " + greaterThan(9,5));
// console.log("greaterThan(5,9) = " + greaterThan(5,9));
// console.log("------------------------------");
// let my_array = [8,1,7,3,6,2];
// console.log("my_array = [8,1,7,3,6,2]");
// console.log("secondLargest(my_array) = " + secondLargest(my_array));
// console.log("------------------------------");
// console.log("containsVowel('rad') is " + containsVowel('rad'));
// console.log("containsVowel('red') is " + containsVowel('red'));
// console.log("containsVowel('rid') is " + containsVowel('rid'));
// console.log("containsVowel('rod') is " + containsVowel('rod'));
// console.log("containsVowel('rud') is " + containsVowel('rud'));
// console.log("containsVowel('rwd') is " + containsVowel('rwd'));
// console.log("pigLatin 'this is a fun school day at IronYard' = " + pigLatin('this is a fun school day at IronYard'));
// console.log("longestWord('this is an exceptionally fun school day at IronYard') = " + longestWord('this is an exceptionally fun school day at IronYard'));
// console.log("longestWord('dhjkasdkjhasdkjlh this is an exceptionally fun school day at IronYard') = " + longestWord('dhjkasdkjhasdkjlh this is an exceptionally fun school day at IronYard'));
// console.log("weave('this_is_very_long_string', 1) --> " + weave('this_is_very_long_string', 1));
// console.log("weave('this_is_very_long_string', 2) --> " + weave('this_is_very_long_string', 2));
// console.log("weave('this_is_very_long_string', 3) --> " + weave('this_is_very_long_string', 3));
// console.log("weave('s', 1) --> " + weave('s', 1));
// console.log("weave('s', 2) --> " + weave('s', 2));
// console.log("bonus(111.89) = " + bonus(111.89));
// console.log("bonus(111.09) = " + bonus(111.09));
// console.log("bonus(1.89) = " + bonus(1.89));
// console.log("bonus(.09) = " + bonus(.09));
// console.log("bonus(20.39) = " + bonus(20.39));
// console.log("multiples(2,3) --> " + multiples(2,3));
// console.log("multiples(3,5) --> " + multiples(3,5));
// console.log("blackjack([A,A,A]) busted = " + blackjack(['A', 'A', 'A']));
// console.log("----------------------");
// console.log("blackjack([9,9,7]) busted = " + blackjack([9,9,7]));
// console.log("----------------------");
// console.log("blackjack([2,J,A]) busted = " + blackjack([2, 'J', 'A']));
// console.log("----------------------");
// console.log("blackjack([A,J,A]) busted = " + blackjack(['A', 'J', 'A']));
// console.log("----------------------");
// console.log("blackjack([3,J,A,K]) busted = " + blackjack([3, 'J', 'A', 'K']));
// console.log("divors(99) = " + divisors(99));
// console.log("divors(34782) = " + divisors(34782));
// console.log("hamming('This is a short string', 'This is a silly string')");
// console.log(hamming('This is a short string', 'This is a silly string'));
// console.log("hamming('This is a short string', 'This is a longer silly string')");
// console.log(hamming('This is a short string', 'This is a longer silly string'));
// console.log("hamming('This is a short string', 'This is a short string')");
// console.log(hamming('This is a short string', 'This is a short string'));
// console.log("pokemon ([1, 2, 5, 1, 3]) = " + pokemon([1, 2, 5, 1, 3]));
// console.log("find([1,2,3,4,5,6,7], 3) = " + find([1,2,3,4,5,6,7],3));
// console.log("find([1,2,3,4,5,6,8], 3) = " + find([1,2,3,4,5,6,7],8));
// console.log("map([3,5,8,12], squareIt) = " + map([3, 5, 8, 12], squareIt));
// console.log("filter([3,5,9,12,25], r_u_a_square) = " + filter([3, 5, 9, 12, 25], r_u_a_square));
// let sprinters = [{
// name: "<NAME>",
// time: 9.79
// },
// {
// name: "<NAME>",
// time: 9.85
// },
// {
// name: "<NAME>",
// time: 9.86
// },
// {
// name: "<NAME>",
// time: 9.58
// },
// {
// name: "<NAME>",
// time: 9.84
// },
// {
// name: "<NAME>",
// time: 9.85
// },
// {
// name: "<NAME>",
// time: 9.84
// },
// {
// name: "<NAME>",
// time: 9.72
// },
// {
// name: "<NAME>",
// time: 9.69
// },
// {
// name: "<NAME>",
// time: 9.85
// }
// ];
//
// console.log("sprint(sprinters) fastest = " + sprint(sprinters));
//
// let scrabble_char_values = {
// A: 1,
// B: 3,
// C: 3,
// D: 2,
// E: 1,
// F: 4,
// G: 2,
// H: 4,
// I: 1,
// J: 8,
// K: 5,
// L: 1,
// M: 3,
// N: 1,
// O: 1,
// P: 3,
// Q: 10,
// R: 1,
// S: 1,
// T: 1,
// U: 1,
// V: 4,
// W: 4,
// X: 8,
// Y: 4,
// Z: 10
// };
//
// console.log("scrabble('Oxyphenbutazone',scrabble_char_values) = " + scrabble('Oxyphenbutazone', scrabble_char_values));
})();
|
0633bc4cc45b914f4cabe8583e4f2032aaa31549
|
[
"JavaScript"
] | 1 |
JavaScript
|
dab80/js_additional_challenges
|
50a3215a3f8fd59d92c8bd85bd7c3c12a1240eaf
|
ebb6df1c4b0bc30ab6e9f8a70295c18b619516f8
|
refs/heads/master
|
<file_sep><?php
// Starting/Resuming Session
session_start();
// Including Database Connection File
include_once('inc/connection.inc.php');
$query = "select*from tblArticles order by articleTitle";
$result =$db -> query ($query);
$num = mysqli_num_rows($result);
//Check to see if the form has been submitted
if (isset($_POST['submit']))
{
// Grab select element which is an array and store its value
foreach ($_POST['articleID'] as $articleID);
// SQL Statement to delete record
$query = "DELETE FROM tblArticles WHERE articleID = '$articleID'";
//Perform SQL Query
$result = $db->query($query);
if ($result)
header( "entryarticlechoice.php" );
$db->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP Data Entry Login</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/entry.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="#">ESP</a>
</li>
<li>
<a href='entryarticlechoice.php'>Articles</a>
</li>
<li>
<a href='entryathletechoice.php'>Athletes</a>
</li>
<li>
<a href='entrycompetitionchoice.php'>Competitions</i></a>
</li>
<li>
<a href='entrydisciplinechoice.php'>Disciplines</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<section id="form" class="bg-light" style="padding-top:1rem">
<form action="#" method="post" class="entryform">
<ul>
<li>
<Label for="articleID[]">Article Title</label>
<select name="articleID[]">
<?php
$num = mysqli_num_rows($result);
for ($i=0; $i < $num; $i++)
{
$row = $result->fetch_assoc();
?>
<?php
// single quotes used for html so double quotes can be identifiers, double quotes used for new lines
echo '<option value="' . $row['articleID'] . '">' . $row['articleTitle'] . '</option>' . "\r\n";
?>
<?php
}
?>
</select>
<span>Choose what post to delete</span>
</li>
<li>
<input type="submit" name="submit" i value="Submit">
</li>
</ul>
</form>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation - Main Site</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
<li>
<a href='logout.php'>Logout</a>
</li>
</ul>
</div>
<div class="footer-right-entry">
<ul>
<li>Navigation - Admin Site</li>
<li>
<a href="entryarticlechoice.php">Edit Articles</a>
</li>
<li>
<a href="entryathletechoice.php">Edit Athletes</a>
</li>
<li>
<a href="entrycompetitionchoice.php">Edit Competitions</a>
</li>
<li>
<a href="entrydisciplinechoice.php">Edit Disciplines</a>
</li>
<li>
<a href="register.php">Add New User</a>
</li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep>$(function () {
$(document).ready(function () {
$('.flexslider').flexslider({
animation: "fade",
slideshowSpeed: 4000,
animationSpeed: 600,
controlNav: false,
directionNav: true,
controlsContainer: ".flex-container" // the container that holds the flexslider
});
});
});
function passwordReveal() {
var x = document.getElementById("passwordfield");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}<file_sep><?php
//Starting/Resuming Session
session_start();
//Include database connection file
include_once('inc/connection.inc.php');
$query = "select*from tblCompetitions order by CompetitionDate";
$result =$db -> query ($query);
$num = mysqli_num_rows($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | Elite Competitions</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<!-- Hosted Stylesheets -->
<!-- W3.CSS --> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<!-- Font Awesome--> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="index.php">ESP</a>
</li>
<li>
<a href='become.php'>Become</i></a>
</li>
<li>
<a href='allarticles.php'>Posts</a>
</li>
<li>
<a href='upcoming.php' class="active">Competitions</a>
</li>
<li>
<a href='disciplinechoice.php'>Disciplines</a>
</li>
<li>
<a href='athletechoice.php'>Athletes</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<br>
<?php
$num = mysqli_num_rows($result);
for ($i=0; $i < $num; $i++)
{
$row = $result->fetch_assoc();
?>
<?php
// every other section switches between light and dark class
if ($i % 2 == 0) {
echo '<section id="article' . $row['articleID'] . '" class="section bg-light">';
}
else {
echo '<section id="article' . $row['articleID'] . '" class="section">';
}
// single quotes used for html so double quotes can be identifiers, double quotes used for new lines
echo '<div class="container">';
echo '<h2 class="section-head">';
echo '<a href="competition.php?id=' . $row['competitionID'] . '"><img src="' . $row['competitionImg'] . '" alt="' . $row['competitionTitle'] . '" style="height:250px; width:auto;"></a>' . "\r\n";
echo '</h2>';
echo '<a href="competition.php?id=' . $row['competitionID'] . '">' . $row['competitionTitle'] . '</a>' . "\r\n";
echo '</div>';
echo '</section>';
?>
<?php
}
?>
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right">
<ul>
<li>Contact Us</li>
<a href="https://www.facebook.com/elitestrongman"><i class="fab fa-facebook-f socialbtm"></i></a>
<a href="https://m.me/elitestrongman"><i class="fab fa-facebook-messenger socialbtm" target="_blank"></i></a>
<a href="https://instagram.com/bobelitestrongman"><i class="fab fa-instagram socialbtm"></i></a>
<a href="mailto:<EMAIL>?subject=Contact%20Us"><i class="far fa-envelope socialbtm"></i></a>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
<script src="js/indexslide.js"></script>
</body>
</html><file_sep># Elite Strongman Promotions
A bespoke website hand-built using HTML, CSS & PHP for a client, submitted as a Work-Based Learning project in my FdSc Applied Computing course at Level 5.
## Getting Started
The code for this website is stored here on GitHub as a way to preserve the project and to be retrospectively accessed as a part of my online portfolio.
Users are welcome to download, view, and re-use the code & styling for their own projects, however I urge users to seek other resources with which to learn these technologies.
## Built With
* [Visual Studio Code](https://code.visualstudio.com) - The Text Editor Used
* [PHP](https://php.net) - Scripting Language Used to process dynamic content
* [ImageOptim](https://imageoptim.com/mac) - Used to optimise image filesize
## Authors
* **<NAME>** - [MetalMitch](https://github.com/MetalMitch)
<file_sep><?php
//Starting/Resuming Session
session_start();
//Include database connection file
include_once('inc/connection.inc.php');
//Query ignores competitions that have passed
$query = "SELECT * FROM tblCompetitions WHERE competitionDate >= CURDATE() order by competitionDate";
$result =$db -> query ($query);
$num = mysqli_num_rows($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Elite Strongman Promotions</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<!-- Hosted Stylesheets -->
<!-- W3.CSS --> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<!-- Font Awesome--> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<div id="showcase">
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="#showcase">ESP</a>
</li>
<li>
<a href='#overview'>Become</i></a>
</li>
<li>
<a href='#articles'>Posts</a>
</li>
<li>
<a href='#upcoming'>Competitions</a>
</li>
<li>
<a href='#disciplines'>Disciplines</a>
</li>
<li>
<a href='#athletes'>Athletes</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
</div>
<!-- Overview -->
<section class="section">
<div class="container">
<h2>You are not authorised to view this page</h2>
<h4>You must log in by following the button below to access this page</h4>
<a href="entry.php" class=" btn btn-primary mb mt">Click Here to log in</a>
</div>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right">
<ul>
<li>Contact Us</li>
<a href="https://www.facebook.com/elitestrongman"><i class="fab fa-facebook-f socialbtm"></i></a>
<a href="https://m.me/elitestrongman"><i class="fab fa-facebook-messenger socialbtm" target="_blank"></i></a>
<a href="https://instagram.com/bobelitestrongman"><i class="fab fa-instagram socialbtm"></i></a>
<a href="mailto:<EMAIL>?subject=Contact%20Us"><i class="far fa-envelope socialbtm"></i></a>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
<script src="js/indexslide.js"></script>
</body>
</html><file_sep><?php
// Starting/Resuming Session
session_start();
// If not logged in, re-direct
if (!isset ($_SESSION['logged'])){
header('location:unauthorised.php');
}
// Including Database Connection File
include_once('inc/connection.inc.php');
//Check to see if the form has been submitted
if (isset($_POST['submit']))
{
// Grab select element which is an array and store its value
foreach ($_POST['articleType'] as $articleType);
//Check to see all fields have been completed, fields using an escape string to prevent illegal characters
$articleTitle = mysqli_real_escape_string($db,$_POST['articleTitle']);
$articleAuthor = mysqli_real_escape_string($db,$_POST['articleAuthor']);
$articleImg = mysqli_real_escape_string($db,$_POST['articleImg']);
// Storing content with spacing
$articleContent = nl2br(htmlentities($_POST['articleContent'], ENT_QUOTES, 'UTF-8'));
//Create an SQL Query to add the user and submit using prepared statement
$stmt = $db-> prepare("INSERT INTO tblArticles (articleTitle, articleAuthor, articleType, articleContent, articleImg) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $articleTitle, $articleAuthor, $articleType, $articleContent, $articleImg);
$stmt->execute();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | Admin | New Article</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/entry.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="#">ESP</a>
</li>
<li>
<a href='entryarticlechoice.php' class="active">Articles</a>
</li>
<li>
<a href='entryathletechoice.php'>Athletes</a>
</li>
<li>
<a href='entrycompetitionchoice.php'>Competitions</i></a>
</li>
<li>
<a href='entrydisciplinechoice.php'>Disciplines</a>
</li>
<li style="float:right">
<a href='logout.php'>Logout</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<section id="form" class="bg-light" style="padding-top:1rem">
<form action="#" method="post" class="entryform">
<ul>
<li>
<label for="articleTitle">Article Title</label>
<input type="text" name="articleTitle" maxlength="35">
<span>Enter the title of the article here</span>
</li>
<li>
<Label for="articleType[]">Article Type</label>
<select name="articleType[]">
<option value="Blog">Blog</option>
<option value="Results">Results</option>
<option value="Announcement">Announcement</option>
<option value="Other" selected>Other</option>
</select>
<span>Choose what kind of post this is</span>
</li>
<input type="hidden" name="articleAuthor" maxlength="35" value="<?php echo $_SESSION['firstName'] . ' ' . $_SESSION['surname']?>">
<li>
<label for="articleImg">Article Image</label>
<input type="text" name="articleContent">
<span>Enter the path of the article image here</span>
</li>
<li>
<label for="articleContent">Content</label>
<textarea name="articleContent" style="height:8rem"></textarea>
<span>Please enter your article content here</span>
</li>
<li>
<input type="submit" name="submit" i value="Submit"> <input type="reset">
</li>
</ul>
</form>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation - Main Site</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right-entry">
<ul>
<li>Navigation - Admin Site</li>
<li>
<a href="entryarticlechoice.php">Edit Articles</a>
</li>
<li>
<a href="entryathletechoice.php">Edit Athletes</a>
</li>
<li>
<a href="entrycompetitionchoice.php">Edit Competitions</a>
</li>
<li>
<a href="entrydisciplinechoice.php">Edit Disciplines</a>
</li>
<li>
<a href="register.php">Add New User</a>
</li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep><?php
//Starting/Resuming Session
session_start();
// If not logged in, re-direct
if (!isset ($_SESSION['logged'])){
header('location:unauthorised.php');
}
//Include database connection file
include_once('inc/connection.inc.php');
//Check to see if the form has been submitted
if (isset($_POST['submit']))
{
//Check to see all fields have been completed, fields using an escape string to prevent illegal characters
$userName = mysqli_real_escape_string($db,$_POST['userName']);
$password = password_hash($_POST['password'],PASSWORD_DEFAULT);
$firstName = mysqli_real_escape_string($db,$_POST['firstName']);
$surname = mysqli_real_escape_string($db,$_POST['surname']);
//Create an SQL Query to add the user and submit using prepared statement
$stmt = $db-> prepare("INSERT INTO tblLogin (userName, password, firstName, surname) VALUES (?,?,?,?)");
$stmt->bind_param("ssss", $userName, $password, $firstName, $surname);
$stmt->execute();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | Admin | New User</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="#">ESP</a>
</li>
<li>
<a href='entryarticlechoice.php'>Articles</a>
</li>
<li>
<a href='entryathletechoice.php'>Athletes</a>
</li>
<li>
<a href='entrycompetitionchoice.php'>Competitions</i></a>
</li>
<li>
<a href='entrydisciplinechoice.php'>Disciplines</a>
</li>
<li style="float:right">
<a href='logout.php'>Logout</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<!-- Overview -->
<section id="main" class="section bg-light">
<form name="register" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="entryform">
<ul>
<li>
<label for="userName">Username</label>
<input type="text" name="userName" maxlength="35">
<span>Enter the username to log in with</span>
</li>
<li>
<label for="password">Password</label>
<input type="password" name="password" class="showpassword" id="passwordfield">
<span>Enter the password to log in with.</span>
<span><input type="checkbox" onclick="passwordReveal()">Tick this box to reveal the Password</span>
</li>
<li>
<label for="firstName">First Name</label>
<input type="text" name="firstName" maxlength="35">
<span>Enter the user's first name</span>
</li>
<li>
<label for="surname">Surname</label>
<input type="text" name="surname" maxlength="35">
<span>Enter the user's surname</span>
</li>
<li>
<input type="submit" name="submit" i value="Submit"> <input type="reset">
</li>
</ul>
</form>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation - Main Site</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right">
<ul>
<li>Navigation - Admin Site</li>
<li>
<a href="entryarticlechoice.php">Edit Articles</a>
</li>
<li>
<a href="entryathletechoice.php">Edit Athletes</a>
</li>
<li>
<a href="entrycompetitionchoice.php">Edit Competitions</a>
</li>
<li>
<a href="entrydisciplinechoice.php">Edit Disciplines</a>
</li>
<li>
<a href="register.php">Add New User</a>
</li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
<script src="js/reveal.js"></script>
</body>
</html><file_sep><?php
//Starting/Resuming Session
session_start();
//Include database connection file
include_once('inc/connection.inc.php');
//Query ignores competitions that have passed
$query = "SELECT * FROM tblCompetitions WHERE competitionDate >= CURDATE() order by competitionDate";
$result =$db -> query ($query);
$num = mysqli_num_rows($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Elite Strongman Promotions</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<!-- Hosted Stylesheets -->
<!-- W3.CSS --> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<!-- Font Awesome--> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<div id="showcase">
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="#showcase">ESP</a>
</li>
<li>
<a href='#overview'>Become</i></a>
</li>
<li>
<a href='#articles'>Posts</a>
</li>
<li>
<a href='#upcoming'>Competitions</a>
</li>
<li>
<a href='#disciplines'>Disciplines</a>
</li>
<li>
<a href='#athletes'>Athletes</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<div class="section-main container">
<img src="images/logosmall.png">
<h1>Elite Strongman Promotions</h1>
</div>
</div>
<!-- Overview -->
<section id="overview" class="section bg-light">
<div class="container">
<h2 class="section-head">
<strong>Elite Competitions</strong> <i class="fab fa-creative-commons-nd"></i> Elite Athletes
</h2>
<!-- Full-width images -->
<p class="lead">Starting around 1993, organiser <NAME> began promoting Strongman Events, steadily adding more and more yearly
competitions to his repertoire.</p>
<p class="lead">In 2000, he branded himself Elite Strongman Promotions.</p>
<p class="lead">Nationwide, we have held a wealth of competitions, such as England’s and Britain’s Strongest
Man, with athletes of all calibres, from novice athletes, to some of Britain’s, and indeed the World’s most
recognisable competitors.</p>
<br>
<p class="lead">If you are interested in becoming a strongman or woman, we host classes regularly. Fill out our contact form to "Become an Elite Athlete" and we will make contact with you shortly.</p>
<a href="become.php" class=" btn btn-primary mb mt">Become an Elite Athlete</a>
</div>
</section>
<!-- Articles -->
<section id="articles" class="section">
<div class="container">
<h2 class="section-head">
<strong>Elite Strongman Posts</strong>
</h2>
<p class="lead">Elite Strongman Promotions will from time to time post articles</p>
<p class="lead">Announcements, Competition Results and more</p>
<br>
<a href="allarticles.php" class=" btn btn-primary mb mt">Click Here to see ESP posts</a>
</div>
</section>
<!-- Upcoming Competitions -->
<section id="upcoming" class="section bg-light">
<br>
<div class="container">
<div class="grid-choice">
<?php
$num = mysqli_num_rows($result);
for ($i=0; $i < 3; $i++)
{
$row = $result->fetch_assoc();
?>
<?php
// single quotes used for html so double quotes can be identifiers, double quotes used for new lines
echo '<div class="polaroid">' . "\r\n";
echo '<a href="competition.php?id=' . $row['competitionID'] . '"><img src="' . $row['competitionImg'] . '" alt="' . $row['competitionTitle'] . '"></a>' . "\r\n";
echo '<div class="polaroidtext">';
echo '<p>' . $row['competitionTitle'] . '</p>';
echo '</div>' . "\r\n" . '</div>';
?>
<?php
}
?>
</div>
<a href="upcoming.php" class=" btn btn-primary mb mt">All Upcoming Competitions</a>
</div>
</section>
<!-- Disciplines -->
<section id="disciplines" class="section">
<div class="container">
<h2>Learn about our Elite Disciplines:</h2>
<p class="lead">Elite Strongman Promoions has many disciplines in which to test our athletes</p>
<p class="lead">Some test an athletes strength</p>
<p class="lead">Some test their endurance</p>
<h2>All of them test an athletes will to succeed</h2>
<a href="disciplinechoice.php" class=" btn btn-primary mb mt">Elite Disciplines</a>
</div>
</section>
<!-- Athletes -->
<section id="athletes" class="section bg-light">
<div class="container">
<h2>Meet our Elite Athletes:</h2>
<p class="lead">Bodybuilders, Powerlifters, ex-rugby players, even school teachers!</p>
<p class="lead">Elite Strongman Promoions has many athletes of all calibres</p>
<p class="lead">Some compete for fun, others compete for personal growth</p>
<h2>Others even become england's or even world's strongest man</h2>
<a href="athletechoice.php" class=" btn btn-primary mb mt">Elite Athletes</a>
</div>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right">
<ul>
<li>Contact Us</li>
<a href="https://www.facebook.com/elitestrongman"><i class="fab fa-facebook-f socialbtm"></i></a>
<a href="https://m.me/elitestrongman"><i class="fab fa-facebook-messenger socialbtm" target="_blank"></i></a>
<a href="https://instagram.com/bobelitestrongman"><i class="fab fa-instagram socialbtm"></i></a>
<a href="mailto:<EMAIL>?subject=Contact%20Us"><i class="far fa-envelope socialbtm"></i></a>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
<script src="js/indexslide.js"></script>
</body>
</html><file_sep><?php
// Starting/Resuming Session
session_start();
// If not logged in, re-direct
if (!isset ($_SESSION['logged'])){
header('location:unauthorised.php');
}
// Including Database Connection File
include_once('inc/connection.inc.php');
//Check to see if the form has been submitted
if (isset($_POST['submit']))
{
//Check to see all fields have been completed, fields using an escape string to prevent illegal characters
$athleteFirstName = mysqli_real_escape_string($db,$_POST['athleteFirstName']);
$athleteSurname = mysqli_real_escape_string($db,$_POST['athleteSurname']);
$athleteDOB = mysqli_real_escape_string($db,$_POST['athleteDOB']);
$athleteHome = mysqli_real_escape_string($db,$_POST['athleteHome']);
$athleteImg = mysqli_real_escape_string($db,$_POST['athleteImg']);
// Storing content with spacing
$athleteContent = nl2br(htmlentities($_POST['athleteContent'], ENT_QUOTES, 'UTF-8'));
//Create an SQL Query to add the user and submit using prepared statement
$stmt = $db-> prepare("INSERT INTO tblAthletes (athleteFirstName, athleteSurname, athleteDOB, athleteHome, athleteImg, athleteContent) VALUES (?,?,?,?,?,?)");
$stmt->bind_param("ssssss", $athleteFirstName, $athleteSurname, $athleteDOB, $athleteHome, $athleteImg, $athleteContent);
$stmt->execute();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | Admin | New Athlete</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/entry.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
<!-- Datepicker Jquery -->
<script type="text/javascript">
var datefield=document.createElement("input")
datefield.setAttribute("type", "date")
if (datefield.type!="date"){ //if browser doesn't support input type="date", load files for jQuery UI Date Picker
document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
}
</script>
<script>
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($){ //on document.ready
$('#birthday').datepicker();
})
}
</script>
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="#">ESP</a>
</li>
<li>
<a href='entryarticlechoice.php'>Articles</a>
</li>
<li>
<a href='entryathletechoice.php' class="active">Athletes</a>
</li>
<li>
<a href='entrycompetitionchoice.php'>Competitions</i></a>
</li>
<li>
<a href='entrydisciplinechoice.php'>Disciplines</a>
</li>
<li style="float:right">
<a href='logout.php'>Logout</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<section id="form" class="bg-light" style="padding-top:1rem">
<form action="#" method="post" class="entryform">
<ul>
<li>
<label for="athleteFirstName">Athlete First Name</label>
<input type="text" name="athleteFirstName" maxlength="35">
<span>Enter the first name of the athlete here</span>
</li>
<li>
<label for="athleteSurname">Athlete Surname</label>
<input type="text" name="athleteSurname" maxlength="35">
<span>Enter the surname of the athlete here</span>
</li>
<li>
<label for="athleteDOB">Athlete Date of Birth</label>
<input type="date" name="athleteDOB">
<span>Enter the DOB of the athlete here</span>
</li>
<li>
<label for="athleteHome">Athlete Hometown</label>
<input type="text" name="athleteHome" maxlength="35">
<span>Enter the Hometown of the athlete here</span>
</li>
<li>
<label for="athleteImg">Athlete Image</label>
<input type="text" name="athleteImg">
<span>Enter the path of the image</span>
</li>
<li>
<label for="athleteContent">Content</label>
<textarea name="athleteContent" style="height:8rem"></textarea>
<span>Please enter your athlete content here</span>
</li>
<li>
<input type="submit" name="submit" i value="Submit"> <input type="reset">
</li>
</ul>
</form>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation - Main Site</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right-entry">
<ul>
<li>Navigation - Admin Site</li>
<li>
<a href="entryarticlechoice.php">Edit Articles</a>
</li>
<li>
<a href="entryathletechoice.php">Edit Athletes</a>
</li>
<li>
<a href="entrycompetitionchoice.php">Edit Competitions</a>
</li>
<li>
<a href="entrydisciplinechoice.php">Edit Disciplines</a>
</li>
<li>
<a href="register.php">Add New User</a>
</li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep><?php
//Starting/Resuming Session
session_start();
// Include database connection file
include_once('inc/connection.inc.php');
mysqli_real_escape_string($db,$userName = $_POST['userName']);
mysqli_real_escape_string($db,$password = $_POST['password']);
// AN SQL QUERY TO VERIFY USERNAME & PASSWORD MATCH DETAILS IN DB HASHED
$query = "SELECT password from tblLogin where userName = '$userName' ";
$result =$db -> query ($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($password,$row['password']))
{
$_SESSION['logged'] = 1;
$_SESSION['firstName'] = $row['firstName'];
$_SESSION['surname'] = $row['surname'];
header("location:entrychoice.php");
}
else
{
echo "Username or password is incorrect";
}
?><file_sep><?php
// Message Vars
$msg = '';
$msgClass = '';
//check for submit
if (filter_has_var(INPUT_POST, 'submit')){
//Get Form Data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$number = htmlspecialchars($_POST['number']);
$message = htmlspecialchars($_POST['message']);
// Check Required Fields
if(!empty($name) && !empty($email) && !empty($number) && !empty($message)){
//Passed
//Check Email
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false){
//Failed
$msg = 'Please use a Valid email';
$msgClass - 'alert-danger';
} else {
//Passed
//Receipent email
$toEmail = '<EMAIL>';
$subject = 'Contact Request From ' . $name;
$body = '<h2>Contact Request</h2>
<h4>Name</h4><p>' . $name . '</p>
<h4>Email</h4><p>' . $email . '</p>
<h4>Number</h4><p>' . $number . '</p>
<h4>Message</h4><p>' . $message . '</p>
';
//Email Headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .="Content-Type:text/html;charset=UTF-8" . "
\r\n";
// Additional Headers
$headers .= "From " . $name . "<" . $email . ">" . "\r\n";
if(mail($toEmail, $subject, $body, $headers)){
// Email Sent
$msg = 'Your Request has been submitted';
$msgClass - 'alert-success';
} else {
// Failed
$msg = 'Your Email was not sent';
$msgClass - 'alert-danger';
}
}
} else {
//Failed
$msg = 'Please fill in all fields';
$msgClass - 'alert-danger';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | Become an Elite Athlete</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous">
<!-- Facebook OG Meta tags -->
<meta property="og:url" content="http://hecomplin.ncl-coll.ac.uk/~mskee/esp/become.php" />
<meta property="og:type" content="article" />
<meta property="og:title" content="Elite Strongman Promotions" />
<meta property="og:description" content="Become an Elite Athlete" />
<meta property="og:image" content="http://hecomplin.ncl-coll.ac.uk/~mskee/esp/images/logosmall.png" />
<meta property="fb:app_id" content="292683564744029" />
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="index.php">ESP</a>
</li>
<li>
<a href='become.php' class="active">Become</i></a>
</li>
<li>
<a href='allarticles.php'>Posts</a>
</li>
<li>
<a href='upcoming.php'>Competitions</a>
</li>
<li>
<a href='disciplinechoice.php'>Disciplines</a>
</li>
<li>
<a href='athletechoice.php'>Athletes</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<!-- Overview -->
<section id="slideshow">
</section>
<section id="main" class="section bg-light">
<div class="container">
<br>
<h1>Become an Elite Athlete</h1>
<h2>Elite Strongman Promotions train many athletes, from novice competitors, to Britain's elite</h2>
<h3>ESP Promoter <NAME> hosts regular training sessions with our equipment and has done for many years. These sessions are open to anyone who is interested.</h3>
<p class="lead">If you think you have what it takes to become an elite athlete, no matter your skill level, fill in our simple form below to contact us, and we'll get back to you</p>
<br>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contactform" class="entryform">
<!-- PHP Validation error message -->
<?php if($msg != ''): ?>
<div class="alert <?php echo $msgClass; ?>" style="color: #721c24;"><?php echo $msg; ?></div>
<?php endif; ?>
<ul>
<li>
<label for="name">Name</label>
<input type="text" name="name" maxlength="35" value="<?php echo isset($_POST['name']) ? $name : ''; ?>">
<span>Enter your full name here</span>
</li>
<li>
<label for="email">Email</label>
<input type="email" name="email" maxlength="100" value="<?php echo isset($_POST['email']) ? $email : ''; ?>">
<span>Enter a valid email address</span>
</li>
<li>
<label for="number">Number</label>
<input type="tel" name="number" maxlength="11" value="<?php echo isset($_POST['number']) ? $number : ''; ?>">
<span>Enter your phone number here</span>
</li>
<li>
<label for="message">About You</label>
<textarea name="message" onkeyup="adjust_textarea(this)"><?php echo isset($_POST['message']) ? $message : ''; ?></textarea>
<span>Enter your message</span>
</li>
<button type="submit" name="submit" class="btn btn-secondary mb mt">Submit</button>
<button type="reset" class="btn btn-primary mb mt">Restart</button>
</form>
</div>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right">
<ul>
<li>Contact Us</li>
<a href="https://www.facebook.com/elitestrongman"><i class="fab fa-facebook-f socialbtm"></i></a>
<a href="https://m.me/elitestrongman"><i class="fab fa-facebook-messenger socialbtm" target="_blank"></i></a>
<a href="https://instagram.com/bobelitestrongman"><i class="fab fa-instagram socialbtm"></i></a>
<a href="mailto:<EMAIL>?subject=Contact%20Us"><i class="far fa-envelope socialbtm"></i></a>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep><?php
//Starting/Resuming Session
session_start();
// Include database connection file
include_once('inc/connection.inc.php');
$id = $_GET['id'];
$competitionTitle = $_POST['competitionTitle'];
$competitionDate = $_POST['competitionDate'];
$competitionLocation = $_POST['competitionLocation'];
$competitionImg = $_POST['competitionImg'];
$competitionContent = nl2br(htmlentities($_POST['competitionContent'], ENT_QUOTES, 'UTF-8'));
// SQL Statement to update record
$query = "UPDATE `tblCompetitions` SET competitionTitle='$competitionTitle', competitionDate='$competitionDate', competitionLocation='$competitionLocation', competitionImg='$competitionImg', competitionContent='$competitionContent' WHERE competitionID='$id'";
//Perform SQL Statement in Database
$result = $db->query($query);
if ($result)
header( "refresh:5;url=entrycompetitionchoice.php" );
echo $competitionTitle . " - record updated successfully. You will be re-directed after 5 seconds. If you have not been redirected, <a href='entrycompetitionchoice.php'>Click Here</a>";
$db->close();
?><file_sep><?php
//Starting/Resuming Session
session_start();
// If not logged in, re-direct
if (!isset ($_SESSION['logged'])){
header('location:unauthorised.php');
}
//Include database connection file
include_once('inc/connection.inc.php');
$query = "select*from tblDiscipline order by disciplineName";
$result =$db -> query ($query);
$num = mysqli_num_rows($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | Admin | Disciplines</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="#">ESP</a>
</li>
<li>
<a href='entryarticlechoice.php'>Articles</a>
</li>
<li>
<a href='entryathletechoice.php'>Athletes</a>
</li>
<li>
<a href='entrycompetitionchoice.php'>Competitions</i></a>
</li>
<li>
<a href='entrydisciplinechoice.php' class="active">Disciplines</a>
</li>
<li style="float:right">
<a href='logout.php'>Logout</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<!-- Overview -->
<section id="main" class="section bg-light">
<br>
<div class="container">
<div class="grid-choice">
<div class="polaroid">
<a href="newdiscipline.php"><img src="images/add.png" alt="Add New Discipline"></a>
<div class="polaroidtext">
<p>Click to edit or add new</p>
<p>Discipline</p>
</div>
</div>
<?php
$num = mysqli_num_rows($result);
for ($i=0; $i < $num; $i++)
{
$row = $result->fetch_assoc();
?>
<?php
// single quotes used for html so double quotes can be identifiers, double quotes used for new lines
echo '<div class="polaroid">' . "\r\n";
echo '<a href="editdiscipline.php?id=' . $row['disciplineID'] . '"><img src="' . $row['disciplineImg'] . '" alt="' . $row['disciplineName'] . '"></a>' . "\r\n";
echo '<div class="polaroidtext">';
echo '<p>' . $row['disciplineName'] . '</p>';
echo '</div>' . "\r\n" . '</div>';
?>
<?php
}
?>
<div class="polaroid">
<a href="deletediscipline.php"><img src="images/delete.png" alt="Delete Discipline"></a>
<div class="polaroidtext">
<p>Click to Delete</p>
<p>Discipline</p>
</div>
</div>
</div>
</div>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation - Main Site</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right-entry">
<ul>
<li>Navigation - Admin Site</li>
<li>
<a href="entryarticlechoice.php">Edit Articles</a>
</li>
<li>
<a href="entryathletechoice.php">Edit Athletes</a>
</li>
<li>
<a href="entrycompetitionchoice.php">Edit Competitions</a>
</li>
<li>
<a href="entrydisciplinechoice.php">Edit Disciplines</a>
</li>
<li>
<a href="register.php">Add New User</a>
</li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep><?php
//Starting/Resuming Session
session_start();
// If not logged in, re-direct
if (!isset ($_SESSION['logged'])){
header('location:unauthorised.php');
}
// Include database connection file
include_once('inc/connection.inc.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | Admin</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="#">ESP</a>
</li>
<li>
<a href='entryarticlechoice.php'>Articles</a>
</li>
<li>
<a href='entryathletechoice.php'>Athletes</a>
</li>
<li>
<a href='entrycompetitionchoice.php'>Competitions</i></a>
</li>
<li>
<a href='entrydisciplinechoice.php'>Disciplines</a>
</li>
<li style="float:right">
<a href='logout.php'>Logout</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<section id="links" class="bg-light" style="padding-top:1rem">
<div id="howto">
<h1>How to Submit Information</h2>
<h2>Add athletes first, then Disciplines, then Competitions</h2>
<h3>Search for the existing athletes or disciplines on the main website first</h3>
</div>
<div class="container-flex">
<div class="articles">
<div class="polaroid">
<a href="entryarticlechoice.php"><img src="images/entry/event.jpg" alt="Articles"></a>
<div class="polaroidtext">
<p>Click to edit or add new</p>
<p>Article</p>
</div>
</div>
</div>
<div class="athletes">
<div class="polaroid">
<a href="entryathletechoice.php"><img src="images/entry/athlete.jpg" alt="Athletes"></a>
<div class="polaroidtext">
<p>Click to edit or add new</p>
<p>Athlete</p>
</div>
</div>
</div>
<div class="competitions">
<div class="polaroid">
<a href="entrycompetitionchoice.php"><img src="images/entry/event.jpg" alt="Competitions"></a>
<div class="polaroidtext">
<p>Click to edit or add new</p>
<p>Competition</p>
</div>
</div>
</div>
<div class="disciplines">
<div class="polaroid">
<a href="entrydisciplinechoice.php"><img src="images/entry/discipline.jpg" alt="Disciplines"></a>
<div class="polaroidtext">
<p>Click to edit or add new</p>
<p>Discipline</p>
</div>
</div>
</div>
</div>
<br>
</section>
<section id="admin">
<div class="container">
<h1>Administrative Tools</h1>
<a href="register.php" class=" btn btn-primary mb mt">Add New User</a>
</div>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation - Main Site</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right-entry">
<ul>
<li>Navigation - Admin Site</li>
<li>
<a href="entryarticlechoice.php">Edit Articles</a>
</li>
<li>
<a href="entryathletechoice.php">Edit Athletes</a>
</li>
<li>
<a href="entrycompetitionchoice.php">Edit Competitions</a>
</li>
<li>
<a href="entrydisciplinechoice.php">Edit Disciplines</a>
</li>
<li>
<a href="register.php">Add New User</a>
</li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep><?php
// Starting/Resuming Session
session_start();
// Including Database Connection File
include_once('inc/connection.inc.php');
$id = $_GET['id'];
$query2 = "select * from tblArticles WHERE articleID = $id";
$result =$db -> query ($query2);
$num = mysqli_num_rows($result);
$row = $result->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | Admin | Edit <?php echo $row['articleTitle'] ;?></title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/entry.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="#">ESP</a>
</li>
<li>
<a href='entryarticlechoice.php' class="active">Articles</a>
</li>
<li>
<a href='entryathletechoice.php'>Athletes</a>
</li>
<li>
<a href='entrycompetitionchoice.php'>Competitions</i></a>
</li>
<li>
<a href='entrydisciplinechoice.php'>Disciplines</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<section id="form" class="bg-light" style="padding-top:1rem">
<form action="updatearticle.php?id=<?php echo $id?>" method="post" class="entryform">
<ul>
<li>
<label for="articleTitle">Article Name</label>
<input type="text" name="articleTitle" maxlength="35" value="<?php echo $row['articleTitle']?>">
<span>Enter the title of the article here</span>
</li>
<li>
<Label for="articleType[]">Article Type</label>
<!-- if blog article type -->
<?php if ($row['articleType'] === "Blog")
{ ?>
<select name="articleType[]">
<option value="Blog" selected>Blog</option>
<option value="Results">Results</option>
<option value="Announcement">Announcement</option>
<option value="Other">Other</option>
</select>
<?php }
// if results article type
elseif ($row['articleType'] === "Results")
{ ?>
<select name="articleType[]">
<option value="Blog">Blog</option>
<option value="Results" selected>Results</option>
<option value="Announcement">Announcement</option>
<option value="Other">Other</option>
</select>
<?php }
// if announcement article type
elseif ($row['articleType'] === "Announcement")
{ ?>
<select name="articleType[]">
<option value="Blog">Blog</option>
<option value="Results">Results</option>
<option value="Announcement" selected>Announcement</option>
<option value="Other">Other</option>
</select>
<?php }
// if other article type
else
{ ?>
<select name="articleType[]">
<option value="Blog">Blog</option>
<option value="Results">Results</option>
<option value="Announcement">Announcement</option>
<option value="Other" selected>Other</option>
</select>
<?php } ?>
<span>Choose what kind of post this is</span>
</li>
<li>
<label for="articleImg">Article Image</label>
<input type="text" name="articleImg" value="<?php echo $row['articleImg']?>">
<span>Enter the path of the article image here</span>
</li>
<li>
<label for="articleContent">Content</label>
<textarea name="articleContent" style="height:8rem"><?php echo strip_tags($row['articleContent'], '<iframe>');?></textarea>
<span>Please enter your article content here</span>
</li>
<li>
<input type="submit" name="submit" i value="Submit"> <input type="reset">
</li>
</ul>
</form>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation - Main Site</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right-entry">
<ul>
<li>Navigation - Admin Site</li>
<li>
<a href="entryarticlechoice.php">Edit Articles</a>
</li>
<li>
<a href="entryathletechoice.php">Edit Athletes</a>
</li>
<li>
<a href="entrycompetitionchoice.php">Edit Competitions</a>
</li>
<li>
<a href="entrydisciplinechoice.php">Edit Disciplines</a>
</li>
<li>
<a href="register.php">Add New User</a>
</li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep><?php
//Starting/Resuming Session
session_start();
// Include database connection file
include_once('inc/connection.inc.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | Admin</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
</nav>
</header>
<!-- Overview -->
<section class="section">
<div class="container">
<h2>You are not authorised to view this page</h2>
<h4>You must log in by following the button below to access this page</h4>
<a href="entry.php" class=" btn btn-primary mb mt">Click Here to log in</a>
</div>
</section>
<!-- Footer -->
<footer>
<div class="container">
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY>8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="js/main.js"></script>
<script src="js/reveal.js"></script>
</body>
</html><file_sep><?php
//Starting/Resuming Session
session_start();
// Include database connection file
include_once('inc/connection.inc.php');
$id = $_GET['id'];
$athleteFirstName = $_POST['athleteFirstName'];
$athleteSurname = $_POST['athleteSurname'];
$athleteDOB = $_POST['athleteDOB'];
$athleteHome = $_POST['athleteHome'];
$athleteImg = $_POST['athleteImg'];
$athleteContent = nl2br(htmlentities($_POST['athleteContent'], ENT_QUOTES, 'UTF-8'));
// SQL Statement to update record
$query = "UPDATE `tblAthletes` SET athleteFirstName='$athleteFirstName', athleteSurname='$athleteSurname', athleteDOB='$athleteDOB', athleteHome='$athleteHome', athleteImg='$athleteImg', athleteContent='$athleteContent' WHERE athleteID='$id'";
//Perform SQL Statement in Database
$result = $db->query($query);
if ($result)
header( "refresh:5;url=entryathletechoice.php" );
echo $athleteFirstName . ' ' . $athleteSurname . " - record updated successfully. You will be re-directed after 5 seconds. If you have not been redirected, <a href='entryathletechoice.php'>Click Here</a>";
$db->close();
?><file_sep><?php
//Include database connection file
include_once('inc/connection.inc.php');
$id = $_GET['id'];
$query2 = "select * from tblArticles WHERE articleID = $id";
$result =$db -> query ($query2);
$num = mysqli_num_rows($result);
$row = $result->fetch_assoc();
$date = new DateTime($row['articleDateTime']);
$content = $row['articleContent'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | <?php echo $row['articleTitle'];?></title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
<!-- Facebook OG Meta tags -->
<meta property="og:url" content="<?php echo 'http://hecomplin.ncl-coll.ac.uk/~mskee/esp/article.php?' . $id;?>" />
<meta property="og:type" content="article" />
<meta property="og:title" content="Elite Strongman Promotions" />
<meta property="og:description" content="<?php echo $row['articleTitle'];?>" />
<meta property="og:image" content="<?php echo $row['articleImg'];?>" />
<meta property="fb:app_id" content="292683564744029" />
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="index.php">ESP</a>
</li>
<li>
<a href='become.php'>Become</i></a>
</li>
<li>
<a href='allarticles.php' class="active">Posts</a>
</li>
<li>
<a href='upcoming.php'>Competitions</a>
</li>
<li>
<a href='disciplinechoice.php'>Disciplines</a>
</li>
<li>
<a href='athletechoice.php'>Athletes</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<!-- Overview -->
<section id="main" class="section bg-light">
<div class="container">
<div class="grid-display">
<div class="main-right">
<p><h2><strong><?php echo $row['articleTitle'];?></strong></h2>
<p><strong>Author: </strong><?php echo $row['articleAuthor'];?></p>
<p><strong>Created: </strong><?php echo date_format($date, 'g:ia \o\n l jS F Y');?></p>
</div>
<div class="main-description">
<br>
<img src="<?php echo $row["articleImg"] ;?>" alt="<?php echo $row["articleTitle"];?>">
<br>
<?php echo nl2br($content);?>
<br>
</div>
</div>
</div>
</section>
<section id="slideshow" class="section bg-light">
<div class="container">
</div>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right">
<ul>
<li>Contact Us</li>
<a href="https://www.facebook.com/elitestrongman"><i class="fab fa-facebook-f socialbtm"></i></a>
<a href="https://m.me/elitestrongman"><i class="fab fa-facebook-messenger socialbtm" target="_blank"></i></a>
<a href="https://instagram.com/bobelitestrongman"><i class="fab fa-instagram socialbtm"></i></a>
<a href="mailto:<EMAIL>?subject=Contact%20Us"><i class="far fa-envelope socialbtm"></i></a>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep><?php
//Starting/Resuming Session
session_start();
// Include database connection file
include_once('inc/connection.inc.php');
$id = $_GET['id'];
$disciplineName = $_POST['disciplineName'];
$disciplineType = $_POST['disciplineType'];
$disciplineShortDesc = nl2br(htmlentities($_POST['disciplineShortDesc'], ENT_QUOTES, 'UTF-8'));
$disciplineDescription = nl2br(htmlentities($_POST['disciplineDescription'], ENT_QUOTES, 'UTF-8'));
$disciplineImg = $_POST['disciplineImg'];
// SQL Statement to update record
$query = "UPDATE `tblDiscipline` SET disciplineName='$disciplineName', disciplineType='$disciplineType', disciplineShortDesc='$disciplineShortDesc', disciplineDescription='$disciplineDescription', disciplineImg='$disciplineImg' WHERE disciplineID='$id'";
//Perform SQL Statement in Database
$result = $db->query($query);
if ($result)
header( "refresh:5;url=entrydisciplinechoice.php" );
echo $disciplineName . " - record updated successfully. You will be re-directed after 5 seconds. If you have not been redirected, <a href='entrydisciplinechoice.php'>Click Here</a>";
$db->close();
?><file_sep><?php
// Starting/Resuming Session
session_start();
// Including Database Connection File
include_once('inc/connection.inc.php');
$id = $_GET['id'];
$query2 = "select * from tblDiscipline WHERE disciplineID = $id";
$result =$db -> query ($query2);
$num = mysqli_num_rows($result);
$row = $result->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP Data Entry Login</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/entry.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
<ul class='cf'>
<li class="hide-on-small">
<a href="#">ESP</a>
</li>
<li>
<a href='entryarticlechoice.php'>Articles</a>
</li>
<li>
<a href='entryathletechoice.php'>Athletes</a>
</li>
<li>
<a href='entrycompetitionchoice.php'>Competitions</i></a>
</li>
<li>
<a href='entrydisciplinechoice.php' class="active">Disciplines</a>
</li>
</ul>
<a href='#' id='openup'>ESP</a>
</nav>
</header>
<section id="form" class="bg-light" style="padding-top:1rem">
<form action="updatediscipline.php?id=<?php echo $id?>" method="post" class="entryform">
<ul>
<li>
<label for="disciplineName">Discipline Name</label>
<input type="text" name="disciplineName" maxlength="35" value="<?php echo $row['disciplineName']?>">
<span>Enter the name of the discipline here</span>
</li>
<li>
<Label for="disciplineType[]">Discipline Type</label>
<!-- if rep discipline type -->
<?php if ($row['disciplineType'] === "reps")
{ ?>
<select name="disciplineType[]">
<option value="reps" selected>Reps</option>
<option value="repweight">Reps/Weight</option>
<option value="disttime">Distance/Time</option>
<option value="distance">Distance</option>
<option value="time">Time</option>
<option value="none">None</option>
</select>
<?php }
// if repweight discipline type
elseif ($row['disciplineType'] === "repweight")
{ ?>
<select name="disciplineType[]">
<option value="reps">Reps</option>
<option value="repweight" selected>Reps/Weight</option>
<option value="disttime">Distance/Time</option>
<option value="distance">Distance</option>
<option value="time">Time</option>
<option value="none">None</option>
</select>
<?php }
// if disttime discipline type
elseif ($row['disciplineType'] === "disttime")
{ ?>
<select name="disciplineType[]">
<option value="reps">Reps</option>
<option value="repweight">Reps/Weight</option>
<option value="disttime" selected>Distance/Time</option>
<option value="distance">Distance</option>
<option value="time">Time</option>
<option value="none">None</option>
</select>
<?php }
// if distance discipline type
elseif ($row['disciplineType'] === "distance")
{ ?>
<select name="disciplineType[]">
<option value="reps">Reps</option>
<option value="repweight">Reps/Weight</option>
<option value="disttime">Distance/Time</option>
<option value="distance" selected>Distance</option>
<option value="time">Time</option>
<option value="none">None</option>
</select>
<?php }
// if time discipline type
elseif ($row['disciplineType'] === "time")
{ ?>
<select name="disciplineType[]">
<option value="reps">Reps</option>
<option value="repweight">Reps/Weight</option>
<option value="disttime">Distance/Time</option>
<option value="distance">Distance</option>
<option value="time" selected>Time</option>
<option value="none">None</option>
</select>
<?php }
// if none discipline type
else
{ ?>
<select name="disciplineType[]">
<option value="reps">Reps</option>
<option value="repweight">Reps/Weight</option>
<option value="disttime">Distance/Time</option>
<option value="distance">Distance</option>
<option value="time">Time</option>
<option value="none" selected>None</option>
</select>
<?php } ?>
<span>Choose how this discipline will ultimately be decided</span>
</li>
<li>
<label for="disciplineShortDesc">Short Description</label>
<textarea name="disciplineShortDesc" style="height:5rem"><?php echo strip_tags($row['disciplineShortDesc']);?></textarea>
<span>Enter a short description to preview the discipline</span>
</li>
<li>
<label for="disciplineDescription">Description</label>
<textarea name="disciplineDescription" style="height:8rem"><?php echo strip_tags($row['disciplineDescription']);?></textarea>
<span>Finish the description (its page will show the Short description, then this)</span>
</li>
<li>
<label for="disciplineImg">Discipline Image</label>
<input type="text" name="disciplineImg" value="<?php echo $row['disciplineImg']?>">
<span>Enter the path of the image</span>
</li>
<li>
<input type="submit" name="submit" i value="Submit"> <input type="reset">
</li>
</ul>
</form>
</section>
<!-- Footer -->
<footer>
<div class="container">
<div class="footer-cols">
<div class="footer-left">
<ul>
<li>Navigation - Main Site</li>
<li>
<a href="become.php">Become an Elite Athlete</a>
</li>
<li>
<a href="allarticles.php">Elite Posts</a>
</li>
<li>
<a href="upcoming.php">Elite Competitions</a>
</li>
<li>
<a href="disciplinechoice.php">Elite Disciplines</a>
</li>
<li>
<a href="athletechoice.php">Elite Athletes</a>
</li>
</ul>
</div>
<div class="footer-right-entry">
<ul>
<li>Navigation - Admin Site</li>
<li>
<a href="entryarticlechoice.php">Edit Articles</a>
</li>
<li>
<a href="entryathletechoice.php">Edit Athletes</a>
</li>
<li>
<a href="entrycompetitionchoice.php">Edit Competitions</a>
</li>
<li>
<a href="entrydisciplinechoice.php">Edit Disciplines</a>
</li>
<li>
<a href="register.php">Add New User</a>
</li>
</ul>
</div>
</div>
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep><?php
//Starting/Resuming Session
session_start();
// Include database connection file
include_once('inc/connection.inc.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ESP | Admin</title>
<!-- Favourites icon -->
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
<!-- Local Stylesheets -->
<link rel="stylesheet" href="css/style.css">
<!-- Hosted Stylesheets -->
<!-- Font Awesome-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<!-- Showcase & Nav -->
<header>
<nav class='cf'>
</nav>
</header>
<!-- Overview -->
<section id="main" class="section bg-light">
<div class="container">
<form method="post" action="login.php">
<h1><span class="log-in">Log in</span></h1>
<p class="float">
<label for="login">Username</label>
<input type="text" name="userName" placeholder="Username or email">
</p>
<p class="float">
<label for="password"></i>Password</label>
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" class="showpassword" id="passwordfield">
<input type="checkbox" onclick="passwordReveal()"><p>Show Password</p>
</p>
<p class="clearfix">
<input type="submit" name="submit" value="Submit">
</p>
</form>
</div>
</section>
<!-- Footer -->
<footer>
<div class="container">
</div>
<div class="footer-bottom text-center">
Copyright © <?php echo date("Y"); ?> Elite Strongman Promotions
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/main.js"></script>
<script src="js/reveal.js"></script>
</body>
</html><file_sep><?php
//Starting/Resuming Session
session_start();
// Include database connection file
include_once('inc/connection.inc.php');
$id = $_GET['id'];
$articleTitle = $_POST['articleTitle'];
$articleType = $_POST['articleType'];
$articleImg = $_POST['articleImg'];
$articleContent = nl2br(htmlentities($_POST['articleContent'], ENT_QUOTES, 'UTF-8'));
// SQL Statement to update record
$query = "UPDATE `tblArticle` SET articleTitle='$articleTitle', articleType='$articleType', articleImg='$articleImg', articleContent='$articleContent' WHERE articleID='$id'";
//Perform SQL Statement in Database
$result = $db->query($query);
if ($result)
header( "refresh:5;url=entryarticlechoice.php" );
echo $articleTitle . " - record updated successfully. You will be re-directed after 5 seconds. If you have not been redirected, <a href='entryarticlechoice.php'>Click Here</a>";
$db->close();
?>
|
5422c22726db4b837dbfe56ffda540a4732ee556
|
[
"JavaScript",
"Markdown",
"PHP"
] | 22 |
PHP
|
MetalMitch/EliteStrongmanPromotions
|
58ecac2364e2001381e88b254c1677abb783e753
|
06a8615e98294c300809f8100787601453de9949
|
refs/heads/master
|
<file_sep>#!/bin/bash
SPARK_HOME=/opt/spark20/spark-2.0.0/ \
HADOOP_CONF_DIR=/etc/hadoop/conf/ \
/opt/spark20/spark-2.0.0//bin/spark-submit \
--master yarn \
--deploy-mode client \
--driver-java-options "-Dhive.metastore.uris=thrift://hadoop-m2.rtk:9083" \
--queue DMC \
--driver-memory 4g --num-executors 10 --executor-cores 4 --executor-memory 30g \
--class "ideas.Main" \
./scala-spark-hadoop-admin-WIFI-0-monitoring_N1-1.0.jar
<file_sep>#!/bin/bash
# /*
# * COMMAND FOR LOCAL MODE:
# * -XX:+UseG1GC -Xmx40g -Xms40g
# *
# * # Set SPARK_MEM if it isn't already set since we also use it for this process
# * SPARK_MEM=${SPARK_MEM:-512m}
# * export SPARK_MEM
# * # Set JAVA_OPTS to be able to load native libraries and to set heap size
# * JAVA_OPTS="$OUR_JAVA_OPTS"
# * JAVA_OPTS="$JAVA_OPTS -Djava.library.path=$SPARK_LIBRARY_PATH"
# * JAVA_OPTS="$JAVA_OPTS -Xms$SPARK_MEM -Xmx$SPARK_MEM"
# */
# /*
# * COMMAND FOR CLUSTER MODE:
# #!/bin/bash
# SPARK_HOME=/opt/spark20/spark-2.0.0/ \
# HADOOP_CONF_DIR=/etc/hadoop/conf/ \
# /opt/spark20/spark-2.0.0//bin/spark-submit \
# --master yarn \
# --deploy-mode client \
# --driver-java-options "-Dhive.metastore.uris=thrift://hadoop-m2.rtk:9083" \
# --queue DMC \
# --driver-memory 4g --num-executors 10 --executor-cores 4 --executor-memory 30g \
# --class "ideas.Main" \
# ./scala-spark-hadoop-admin-WIFI-0-monitoring_N1-1.0.jar
# */
java -jar -XX:+UseG1GC -Xmx40g -Xms40g ./scala-spark-hadoop-admin-WIFI-0-monitoring_N1-1.0.jar
<file_sep># routes
prototype
<file_sep>Размещение файлов на hdfs
hdfs://hadoop/project-MD2/jobs/daily-statistic/lib/daily-statistic-0.1.jar
hdfs://hadoop/project-MD2/jobs/daily-statistic/workflow.xml
hdfs://hadoop/project-MD2/jobs/daily-statistic/coordinator.xml
hdfs://hadoop/project-MD2/jobs/daily-statistic/sharelib
Здесь в принципе всё понятно без комментариев за исключением директории sharelib. В эту директорию мы положим все библиотеки, которые использовались в процессе создания зашей задачи.
В нашем случае это все библиотеки Spark 2.0.0, который мы указывали в зависимостях проекта. Зачем это нужно? Дело в том, что в зависимостях проекта мы указали "provided". Это говорит системе сборки не нужно включать зависимости в проект, они будут предоставлены окружением запуска, но мир не стоит на месте, администраторы кластера могут обновить версию Spark. Наша задача может оказаться чувствительной к этому обновлению, поэтому для запуска будет использоваться набор библиотек из директории sharelib. Как это конфигурируется покажу ниже.
Написание workflow.xml
Для запуска задачи через Oozie нужно описать конфигурацию запуска в файле workflow.xml. Ниже привожу пример для нашей задачи:
<workflow-app name="project-md2-daily-statistic" xmlns="uri:oozie:workflow:0.5">
<global>
<configuration>
<property>
<name>oozie.launcher.mapred.job.queue.name</name>
<value>${queue}</value>
</property>
</configuration>
</global>
<start to="project-md2-daily-statistic" />
<action name="project-md2-daily-statistic">
<spark xmlns="uri:oozie:spark-action:0.1">
<job-tracker>${jobTracker}</job-tracker>
<name-node>${nameNode}</name-node>
<master>yarn-client</master>
<name>project-md2-daily-statistic</name>
<class>ru.daily.Statistic</class>
<jar>${nameNode}${jobDir}/lib/daily-statistic-0.1.jar</jar>
<spark-opts>
--queue ${queue}
--master yarn-client
--num-executors 5
--conf spark.executor.cores=8
--conf spark.executor.memory=10g
--conf spark.executor.extraJavaOptions=-XX:+UseG1GC
--conf spark.yarn.jars=*.jar
--conf spark.yarn.queue=${queue}
</spark-opts>
<arg>${nameNode}${dataDir}</arg>
<arg>${datePartition}</arg>
<arg>${nameNode}${saveDir}</arg>
</spark>
<ok to="end" />
<error to="fail" />
</action>
<kill name="fail">
<message>Statistics job failed [${wf:errorMessage(wf:lastErrorNode())}]</message>
</kill>
<end name="end" />
</workflow-app>
В блоке global устанавливается очередь, для MapReduce задачи которая будет находить нашу задачи и запускать её.
В блоке action описывается действие, в нашем случае запуск spark задачи, и что нужно делать при завершении со статусом ОК или ERROR.
В блоке spark определяется окружение, конфигурируется задача и передаются аргументы. Конфигурация запуска задачи описывается в блоке spark-opts. Параметры можно посмотреть в официальной документации
Если задача завершается со статусом ERROR, то выполнение переходит в блок kill и выводится кратное сообщение об ошибки. Параметры в фигурных скобках, например ${queue}, мы будем определять при запуске.
Написание coordinator.xml
Для организации регулярного запуска нам потребуется ещё coordinator.xml. Ниже приведу пример для нашей задачи:
<coordinator-app name="project-md2-daily-statistic-coord" frequency="${frequency}" start="${startTime}" end="${endTime}" timezone="UTC" xmlns="uri:oozie:coordinator:0.1">
<action>
<workflow>
<app-path>${workflowPath}</app-path>
<configuration>
<property>
<name>datePartition</name>
<value>${coord:formatTime(coord:dateOffset(coord:nominalTime(), -1, 'DAY'), "yyyy/MM/dd")}</value>
</property>
</configuration>
</workflow>
</action>
</coordinator-app>
Здесь из интересного, параметры frequency, start, end, которые определяют частоту выполнения, дату и время начала выполнения задачи, дату и время окончания выполнения задачи соответственно.
В блоке workflow указывается путь к директории с файлом workflow.xml, который мы определим позднее при запуске.
В блоке configuration определяется значение свойства datePartition, которое в данном случае равно текущей дате в формате yyyy/MM/dd минус 1 день.
Запуск регулярного выполнения
И так сё готово к волнительному моменту запуска. Мы будем запускать задачу через консоль. При запуске нужно задать значения свойствам, которые мы использовали в xml файлах. Вынесем эти свойства в отдельный файл coord.properties:
# описание окружения
nameNode=hdfs://hadoop
jobTracker=hadoop-m1.rtk:8032
# путь к директории с файлом coordinator.xml
oozie.coord.application.path=/project-MD2/jobs/daily-statistic
# частота в минутах (раз в 24 часа)
frequency=1440
startTime=2017-09-01T07:00Z
endTime=2099-09-01T07:00Z
# путь к директории с файлом workflow.xml
workflowPath=/project-MD2/jobs/daily-statistic
# имя пользователя, от которого будет запускаться задача
mapreduce.job.user.name=username
user.name=username
# директория с данными и для сохранения результата
dataDir=/project-MD2/data
saveDir=/project-MD2/status
jobDir=/project-MD2/jobs/daily-statistic
# очередь для запуска задачи
queue=DMC
# использовать библиотеке из указанной директории на hdfs вместо системных
oozie.libpath=/project-MD2/jobs/daily-statistic/sharelib
oozie.use.system.libpath=false
Замечательно, тереть всё готово. Запускаем регулярное выполнение командой:
oozie job -oozie http://hadoop-m2.rtk:11000/oozie -config coord.properties -run
После запуска в консоль выведется id задачи. Используя это id можно посмотреть информацию о статусе выполнения задачи:
oozie job -info {job_id}
Остановить задачу:
oozie job -kill {job_id}
Если Вы не знаете id задачи, то можно найти его, показав все регулярные задачи для вашего пользователя:
oozie jobs -jobtype coordinator -filter user={user_name}
|
6976618274217d9cb5fd97611ec8daeee4c2a779
|
[
"Markdown",
"Text",
"Shell"
] | 4 |
Shell
|
musicnova/routes
|
fafc392583c5791e53fde9f4a8ce93a4a9c5444f
|
9b0c750466d07806c5dd237f1510e6b835772e1b
|
refs/heads/master
|
<file_sep>#ifndef HEADERINFO_H
#define HEADERINFO_H
#define MAX_FILENAME_SIZE 20000
enum Method{ GET, POST, HEAD };
struct headerinfo
{
enum Method method_type;
char version[4];
char filename[MAX_FILENAME_SIZE];
int filename_size;
int filesize;
char file_found;
};
#endif<file_sep>/* A simple server in the internet domain using TCP
The port number is passed as an argument
This version runs forever, forking off a separate
process for each connection
*/
#include <stdio.h>
#include <sys/types.h> // definitions of a number of data types used in socket.h and netinet/in.h
#include <sys/socket.h> // definitions of structures needed for sockets, e.g. sockaddr
#include <netinet/in.h> // constants and structures needed for internet domain addresses, e.g. sockaddr_in
#include <stdlib.h>
#include <strings.h>
#include <sys/wait.h> /* for the waitpid() system call */
#include <signal.h> /* signal name macros, and the kill() prototype */
#include <sys/time.h>
#include "headerinfo.h"
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX_LINE_LENGTH 100
#define HEADER_LENGTH 5000
void sigchld_handler(int s)
{
while(waitpid(-1, NULL, WNOHANG) > 0);
}
void dostuff(int); /* function prototype */
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, pid;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
struct sigaction sa; // for signal SIGCHLD
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
/****** Kill Zombie Processes ******/
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
/*********************************/
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
pid = fork(); //create a new process
if (pid < 0)
error("ERROR on fork");
if (pid == 0) { // fork() returns a value of 0 to the child process
close(sockfd);
dostuff(newsockfd);
exit(0);
}
else //returns the process ID of the child process to the parent
close(newsockfd); // parent doesn't need this
} /* end of while */
return 0; /* we never get here */
}
/******** DOSTUFF() *********************
There is a separate instance of this function
for each connection. It handles all communication
once a connnection has been established.
*****************************************/
void processLine(const char* line, int size, struct headerinfo* hi, char* namebuf)
{
char* pos = line;
int sz = 0, i = 0;
static char first_line = 't';
if(first_line == 't')
{
if( pos = strstr(line, "GET"))
{
hi->method_type = GET;
pos += 4;
while(*pos != ' ')
{
hi->filename[hi->filename_size++] = *pos++;
}
hi->filename[hi->filename_size] = '\0';
}
printf("IT REQUESTS FOR FILE: %s \n", hi->filename);
if(findFile(hi->filename, &sz, namebuf))
{
hi->filesize = sz;
hi->file_found = 't';
}
if(pos = strstr(line, "HTTP"))
{
pos+=5;
for( i = 0; i < 3;i++)
hi->version[i] = *(pos+i);
hi->version[3] = '\0';
}
}
printf("%s\n", line);
first_line = 'f';
}
int findFile(char* filename, int* size, char* namebuf)
{
DIR *dir;
int i , n;
struct dirent **namelist;
char* name, *slash_pos, *current_pos;
struct dirent *ent;
struct stat st;
char buf[PATH_MAX];
current_pos = filename+1;
if ((dir = opendir(".")) == NULL)
{printf("directory is fucked up");}
else
{
while(1)
{
if((slash_pos = strstr(current_pos, "/")) == NULL)
{
char found = 'f';
//this is the file - read it and put it into a buffer
n = scandir(".", &namelist, 0, alphasort);
char fname[MAX_FILENAME_SIZE];
strcpy(fname, current_pos);
for (i = 2; i < n; i++)
{
// printf("%s\n",namelist[i]->d_name);
stat(namelist[i]->d_name, &st);
if(S_ISREG(st.st_mode))
{
if(!strcmp(namelist[i]->d_name, fname))
{
printf("file ducking found %s having size %d\n", fname, st.st_size);
found = 't';
strcpy(namebuf, fname);
*size = st.st_size;
break;
}
}
}
if(found == 'f')
{
printf("no such file ducking found %s \n", fname);
return 0;
}
return 1;
}
else
{
//change to subdirectory
char dir_name[MAX_FILENAME_SIZE];
strncpy(dir_name, current_pos, slash_pos-current_pos);
dir_name[slash_pos-current_pos] = '\0';
current_pos = slash_pos+1;
char found = 'f';
n = scandir(".", &namelist, 0, alphasort);
for (i = 2; i < n; i++)
{
// printf("%s\n",namelist[i]->d_name);
stat(namelist[i]->d_name, &st);
if(S_ISDIR(st.st_mode))
{
if(!strcmp(namelist[i]->d_name, dir_name))
{
printf("directory ducking found %s\n", dir_name);
chdir(dir_name);
found = 't';
break;
}
}
}
if(found == 'f')
{
printf("no such ducking directory %s\n", dir_name);
return 0;
}
}
}
}
return 0;
}
void dostuff (int sock)
{
/*
objective:
1)read line by line the http headers untill you get \r\n\r\n
2)store each line into fixed size buffer.
3)process the buffer to get header field information, store that into a struct .
4)build response by pasting headers info and then opening the file required.
*/
struct headerinfo hi;
hi.filename[0] = '\0';
hi.filename_size = 0;
hi.file_found = 'f';
char name_buf[MAX_FILENAME_SIZE];
int n, fd;
char c;
char* buffer = (char*) malloc(MAX_LINE_LENGTH);
size_t size_multiplier = 1;
int count = 0;
//char end[4] = {'\r', '\n', '\r', '\n', '\0'};
char prev_cr = 'f'; //back to back carriage returns
memset((void *)buffer, 0, size_multiplier * MAX_LINE_LENGTH);
while((n=read(sock, &c, 1)) == 1)
{
if(c == '\n')
{
buffer[count] = '\0';
if(count == 1 && buffer[0] == '\r')
{
break;
}
else
{
prev_cr = 'f';
processLine(buffer, count, &hi, name_buf);
}
memset((void *)buffer, 0, size_multiplier * MAX_LINE_LENGTH);
count = 0;
continue;
}
buffer[count++] = c;
if(count == size_multiplier * MAX_LINE_LENGTH-1)
buffer = (char*)realloc(buffer, ++size_multiplier * MAX_LINE_LENGTH);
}
printf("out of loop");
if(n < 0)
error("ERROR reading from socket");
char str[HEADER_LENGTH];
if((fd = open(name_buf, O_RDONLY)) == -1)
{
sprintf ( str, "HTTP/%s 404 Not Found\r\nContent-type: text/html\r\nContent-length: 135\r\n\r\n<html><head><title>Not Found</title></head><body>Sorry, the object you requested was not found.</body><html>", hi.version );
printf(str);
write(sock, str, strlen(str));
}
else
{
sprintf(str , "HTTP/%s 200 OK\r\nContent-length: %d\r\n\r\n", hi.version, hi.filesize);
printf(str);
write(sock, str, strlen(str));
while((n=read(fd,&c, 1) == 1))
{
if (n < 0) error("ERROR reading from file");
if((n = write(sock,&c, 1)) == 1)
continue;
else
error("ERROR reading from file");
}
}
}
//
// int n;
// char c;
// char buffer[MAX_LINE_LENGTH] = {0};
// struct timeval tv;
// fd_set active_fd;
// int select_return;
// tv.tv_sec = 10;
// tv.tv_usec = 0;
// printf("Here is the message: ");
// do{
// FD_ZERO(&active_fd);
// FD_SET(sock, &active_fd);
// if((select_return = select(sock+1, &active_fd, NULL, NULL, &tv)) < 0)
// error("ERROR reading from socket");
// else if( select_return > 0)
// {
// int n = read(sock, buffer, MAX_LINE_LENGTH-1);
// buffer[n] = '\0';
// if(n < 0)
// if (n < 0) error("ERROR reading from socket");
// if(n > 0)
// printf("%s", buffer);
// }
// }while(select_return != 0);
// printf("\n");
// n = write(sock,"I got your message",18);
// if (n < 0) error("ERROR writing to socket");
|
b73ccc7eeff9f7531f7c945cf1db3c70d0a9d581
|
[
"C"
] | 2 |
C
|
tsleeve/HTTP-Web-Server
|
56f78d840638853935eaa1458d8e1cf200f97806
|
0d8e603047ec28ac0107c2df98622d25c2e8ea2e
|
refs/heads/master
|
<repo_name>LarryMatrix/random-password-generator<file_sep>/rpg/signup/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<NAME>">
<title>RPG</title>
<link href="../creation/css/mine.css" rel="stylesheet">
<link href="../creation/css/styling.css" rel="stylesheet">
<style>
body {
padding-top: 70px;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a style="color: white;" class="navbar-brand" href="../">:- RPG</a>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h3>Random Password Generator Manager (RPG - Man)</h3>
<p class="lead">Manages secret and secured passwords for anyone to be used anywhere</p>
</div>
<div class="col-md-6">
<div class="jumbotron">
<h4 class="text-center">Random Password Genarator Manager</h4>
<p class="lead" style="font-size: 17px;">This is the free software that lets anyone to create a unique, strong, and secured password for the use of online or even offline accounts or systems <i>i.e Gmail, Facebook, Twitter, Instagram etc</i></p>
<p class="lead" style="font-size: 17px;">We also save your passwords as for future use and in case of forgetting, it is safe with RPG - Man</p></font>
<p><a class="btn btn-success" href="../login/">Login</a></p>
</div>
</div>
<div class="col-md-6">
<div class="jumbotron">
<p class="lead"></p>
<form action="" method="POST">
<div class="form-group row">
<label for="length" class="form-control-label"><p class="lead">Sign up with RPG- Man</p></label>
<div class="col-sm-10">
<input type="text" name="full_name" class="form-control" placeholder="Enter your full name here" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="text" name="username" class="form-control" placeholder="Enter your username here" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="number" name="mob_no" class="form-control" placeholder="Enter your mobile number here" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="password" name="pswd" class="form-control" placeholder="Enter your password here" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-9">
<input type="submit" class="form-control btn btn-info" name="submit" value="Sign Up">
</div>
<div class="col-sm-3">
<input type="reset" class="form-control btn btn-default" value="Clear">
</div>
</div>
</form>
<?php
if (isset($_POST['submit'])){
$conn = new mysqli("localhost","root","","pass_gen");
if(!$conn){
die("Connection Lost:".connect_error);
}
$fname = mysqli_real_escape_string($conn, htmlspecialchars($_POST['full_name']));
$usid = mysqli_real_escape_string($conn, htmlspecialchars($_POST['username']));
$mob_no = mysqli_real_escape_string($conn, htmlspecialchars($_POST['mob_no']));
$pswd = md5($_POST['pswd']);
$level = "User";
if(empty($usid)){
echo "<script>window.location='../signup/';</script>";
}else if(empty($pswd)){
echo "<script>window.location='../signup/';</script>";
}else if(empty($mob_no)){
echo "<script>window.location='../signup/';</script>";
}else if(empty($fname)){
echo "<script>window.location='../signup/';</script>";
}else{
$signup = "INSERT INTO `account` (`usid`, `full_name`, `mob_no`, `level`, `password`) VALUES ('$usid', '$fname', '$mob_no', '$level', '$pswd')";
if ($conn -> query($signup) === TRUE) {
echo "<script>window.location='../login/';</script>";
} else {
echo "<p style='font-size: 16px;'>The username <i><u><font color='red'>".$usid."</font></u></i> already exists.</p>";
}
}
mysqli_close($conn);
}
?>
</div>
</div>
</div>
</div>
<script src="../creation/js/jquery.js"></script>
<script src="../creation/js/name.js"></script>
<script src="../creation/js/bootstrap.min.js"></script>
</body>
</html><file_sep>/rpg/home/logout.php
<?php
session_start();
session_unset();
session_destroy();
setcookie("SESSION-ID", "", time() - 3600);
header ("Location: ../");
?><file_sep>/rpg/home/add_password.php
<h3>Add Password</h3><hr/><br/>
<div class="col-md-6">
<form action="" method="POST">
<div class="form-group row">
<div class="col-sm-10">
<input type="text" name="pswd" class="form-control" placeholder="Enter Password here">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="text" name="purpose" class="form-control" placeholder="Enter Password Purpose here">
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<input type="submit" class="form-control btn btn-primary" name="submit" value="Add Password">
</div>
<div class="col-sm-6">
<input type="reset" class="form-control btn btn-danger" value="Clear">
</div>
</div>
</form>
<?php
if(isset($_POST['submit'])){
include("../eng/connect.php");
$usid = $_SESSION["user_id"];
$addpassword = $_POST['pswd'];
$purpose = $_POST['purpose'];
if (empty($addpassword) || empty($purpose) || (empty($addpassword) && empty($purpose))) {
echo "<script>window.location='../home/?p=add_password';</script>";
}
$addsql = "INSERT INTO `passwords` (`id`, `pass`, `purpose`, `usid`) VALUES (NULL, '$addpassword', '$purpose', '$usid')";
if ($conn -> query($addsql) === TRUE) {
echo "<script>window.location='../home/?p=add_password';</script>";
} else {
die(mysqli_error($conn));
}
mysqli_close($conn);
}
?>
</div>
<div class="col-md-6">
<p class="lead"></p>
<form action="" method="POST">
<div class="form-group row">
<div class="col-sm-10">
<input type="number" name="length" class="form-control" placeholder="Not Greater Than 61">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="checkbox" name="checkCapital" value="CapitalLetters" checked>Capital Letters
<input type="hidden" name="hidden" value="hidden" checked required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="checkbox" name="checkSmall" value="SmallLetters" checked>Small Letters
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="checkbox" name="checkNums" value="Numerals" checked>Numbers
</div>
</div>
<div class="form-group row">
<div class="col-sm-9">
<input type="submit" class="form-control btn btn-primary" placeholder="Not Greater Than 61" name="gen_pass" value="Generate Password">
</div>
<div class="col-sm-3">
<a href="/rpg/home/?p=add_password" class="btn btn-default">Clear</a>
</div>
</div>
</form>
<?php
if (isset($_POST['gen_pass'])) {
$conn = new mysqli("localhost","root","","pass_gen");
if(!$conn){
die("Connection Lost:".connect_error);
}
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
$length = $_POST['length'];
$password = '';
if (isset($_POST['checkCapital']) && !isset($_POST['checkSmall']) && !isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(0, 25)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(0, 25)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (isset($_POST['checkSmall']) && !isset($_POST['checkCapital']) && !isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(26, 51)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(26, 51)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$<PASSWORD>'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (isset($_POST['checkNums']) && !isset($_POST['checkCapital']) && !isset($_POST['checkSmall']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(52, 61)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(52, 61)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (!isset($_POST['checkNums']) && !isset($_POST['checkCapital']) && !isset($_POST['checkSmall']) && isset($_POST['hidden'])) {
echo "<p class='lead' style='color: red;'>Please select at least one field above.<br/>No Password is Generated.</h3>";
} else if (isset($_POST['checkCapital']) && isset($_POST['checkSmall']) && !isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(0, 51)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(0, 51)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (isset($_POST['checkCapital']) && !isset($_POST['checkSmall']) && isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(0, 25)].$characters[mt_rand(52, 61)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(0, 25)].$characters[mt_rand(52, 61)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (!isset($_POST['checkCapital']) && isset($_POST['checkSmall']) && isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(26, 61)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(26, 61)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (isset($_POST['checkCapital']) && isset($_POST['checkSmall']) && isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(0, 61)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(0, 61)];
}
echo "<p style='font-size: 14px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else {
echo "<p style='font-size: 18px;'>Please retry randomizing again</p>";
}
}
?>
</div>
<file_sep>/rpg/pass_gen.sql
-- phpMyAdmin SQL Dump
-- version 4.5.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jan 09, 2017 at 04:56 PM
-- Server version: 10.1.13-MariaDB
-- PHP Version: 5.6.21
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `pass_gen`
--
-- --------------------------------------------------------
--
-- Table structure for table `account`
--
CREATE TABLE `account` (
`usid` varchar(50) NOT NULL,
`full_name` text,
`mob_no` varchar(20) DEFAULT NULL,
`level` text NOT NULL,
`password` varchar(62) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `account`
--
INSERT INTO `account` (`usid`, `full_name`, `mob_no`, `level`, `password`) VALUES
('demo', '<PASSWORD>', '<PASSWORD>', 'User', '<PASSWORD>'),
('massanjal', 'Lawrance Massanja', '0717455043', 'User', '<PASSWORD>');
-- --------------------------------------------------------
--
-- Table structure for table `passwords`
--
CREATE TABLE `passwords` (
`id` int(5) UNSIGNED NOT NULL,
`pass` varchar(55) NOT NULL,
`purpose` text NOT NULL,
`usid` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `passwords`
--
INSERT INTO `passwords` (`id`, `pass`, `purpose`, `usid`) VALUES
(1, 'cXDdRFDk', '', ''),
(2, 'bMebdJtA', '', ''),
(3, 'UwPpHtuj', '', ''),
(4, 'UIaQTthj', '', ''),
(5, 'aqMXNxzi', 'Twitter', 'massanjal'),
(6, 'VjGGAfxY', '', ''),
(7, 'tFRhPUjH', 'Facebook', 'massanjal'),
(8, 'GYCJbPla', '', ''),
(9, 'ffJIhygD', '', ''),
(10, 'zwYFobAP', 'Twitter', 'massanjal'),
(11, 'qOnbBIAk', '', ''),
(12, 'YrXyWNbK', '', ''),
(13, 'AmCJABYO', '', ''),
(14, 'YJwvHeju', 'Instagram', 'massanjal'),
(15, 'GtZTIJYp', '', ''),
(16, 'hRTJNMNJ', '', ''),
(17, 'SvIFTtoJ', '', ''),
(18, 'LOFgagrO', '', ''),
(19, 'NFWxQyov', '', ''),
(20, 'wDzVrZgy', '', ''),
(21, 'aZDnysLB', '', ''),
(22, 'oEAMwNoo', '', ''),
(23, 'YOHYkakB', '', ''),
(24, 'uxLSBUws', 'Gmail', 'massanjal'),
(25, 'UIMEvzBf', '', ''),
(26, 'yChmwuXk', '', ''),
(27, 'XEvVHiQS', 'Instagram', 'massanjal'),
(28, 'otMJXpRx', '', ''),
(29, 'ZszGXBKB', '', ''),
(30, 'RmKAYXdq', '', ''),
(31, 'CxJNbBPs', '', ''),
(32, 'PdOGowPD', '', ''),
(33, 'TCaADOOK', 'Gmail', 'massanjal'),
(34, 'KmvMQSlZ', '', ''),
(35, 'tfwvTHPw', '', ''),
(36, 'KuCHUelj', '', ''),
(37, 'yHSXrGcg', '', ''),
(38, 'PfGmYFeVJpYwtnMJgdDtwLhgRAyzeUeacc', '', ''),
(39, 'xMnLZRUV', '', ''),
(40, 'upBoPXvg', 'Gmail', 'massanjal'),
(41, 'DfmgdYIo', '', ''),
(42, 'ZSpnaZOx', '', ''),
(43, 'XuiOguMH', '', ''),
(44, 'BMTvWGWC', 'Vine', 'massanjal'),
(45, 'wiqvmSeh', '', ''),
(46, 'aCNKxyPV', '', ''),
(47, 'SmYsAcFc', '', ''),
(48, 'LTJoGvje', '', ''),
(49, 'WfPKsury', '', ''),
(50, 'eYFiBNfN', 'Aris', 'massanjal'),
(51, 'ytUIZRNl', '', ''),
(52, 'CHzKjBHM', '', ''),
(53, 'OgoGHjDL', '', ''),
(54, 'VcMQcUfE', '', ''),
(55, 'EaaheeIQ', '', ''),
(56, 'LDBxwsZo', '', ''),
(57, 'NNNJzMor', '', ''),
(58, 'hXTmFnBx', '', ''),
(59, 'MFboFxkc', '', ''),
(60, 'nAHYAfyb', '', ''),
(61, 'DOfYdlXd', '', ''),
(62, 'koQiXegK', '', ''),
(63, 'BZMYzZib', '', ''),
(64, 'benLXuRC', '', ''),
(65, 'FlxWGyBq', '', ''),
(66, 'BeehbXNX', '', ''),
(67, 'aLTVgVql', '', ''),
(68, 'BROvrppj', '', ''),
(69, 'pYb', '', ''),
(70, 'd', '', ''),
(71, 'e', '', ''),
(72, 'E', '', ''),
(73, 'Z', '', ''),
(74, 'N', '', ''),
(75, 'N', '', ''),
(76, 'oIgKWuXxWHuLzhkSOOkRmNWIfxTtOcSGitNdMIbq', '', ''),
(77, '', '', ''),
(78, 'dUZUaMTBOpAMZxSIXKVwgjeAoiuvoEUtZDnKWXMBAoQrhAhdaVp', '', ''),
(79, 'skxKl', '', ''),
(80, 'vVencDkb', '', ''),
(81, 'taAx', '', ''),
(82, 'WoO', '', ''),
(83, 'aeQA', '', ''),
(84, 'msqBBVvX', '', ''),
(85, 'kMnvyHcO', '', ''),
(86, 'RHUJtACv', '', ''),
(87, 'OfJbNQUY', '', ''),
(88, 'xjotPaFf', '', ''),
(89, 'hyFohlkq', '', ''),
(90, 'FvaNgMnC', '', ''),
(91, 'mghwsiZA', '', ''),
(92, 'jvIMwUzP', '', ''),
(93, 'NhVHOaPt', '', ''),
(94, 'lDgzeSOT', '', ''),
(95, 'KHkNCCwz', '', ''),
(96, 'ncviCDWj', '', ''),
(97, 'dUBdFNzt', '', ''),
(98, 'KoJWLqSz', '', ''),
(99, 'gQICgabQ', '', ''),
(100, 'RWvYQuhN', '', ''),
(101, 'UOyQxPZe', '', ''),
(102, 'OHknBgkE', '', ''),
(103, 'dJOvHQFG', '', ''),
(104, 'gDqmrRLJ', '', ''),
(105, 'AQVEvWEq', '', ''),
(106, 'auINRcQU', '', ''),
(107, 'UoZGEirj', '', ''),
(108, 'jpyAnyFn', '', ''),
(109, 'LveyyRnN', '', ''),
(110, 'aSGkfHpG', '', ''),
(111, 'HoMiimEb', '', ''),
(112, 'muRiQtpG', '', ''),
(113, 'JRcegmqw', '', ''),
(114, 'MCgsfLCm', '', ''),
(115, 'EgNMbzCD', '', ''),
(116, 'LVoCRaPi', '', ''),
(117, 'yERecpAL', '', ''),
(118, 'HAPDFtKz', '', ''),
(119, 'wZxZXxGV', '', ''),
(120, 'ZLVaGwmD', '', ''),
(121, 'bNjWUnvO', '', ''),
(122, 'CLLbAwVV', '', ''),
(123, 'amvJV', '', ''),
(124, 'YNYXp', '', ''),
(125, 'jOzLAwTT', '', ''),
(126, 'LQfkRMvI', '', ''),
(127, 'KunNYVpQ', '', ''),
(128, 'NOVgPSvf', '', ''),
(129, 'hOhLQfrA', '', ''),
(130, 'dPFpInFQ', '', ''),
(131, 'ypzXEkPL', '', ''),
(132, 'hLTTFrnv', '', ''),
(133, 'OObeuqeS', '', ''),
(134, 'RhjxakZL', '', ''),
(135, 'DPOEfoXC', '', ''),
(136, 'QLENQwHX', '', ''),
(137, 'YQBCexSR', '', ''),
(138, 'rvaimiFx', '', ''),
(139, 'qWbrVQWY', '', ''),
(140, 'qRXgwIUw', '', ''),
(141, 'kpXWSWXe', '', ''),
(142, 'bqvAQxMW', '', ''),
(143, 'ZKDTLtwo', '', ''),
(144, 'cZkevGeo', '', ''),
(145, 'bcufKYPm', '', ''),
(146, 'NbiVmOIw', '', ''),
(147, 'vSJuACMl', '', ''),
(148, 'aNDrfayN', '', ''),
(149, 'znvAkeqn', '', ''),
(150, 'rlglAXxT', '', ''),
(151, 'zOmKhywO', '', ''),
(152, 'piYAtsyg', '', ''),
(153, 'fEoQsfww', '', ''),
(154, 'wxPYWrSC', '', ''),
(155, 'CpnbblEl', '', ''),
(156, 'jQYVywsr', '', ''),
(157, 'qVUThZYg', '', ''),
(158, 'gQIFsuIj', '', ''),
(159, 'EdYhkFbd', '', ''),
(160, 'uRcojbMt', '', ''),
(161, 'QDqLdxqf', '', ''),
(162, 'JceozzOL', '', ''),
(163, 'LtvYPQeB', '', ''),
(164, 'JYhYOEpn', '', ''),
(165, 'KYhdqrqg', '', ''),
(166, 'ekTvhImo', '', ''),
(167, 'SIoyvSOc', '', ''),
(168, 'HITHCrnt', '', ''),
(169, 'plFgdJKk', '', ''),
(170, 'lzCcJkja', '', ''),
(171, 'LGBHtnVd', '', ''),
(172, 'BTLodsZF', '', ''),
(173, 'jeqdZmtD', '', ''),
(174, 'fJkyFIWc', '', ''),
(175, 'fMXmjJOl', '', ''),
(176, 'vJQjkMlu', '', ''),
(177, 'OxaEjFKH', '', ''),
(178, 'GUZPTkGV', '', ''),
(179, 'nyqLgZQb', '', ''),
(180, 'pqGnvuXA', '', ''),
(181, 'ZOrXrrda', '', ''),
(182, 'PUJyyZtO', '', ''),
(183, 'YrVLaCBW', '', ''),
(184, 'qyqmvcEZ', '', ''),
(185, 'tKmEXIhA', '', ''),
(186, 'WcAgHtXm', '', ''),
(187, 'TCvHQrua', '', ''),
(188, 'mQnLIIuX', '', ''),
(189, 'SuxSFIfk', '', ''),
(190, 'qNOXLtRG', '', ''),
(191, 'DHozlPvD', '', ''),
(192, 'SGThChum', '', ''),
(193, 'BIALWqpG', '', ''),
(194, 'DJkmTtQx', '', ''),
(195, 'HbGeuNAi', '', ''),
(196, 'RIvXXuss', '', ''),
(197, 'GRSnqcsJ', '', ''),
(198, 'swkndXoz', '', ''),
(199, 'ViUBgOOQ', '', ''),
(200, 'GKudyyBN', '', ''),
(201, 'lobJjqgU', '', ''),
(202, 'rioHVKuK', '', ''),
(203, 'xopQz', '', ''),
(204, 'znUJJZMNSFBMAtRqOElNrQBCfbUJXHFlHNaNXgYtdjFth', '', ''),
(205, 'XnnXKc', '', ''),
(206, 'CYtAAKPo', '', ''),
(207, 'WhZyHiiki', '', ''),
(208, 'OKCCzNad', '', ''),
(209, 'eqyHsMLEq', '', ''),
(210, 'GsPfwjrb', '', ''),
(211, '2c758d7c878cbcfbee338962f34b26af', '', ''),
(212, '7f9bcb24ee6f025243a03b44bd4481be', '', ''),
(213, 'd3407b62b5bc6215e799e7923985dd33', '', ''),
(214, '438d02e7d3f1b5c155866d8963a4da0d', '', ''),
(215, '0a9045c120db1bade1d67e0e5f8b2b2e', '', ''),
(216, '4d17e8174a89e1cff8815157836e7cec365f2b4b', '', ''),
(217, 'EfiCeTkx', '', ''),
(218, 'BnMbVqzS', '', ''),
(219, 'UmRx', '', ''),
(220, 'xfCMI', '', ''),
(221, 'PjmrXg', '', ''),
(222, 'reFneqWWdV', '', ''),
(223, 'FWwSIJrQUMsNCrv', '', ''),
(224, '6f6a38ceb240b2bda3d3f2e547f2d4df84843b15', '', ''),
(225, 'dec9e33158b87c82c8d733327737d46c8fdee034', '', ''),
(226, 'efd1b5411131961e1d37197518b0a838b6a328fc', '', ''),
(227, '3545ad968e98af9cfffe05f737b910b08f1a80e4', '', ''),
(228, '9722483d4411bea228c36d8ac20d20aaf4e7d848', '', ''),
(229, '13021855ccac22ea5d12bc066879042a48ae2c56', '', ''),
(230, '<KEY>', '', ''),
(231, '5ff42c1e27ae2dba6e8941d562cbfdab308ba2c3', '', ''),
(232, '<KEY>', '', ''),
(233, '<KEY>', '', ''),
(234, '<KEY>', '', ''),
(235, '<KEY>', '', ''),
(236, '<KEY>', '', ''),
(237, '909f99a779adb66a76fc53ab56c7dd1caf35d0fd', '', ''),
(238, 'c2c53d66948214258a26ca9ca845d7ac0c17f8e7', '', ''),
(239, '283de25463098b2f2bb1824450661e0d0445bdfa', '', ''),
(240, '<KEY>', '', ''),
(241, '<KEY>', '', ''),
(242, '44c21146634df1305f8f38ed744f5569d6468343', '', ''),
(243, '<KEY>', '', ''),
(244, '<KEY>', '', ''),
(245, 'apple', '', ''),
(246, 'appla', '', ''),
(247, 'chris', '', ''),
(248, 'd41d8cd98f00b204e9800998ecf8427e', '', ''),
(249, 'ee3d795068ecddc12d850712a6b36514', '', ''),
(250, 'd8e58d65e49ff97d1b6b2887988e6801', '', ''),
(251, 'e40ff021124c5c760f380bb76823ca1c', '', ''),
(252, '7c002f9aa9a949fc156210542d4db696', '', ''),
(253, 'e281852d28ddf7f836ba0dd8082b1a2b', '', ''),
(254, '77cbc257e66302866cf6191754c0c8e3', '', ''),
(255, '0f319c8ba51118b1db20fc5e7867c7df', '', ''),
(256, '2bf227301cc6151ecddf582fc65559de', '', ''),
(257, '7a6cf0cb35ad839a8172c79da40cb99f', '', ''),
(258, '14b6737b71633d31cfbef3296bdd791a', '', ''),
(259, 'b45e182b492a3449cd52d15eb4fc4959', '', ''),
(260, 'be7116355f077069296f79ff54c26174', '', ''),
(261, '33457dd68ab8b33509400b31ee12fe5a', '', ''),
(262, 'd2766db2e26e149e610131a83fab0a85', '', ''),
(263, 'c590328fa22366acab458b0ee3d7856f', '', ''),
(264, '6469e7edde399c74c42c502d7a2b0c56', '', ''),
(265, '8cf9d1a6ef1d7eeea738789fecec78e6', '', ''),
(266, '3db4a05ffab4a5efdd63495a4977adc6', '', ''),
(267, 'f5ca99c6e001d4f7209730396e82791a', '', ''),
(268, '1f2673c5dff63b9083eefb9a2f65b6d0', '', ''),
(269, '5fb840e6a673c0c790d18b24298359aa', '', ''),
(270, '817a3893f0315643c15f8a4508cc3f3e', '', ''),
(271, 'a76696183c52a6ee375a90d728696112', '', ''),
(272, 'kl1oIu2W', '', ''),
(273, 'DYyeubTS', '', ''),
(274, 'rUSY9bUo', '', ''),
(275, 'CwyORO8f', '', ''),
(276, 'B2ltW9se', '', ''),
(277, 'bKy7b41B', '', ''),
(278, 'EqKxVbmm', '', ''),
(279, '8ircM56J', '', ''),
(280, 'grwv3LPg', '', ''),
(281, 'W8n2K1aj', '', ''),
(282, 'RYPKHhSR', '', ''),
(283, 'SmP93FxZ', '', ''),
(284, 'sSqNNLem', '', ''),
(285, 'CDR7Jojq', '', ''),
(286, 'x9x4UrNe', '', ''),
(287, 'pJNmRnNV', '', ''),
(288, 'jliSmkpl', '', ''),
(289, 'gIwcd7YB', '', ''),
(290, 'K86wff34', '', ''),
(291, 'FWTGI4b7', '', ''),
(292, '92C50EiP', '', ''),
(293, 'gewk3olT', '', ''),
(294, 'ckRY9V9C', '', ''),
(295, 'yTsObpQXWxaPEOvTYfUguaKKxsoBVwWRczKVOnLWinWsuatTdzb', '', ''),
(296, 'yrXDx7He', '', ''),
(297, 'jmtTIZb6', '', ''),
(298, 'O0Uw0EUY', '', ''),
(299, 'c88v27r4', '', ''),
(300, 'wDdg3d5o', '', ''),
(301, 'ShLGTmKh', '', ''),
(302, '1TnI2Dki', '', ''),
(303, 'pvPSgDDC', '', ''),
(304, 'O2ZFtk6J', '', ''),
(305, 'AqJelLyE', '', ''),
(306, 'u8pX6l83', '', ''),
(307, 'EqwvHXba', '', ''),
(308, 'pYerA0xV', '', ''),
(309, 'N7ZtRJqJ', '', ''),
(310, 'N4l7wBKF', '', ''),
(311, 'mKODdNHB', '', ''),
(312, '17swX1CL', '', ''),
(313, 'RYhplKS1', '', ''),
(314, 'y1vqxQrQ', '', ''),
(315, 'KnY73dUW', '', ''),
(316, '3xDfWP', '', ''),
(317, '6dojbiCS', '', ''),
(318, 'd6mTaRSV', '', ''),
(319, 'mZGSW4Q3', '', ''),
(320, 'z8MAGuVH', '', ''),
(321, 'gwFNotRG', '', ''),
(322, '94cc85M7', '', ''),
(323, 'RvwodwKR', '', ''),
(324, 'Ujxkt0vz', '', ''),
(325, '9yLqrDTw', '', ''),
(326, 'NV85GDRC', '', ''),
(327, 'TP1IyZIp', '', ''),
(328, 'Xq5MZjiX', '', ''),
(329, '4jzO65bb', '', ''),
(330, '7ZioEHPz', '', ''),
(331, 'E8DFdcQg', '', ''),
(332, 'b2bYVZ1wFvmLx4W3aLoDoKXTu8cRfCPZ72', '', ''),
(333, 'qCfaQuHY', '', ''),
(334, 'MDRoZI22', '', ''),
(335, 'H7B9Xx0b', '', ''),
(336, 'QJAs4yDG', '', ''),
(337, 'KUNfvOAK', '', ''),
(338, 'xOIwzGST', '', ''),
(339, 'JDxjIUw1', '', ''),
(340, 'y8ra91dk', '', ''),
(346, 'Qw96TPzb5QgA9YtZ', 'Facebok', 'massanjal'),
(347, 'jAWV8tIb', 'Flickr', 'massanjal'),
(351, 'qCKwF7DUDQAuD7VoCMy6WZEQKtNLCpmUzMiYJneAiYNDg93Kkba', 'vine', 'massanjal'),
(354, 'zZXr8agmytBg0uWumZ7w', 'aris', 'demo');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `account`
--
ALTER TABLE `account`
ADD PRIMARY KEY (`usid`);
--
-- Indexes for table `passwords`
--
ALTER TABLE `passwords`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `passwords`
--
ALTER TABLE `passwords`
MODIFY `id` int(5) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=355;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/rpg/login/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<NAME>">
<title>RPG</title>
<link href="../creation/css/mine.css" rel="stylesheet">
<link href="../creation/css/styling.css" rel="stylesheet">
<style>
body {
padding-top: 70px;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a style="color: white;" class="navbar-brand" href="../">:- RPG</a>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h3>Random Password Generator Manager (RPG - Man)</h3>
<p class="lead">Manages secret and secured passwords for anyone to be used anywhere</p>
</div>
<div class="col-md-6">
<div class="jumbotron">
<h4 class="text-center">Random Password Genarator Manager</h4>
<p class="lead" style="font-size: 17px;">This is the free software that lets anyone to create a unique, strong, and secured password for the use of online or even offline accounts or systems <i>i.e Gmail, Facebook, Twitter, Instagram etc</i></p>
<p class="lead" style="font-size: 17px;">We also save your passwords as for future use and in case of forgetting, it is safe with RPG - Man</p></font>
<p><a class="btn btn-info" href="../signup/">Create Account with RPG</a></p>
</div>
</div>
<div class="col-md-6">
<div class="jumbotron">
<p class="lead"></p>
<form action="" method="POST">
<div class="form-group row">
<label for="length" class="form-control-label"><p class="lead">Login to RPM - Man</p></label>
<div class="col-sm-10">
<input type="text" name="usid" class="form-control" placeholder="Enter Username here">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="password" name="pswd" class="form-control" placeholder="Enter Password here">
</div>
</div>
<div class="form-group row">
<div class="col-sm-9">
<input type="submit" class="form-control btn btn-primary" name="submit" value="Login">
</div>
<div class="col-sm-3">
<input type="reset" class="form-control btn btn-default" value="Clear">
</div>
</div>
</form>
<?php
if (isset($_POST['submit'])){
$conn = new mysqli("localhost","root","","pass_gen");
if(!$conn){
die("Connection Lost:".connect_error);
}
session_start();
$usid = $_POST['usid'];
$pswd = md5($_POST['pswd']);
if(empty($usid)){
echo "<script>window.location='../login/';</script>";
}else if(empty($pswd)){
echo "<script>window.location='../login/';</script>";
}else{
$login = "SELECT `usid`, `password`, `level` FROM `account` WHERE `usid` = '$usid'";
$results = $conn -> query($login);
if(!$results){
die(mysqli_error($conn));
}
if(mysqli_num_rows($results) > 0){
$row = $results -> fetch_assoc();
if ($usid == $row['usid'] && $pswd == $row['password']){
//store session variables
$_SESSION['user_id']=$row["usid"];
$_SESSION['password']=$row["<PASSWORD>"];
//set cookie values
$cookie_name = "SESSION-ID";
$cookie_value = $pswd.mt_rand();
$_SESSION["SESSION-ID"] = $cookie_value;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
$_SESSION["cookie_name"]=$cookie_name;
if($row["level"]=="User"){
echo "<script>window.location='../home/';</script>";
exit;
} else if ($row['level'] == "Admin"){
echo "<script>window.location='../admin/';</script>";
exit;
}
}
if ($pswd != $row['password'] || $usid != $row['usid'] || ($pswd != $row['password'] && $usid != $row['usid'])) {
echo "<script>window.location='../login/';</script>";
}else {
echo "<script>window.location='../login/';</script>";
}
}
}
}
?>
</div>
</div>
</div>
</div>
<script src="../creation/js/jquery.js"></script>
<script src="../creation/js/name.js"></script>
<script src="../creation/js/bootstrap.min.js"></script>
</body>
</html><file_sep>/rpg/home/lock.php
<?php
//load the session id from php session
if(!isset($_SESSION["SESSION-ID"])){
echo"<script>window.location='../login/'</script>";
exit;
}
if(!isset($_SESSION["cookie_name"])){
echo"<script>window.location='../login/'</script>";
exit;
}else{
$cookie_value=$_SESSION["SESSION-ID"];
$cookie_name=$_SESSION["cookie_name"];
}
//compare the session id from php session with session id in cookie
if(!isset($_COOKIE[$cookie_name])) {
echo"<script>window.location='../login/'</script>";
exit;
}
else if($_COOKIE[$cookie_name]!= $_SESSION["SESSION-ID"]) {
echo"<script>window.location='../login/'</script>";
exit;
}
?><file_sep>/rpg/home/my_passwords.php
<h3>My Passwords</h3><hr/>
<table class="table table-striped table-hover">
<thead>
<tr class="info">
<th>Password</th>
<th>Purpose</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<?php
include("../eng/connect.php");
$usid = $_SESSION["user_id"];
$pass = "SELECT `id`, `pass`, `purpose` FROM `passwords` WHERE `usid` = '$usid'";
$result = mysqli_query($conn, $pass);
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr class='success'>
<td><input id='".$row['pass']."' type='text' value='".$row['pass']."'/><button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#".$row['pass']."'></button></td>
<td>".$row['purpose']."</td>
<td><a href='' class='btn btn-xs btn-primary'>Go to login site</a> <a href='' class='btn btn-xs btn-danger'>Delete</a></td>
</tr>";
}
mysqli_close($conn);
?>
</tbody>
</table>
<hr/><file_sep>/rpg/home/change_password.php
<h3>Change Password</h3><hr/><br/>
<div class="col-md-10">
<?php
if(!isset($_GET['error'])){
echo"<div class='alert alert-info' role='alert'><p>This action is not revesrible, don't rush.</p></div>";
}
else{
$error = $_GET['error'];
Switch($error){
case 0:
echo"<div class='alert alert-success' role='alert'><p>Password Successfully Changed</p></div>";
break;
case 1:
echo"<div class='alert alert-danger' role='alert'><p>Password was not changed, please try again.</p></div>";
break;
case 2:
echo"<div class='alert alert-danger' role='alert'><p>Passwords do not match.</p></div>";
break;
}
}
?>
<form action="" method="POST">
<div class="form-group row">
<div class="col-sm-10">
<input type="text" name="curr_pass" class="form-control" placeholder="Enter current/old password">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="text" name="new_pass" class="form-control" placeholder="Enter new password Purpose">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="text" name="conf_pass" class="form-control" placeholder="Confirm new password Purpose">
</div>
</div>
<div class="form-group row">
<div class="col-sm-5">
<input type="submit" class="form-control btn btn-primary" name="submit" value="Change Password">
</div>
</div>
</form>
<?php
if(isset($_POST['submit'])){
include("../eng/connect.php");
$usid = $_SESSION["user_id"];
$curr_pass = $_POST['curr_pass'];
$new_pass = $_POST['new_pass'];
$conf_pass = $_POST['conf_pass'];
$run_pass = $_SESSION["<PASSWORD>"];
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($run_pass != $curr_pass) {
echo "<script>window.location=''../home/?p=change_password.php?error=2';</script>";
}
if($new_pass != $conf_pass) {
echo "<script>window.location=''../home/?p=change_password.php?error=2';</script>";
} else {
$updatepass = "UPDATE `account` SET `password` = <PASSWORD>' WHERE `usid` = '$usid'";
if ($conn -> query($addsql) === TRUE) {
echo "<script>window.location='../home/?p=change_password?error=0';</script>";
exit;
} else {
echo "<script>window.location='../home/?p=change_password?error=1';</script>";
exit;
}
}
}
mysqli_close($conn);
}
?>
</div>
<file_sep>/rpg/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<NAME>">
<title>RPG</title>
<link href="creation/css/mine.css" rel="stylesheet">
<link href="creation/css/styling.css" rel="stylesheet">
<style>
body {
padding-top: 60px;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a style="color: white;" class="navbar-brand" href="/rpg/">:- RPG</a>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h3>Random Password Generator Manager (RPG - Man)</h3>
<p class="lead">Manages secret and secured passwords for anyone to be used anywhere</p>
</div>
<div class="col-md-6">
<div class="jumbotron">
<h4 class="text-center">Random Password Genarator Manager</h4>
<p class="lead" style="font-size: 17px;">This is the free software that lets anyone to create a unique, strong, and secured password for the use of online or even offline accounts or systems <i>i.e Gmail, Facebook, Twitter, Instagram etc</i></p>
<p class="lead" style="font-size: 17px;">We also save your passwords as for future use and in case of forgetting, it is safe with RPG - Man</p></font>
<p><a class="btn btn-info" href="signup/">Create Account with RPG</a> or <a class="btn btn-success" href="login/">Login</a></p>
</div>
</div>
<div class="col-md-6">
<div class="jumbotron">
<form action="" method="POST">
<div class="form-group row">
<p style="font-size: 18px;">Enter the maximum number of password limit to be generated <i>eg: 16</i></p>
<div class="col-sm-10">
<input type="number" name="length" class="form-control" placeholder="Not Greater Than 61">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="checkbox" name="checkCapital" value="CapitalLetters" checked>Capital Letters
<input type="hidden" name="hidden" value="hidden" checked required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="checkbox" name="checkSmall" value="SmallLetters" checked>Small Letters
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="checkbox" name="checkNums" value="Numerals" checked>Numbers
</div>
</div>
<div class="form-group row">
<div class="col-sm-9">
<input type="submit" class="form-control btn btn-primary" placeholder="Not Greater Than 61" name="submit" value="Generate Password">
</div>
<div class="col-sm-3">
<a href="/rpg/" class="btn btn-default">Clear</a>
</div>
</div>
</form>
<?php
if (isset($_POST['submit'])) {
$conn = new mysqli("localhost","root","","pass_gen");
if(!$conn){
die("Connection Lost:".connect_error);
}
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
$length = $_POST['length'];
$password = '';
if (isset($_POST['checkCapital']) && !isset($_POST['checkSmall']) && !isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(0, 25)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(0, 25)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (isset($_POST['checkSmall']) && !isset($_POST['checkCapital']) && !isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(26, 51)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(26, 51)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (isset($_POST['checkNums']) && !isset($_POST['checkCapital']) && !isset($_POST['checkSmall']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(52, 61)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(52, 61)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (!isset($_POST['checkNums']) && !isset($_POST['checkCapital']) && !isset($_POST['checkSmall']) && isset($_POST['hidden'])) {
echo "<p class='lead' style='color: red;'>Please select at least one field above.<br/>No Password is Generated.</h3>";
} else if (isset($_POST['checkCapital']) && isset($_POST['checkSmall']) && !isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(0, 51)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(0, 51)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (isset($_POST['checkCapital']) && !isset($_POST['checkSmall']) && isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(0, 25)].$characters[mt_rand(52, 61)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$<PASSWORD>'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(0, 25)].$characters[mt_rand(52, 61)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (!isset($_POST['checkCapital']) && isset($_POST['checkSmall']) && isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(26, 61)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(26, 61)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else if (isset($_POST['checkCapital']) && isset($_POST['checkSmall']) && isset($_POST['checkNums']) && isset($_POST['hidden'])) {
if (empty($length)) {
for ($i = 0; $i < 8; $i++){
$password .= $characters[mt_rand(0, 61)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
if ($length > 61 || $length < 0){
echo "<p class='lead' style='color: red;'>Please try again<br/>The number entered is out of range<br/>No Password is Generated.</h3>";
}
if (!empty($length) && $length < 62 && $length > -1) {
for ($i = 0; $i < $length; $i++){
$password .= $characters[mt_rand(0, 61)];
}
echo "<p style='font-size: 16px;'>The Generated Password According To The Defined Length Here.</p>
<input id='password' type='text' value='$password'/>
<button class='glyphicon glyphicon-copy btn-sm btn-danger' data-copytarget='#password'></button>";
}
} else {
echo "<p style='font-size: 18px;'>Please retry randomizing again</p>";
}
}
?>
</div>
</div>
</div>
</div>
<script src="creation/js/jquery.js"></script>
<script src="creation/js/name.js"></script>
<script src="creation/js/bootstrap.min.js"></script>
</body>
</html><file_sep>/rpg/home/index.php
<?php
session_start();
include("lock.php");
include("../eng/connect.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="<NAME>">
<title>RPG</title>
<link href="../creation/css/mine.css" rel="stylesheet">
<link href="../creation/css/styling.css" rel="stylesheet">
<style>
body {
padding-top: 60px;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a style="color: white;" class="navbar-brand" href="../home/">:- RPG</a>
</div>
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<div class="btn-group">
<img src="kali/mine.jpg" data-toggle="dropdown" class="img-responsive img-circle dropdown-toggle" width="40" length="auto"/>
<ul class="dropdown-menu">
<?php
$usid = $_SESSION["user_id"];
$profile = "SELECT `full_name` FROM `account` WHERE `usid` = '$usid'";
$result = mysqli_query($conn, $profile);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
echo "<li><a><span class='glyphicon glyphicon-user'></span> ".$row['full_name']."</a></li>";
}
mysqli_close($conn);
?>
<li class="divider"></li>
<li><a href="settings.php"><span class="glyphicon glyphicon-cog"></span> Settings</a></li>
<li><a href="logout.php"><span class="glyphicon glyphicon-off"></span> Logout</a></li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<h3>Random Password Generator Manager (RPG - Man)</h3>
<p class="lead">It is a free software that manages secret and secured passwords for anyone to be used anywhere</p>
</div>
<div class="col-md-3">
<h3>Dashboard</h3><hr/>
<div class="list-group">
<a href="./?p=my_password" class="list-group-item list-group-item-info">My Passwords</a>
<a href="./?p=add_password" class="list-group-item list-group-item-primary">Add Password</a>
<a href="./?p=change_password" class="list-group-item list-group-item-danger">Change Password</a>
</div>
</div>
<div class="col-md-9">
<?php
if(isset($_GET["p"])){
$p = $_GET["p"];
switch($p){
case "my_password": require_once("my_passwords.php"); break;
case "add_password": require_once("add_password.php"); break;
case "change_password": require_once("change_password.php"); break;
default: require_once("my_passwords.php"); break;
}
}else{
require_once("my_passwords.php");
}
?>
</div>
</div>
</div>
<script src="../creation/js/jquery.js"></script>
<script src="../creation/js/name.js"></script>
<script src="../creation/js/bootstrap.min.js"></script>
</body>
</html>
|
385412c1f1e4a8a13f6d4f75a333b93b98ffad15
|
[
"SQL",
"PHP"
] | 10 |
PHP
|
LarryMatrix/random-password-generator
|
f3f62e6930a64364de62a4ff7d144be7c61a2e62
|
df71da9a05c6ff35808ebfcea72823f6723c1d12
|
refs/heads/master
|
<repo_name>whenTheMorningDark/vue-kai-admin<file_sep>/src/views/loadsh/array/compactAndConct.md
> 鲁迅说过:只有阅读过优秀库源码的人,才能配的上是真正的勇士。
## compact
> 创建一个新数组,包含原数组中所有的非假值元素。例如false, null,0, "", undefined, 和 NaN 都是被认为是“假值”。
注意以上的描述并不包括[],{}因为在js中,这个两个会进行隐式转换会把这两个值转换成为true。换句话来说该函数并不会去过滤这两个值。

官方代码:
```javascript
export function compact(array){
let resIndex = 0;
const result = []
if(array == null){ // 会把undefined给排除掉 因为 undefined == null 为true
return result
}
for(const value of array){
if(value){
result[resIndex++] = value
}
}
return result
}
```
个人理解代码:
```javascript
export function compact(array){
let resIndex = 0;
const result = []
if(array == null){ // 会把undefined给排除掉 因为 undefined == null 为true
return result
}
result = array.filter(v=>Boolean(v))
return result
}
```
直接利用filter进行遍历,利用boolean,来对元素进行真假转换。
## concat
>创建一个新数组,将array与任何数组 或 值连接在一起。
```javascript
var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(other);
// => [1, 2, 3, [4]]
console.log(array);
// => [1]
```
相对来说,concat函数所依赖的工具函数就多几个。
1. [arrayPush](https://github.com/lodash/lodash/blob/ded9bc66583ed0b4e3b7dc906206d40757b4a90a/dist/lodash.js#L652)数组添加方法
2. [copyArray](https://github.com/lodash/lodash/blob/ded9bc66583ed0b4e3b7dc906206d40757b4a90a/dist/lodash.js#L2933)拷贝数组元素
3. [baseFlatten](https://github.com/lodash/lodash/blob/ded9bc66583ed0b4e3b7dc906206d40757b4a90a/dist/lodash.js#L2933)扁平层级数组
```javascript
export function concat(){
let length = arguments.length; // 获取参数的个数
if (!length) {
return [];
}
let args = Array(length - 1); // 取除了第一个参数以外的参数的长度
let array = arguments[0]; // 取出数组的第一项
let index = length;
while (index--) {
args[index - 1] = arguments[index];
}
console.log(args); // 把第一个参数也就是目标数组,当作-1项添加为array
// 判断一个参数是否是数组,不是就把它转换成为数组,如果是数组则拷贝一份数组,再使用arrayPush方法,把每项的参数推进数组里面去。
return arrayPush(Array.isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
}
```
## copyArray
拷贝数组,此操作不会影响到原有的数组。
|参数| 说明 |
|--|--|
| soure | 原数组参数 |
| array| 结果数组 |
```javascript
export function copyArray(source,array){
let index = -1;
let length = source.length;
array || (array = Array(length));
while(++index < length){
array[index] = source[index]
}
return array
}
```
## baseFlatten
该方法主要用于扁平数组的操作
```javascript
export function baseFlatten(array, depth, predicate, isStrict, result) {
let index = -1;
let length = array.length;
predicate || (predicate = isFlattenable); // isFlattenable 判断是否是数组
result || (result = []);
while (++index < length) {
let value = array[index];
console.log(value);
if (depth > 0 && predicate(value)) { // 如果层级大于0并且该项是数组的话
if (depth > 1) { // 如果需要递归的层级大于1的情况则继续递归下去解套
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else { // 如果需要递归的层级为1的情况,则把所有的项添加目标数组
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
isFlattenable(value){
return Array.isArray(value)
}
```
发散思考,该函数只要是通过depth变量,来控制筛选的层级,那么我希望实现扁平所有的数组,那应该怎么操作呢?
```javascript
function flattern(arr) {
return arr.reduce((cur, next) => cur.concat(Array.isArray(next) ? flattern(next) : next), []);
}
```
## arrayPush
添加元素进入原数组,会改变原数组结构,类似push方法
```javascript
let index = -1;
let length = values.length;
let offset = array.length;
while (++index < length) {
array[index + offset] = values[index];
}
return array;
```
## 总结
1. ++index和index++不同之处,++i就是先加后用,i++就是先用后加。前置++下标不会越界,后置++下标越界。
2. lodash库操作数组一般都不会影响原有数组。
<file_sep>/src/components/selectProvince/README.md
**业务背景**
在我业务需求中,需要有个省份区城市联动的组件,并且该组件的开发也是基于 elementUi 原有的效果上面去。在原有的 elementui 库中并没有这样的组件,所以也只能自己手写一个,效果如下:

**需求分析** 1.需要包含国内的省份,省份下面所对应的城市,城市下方所对应的区,街道不做要求。 2.需要配置每个下拉列表是否可以选择状态,这个是需要更加具体场景进行分析,需要对外提高可控制列表是否可以选择。例如:一层选择了**广东省**后,某些场景**广州市**不能够被选择到。
**基础组件选择**
基础组件还是还是采用 el-select 作为基础模板,进行二次开发,基本 vue 结构如下:
```javascript
<template>
<div class="selectProvinceWrapper" :style="{width:width+'px'}">
<el-select
v-model="province"
:size="size"
placeholder="请选择省份"
clearable
@change="getCities"
:disabled="provinceDisabled"
filterable
>
<el-option
v-for="item in provinceOptions"
:key="item.value"
:value="item.value"
:label="item.label"
:disabled="item.disabled"
>
</el-option>
</el-select>
<el-select
v-model="city"
:size="size"
placeholder="请选择城市"
clearable
@change="getArea"
:disabled="cityDisabled"
filterable
>
<el-option
v-for="item in cityOptions"
:key="item.value"
:value="item.value"
:label="item.label"
:disabled="item.disabled"
>
</el-option>
</el-select>
<el-select
v-model="area"
:size="size"
placeholder="请选择地区"
clearable
:disabled="areaDisable"
@change="areaChange"
filterable
>
<el-option
v-for="item in areaOptions"
:key="item.value"
:value="item.value"
:label="item.label"
:disabled="item.disabled"
>
</el-option>
</el-select>
</div>
</template>
```
对于每个省份,城市和地区,我们都有一份 json 数据来进行维护,具体数据地址可参考[数据地址](https://github.com/whenTheMorningDark/vue-kai-admin/blob/master/src/components/selectProvince/districts.js)
**确定对外接受参数和对外暴露事件**
```javascript
props: {
width: { // 外围容器的宽度
type: [String, Number],
default: "100%"
},
size: { // select的大小
type: String,
default: "small"
},
defaultProvince: { // 默认的省份
type: [String, Number],
default: ""
},
defaultCity: { // 默认的城市
type: [String, Number],
default: ""
},
defaultArea: { // 默认的地区
type: [String, Number],
default: ""
},
provinceDisabled: { // 省份是否可以编辑
type: Boolean,
default: false
},
disableProvinceOptions: { // 省份的options项目是否可以编辑
type: Array,
default: () => []
},
cityDisabled: { // 城市是否可以编辑
type: Boolean,
default: false
},
disableCityOptions: {
type: Array,
default: () => []
},
areaDisable: { // 地区是否可以编辑
type: Boolean,
default: false
},
disableAreaOptions: { // 地区是否可以编辑
type: Array,
default: () => []
},
},
```
**业务代码编写**
由于我们省份,城市和地区的参数都是为一些特殊的数字,在编写业务的过程中,我们往往会忘记某个城市所对应的编号,所以我们有可能需要通过中文来进行逻辑判断。
```javascript
// 判断是否是中文
isChineseChar(str) {
var reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
return reg.test(str);
},
// 获取省市区的默认数组
getDefaultValue(targetOptions = [], value = "") {
let targetStr = "";
if (targetOptions.length === 0 || value.length === 0) {
return targetStr;
}
if (value.length > 0) {
if (this.isChineseChar(value)) { // 如果是中文的情况
let targetObj = targetOptions.find(v => v.label === value) || {};
targetStr = targetObj.value;
} else {
targetStr = value;
}
}
return targetStr;
},
```
另外每次下拉框值的改变,我们都需要对外暴露出当前的 label 和 value 以供给业务使用,
```javascript
// 获取key-value
getMapKeyValue(options, code) {
return {
label: this.getOptionsLabel(options, code),
value: code
};
},
```
参数说明:
参数 | 类型
-------- | -----
defaultProvince| 【String,number】默认省份为空
defaultCity| 【String,number】默认城市为空
defaultArea | 【String,number】默认地区为空
disableProvinceOptions| 【Array】默认省份下拉项目不可编辑
disableCityOptions| 【Array】默认城市下拉项目不可编辑
disableAreaOptions| 【Array】默认地区下拉项目不可编辑
size| 【String】默认下拉框大小为 small
provinceDisabled| 【Boolean】默认省份下拉框是否可以编辑
cityDisabled| 【String】默认城市下拉框是否可以编辑
areaDisable| 【String】默认地区下拉框是否可以编辑
**事件说明**
|事件|说明
|--|--|
| province | 省份选择的回调 val={value:"",label:""} |
| city| 城市选择的回调 val={value:"",label:""} |
| area| 地区选择的回调 val={value:"",label:""} |
**方法说明**
|方法|说明 |
|--|--|
| getSelectData | 获取当前下拉选择的数据 |
| setOptionsDisabled| 设置下拉项目是否可选 参数 1:type:"city area province".参数 2:Array:[] 不可选择的项的 code 或者中文
**地址**
完整源码地址在[组件地址](https://github.com/whenTheMorningDark/vue-kai-admin/blob/master/src/components/selectProvince/index.vue)
<file_sep>/src/views/echarts/echartComponent/mixins/init.js
/* eslint-disable indent */
let echarts = require("echarts/lib/echarts");
require("echarts/lib/chart/bar");
require("echarts/lib/chart/line");
require("echarts/lib/chart/pie");
require("echarts/lib/chart/scatter");
require("echarts/lib/chart/radar");
require("echarts/lib/chart/map");
require("echarts/lib/chart/tree");
require("echarts/lib/chart/treemap");
require("echarts/lib/chart/graph");
require("echarts/lib/chart/gauge");
require("echarts/lib/chart/funnel");
require("echarts/lib/chart/parallel");
require("echarts/lib/chart/sankey");
require("echarts/lib/chart/boxplot");
require("echarts/lib/chart/candlestick");
require("echarts/lib/chart/effectScatter");
require("echarts/lib/chart/lines");
require("echarts/lib/chart/heatmap");
require("echarts/lib/chart/pictorialBar");
require("echarts/lib/chart/themeRiver");
require("echarts/lib/chart/sunburst");
require("echarts/lib/chart/custom");
require("echarts/lib/component/grid");
require("echarts/lib/component/polar");
require("echarts/lib/component/geo");
require("echarts/lib/component/singleAxis");
require("echarts/lib/component/parallel");
require("echarts/lib/component/calendar");
require("echarts/lib/component/graphic");
require("echarts/lib/component/toolbox");
require("echarts/lib/component/tooltip");
require("echarts/lib/component/axisPointer");
require("echarts/lib/component/brush");
require("echarts/lib/component/title");
require("echarts/lib/component/timeline");
require("echarts/lib/component/markPoint");
require("echarts/lib/component/markLine");
require("echarts/lib/component/markArea");
require("echarts/lib/component/legendScroll");
require("echarts/lib/component/legend");
require("echarts/lib/component/dataZoom");
// require("echarts/lib/component/dataZoomInside");
// require("echarts/lib/component/dataZoomSlider");
// require("echarts/lib/component/visualMap");
// require("echarts/lib/component/visualMapContinuous");
// require("echarts/lib/component/visualMapPiecewise");
// require("zrender/lib/vml/vml");
// require("zrender/lib/svg/svg");
// 引入提示框和标题组件
// require("echarts/lib/component/tooltip");
// require("echarts/lib/component/title");
export default {
props: {
id: [String],
optionsData: {},
},
data() {
return {
myChart: null,
};
},
methods: {
resizeFun() {
this.myChart.resize();
},
setOption(optionsData) {
console.log(optionsData);
this.myChart.setOption(optionsData);
},
init() {
this.myChart = echarts.init(document.getElementById(this.id));
this.setOption(this.optionsData);
},
},
mounted() {
this.init();
},
};<file_sep>/src/views/echarts/echartComponent/data/scatter/index.js
import { fileToData } from "../utils/common";
const componentsContext = require.context("./", true, /(vue|js)$/);
export const scatterChildren = fileToData(componentsContext);
<file_sep>/src/components/mxGraph/mxEvent.js
/* eslint-disable eol-last */
/* eslint-disable new-cap */
import {
mxEvent as MxEvent,
mxUndoManager,
mxKeyHandler,
mxClipboard,
// mxPerimeter
} from "mxgraph/javascript/mxClient";
// 主要处理键盘触发事件
export default {
mounted () {
console.log("mixs");
// this.setKeyHandler()
},
methods: {
setKeyHandler () {
console.log(this.graph);
const graph = this.graph;
const undoManager = new mxUndoManager();
const listener = function (sender, evt) {
// console.log(undoManager.undoableEditHappened);
undoManager.undoableEditHappened(evt.getProperty("edit"));
};
graph.getModel().addListener(MxEvent.UNDO, listener);
graph.getView().addListener(MxEvent.UNDO, listener);
const keyHandler = new mxKeyHandler(graph);
// 绑定删除键
keyHandler.bindKey(46, (evt) => {
if (graph.isEnabled()) {
graph.removeCells();
let veterxs = this.getAllCell();
veterxs.forEach(v => {
this.edgeTo(v);
});
// this.$confirm("确定删除吗")
// .then(res => {
// graph.removeCells();
// let veterxs = this.getAllCell();
// veterxs.forEach(v => {
// this.edgeTo(v);
// });
// })["catch"](cancel => console.log(cancel));
}
});
// 绑定Ctrl+A全选
keyHandler.bindControlKey(65, function (evt) {
if (graph.isEnabled()) {
graph.selectAll();
}
});
// 绑定Ctrl+C复制节点
keyHandler.bindControlKey(67, function (evt) {
if (graph.isEnabled()) {
var cells = graph.getSelectionCells();
if (cells.length > 0) {
cells = graph.cloneCells(cells);
var newCells = [];
// 修改 cells 中的元素属性
cells.forEach(function (cell, i) {
cell.id = "";
cell.value = (cell.value || "");
// cell.uid = vm.$utils.uuid()
newCells.push(cell);
});
mxClipboard.setCells(newCells);
mxClipboard.paste(graph);
}
}
});
// 绑定Ctrl+Z撤销
keyHandler.bindControlKey(90, (evt) => {
if (graph.isEnabled()) {
undoManager.undo();
// if(this)
let veterxs = this.getAllCell();
console.log(veterxs);
// let edges = vm.getAllEdge();
veterxs.forEach(v => {
this.edgeTo(v);
});
}
});
// 绑定Ctrl+Y重做
keyHandler.bindControlKey(89, (evt) => {
if (graph.isEnabled()) {
undoManager.redo();
let veterxs = this.getAllCell();
veterxs.forEach(v => {
this.edgeTo(v);
});
}
});
graph.isCellDeletable = function (cell) {
return true;
};
}
}
};<file_sep>/src/views/echarts/echartComponent/data/bar/barAnimationDelay/barAnimationDelay.js
/* eslint-disable indent */
import { defaultTtileKeys } from "../../../../rightTool/components/commonData/commonData";
import { cloneDeep } from "lodash";
import { legendData } from "../../../../rightTool/components/commonData/legendData";
import { xData } from "../../../../rightTool/components/commonData/xData";
let currentLegendData = {
data: ["bar", "bar2"],
};
var xAxisData = [];
var data1 = [];
var data2 = [];
for (var i = 0; i < 100; i++) {
xAxisData.push("类目" + i);
data1.push((Math.sin(i / 5) * (i / 5 - 10) + i / 6) * 5);
data2.push((Math.cos(i / 5) * (i / 5 - 10) + i / 6) * 5);
}
let currentXdata = {
data: xAxisData,
splitLine: {
show: false,
},
};
export const barAnimationDelay = {
name: "柱状图动画延迟",
type: "bar",
images: require("@/assets/images/bar-animation-delay.jpg"),
optionsData: {
title: JSON.parse(JSON.stringify(defaultTtileKeys)),
legend: Object.assign({}, cloneDeep(legendData), currentLegendData),
toolbox: {
// y: 'bottom',
feature: {
magicType: {
type: ["stack", "tiled"],
},
dataView: {},
saveAsImage: {
pixelRatio: 2,
},
},
},
tooltip: {},
xAxis: Object.assign({}, cloneDeep(xData), currentXdata),
yAxis: {},
series: [
{
name: "bar",
type: "bar",
data: data1,
animationDelay: function(idx) {
return idx * 10;
},
},
{
name: "bar2",
type: "bar",
data: data2,
animationDelay: function(idx) {
return idx * 10 + 100;
},
},
],
animationEasing: "elasticOut",
animationDelayUpdate: function(idx) {
return idx * 5;
},
},
};
<file_sep>/src/utils/common.js
/* eslint-disable indent */
/* eslint-disable require-jsdoc */
export const debounce = (func, wait, immediate) => {
let timeout;
return function () {
const context = this;
const args = arguments;
if (timeout) {
clearTimeout(timeout);
}
if (immediate) {
const callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait);
if (callNow) {
func.apply(context, args);
}
} else {
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
}
};
};
export function throttle(func, wait) {
var previous = 0;
return function () {
const now = Date.now();
const context = this;
const args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
};
}
// 判断元素是否是undefine
export const isUndefined = (val) => val === void 0;
// 判断元素是否是对象
export const isObject = (obj) => Object.prototype.toString.call(obj) === "[object Object]";
// 根据路径寻找元素的value
// let obj = {
// a: {
// b: {
// c: ["asddsa"]
// }
// }
// };
// console.log(getPropByPath(obj, "a.b.c.0"));
export function getPropByPath(obj, path, strict) {
let tempObj = obj;
path = path.replace(/\[(\w+)\]/g, ".$1");
path = path.replace(/^\./, "");
let keyArr = path.split(".");
let i = 0;
for (let len = keyArr.length; i < len - 1; ++i) {
if (!tempObj && !strict) {
break;
}
let key = keyArr[i];
if (key in tempObj) {
tempObj = tempObj[key];
} else {
if (strict) {
throw new Error("please transfer a valid prop path to form item!");
}
break;
}
}
return {
o: tempObj,
k: keyArr[i],
v: tempObj ? tempObj[keyArr[i]] : null,
};
}
// let obj = {
// key1: 'str1',
// key2: {
// key3: 'str3'
// },
// key4: {
// key5: {
// key6: 'str6',
// key7: 'str7'
// },
// key8: 'str8'
// },
// key9: 'str9'
// };
// searchKeys(obj, 'str3') return 'key3, key2'
export function searchKeys(obj, value) {
for (let key in obj) {
if (obj[key] === value) {
// 找到了 value
return key;
} else {
// 不是要找的 value
if (typeof obj[key] === "object") {
// 该值为对象
let temp = searchKeys(obj[key], value);
console.log(temp);
if (temp) {
// temp 不是 undefined,找到了 value
return `${temp}, ${key}`;
}
}
}
}
}<file_sep>/src/views/echarts/utils/event.js
/* eslint-disable indent */
import { mapGetters } from "vuex";
export default {
data() {
return {
steps: 5,
};
},
computed: {
...mapGetters(["currentTarget"]),
},
methods: {
move(direction) {
let targetKeys = [40, 37, 39, 38];
if (
!targetKeys.includes(direction) ||
this.currentTarget === null ||
Object.keys(this.currentTarget).length === 0
) {
return;
}
let map = {
40: this.downFun,
37: this.leftFun,
39: this.rightFun,
38: this.upFun,
};
map[direction]();
},
// 向下的方法
downFun() {
let y = this.currentTarget.y + this.steps;
this.$store.commit("echart/changeCurrentTagetAttr", {
key: "y",
value: y,
});
},
// 向上的方法
upFun() {
let y = this.currentTarget.y - this.steps;
this.$store.commit("echart/changeCurrentTagetAttr", {
key: "y",
value: y,
});
},
// 向左的方法
leftFun() {
let x = this.currentTarget.x - this.steps;
this.$set(this.currentTarget, "x", x);
this.$store.commit("echart/changeCurrentTagetAttr", {
key: "x",
value: x,
});
},
// 向右的方法
rightFun() {
let x = this.currentTarget.x + this.steps;
this.$store.commit("echart/changeCurrentTagetAttr", {
key: "x",
value: x,
});
},
},
mounted() {
window.addEventListener("keydown", (e) => this.move(e.keyCode));
},
destory() {
window.removeEventListener("keydown", (e) => this.move(e.keyCode));
},
};
<file_sep>/src/views/echarts/echartComponent/data/line/lineSmooth/lineSmooth.js
/* eslint-disable indent */
import { defaultTtileKeys } from "../../../../rightTool/components/commonData/commonData";
import { cloneDeep } from "lodash";
import { legendData } from "../../../../rightTool/components/commonData/legendData";
export const lineSmooth = {
name: "平滑折线图",
type: "line",
images: require("@/assets/images/line-smooth.jpg"),
optionsData: {
title: defaultTtileKeys,
legend: cloneDeep(legendData),
xAxis: {
type: "category",
data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
},
yAxis: {
type: "value",
},
series: [
{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: "line",
smooth: true,
},
],
},
};
<file_sep>/src/store/getters.js
const getters = {
sidebar: (state) => state.app.sidebar,
language: (state) => state.app.language,
size: (state) => state.app.size,
device: (state) => state.app.device,
permission_routes: (state) => state.permission.routes,
token: (state) => state.user.token,
roles: (state) => state.user.userInfo.userName, // 当前用户名称
visitedViews: (state) => state.tagsView.visitedViews,
cachedViews: (state) => state.tagsView.cachedViews,
currentTarget: (state) => state.echart.currentTarget
};
// eslint-disable-next-line eol-last
export default getters;<file_sep>/src/layout/components/index.js
/* eslint-disable eol-last */
/* eslint-disable indent */
export {
default as AppMain
}
from "./AppMain";
export {
default as Sidebar
}
from "./Sidebar";
export {
default as navBar
}
from "./navBar";
export {
default as TagsView
}
from "./TagsView";<file_sep>/src/views/echarts/echartComponent/data/bar/barWaterfall/barWaterfall.js
/* eslint-disable indent */
import { defaultTtileKeys } from "../../../../rightTool/components/commonData/commonData";
import { legendData } from "../../../../rightTool/components/commonData/legendData";
import { cloneDeep } from "lodash";
import { xData } from "../../../../rightTool/components/commonData/xData";
let currentXdata = {
type: "category",
splitLine: {
show: false,
},
data: (function() {
var list = [];
for (var i = 1; i <= 11; i++) {
list.push("11月" + i + "日");
}
return list;
})(),
};
let currentLegendData = {
data: ["支出", "收入"],
left: 10,
show: true,
};
export const barWaterfall = {
name: "阶梯瀑布图",
type: "bar",
images: require("@/assets/images/bar-waterfall2.jpg"),
optionsData: {
title: JSON.parse(JSON.stringify(defaultTtileKeys)),
tooltip: {
trigger: "axis",
axisPointer: {
// 坐标轴指示器,坐标轴触发有效
type: "shadow", // 默认为直线,可选为:'line' | 'shadow'
},
formatter: function(params) {
var tar;
if (params[1].value !== "-") {
tar = params[1];
} else {
tar = params[0];
}
return tar.name + "<br/>" + tar.seriesName + " : " + tar.value;
},
},
legend: Object.assign({}, cloneDeep(legendData), currentLegendData),
grid: {
left: "3%",
right: "4%",
bottom: "3%",
containLabel: true,
},
xAxis: Object.assign({}, cloneDeep(xData), currentXdata),
yAxis: {
type: "value",
},
series: [
{
name: "辅助",
type: "bar",
stack: "总量",
itemStyle: {
barBorderColor: "rgba(0,0,0,0)",
color: "rgba(0,0,0,0)",
},
emphasis: {
itemStyle: {
barBorderColor: "rgba(0,0,0,0)",
color: "rgba(0,0,0,0)",
},
},
data: [0, 900, 1245, 1530, 1376, 1376, 1511, 1689, 1856, 1495, 1292],
},
{
name: "收入",
type: "bar",
stack: "总量",
label: {
show: true,
position: "top",
},
data: [900, 345, 393, "-", "-", 135, 178, 286, "-", "-", "-"],
},
{
name: "支出",
type: "bar",
stack: "总量",
label: {
show: true,
position: "bottom",
},
data: ["-", "-", "-", 108, 154, "-", "-", "-", 119, 361, 203],
},
],
},
};
<file_sep>/src/views/mxgraph/components/index.js
/* eslint-disable eol-last */
/* eslint-disable indent */
export {
default as Arrange
}
from './Arrange'
export {
default as Style
}
from './Style'
export {
default as TextStyle
}
from './TextStyle'<file_sep>/src/components/G2Template/data/g2Line.js
/* eslint-disable comma-dangle */
/* eslint-disable indent */
// 这是折线图默认的数据
import { randomStr } from "@/utils";
export const g2LineData = [
{
year: "1991",
value: 3,
},
{
year: "1992",
value: 4,
},
{
year: "1993",
value: 3.5,
},
{
year: "1994",
value: 5,
},
{
year: "1995",
value: 4.9,
},
{
year: "1996",
value: 6,
},
{
year: "1997",
value: 7,
},
{
year: "1998",
value: 9,
},
{
year: "1999",
value: 13,
},
];
export const baseOptions = {
container: "g2Line" + randomStr(3),
width: 400,
height: 250,
};
<file_sep>/src/views/echarts/echartComponent/data/line/defaultline/defaultline.js
/* eslint-disable indent */
import { defaultTtileKeys } from "../../../../rightTool/components/commonData/commonData";
import { legendData } from "../../../../rightTool/components/commonData/legendData";
console.log(defaultTtileKeys);
export const defaultline = {
name: "默认折线图",
type: "line",
images: require("@/assets/images/line-simple.jpg"),
optionsData: {
title: JSON.parse(JSON.stringify(defaultTtileKeys)),
legend: legendData,
xAxis: {
type: "category",
data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
},
yAxis: {
type: "value",
},
series: [
{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: "line",
},
],
},
};
<file_sep>/src/components/virtualList/README.MD
**前提:**
在我负责一个模块中,有一个是日志管理模块,它会输出很多很多的操作的日志,起初与后台对接对接的时候并没有考虑到性能渲染问题,只是简单的用 v-for 把所有的数据都渲染出来,那么这样导致的后果就是页面卡顿,这个原因是你的模块中渲染出太多的 DOM 节点导致,为了避免这样的问题我采取了虚拟列表来进行渲染。
**什么是虚拟列表**
虚拟列表就是一个按需渲染的过程,简单来说就是渲染你所看到的内容,对于你非可视的内容不进行渲染,达到性能的优化。

在图中我们可以看到,你所能看到的就是元素 7 到元素 14 的内容,当我们的滚动条进行滚动的时候,我们只需要通过滚动条的 scrollTop 对 startIndex 和 endIndex 进行改变,此外我们还需要一个 data.length \* itemHeight 的高度容器去撑开外围 DIV,从而去获取滚动条。
实现虚拟列表就是在处理用户滚动时,要改变列表在可视区域的渲染部分,其具体步骤如下:
计算当前可见区域起始数据的 startIndex
计算当前可见区域结束数据的 endIndex
计算当前可见区域的数据,并渲染到页面中
计算 startIndex 对应的数据在整个列表中的偏移位置 startOffset,并设置到列表上
计算 endIndex 对应的数据相对于可滚动区域最底部的偏移位置 endOffset,并设置到列表上
这里的滚动条组件,我是使用 element 中 el-scrollBar 滚动条组件。**我们假设现在每个 item 都是固定的高度值为 30。**
virtualList/index.vue
```javascript
<template>
<el-scrollbar class="virtualList z-h-100" ref="scrollbar">
<div class="virtualList-phantom" ref="content" :style="{height:contentHeight}">
<div class="virtualList-wrapper" ref="wrapper">
<div
class="virtualList-phantom-item"
v-for="item in visibleData" :key="item.id"
:style="{height:itemHeight+'px'}"
>
<!-- <slot ref="slot" :item="item.item"></slot> -->
<slot ref="slot" :item="item"></slot>
</div>
</div>
</div>
</el-scrollbar>
</template>
<script>
export default {
name: "virtualList",
props: {
listData: {
type: Array,
default: () => []
},
itemHeight: {
type: Number,
default: 30
}
},
computed: {
contentHeight() {
return this.listData.length * this.itemHeight + "px"; // 计算总高度用来撑开滚动条
}
},
data() {
return {
visibleData: [] // 可视的数据
};
},
mounted () {
this.updateVisibleData();
this.handleScroll();
},
methods: {
updateVisibleData(scrollTop = 0) {
const visibleCount = Math.ceil(this.$el.clientHeight / this.itemHeight);
const start = Math.floor(scrollTop / this.itemHeight);
const end = start + visibleCount;
this.visibleData = this.listData.slice(start, end);
let pH = start * this.itemHeight;
this.$refs.content.style.webkitTransform = `translate3d(0, ${-pH}px, 0)`;
this.$refs.wrapper.style.webkitTransform = `translate3d(0, ${pH * 2}px, 0)`;
},
handleScroll() {
this.$nextTick(() => {
let scrollbarEl = this.$refs.scrollbar.wrap;
scrollbarEl.onscroll = () => {
var st = this.$refs.scrollbar.$refs.wrap.scrollTop; // 滚动条距离顶部的距离
this.updateVisibleData(st);
};
});
},
}
};
</script>
<style lang="scss">
.z-h-100{
height: 100%;
}
.virtualList{
width:100%;
height:100%;
position: relative;
overflow: hidden;
border: 1px solid #aaa;
.virtualList-phantom{
width:100%;
}
.virtualList-wrapper{
position: absolute;
left: 0;
top: 0;
right: 0;
}
.el-scrollbar__wrap{
overflow-x: hidden;
}
}
</style>
```
item.vue
```javascript
<template>
<p>
<span style="color:red">{{item.id}}</span>
{{item.value}}
</p>
</template>
<script>
export default {
props: {
// 所有列表数据
item: {
type: Object,
default: () => ({})
}
}
};
</script>
<style scoped>
</style>
```
父组件调用
```javascript
<template>
<div class="virtualListView">
<virtualList :listData="data" v-slot="slotProps">
<Item :item="slotProps.item"/>
</virtualList>
</div>
</template>
<script>
import virtualList from "@/components/virtualList/index";
import Item from "@/components/virtualList/item";
export default {
name: "virtualListView",
components: {
virtualList,
Item
},
data() {
return {
data: Array.from({ length: 3000 }, (k, v) => ({
date: "2016-05-02" + v,
name: "王小虎" + v,
value: "上海市普陀区金沙江路 1518 弄" + v,
id: v
}))
};
}
};
</script>
<style>
.virtualListView{
padding:10px;
height: 100%;
}
</style>
```
通过打开 F12 我们可以发现,你所需渲染的节点,你所看不到的 dom 节点,都会动态的消失和隐藏掉。

**不定高度的虚拟列表**
由于业务的需求,这个时候每个列表的高度,都是不统一的,有些文字长,有些文字短,那么这种情况就很烦恼了,由于高度不知道,我们无法计算出总高度,那么也无法计算出当前渲染显示出多少个列表元素,为了解决这个问题,我可是撒费了苦心,都不知道查阅了多少资料和熬掉了多少根头发。
我们需要一个 estimatedItemSize 变量去预设置每个列表的高度,为了数据缓存起见,我们需要一个 position 数组来对每个 item 存放它的下标,高度(预设高度或者真实高度),item 距离顶部的大小,当前列表的总高度。
```javascript
<template>
<el-scrollbar class="virtualList z-h-100" ref="scrollbar">
<div ref="list" :style="{height:contentHieghtS+'px'}" class="infinite-list-container">
<div ref="content" class="infinite-list">
<div class="infinite-list-item" ref="items" :id="item._index" :key="item._index" v-for="item in visibleData">
<slot ref="slot" :item="item.item"></slot>
</div>
</div>
</div>
</el-scrollbar>
</template>
<script>
export default {
name: "VirtualList",
props: {
// 所有列表数据
listData: {
type: Array,
default: () => []
},
// 预估高度
estimatedItemSize: {
type: Number,
required: true
},
},
computed: {
_listData() {
return this.listData.map((item, index) => ({
_index: `_${index}`,
item
}));
},
visibleData() { // 可见的数据
let start = this.start;
let end = this.end;
return this._listData.slice(start, end);
},
visibleCount() { // 可视区域存放的数量
return Math.ceil(this.screenHeight / this.estimatedItemSize);
},
},
created() {
this.initPositions();
},
mounted() {
this.screenHeight = this.$el.clientHeight;
this.start = 0;
this.end = this.start + this.visibleCount;
},
updated() {
console.log("updated");
this.$nextTick(() => {
if (!this.$refs.items || !this.$refs.items.length) {
return ;
}
// 更新列表总高度
let height = this.positions[this.positions.length - 1].bottom;
this.contentHieghtS = height;
});
},
data() {
return {
// 可视区域高度
screenHeight: 0,
// 起始索引
start: 0,
// 结束索引
end: 0,
contentHieghtS: 0 // 内容撑开的真实高度
};
},
methods: {
initPositions() {
this.positions = this.listData.map((d, index) => ({
index,
height: this.estimatedItemSize,
top: index * this.estimatedItemSize,
bottom: (index + 1) * this.estimatedItemSize
})
);
},
}
};
</script>
<style lang="scss">
.z-h-100{
height: 100%;
}
.el-scrollbar__wrap{
overflow-x: hidden !important;
}
// .virtualList{
// .el-scrollbar__wrap{
// overflow-x: hidden;
// }
// }
.infinite-list-container {
overflow: hidden;
position: relative;
height: 900px;
// -webkit-overflow-scrolling: touch;
}
.infinite-list-phantom {
position: absolute;
left: 0;
top: 0;
right: 0;
z-index: -1;
}
.infinite-list {
left: 0;
right: 0;
top: 0;
position: absolute;
}
.infinite-list-item {
padding: 5px;
color: #555;
box-sizing: border-box;
border-bottom: 1px solid #999;
}
/* .infinite-list-scrollItem{
padding: 5px;
color: #555;
box-sizing: border-box;
border-bottom: 1px solid #999;
} */
</style>
```
**注意**:列表的最后一项的 bottom 值是当前列表的总高度。虽然目前是能够渲染出来数据,但仍然无法变化到每个 item 的高度,目前他们的高度还是由父组件传递过来的 estimatedItemSize 值(假设 100),所以我们还需要在 update 生命周期中改变每个列表当前的 height 值,
```javascript
<script>
export default {
name: "VirtualList",
props: {
// 所有列表数据
listData: {
type: Array,
default: () => []
},
// 预估高度
estimatedItemSize: {
type: Number,
required: true
},
},
computed: {
_listData() {
return this.listData.map((item, index) => ({
_index: `_${index}`,
item
}));
},
visibleData() { // 可见的数据
let start = this.start;
let end = this.end;
return this._listData.slice(start, end);
},
visibleCount() { // 可视区域存放的数量
return Math.ceil(this.screenHeight / this.estimatedItemSize);
},
},
created() {
this.initPositions();
},
mounted() {
this.screenHeight = this.$el.clientHeight;
this.start = 0;
this.end = this.start + this.visibleCount;
},
updated() {
console.log("updated");
this.$nextTick(() => {
if (!this.$refs.items || !this.$refs.items.length) {
return ;
}
// 获取真实元素大小,修改对应的尺寸缓存
this.updateItemsSize();
// 更新列表总高度
let height = this.positions[this.positions.length - 1].bottom;
this.contentHieghtS = height;
});
},
data() {
return {
// 可视区域高度
screenHeight: 0,
// 起始索引
start: 0,
// 结束索引
end: 0,
contentHieghtS: 0 // 内容撑开的真实高度
};
},
methods: {
// 初始化位置
initPositions() {
this.positions = this.listData.map((d, index) => ({
index,
height: this.estimatedItemSize,
top: index * this.estimatedItemSize,
bottom: (index + 1) * this.estimatedItemSize
})
);
},
// 获取列表项的当前尺寸
updateItemsSize() {
let nodes = this.$refs.items;
nodes.forEach((node) => {
let rect = node.getBoundingClientRect();
let height = rect.height;
let index = +node.id.slice(1);
let oldHeight = this.positions[index].height;
let dValue = oldHeight - height;
// 存在差值
if (dValue) {
this.positions[index].bottom = this.positions[index].bottom - dValue;
this.positions[index].height = height;
for (let k = index + 1;k < this.positions.length; k++) { // 后面的元素top和bottom也要发生变化
this.positions[k].top = this.positions[k - 1].bottom;
this.positions[k].bottom = this.positions[k].bottom - dValue;
}
}
});
},
}
};
</script>
```
另外还需要获取可视区域的偏移值,保证可视区域在容器里面
```javascript
<template>
<el-scrollbar class="virtualList z-h-100" ref="scrollbar">
<div ref="list" :style="{height:contentHieghtS+'px'}" class="infinite-list-container">
<div ref="content" class="infinite-list">
<div class="infinite-list-item" ref="items" :id="item._index" :key="item._index" v-for="item in visibleData">
<slot ref="slot" :item="item.item"></slot>
</div>
</div>
</div>
</el-scrollbar>
</template>
<script>
export default {
name: "VirtualList",
props: {
// 所有列表数据
listData: {
type: Array,
default: () => []
},
// 预估高度
estimatedItemSize: {
type: Number,
required: true
},
},
computed: {
_listData() {
return this.listData.map((item, index) => ({
_index: `_${index}`,
item
}));
},
visibleData() { // 可见的数据
let start = this.start;
let end = this.end;
return this._listData.slice(start, end);
},
visibleCount() { // 可视区域存放的数量
return Math.ceil(this.screenHeight / this.estimatedItemSize);
},
},
created() {
this.initPositions();
},
mounted() {
this.screenHeight = this.$el.clientHeight;
this.start = 0;
this.end = this.start + this.visibleCount;
this.handleScroll();
},
updated() {
console.log("updated");
this.$nextTick(() => {
if (!this.$refs.items || !this.$refs.items.length) {
return ;
}
// 获取真实元素大小,修改对应的尺寸缓存
this.updateItemsSize();
// 更新列表总高度
let height = this.positions[this.positions.length - 1].bottom;
this.contentHieghtS = height;
// 更新真实偏移量
this.setStartOffset();
});
},
data() {
return {
// 可视区域高度
screenHeight: 0,
// 起始索引
start: 0,
// 结束索引
end: 0,
contentHieghtS: 0 // 内容撑开的真实高度
};
},
methods: {
handleScroll() {
this.$nextTick(() => {
let scrollbarEl = this.$refs.scrollbar.wrap;
scrollbarEl.onscroll = () => {
var st = this.$refs.scrollbar.$refs.wrap.scrollTop;
this.scrollEvent(st);
};
});
},
// 初始化位置
initPositions() {
this.positions = this.listData.map((d, index) => ({
index,
height: this.estimatedItemSize,
top: index * this.estimatedItemSize,
bottom: (index + 1) * this.estimatedItemSize
})
);
},
// 获取列表项的当前尺寸
updateItemsSize() {
let nodes = this.$refs.items;
nodes.forEach((node) => {
let rect = node.getBoundingClientRect();
let height = rect.height;
let index = +node.id.slice(1);
let oldHeight = this.positions[index].height;
let dValue = oldHeight - height;
// 存在差值
if (dValue) {
this.positions[index].bottom = this.positions[index].bottom - dValue;
this.positions[index].height = height;
for (let k = index + 1;k < this.positions.length; k++) { // 后面的元素也
this.positions[k].top = this.positions[k - 1].bottom;
this.positions[k].bottom = this.positions[k].bottom - dValue;
}
}
});
},
// 获取当前的偏移量
setStartOffset() {
let startOffset;
if (this.start >= 1) {
startOffset = this.positions[this.start - 1].bottom;
} else {
startOffset = 0;
}
this.$refs.content.style.transform = `translate3d(0,${startOffset}px,0)`;
},
// 获取列表起始索引
getStartIndex(scrollTop = 0) { // 由于数组是有序的可以使用二分法寻找下标
// 二分法查找
return this.binarySearch(this.positions, scrollTop);
},
binarySearch(list, value) {
let start = 0;
let end = list.length - 1;
let tempIndex = null;
while (start <= end) {
let midIndex = parseInt((start + end) / 2, 10);
let midValue = list[midIndex].bottom;
if (midValue === value) {
return midIndex + 1;
} else if (midValue < value) {
start = midIndex + 1;
} else if (midValue > value) {
if (tempIndex === null || tempIndex > midIndex) {
tempIndex = midIndex;
}
end = end - 1;
}
}
return tempIndex;
},
// 滚动事件
scrollEvent(scrollTop) {
// 当前滚动位置
// let scrollTop = this.$refs.list.scrollTop;
// let startBottom = this.positions[this.start - ]
// 此时的开始索引
this.start = this.getStartIndex(scrollTop);
// 此时的结束索引
this.end = this.start + this.visibleCount;
// 此时的偏移量
this.setStartOffset();
}
}
};
</script>
```
其实这个时候留白的区域还是挺多的,所以我们就打算渲染多几个列表,所以我们就借助几个变量
```javascript
computed:{
aboveCount() {
return Math.min(this.start, this.bufferScale * this.visibleCount);
},
belowCount() {
return Math.min(this.listData.length - this.end, this.bufferScale * this.visibleCount);
},
}
props:{
// 缓冲区比例
bufferScale: {
type: Number,
default: 1
},
}
```
[完整的源代码](https://github.com/whenTheMorningDark/vue-kai-admin/blob/master/src/components/virtualList/test.vue)
<file_sep>/src/views/treeSelect/README.md
最近公司有个新需求,希望能有一个下拉选择树的功能,大概的功能和样式如下所示:


然后我的第一反应就是上 elementui 上找现成的组件,但是挺遗憾的就是 element 并没有提供这样的组件,所以只能自己动手造一个了。
**1. 组件需求**
(1) 支持单选和多选功能
(2) 叶子节点控制是否能选择
(3) 数据回显到选择框支持多选和单选显示
(4) 支持树节点搜索功能
(5) 基本样式应与 elementUi 样式保持一致
**2.布局和样式代码编写**
由于这个地方需要用到弹出下拉框,所以我就借助了 el-popover 来实现这个功能,代码如下:
```javascript
<template>
<div class="ka-tree-select" :style="{width:width+'px'}">
<el-popover
placement="bottom"
:width="width"
trigger="click">
<div class="ka-select-box" slot="reference">
<div class="tag-box">
<div v-show="selecteds.length>0">
显示的内容
</div>
<p class="ka-placeholder-box" v-show="selecteds.length===0">请输入内容</p>
</div>
</div>
</el-popover>
</div>
</template>
<script>
export default {
name: "treeSelect",
props: {
width: {
type: [String, Number],
default: 200
}
},
data() {
return {
selecteds: [] // 选择到的数据
};
}
};
</script>
<style lang="scss" scoped>
.ka-tree-select{
position: relative;
display: inline-block;
width: 100%;
vertical-align: middle;
outline: none;
.ka-select-box {
display: flex;
border: 1px solid #dcdfe6;
padding: 0 5px 0 8px;
width: 100%;
min-height: 36px;
// height: 36px;
line-height: 34px;
box-sizing: border-box;
border-radius: 4px;
cursor: pointer;
outline: none;
&:focus {
border-color: #409eff;
}
> .tag-box {
display: inline-block;
width: calc(100% - 20px);
text-align: left;
}
> .icon-box {
float: right;
display: flex;
width: 20px;
justify-content: center;
align-items: Center;
color: #c0c4cc;
// transform: rotateZ(45deg);
.el-icon-arrow-down {
transition: all 0.2s;
}
.down {
transform: rotateZ(180deg);
}
}
.ka-placeholder-box {
color: #c0c4cc;
margin: 0;
}
}
}
</style>
```

样式和基本结构也已经构建好了,值得注意一点就是 HTML 结构中,.tag-box 这个类名容器中会存放所选择到的数据,是用来存放单选和多选的页签。
**3.树结构制作**
这里的树结构我主要使用到了 el-tree 这个组件,为了让它有个好看的滚动条,这里我也选择了 el-scrollBar 滚动条组件,值得一提的就是使用 el-scrollbar 组件时候,必须给父容器添加一个高度,然后 el-scrollBar 的高度为 100%,要不然滚动条为出不来。代码如下:
```javascript
<template>
<div class="ka-tree-select" :style="{width:width+'px'}">
<el-popover
placement="bottom"
:width="width"
trigger="click">
<el-input v-if="filterable" v-model="filterText" :size="size" placeholder="请输入关键词"></el-input>
<el-scrollbar class="ka-treeselect-popover">
<el-tree
:data="data"
:props="selfProps"
:node-key="nodeKey"
highlight-current
:default-checked-keys="checked_keys"
:default-expanded-keys="expandedKeys"
:show-checkbox="checkbox"
check-strictly
ref="tree-select"
:filter-node-method="filterNode"
></el-tree>
<!-- @check="handleCheckChange" -->
<!-- @node-click="handleNodeClick" -->
</el-scrollbar>
<div class="ka-select-box" slot="reference">
<div class="tag-box">
<div v-show="selecteds.length>0">
显示的内容
</div>
<p class="ka-placeholder-box" v-show="selecteds.length===0">请输入内容</p>
</div>
</div>
</el-popover>
</div>
</template>
<script>
export default {
name: "treeSelect",
props: {
width: { // 宽度
type: [String, Number],
default: 200
},
size: { // 尺寸
type: String,
default: "mini"
},
data: { // 树结构的数据
type: Array,
default: () => []
},
nodeKey: { // 树结构的唯一标识
type: String,
default: "id"
},
// 是否使用搜索
filterable: {
type: Boolean,
default: true
},
// 显示的字段
props: {
type: Object,
default: () => ({
label: "label",
children: "children",
})
},
// 是否可多选
checkbox: {
type: Boolean,
default: false
},
},
data() {
return {
selecteds: [], // 选择到的数据
checked_keys: [], // 默认选中的数据
expandedKeys: [], // 默认展开的数据
filterText: "" // 筛选的数据
};
},
computed: {
selfProps () {
return {
label: "label",
children: "children",
disabled: data => data.disabled,
...this.props
};
},
},
methods: {
// 树节点筛选
filterNode (value, data) {
if (!value) {
return true;
}
return data[this.selfProps.label].indexOf(value) !== -1;
}
},
watch: {
filterText (val) {
this.$refs["tree-select"].filter(val);
}
}
};
</script>
<style lang="scss" scoped>
.ka-tree-select{
position: relative;
display: inline-block;
width: 100%;
vertical-align: middle;
outline: none;
.ka-select-box {
display: flex;
border: 1px solid #dcdfe6;
padding: 0 5px 0 8px;
width: 100%;
min-height: 36px;
// height: 36px;
line-height: 34px;
box-sizing: border-box;
border-radius: 4px;
cursor: pointer;
outline: none;
&:focus {
border-color: #409eff;
}
> .tag-box {
display: inline-block;
width: calc(100% - 20px);
text-align: left;
}
> .icon-box {
float: right;
display: flex;
width: 20px;
justify-content: center;
align-items: Center;
color: #c0c4cc;
// transform: rotateZ(45deg);
.el-icon-arrow-down {
transition: all 0.2s;
}
.down {
transform: rotateZ(180deg);
}
}
.ka-placeholder-box {
color: #c0c4cc;
margin: 0;
}
}
}
.ka-treeselect-popover {
height: 360px;
/deep/ .el-scrollbar__wrap {
overflow-x: hidden;
}
}
</style>
```

**4.处理显示的值**
接下来的话就轮到控制显示输入框的值了,我们要考虑一点,作为公共组件是如何提供给业务组件使用的问题,我假设在业务组件 A 中,使用了这个值,并且期望它的使用方式如下:
```javascript
<template>
<div style="padding:10px">
<el-row>
<el-col :span="12">
<treeSelect :data="treeData" v-model="select" checkbox :width="500" ref="treeSelect" ></treeSelect>
</el-col>
</el-row>
</div>
</template>
<script>
import treeSelect from "@/components/treeSelect/test";
export default {
components: {
treeSelect
},
data () {
return {
treeData: [{
id: 1,
label: "一级 1",
children: [{
id: 4,
label: "二级 1-1",
children: [{
id: 9,
label: "三级 1-1-1"
}, {
id: 10,
label: "三级 1-1-2"
}]
}]
}, {
id: 2,
label: "一级 2",
children: [{
id: 5,
label: "二级 2-1"
}, {
id: 6,
label: "二级 2-2"
}]
}, {
id: 3,
label: "一级 3",
children: [{
id: 7,
label: "二级 3-1"
}, {
id: 8,
label: "二级 3-2"
}, {
id: 18,
label: "二级 3-2"
}, {
id: 82,
label: "二级 3-2"
}, {
id: 84,
label: "二级 3-2"
}, {
id: 842,
label: "二级 3-2"
}, {
id: 847,
label: "二级 3-2"
}]
},
{
id: 11,
label: "最外面"
}
],
select: [9, 5]
};
}
};
</script>
<style>
</style>
```
select 这个变量代表我选中了这两个节点,还可以默认展开,并且是在输入框中显示所对应的 label 值,那么就回到 treeSelect 组件中编写对应的逻辑。在 created 中定义处理默认值的方法 handDefaultValue
```javascript
// 处理默认值的方法
handDefaultValue(value) {
if (!Array.isArray(value) || value.length === 0) {
return;
}
this.expandedKeys = [];
if (!this.checkbox) { // 单选的情况
this.$nextTick(() => {
this.$refs["tree-select"].setCurrentNode({
id: value[0]
});
let currentNode = this.$refs["tree-select"].getCurrentNode();
this.expandedKeys.push(value[0]);
this.selecteds = [currentNode];
this.$emit("change", this.selecteds);
});
} else { // 多选的情况
this.$nextTick(() => {
this.$refs["tree-select"].setCheckedKeys(value);
let currentAllNode = this.$refs["tree-select"].getCheckedNodes();
value.forEach(v => {
this.expandedKeys.push(v);
});
this.selecteds = currentAllNode;
this.$emit("change", this.selecteds);
});
}
}
```
这个时候我们的 selecteds 数组中已经初始化了选中当前树节点的数据,这个时候我们只需要把树节点对应的 label 渲染出来即可,这里我使用到 el-tag 这个组件,我把文字的显示分成了两种情况一种是平铺展示,一种折叠显示,代码如下:
```javascript
<template v-if="!collapseTags">
<el-tag
closable
:size="size"
v-for="item in selecteds"
:title="item[selfProps.label]"
:key="item[nodeKey]"
class="ka-select-tag"
@close="tabClose(item[nodeKey])"
>{{ item[selfProps.label] }}</el-tag>
</template>
<template v-else>
<el-tag
closable
:size="size"
class="ka-select-tag"
:title="collapseTagsItem[selfProps.label]"
@close="tabClose(collapseTagsItem[nodeKey])"
>{{ collapseTagsItem[selfProps.label] }}</el-tag>
<el-tag
v-if="this.selecteds.length>1"
:size="size"
class="ka-select-tag"
>+{{ this.selecteds.length-1}}</el-tag>
</template>
```
此时完整的代码:
```javascript
<template>
<div class="ka-tree-select" :style="{width:width+'px'}">
<el-popover
placement="bottom"
:width="width"
trigger="click">
<el-input v-if="filterable" v-model="filterText" :size="size" placeholder="请输入关键词"></el-input>
<el-scrollbar class="ka-treeselect-popover">
<el-tree
:data="data"
:props="selfProps"
:node-key="nodeKey"
highlight-current
:default-checked-keys="checked_keys"
:default-expanded-keys="expandedKeys"
:show-checkbox="checkbox"
check-strictly
ref="tree-select"
:filter-node-method="filterNode"
></el-tree>
<!-- @check="handleCheckChange" -->
<!-- @node-click="handleNodeClick" -->
</el-scrollbar>
<div class="ka-select-box" slot="reference">
<div class="tag-box">
<div v-show="selecteds.length>0">
<template v-if="!collapseTags">
<el-tag
closable
:size="size"
v-for="item in selecteds"
:title="item[selfProps.label]"
:key="item[nodeKey]"
class="ka-select-tag"
@close="tabClose(item[nodeKey])"
>{{ item[selfProps.label] }}</el-tag>
</template>
<template v-else>
<el-tag
closable
:size="size"
class="ka-select-tag"
:title="collapseTagsItem[selfProps.label]"
@close="tabClose(collapseTagsItem[nodeKey])"
>{{ collapseTagsItem[selfProps.label] }}</el-tag>
<el-tag
v-if="this.selecteds.length>1"
:size="size"
class="ka-select-tag"
>+{{ this.selecteds.length-1}}</el-tag>
</template>
</div>
<p class="ka-placeholder-box" v-show="selecteds.length===0">请输入内容</p>
</div>
</div>
</el-popover>
</div>
</template>
<script>
export default {
name: "treeSelect",
props: {
width: { // 宽度
type: [String, Number],
default: 200
},
size: { // 尺寸
type: String,
default: "mini"
},
data: { // 树结构的数据
type: Array,
default: () => []
},
nodeKey: { // 树结构的唯一标识
type: String,
default: "id"
},
// 是否使用搜索
filterable: {
type: Boolean,
default: true
},
// 显示的字段
props: {
type: Object,
default: () => ({
label: "label",
children: "children",
})
},
// 是否可多选
checkbox: {
type: Boolean,
default: false
},
// 选中数据
value: [Array],
// 多选时是否将选中值按文字的形式展示
collapseTags: {
type: Boolean,
default: false
},
},
created () {
this.handDefaultValue(this.value);
},
data() {
return {
selecteds: [], // 选择到的数据
checked_keys: [], // 默认选中的数据
expandedKeys: [], // 默认展开的数据
filterText: "" // 筛选的数据
};
},
computed: {
selfProps () {
return {
label: "label",
children: "children",
disabled: data => data.disabled,
...this.props
};
},
},
methods: {
// 树节点筛选
filterNode (value, data) {
if (!value) {
return true;
}
return data[this.selfProps.label].indexOf(value) !== -1;
},
// 处理默认值的方法
handDefaultValue(value) {
if (!Array.isArray(value) || value.length === 0) {
return;
}
this.expandedKeys = [];
if (!this.checkbox) { // 单选的情况
this.$nextTick(() => {
this.$refs["tree-select"].setCurrentNode({
id: value[0]
});
let currentNode = this.$refs["tree-select"].getCurrentNode();
this.expandedKeys.push(value[0]);
this.selecteds = [currentNode];
this.$emit("change", this.selecteds);
});
} else { // 多选的情况
this.$nextTick(() => {
this.$refs["tree-select"].setCheckedKeys(value);
let currentAllNode = this.$refs["tree-select"].getCheckedNodes();
value.forEach(v => {
this.expandedKeys.push(v);
});
this.selecteds = currentAllNode;
this.$emit("change", this.selecteds);
});
}
}
},
watch: {
filterText (val) {
this.$refs["tree-select"].filter(val);
}
}
};
</script>
<style lang="scss" scoped>
.ka-tree-select{
position: relative;
display: inline-block;
width: 100%;
vertical-align: middle;
outline: none;
.ka-select-box {
display: flex;
border: 1px solid #dcdfe6;
padding: 0 5px 0 8px;
width: 100%;
min-height: 36px;
// height: 36px;
line-height: 34px;
box-sizing: border-box;
border-radius: 4px;
cursor: pointer;
outline: none;
&:focus {
border-color: #409eff;
}
> .tag-box {
display: inline-block;
width: calc(100% - 20px);
text-align: left;
}
> .icon-box {
float: right;
display: flex;
width: 20px;
justify-content: center;
align-items: Center;
color: #c0c4cc;
// transform: rotateZ(45deg);
.el-icon-arrow-down {
transition: all 0.2s;
}
.down {
transform: rotateZ(180deg);
}
}
.ka-placeholder-box {
color: #c0c4cc;
margin: 0;
}
.ka-select-tag {
max-width: 100%;
text-overflow: ellipsis;
overflow: hidden;
word-wrap: break-word;
word-break: break-all;
vertical-align: middle;
}
.ka-select-tag + .ka-select-tag {
margin-left: 4px;
}
}
}
.ka-treeselect-popover {
height: 360px;
/deep/ .el-scrollbar__wrap {
overflow-x: hidden;
}
}
</style>
```
这个时候只需关注点击树节点所触发的函数,点击树节点 el-checkBox 和关闭 el-tag 时的函数即可。
```javascript
// 点击checkbox变化
handleCheckChange (val) {
let nodes = this.$refs["tree-select"].getCheckedNodes(false);
this.selecteds = nodes;
this.$emit("change", this.selecteds);
},
// 点击列表树
handleNodeClick (item, node) {
if (this.checkbox) {
return;
}
this.selecteds = [item];
// this.options_show = false;
this.$emit("change", this.selecteds);
},
// tag标签关闭
tabClose (id) {
if (this.disabled) {
return;
}
if (!this.checkbox) { // 单选
this.selecteds = [];
this.$refs["tree-select"].setCurrentKey(null);
} else { // 多选
this.$refs["tree-select"].setChecked(id, false, true);
this.selecteds = this.$refs["tree-select"].getCheckedNodes();
}
this.$emit("change", this.selecteds);
},
```
那么最后还有最后一个小的功能点,就是实现只能选择叶子节点的功能,那么我们就定义一个变量 isLeaf 来进行标识。在 el-tree 中只需要给节点添加上 disabled 字段即可标识当前节点是否可选了,那么我们只需要遍历这个树节点,循坏遍历,判断当前节点的 children 字段是否是大于 0,大于 0,disable 则为 true。
```javascript
// 转换treedata
changeTreeData (data) {
if (!data) {
return;
}
let stack = [];
data.forEach(v => {
stack.push(v);
});
while (stack.length) {
const result = stack.shift();
if (result.children && result.children.length > 0) {
result.disabled = true;
stack = stack.concat(result.children);
} else {
result.disabled = false;
}
}
return data;
},
created(){
this.isLeaf && this.changeTreeData(this.data);
}
```
这个时候已经完成了下拉选择树的功能,功能要点如下:
(1) 支持单选和多选功能
(2) 叶子节点控制是否能选择
(3) 数据回显到选择框支持多选和单选显示
(4) 支持树节点搜索功能
(5) 基本样式应与 elementUi 样式保持一致
源码地址为:https://github.com/whenTheMorningDark/vue-kai-admin/blob/master/src/components/treeSelect/index.vue
<file_sep>/src/views/form/components/generator/db.js
/* eslint-disable require-jsdoc */
const DRAWING_ID = "idGlobal";
const DRAWING_ITEMS = "drawingItems";
const FORM_CONF = "formConf";
export function getIdGlobal () {
const str = localStorage.getItem(DRAWING_ID);
if (str) {
return parseInt(str, 10);
}
return 100;
}
export function saveIdGlobal (id) {
localStorage.setItem(DRAWING_ID, `${id}`);
}
export function saveDrawingList (list) {
localStorage.setItem(DRAWING_ITEMS, JSON.stringify(list));
}
export function getDrawingList () {
const str = localStorage.getItem(DRAWING_ITEMS);
if (str) {
return JSON.parse(str);
}
return null;
}
export function getFormConf () {
const str = localStorage.getItem(FORM_CONF);
if (str) {
return JSON.parse(str);
}
return null;
}<file_sep>/src/views/documentation/utils.js
/* eslint-disable eol-last */
/* eslint-disable indent */
// 获取数组对象的并集
export const union = (sourceArr, targetArr) => {
// sourceArr.concat()
const arr = sourceArr.concat(targetArr);
// console.log(arr)
return arr.filter((item, index) => {
const len = arr.length;
while (++index < len) {
if (item.id === arr[index].id) {
return false;
}
}
return true;
});
};<file_sep>/src/store/modules/echart.js
/* eslint-disable no-unused-vars */
/* eslint-disable indent */
import Vue from "vue";
// eslint-disable-next-line require-jsdoc
export function getPropByPath(obj, path, strict) {
let tempObj = obj;
path = path.replace(/\[(\w+)\]/g, ".$1");
path = path.replace(/^\./, "");
let keyArr = path.split(".");
let i = 0;
for (let len = keyArr.length; i < len - 1; ++i) {
if (!tempObj && !strict) {
break;
}
let key = keyArr[i];
if (key in tempObj) {
tempObj = tempObj[key];
} else {
if (strict) {
throw new Error("please transfer a valid prop path to form item!");
}
break;
}
}
return {
o: tempObj,
k: keyArr[i],
v: tempObj ? tempObj[keyArr[i]] : null,
};
}
// eslint-disable-next-line require-jsdoc
function getValueByPath(object, prop) {
prop = prop || "";
const paths = prop.split(".");
let current = object;
let result = null;
for (let i = 0, j = paths.length; i < j; i++) {
const path = paths[i];
if (!current) {
break;
}
if (i === j - 1) {
result = current[path];
break;
}
current = current[path];
}
return result;
// console.log(result);
}
const state = {
currentTarget: {}, // 当前单选的对象
currentSelectArr: [] // 当前选中图形的数据
};
const mutations = {
// 设置当前的对象
setCurrentTarget(state, target) {
state.currentTarget = target;
},
// 设置当前echart对象集合
setEchartArr(state, arr) {
state.echartArr = arr;
},
changeCurrentTagetAttr(state, {
key,
value
}) {
state.currentTarget[key] = value;
},
// 改变当前对象的optionsData方法
changeCurrentTagetOptions(state, {
attr,
key,
value
}) {
let targetObj = state.currentTarget.optionsData[attr];
let paddingArr = {
paddingTop: 0,
paddingRight: 1,
paddingBottom: 2,
paddingLeft: 3,
};
if (Object.keys(paddingArr).includes(key)) {
let searchKeys = "padding";
let {
o,
k
} = getPropByPath(targetObj, searchKeys);
Vue.set(o, k[paddingArr[key]], value);
} else {
console.log(getPropByPath(targetObj, key));
let {
o,
k
} = getPropByPath(targetObj, key);
Vue.set(o, k, value);
}
// let { o, k } = getPropByPath(targetObj, key);
// Vue.set(o, k, value);
let targetEchart = state.echartArr.find(
(v) => v.id === state.currentTarget.id
);
targetEchart.setOption(state.currentTarget.optionsData);
},
};
const actions = {};
export default {
namespaced: true,
state,
mutations,
actions,
};<file_sep>/src/components/mxGraph/utils.js
/* eslint-disable eol-last */
/* eslint-disable semi */
/* eslint-disable indent */
/* eslint-disable new-cap */
// 主要处理工具函数
export default {
mounted() {
console.log("mixs");
// this.setKeyHandler()
},
methods: {
// 线条edge变成to数组
edgeTo(source) {
let edges = source.edges;
if (edges && edges.length > 0) {
let arr = []
edges.forEach(s => {
let toOptions = {
edgeOptions: { // 当前线条的属性
id: s.id, // 当前线条的id
value: s.value
},
id: s.target.id, // 指向target的id
style: this.StringToObj(s.style) // 当前线条样式
}
if (source.id !== s.target.id) {
arr.push(toOptions)
}
})
source.to = arr
} else if (edges && edges.length === 0) {
source.to = []
}
},
StringToObj(str) {
let targetObj = {}
if (str && str.includes(";") && str.length > 0) {
let arr = str.split(";");
arr.forEach(v => {
let target = v.split("=")
if (target[0] && target[0].length > 0 && !targetObj[target[0]]) {
targetObj[target[0]] = target[1] || ""
}
})
}
return targetObj
},
convertStyleToString(styleDict) {
// 把对象转成字符{strokeColor:color} => strokeColor=color;
const style = Object.entries(styleDict)
.map(([key, value]) => `${key}=${value}`)
.join(";");
return `${style};`;
},
// 获取id为cell的元素
findCell(id) {
const cells = this.graph.getChildVertices(this.graph.getDefaultParent());
const cell = cells.find(v => v.id === id);
return cell;
},
// 获取所有的图形
getAllCell() {
const cells = this.graph.getChildVertices(this.graph.getDefaultParent());
return cells;
},
// 获取所有的线条
getAllEdge() {
const edges = this.graph.getChildEdges(this.graph.getDefaultParent())
// console.log(edges)
return edges;
},
// 获取grapthData
// { id: "5", value: "开始", styleOptions: { shape: "rectangle", strokeColor: "#662B2B", dashed: "0", strokeWidth: 1 }, x: 100, y: 100, width: 100, height: 100,
// to: [
// { id: "7", style: { strokeColor: "red", edgeStyle: "orthogonalEdgeStyle", rounded: 0, orthogonalLoop: 1 }, edgeOptions: { id: "25", value: "8888", type: "8888edge" } },
// { id: "9", edgeOptions: { id: "35", value: "9999" } }], options: { name: "add", type: "start" }
// },
getGrapthData() {
const currentCell = this.getAllCell();
// console.log(currentCell)
return currentCell.map(v => ({...v}))
// const currentEdge = this.getAllEdge();
// currentCell.forEach(v => {
// const obj = this.getAddObj(v);
// // currentEdge.forEach(s=>{
// // })
// newGraphData.push(obj);
// });
// return newGraphData;
},
// 处理连线向to数据添加数据
handleConnect(edge, source, target) {
const tId = target.id;
const sourceTo = source.to.map(v => v.id);
if (sourceTo.includes(tId)) {
return;
}
source.to.push({
id: tId,
style: edge.style,
edgeOptions: {
id: edge.id,
value: edge.value
}
});
console.log(source)
},
// 处理value变化的情况
handleValueChange(cell) {
console.log(cell);
if (cell.edge) {
this.edgeTo(cell.source)
}
},
// 处理undo的json数组
// handleUnDo(){
// const allCell = this.getAllCell();
// },
getAddObj(vertex) {
const {
id,
options,
style,
to,
value,
styleOptions
} = vertex;
console.log(id);
const {
x,
y,
width,
height
} = vertex.geometry;
return Object.assign({
id,
options,
style,
to,
value,
styleOptions
}, {
x,
y,
width,
height
});
}
}
};<file_sep>/src/store/modules/user.js
import {setStorage, getStorage, TOKEN_KEY, USER_KEY} from "@/utils/localStroage";
const state = {
userInfo: getStorage(USER_KEY) || {},
token: getStorage(TOKEN_KEY) || "",
};
const actions = {
};
const mutations = {
// 设置当前token
SET_TOKEN(state, token) {
state.token = token;
setStorage(TOKEN_KEY, token);
},
// 设置用户信息
SET_USER_INFO(state, userInfo) {
state.userInfo = userInfo;
setStorage(USER_KEY, userInfo);
}
};
export default {
namespaced: true,
state,
actions,
mutations
};<file_sep>/src/views/loadsh/array/chunk.md
> 鲁迅说过:只有阅读过优秀库源码的人,才能配的上是真正的勇士。
**作用和用法**
> 将数组(array)拆分成多个 size 长度的区块,并将这些区块组成一个新数组。 如果 array
> 无法被分割成全部等长的区块,那么最后剩余的元素将组成一个区块。
用法:
> _.chunk(array, [size=1])
> array (Array): 需要处理的数组
> [size=1](number): 每个数组区块的长度
demo:
```javascript
_.chunk(['a', 'b', 'c', 'd'], 2)
// => [['a', 'b'], ['c', 'd']]
_.chunk(['a', 'b', 'c', 'd'], 3)
// => [['a', 'b', 'c'], ['d']]
```
**源码分析**
chunk 所依赖的函数分别有
1.[toNumber.js](https://github.com/lodash/lodash/blob/e0029485ab4d97adea0cb34292afb6700309cf16/toNumber.js#L44)
2.[toFinite](https://github.com/lodash/lodash/blob/e0029485ab4d97adea0cb34292afb6700309cf16/toFinite.js#L28)
3.[toInteger](https://github.com/lodash/lodash/blob/e0029485ab4d97adea0cb34292afb6700309cf16/toInteger.js#L28)
4.[slice](https://github.com/lodash/lodash/blob/e0029485ab4d97adea0cb34292afb6700309cf16/slice.js#L21)
5.[chunk](https://github.com/lodash/lodash/blob/master/chunk.js)
那么我们就逐一来分析每个函数的具体实现过程。
**1.isObject**
顾名思义,这个函数是用来判断传递的参数是否是对象类型,值得一提的是在 js 中,你用 typeof null 出来的结果为 object,这种情况我们需要排除掉。
知识点:
1. typeof null 的值为 object
2. typeof function 的值为 function
```javascript
* isObject({})
* // => true
*
* isObject([1, 2, 3])
* // => true
*
* isObject(Function)
* // => true
*
* isObject(null)
* // => false
```
```javascript
function isObject(value) {
const type = typeof value
return value !== null && (type === 'object' || type === 'function')
}
```
**2.toNumber**
这个函数所作的主要功能为把你所传递参数,以 number 类型返回。
```javascript
* toNumber(3.2)
* // => 3.2
*
* toNumber(Number.MIN_VALUE)
* // => 5e-324
*
* toNumber(Infinity)
* // => Infinity
*
* toNumber('3.2')
* // => 3.2
```
```javascript
const NAN = 0 / 0
// 用来匹配前后两个空格
const reTrim = /^\s+|\s+$/g
// 用来检测二进制的数字 i 不区分(ignore)大小写;
const reIsBinary = /^0b[01]+$/i
// 用来检测八进制的数字 i 不区分(ignore)大小写;
const reIsOctal = /^0o[0-7]+$/i
// 用来检测错误的16进制的数字 i 不区分(ignore)大小写;
const reIsBadHex = /^[-+]0x[0-9a-f]+$/i
const freeParseInt = parseInt
function toNumber(value){
if(typeof === "number"){
return value
}
if(isSymbol(value)){
return NAN
}
if(isObject(value)){
// 把function,arr类型都有valueOf方法 null,undefine是没有
const other = typeof value.valueOf === 'function' ? value.valueOf() : value
// 把function类型变成字符串
value = isObject(other) ? `${other}` : other
}
// 判断null的情况
if(typeof value !=="string"){
return value===0?value:+value // 隐式转换 +null ===0
}
value = value.replace(reTrim, '') // 替换前后两个空格
// 如果是十进制的数字 直接+value 返回
const isBinary = reIsBinary.test(value)
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value)
}
function isSymbol(value){ // 判断是否是symbol类型
const type = typeof value
return type == 'symbol' || (type === 'object' && value != null && getTag(value) == '[object Symbol]')
}
```
知识点:
1. valueof--- 除了 null 和 undefine 没有 valueof 方法之外,其它的基本数据类型都有
2. js 隐式转换
**3.toFinite**
这个函数是把 number 类型的数字转换成为有限的数字
```javascript
const INFINITY = 1 / 0
const MAX_INTEGER = 1.7976931348623157e308
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0
}
value = toNumber(value)
if (value === INFINITY || value === -INFINITY) {
// 转换成为无穷大或者,无穷小
const sign = value < 0 ? -1 : 1
return sign * MAX_INTEGER
}
return value === value ? value : 0 // 如果是NaN === NaN 则为false 此时的值为0
}
```
**4.toInteger**
这个函数是把输入的 value 转换成为整数
```javascript
* toInteger(3.2)
* // => 3
*
* toInteger(Number.MIN_VALUE)
* // => 0
*
* toInteger(Infinity)
* // => 1.7976931348623157e+308
*
* toInteger('3.2')
* // => 3
*/
```
```javascript
function toInteger(value) {
// 这个地方既然是取整,为什么不用math.floor()?,而且 3.2 % 1出来的结果是0.20000000000000018,精度也会不准
const result = toFinite(value)
const remainder = result % 1
return remainder ? result - remainder : result
}
```
**5.slice**
example
```javascript
var array = [1, 2, 3, 4]
_.slice(array, 2)
// => [3, 4]
```
这个函数是用于切割数组,
1. 第一个参数为切割的数组,
2. 第二个参数则是切割的起始值 begin
3. 第三个参数则是切割的终止地址,切割的个数为 end - begin 个数。
```javascript
let length = array == null ? 0 : array.length
if (!length) {
return []
}
start = start == null ? 0 : start
end = end === undefined ? length : end
if (start < 0) {
start = -start > length ? 0 : length + start
}
end = end > length ? length : end
if (end < 0) {
end += length
}
length = start > end ? 0 : (end - start) >>> 0
start >>>= 0
let index = -1
const result = new Array(length)
while (++index < length) {
result[index] = array[index + start]
}
return result
```
知识点:
`>>>`
1 所有非数值转换成 0 2.所有大于等于 0 等数取整数部分
**6.chunk**
剩下来的这个函数就比较简单了,
```javascript
function chunk(array, size = 1) {
size = Math.max(toInteger(size), 0)
// undefine == null 为 true undefine === null false
const length = array == null ? 0 : array.length
if (!length || size < 1) {
return []
}
let index = 0
let resIndex = 0
const result = new Array(Math.ceil(length / size)) // 向上取整获取最大的数组数
while (index < length) {
result[resIndex++] = slice(array, index, (index += size))
// 这两个是一样的意思
// result[resIndex] = slice(array, index, (index += size))
// resIndex++
}
return result
}
```
<file_sep>/src/views/echarts/echartComponent/data/radar/radarMultiple/radarMultiple.js
/* eslint-disable indent */
export const radarMultiple = {
name: "多雷达图",
type: "radar",
images: require("@/assets/images/radar-multiple.jpg"),
optionsData: {
title: {
text: "多雷达图",
},
tooltip: {
trigger: "axis",
},
legend: {
left: "center",
data: ["某软件", "某主食手机", "某水果手机", "降水量", "蒸发量"],
},
radar: [
{
indicator: [
{ text: "品牌", max: 100 },
{ text: "内容", max: 100 },
{ text: "可用性", max: 100 },
{ text: "功能", max: 100 },
],
center: ["25%", "40%"],
radius: 80,
},
{
indicator: [
{ text: "外观", max: 100 },
{ text: "拍照", max: 100 },
{ text: "系统", max: 100 },
{ text: "性能", max: 100 },
{ text: "屏幕", max: 100 },
],
radius: 80,
center: ["50%", "60%"],
},
{
indicator: (function() {
var res = [];
for (var i = 1; i <= 12; i++) {
res.push({ text: i + "月", max: 100 });
}
return res;
})(),
center: ["75%", "40%"],
radius: 80,
},
],
series: [
{
type: "radar",
tooltip: {
trigger: "item",
},
areaStyle: {},
data: [
{
value: [60, 73, 85, 40],
name: "某软件",
},
],
},
{
type: "radar",
radarIndex: 1,
areaStyle: {},
data: [
{
value: [85, 90, 90, 95, 95],
name: "某主食手机",
},
{
value: [95, 80, 95, 90, 93],
name: "某水果手机",
},
],
},
{
type: "radar",
radarIndex: 2,
areaStyle: {},
data: [
{
name: "降水量",
value: [
2.6,
5.9,
9.0,
26.4,
28.7,
70.7,
75.6,
82.2,
48.7,
18.8,
6.0,
2.3,
],
},
{
name: "蒸发量",
value: [
2.0,
4.9,
7.0,
23.2,
25.6,
76.7,
35.6,
62.2,
32.6,
20.0,
6.4,
3.3,
],
},
],
},
],
},
};
<file_sep>/src/views/echarts/echartComponent/data/bar/defaultBar/defaultBar.js
/* eslint-disable indent */
import { defaultTtileKeys } from "../../../../rightTool/components/commonData/commonData";
import { legendData } from "../../../../rightTool/components/commonData/legendData";
import { xData } from "../../../../rightTool/components/commonData/xData";
// import { yData } from "../../../../rightTool/components/commonData/yData";
import { cloneDeep } from "lodash";
let currentXdata = {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
};
export const defaultBar = {
name: "基础柱状图",
type: "bar",
images: require("@/assets/images/bar-simple.jpg"),
optionsData: {
title: JSON.parse(JSON.stringify(defaultTtileKeys)),
legend: legendData,
tooltip: {},
xAxis: Object.assign({}, cloneDeep(xData), currentXdata),
yAxis: Object.assign({}, cloneDeep(xData), {}),
series: [
{
name: "销量",
type: "bar",
data: [5, 20, 36, 10, 10, 20],
},
],
},
};
<file_sep>/src/router/modules/leetCode.js
/* eslint-disable comma-dangle */
/* eslint-disable indent */
/** When your routing table is too long, you can split it into small modules**/
import Layout from "@/layout";
const leetCodeRouter = {
path: "/leetCode",
component: Layout,
redirect: "/leetCode/array",
name: "leetCode",
meta: {
title: "leetCode",
icon: "chart",
affix: false,
},
children: [
{
path: "array",
component: () => import("@/views/leetCode/index"),
name: "array",
meta: {
title: "数组",
affix: true,
},
children: [
{
path: "array1",
name: "数组1",
component: () => import("@/views/leetCode/array/array1"),
meta: {
title: "数组1",
affix: true,
},
},
{
path: "array2",
component: () => import("@/views/leetCode/array/array2"),
meta: {
title: "数组2",
},
},
{
path: "array3",
component: () => import("@/views/leetCode/array/array3"),
meta: {
title: "数组3",
},
},
{
path: "array4",
component: () => import("@/views/leetCode/array/array4"),
meta: {
title: "数组4",
},
},
{
path: "array5",
component: () => import("@/views/leetCode/array/array5"),
meta: {
title: "数组5",
},
},
{
path: "array6",
component: () => import("@/views/leetCode/array/array6"),
meta: {
title: "数组6",
},
},
{
path: "array7",
component: () => import("@/views/leetCode/array/array7"),
meta: {
title: "数组7",
},
},
],
},
{
path: "String",
component: () => import("@/views/leetCode/index"),
name: "String",
meta: {
title: "字符串",
},
children: [
{
path: "string1",
component: () => import("@/views/leetCode/String/String1"),
meta: {
title: "字符串1",
},
},
{
path: "string2",
component: () => import("@/views/leetCode/String/String2"),
meta: {
title: "字符串2",
},
},
{
path: "string3",
component: () => import("@/views/leetCode/String/String3"),
meta: {
title: "字符串3",
},
},
],
},
{
path: "BinaryTree",
component: () => import("@/views/leetCode/index"),
name: "BinaryTree",
meta: {
title: "二叉树",
},
children: [
{
path: "binaryTree1",
component: () => import("@/views/leetCode/BinaryTree/BinaryTree1"),
meta: {
title: "二叉树1",
},
},
{
path: "binaryTree2",
component: () => import("@/views/leetCode/BinaryTree/BinaryTree2"),
meta: {
title: "二叉树2",
},
},
{
path: "binaryTree3",
component: () => import("@/views/leetCode/BinaryTree/BinaryTree3"),
meta: {
title: "二叉树3",
},
},
],
},
{
path: "dynamic",
component: () => import("@/views/leetCode/index"),
name: "dynamic",
meta: {
title: "动态规划",
},
children: [
{
path: "maxChildArray",
name: "动态规划最大子数组",
component: () => import("@/views/leetCode/dynamic/maxChildArray"),
meta: {
title: "动态规划最大子数组",
affix: false,
},
},
{
path: "bagQuestion",
name: "动态规划背包问题",
component: () => import("@/views/leetCode/dynamic/bagQuestion"),
meta: {
title: "动态规划背包问题",
affix: false,
},
},
],
},
],
};
// eslint-disable-next-line eol-last
export default leetCodeRouter;
<file_sep>/src/views/echarts/rightTool/components/commonData/yData.js
/* eslint-disable indent */
export const yData = {
show: true,
name: "",
nameLocation: "middle",
nameTextStyle: {
color: "#333",
fontSize: 14,
fontStyle: "normal",
fontWeight: "bolder",
fontFamily: "Microsoft YaHei",
},
nameGap: 15,
axisLabel: {
formatter: "{value}",
show: true,
},
};
export const nameLocationOptions = [
{ label: "start", value: "start" },
{ label: "middle", value: "middle" },
{ label: "end", value: "end" },
];
<file_sep>/src/views/echarts/README.md
<h2 align="center">vue中实现ehart图表交互和图表展示</h2>
<p align="center">
<img src="http://119.23.36.73/githubImages/echarts1.png">
</p>
<p align="center">
<img src="http://119.23.36.73/githubImages/echarts2.png">
</p>
## 简介
<p>该模块也是平时工作中所负责的一个模块,目的是为了能够快速生成图表。</p>
<p>在实际工作中的项目这是个主要为了绘制大屏所使用,在这里我选择抽了部分的功能与大家一起分享一下,里面的代码或许不是最好的写法,如果你有不同的写法也欢迎分享和提issues</p>
## 技术栈和插件选择
该功能模块技术栈使用了vue,而只要使用到插件则是 echart+[vue-drag-resize](https://github.com/kirillmurashov/vue-drag-resize),echart是一款经典的图形生成库,它内置了许许多多的常见图表,用兴趣的朋友也可以上去官网查看。主要是vue-drag-resize这款插件,项目一开始我是想着自己实现一个可拖拽可伸缩的组件,但随着项目越来越多的需求,发现自己编写的drag-resize越来越多的坑要填,直到我发现这个vue-drag-resize这款插件,这款插件可谓帮了我的大忙,也感谢作者一直在更新和维护。
## 功能要点
<p>目前已完成的功能如下</p>
```
- 图表数据驱动生成(完成)
- 历史记录回撤与前进(完成)
- 图表公用属性编辑(完成)
- 右键删除功能(完成)
```
<p>目前未完成的功能</p>
```
- 右键图表组合,取消组合,上移,下移等功(未完成)
- 组合图层设计(未完成)
- 图表数据联动(未完成)
- 图表刻度尺实现(未完成)
- .....
```
## 公共组件主要代码实现过程
<p>vue实现echart图表是需要一个固定DOM节点的,所以在则必须在生命周期mounted中实现该功能</p>
<p>需要注意的一个是每个图表我都会动态赋值于一个uid,作为图表的唯一标识</p>
```
<div :id="id" style="width:100%;height:100%"></div>
methods: {
resizeFun() {
this.myChart.resize();
},
setOption(optionsData) {
console.log(optionsData);
this.myChart.setOption(optionsData);
},
init() {
this.myChart = echarts.init(document.getElementById(this.id));
this.setOption(this.optionsData);
},
},
mounted() {
this.init();
},
```
<p>我在这里也是对外暴露一个setOptions方法,为了后期可以动态设置图表的属性,另外我们是需要额外引入eachrts的图表包,具体代码存放在echartComponent/minxins/init.js中</p>
<p>设置图表的默认的数据,每一个图表类型都拆分开成为一个个单独的文件夹也是为了方便后期的维护,它们的默认数据的来源,我都是从echarts的官网中获取的。</p>
<p>
在编写代码的过程中我一直在思考的如何让进行最简单和最为高效的开发方式,如果每一个每个图表的引入都要业务组件中引入数据,则会变得非常的麻烦,而这个时候我就想到了webpack中的require.context方法,其中思路与动态生成路由组件是一样的,参考代码在echartComponent/data/utils/common.js中。
</p>
## 业务组件主要代码实现过程
<h3>顶部导航栏组件</h3>
<p>该组件只要是用于实现拖拽图表,并且把图表的数据一一暴露出外部组件以供于使用,这里的拖拽我是使用了HTML5拖拽的api进行实现,主要参考代码在于echarts/components/toolbar</p>
```
<el-popover placement="right" title="选择图表" width="800" trigger="hover">
<el-tabs v-model="activeName" type="card">
<el-tab-pane
:label="item.label"
:name="item.name"
v-for="(item,index) in listData"
:key="index"
>
<el-row :gutter="20">
<el-col :span="6" v-for="(element,index) in item.children" :key="index">
<div class="content-wrapper" @dragstart="drag($event,element)" draggable="true">
<div class="imgages" v-if="element.images">
<img :src="element.images" width="100%" height="140" />
</div>
<div>{{element.name}}</div>
</div>
</el-col>
</el-row>
</el-tab-pane>
</el-tabs>
<div class="toolbar-item" slot="reference">
<SvgIcon iconClass="tubiao" class="icon-item"></SvgIcon>
</div>
</el-popover>
import SvgIcon from "@/components/SvgIcon";
import { barChildren } from "../echartComponent/data/bar/index";
import { lineChildren } from "../echartComponent/data/line/index";
import { pieChildren } from "../echartComponent/data/pie/index";
import { scatterChildren } from "../echartComponent/data/scatter/index";
import { radarChildren } from "../echartComponent/data/radar/index";
listData: [
{ name: "bar", label: "柱形图", children: barChildren },
{ name: "line", label: "折线图", children: lineChildren },
{ name: "pie", label: "饼图", children: pieChildren },
{ name: "scatter", label: "散点图", children: scatterChildren },
{ name: "radar", label: "雷达图", children: radarChildren },
],
```
<h3>侧边栏组件</h3>
<p>该组件主要是用来修改当前选中图表的基本属性,包括当前的x,y,width,height和基本的echarts图表属性,值得注意的一点是,我们是需要对外暴露setData和getData这两种方法的,换句话来说,我们只需要调用该组件的setData方法就可以了去设置侧边栏所有的属性值。这里就涉及到了不同组件中的通信方式,为了后面的维护,我选择了vuex来作为数据管理。主要代码在store/modules/echart.js。另外,由于我是使用到了element中form表单组件,那么在vuex中使用v-model是需要在计算属性中,重写set和get方法的。而且我们也不可能一一去重写每个属性,这样代码量就太多了。我在这个地方是通过计算属性去动态获取当前currentData,然后去设置当前的属性值。主要参考代码在echarts/rightTool/tabComponents/echartClass中。</p>
## 关于历史记录代码实现
<p>实现历史记录的功能无非就是使用一个栈堆思想,记录当前你所操作的数据,然后push进这个stack中,然后通过步数来对应stack中的下标元素,但值得注意一点就是,当前操作中断后,我们需要删除后续所有的元素。而且在这个过程中我们需要保证数据的不变性,你可以使用JSON.parse(JSON.stringfly(data))的方式去实现数据的深拷贝,我在这个地方就是用loadsh库中cloneDeep函数。主要实现的代码在src/utils/history.js中</p>
## 最后
这个模块,只是我工作中所抽取出来的一下部分,但是核心的思路是不会变,只是会给添加到许多奇奇怪怪的需求上去而已。如果我这个模块对你有所帮助也希望你能点个star,稍微的小小支持一下。
```
如果你有其它的问题或者你有其它更加好的实现方法,也欢迎联系我.
- qq 404792402
```
<file_sep>/src/views/echarts/utils/utils.js
/* eslint-disable indent */
import { cloneDeep, isPlainObject } from "lodash";
let needBoolean = ["show"];
let numberArr = [
"fontSize",
"paddingTop",
"paddingRight",
"paddingBottom",
"paddingLeft",
];
let ArrayArr = ["padding"];
export const clearValues = (Obj) => {
let targetObj = cloneDeep(Obj);
for (let key in targetObj) {
if (isPlainObject(targetObj[key])) {
targetObj[key] = clearValues(targetObj[key]);
} else {
if (needBoolean.includes(key)) {
targetObj[key] = false;
} else {
if (numberArr.includes(key)) {
targetObj[key] = 12;
} else if (ArrayArr.includes(key)) {
// targetObj[key] =
if (key === "padding") {
targetObj[key] = [5, 5, 5, 5];
} else {
targetObj[key] = [];
}
} else {
targetObj[key] = "";
}
}
}
}
return targetObj;
};
<file_sep>/src/views/echarts/rightTool/components/commonData/commonData.js
/* eslint-disable indent */
// import { clearValues } from "../../../utils/utils";
export const defaultTtileKeys = {
text: "默认标题",
show: true,
subtext: "默认二级标题",
textStyle: {
color: "#333",
fontStyle: "normal",
fontWeight: "bolder",
fontFamily: "Microsoft YaHei",
fontSize: 20,
},
subtextStyle: {
color: "#333",
fontStyle: "normal",
fontWeight: "bolder",
fontFamily: "Microsoft YaHei",
fontSize: 20,
},
x: "left",
y: "top",
};
export const fontStyleOptions = [
{ label: "normal", value: "normal" },
{ label: "italic", value: "italic" },
{ label: "oblique", value: "oblique" },
];
export const fontFamilyOptions = [
{ label: "serif", value: "serif" },
{ label: "monospace", value: "monospace" },
{ label: "Arial", value: "Courier New" },
{ label: "Microsoft YaHei", value: "Microsoft YaHei" },
];
export const xDirections = [
{ label: "水平居左", value: "left" },
{ label: "水平居中", value: "center" },
{ label: "水平居右", value: "right" },
];
export const yDirections = [
{ label: "顶部", value: "top" },
{ label: "底部", value: "bottom" },
];
<file_sep>/src/components/G2Template/data/g2Bar.js
/* eslint-disable comma-dangle */
/* eslint-disable indent */
// 这是柱状图默认的数据
import { randomStr } from "@/utils";
export const g2BarData = [
{ genre: "Sports", sold: 275 },
{ genre: "Strategy", sold: 115 },
{ genre: "Action", sold: 120 },
{ genre: "Shooter", sold: 350 },
{ genre: "Other", sold: 150 },
];
export const baseOptions = {
container: "g2Bar" + randomStr(3),
width: 400,
height: 250,
};
<file_sep>/README.md
## 简介
该项目主要是我个人在工作中所编写的一些组件或者是有一些有意思的组件我都会一一记录下来
## 组件
<p>
[虚拟列表](http://whenthemorningdark.gitee.io/vue-kafei-admin/#/components/virtualList)
</p>
<p>
[下拉选择树](http://whenthemorningdark.gitee.io/vue-kafei-admin/#/components/treeSelect)
</p>
<p>
[mxgraph 流程图](http://whenthemorningdark.gitee.io/vue-kafei-admin/#/dataView/index)
</p>
<p>
[拖拽布局](http://whenthemorningdark.gitee.io/vue-kafei-admin/#/dataView/draggbleLayout)
</p>
<p>
[echarts 可视化布局](http://whenthemorningdark.gitee.io/vue-kafei-admin/#/dataView/echarts)
</p>
<p>
[表单可视化](http://whenthemorningdark.gitee.io/vue-kafei-admin/#/dataView/form)
</p>
<p>
[甘特图](http://whenthemorningdark.gitee.io/vue-kafei-admin/#/dataView/gantt)
</p>
<p>
[圆形进度条](http://whenthemorningdark.gitee.io/vue-kafei-admin/#/dataView/circle)
</p>
<p>
[省市区联动](https://github.com/whenTheMorningDark/vue-kai-admin/blob/master/src/components/selectProvince/index.vue)
</p>
## lodash 源码分析
<p>
<p>数组方法分析</p>
[chunk](https://github.com/whenTheMorningDark/vue-kai-admin/blob/master/src/views/loadsh/array/chunk.md)
</p>
<p>
[compactAndConct](https://github.com/whenTheMorningDark/vue-kai-admin/blob/master/src/views/loadsh/array/compactAndConct.md)
</p>
<file_sep>/src/views/echarts/utils/history.js
/* eslint-disable indent */
import { cloneDeep, isEqual } from "lodash";
import { Message } from "element-ui";
class History {
state = []; // 历史状态
index = 0; // 当前状态下标
maxState = 20; // 最大保存状态个数 (防止爆栈)
setState(state) {
debounce(() => {
console.log(this.checkRepeat(state));
if (this.checkRepeat(state)) {
// 判断是否是重复对象进来
return;
}
// 限制长度
if (this.state.length >= this.maxState) {
this.state.shift();
}
// 如果this.state.length 与this.index不一致说明,当前指针发生了变化,所以将指针后面的都去掉
if (this.index < this.state.length - 1) {
this.state.splice(this.index + 1, this.state.length - 1);
}
this.state.push(cloneDeep(state));
this.index = this.state.length - 1; // 方便下标的计算 都从0开始计算
}, 200);
}
getState() {
return this.state;
}
replaceState() {
// 撤销
if (this.index > 0) {
this.index--;
let state = cloneDeep(this.state[this.index]);
return state;
} else {
// alert("已经无法再进行撤回");
Message({
message: "无法再撤销操作",
type: "warning",
});
}
}
unReplaceState() {
if (this.state.length - 1 > this.index) {
// 反撤销
this.index++;
let state = cloneDeep(this.state[this.index]);
return state;
} else {
Message({
message: "无法再进行前进操作",
type: "warning",
});
}
}
// 检验是否重复元素
checkRepeat(snapshot) {
const next = snapshot;
let prev;
if (this.index >= 0) {
prev = this.state[this.index];
} else {
prev = {};
}
// if(isEqual(next,prev))
return isEqual(next, prev);
}
}
export default History;
let timeout = null;
/* eslint-disable valid-jsdoc */
/**
* 去抖函数封装体
* @param {Fun} fn 执行函数
* @param {Number} wait 触发时间
*/
export function debounce(fn, wait) {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(fn, wait);
}
<file_sep>/src/components/mxGraph/README.md
## 简介
该项目主要是我个人在工作中所编写的一些组件或者是有一些有意思的组件我都会一一记录下来
## 封装 mxGraph 组件
mxgraph 是一个非常强大的一个绘图库,但是我个人认为它是比较难用的,而且原本库数据传递的方法都是 xml 格式的,这种格式我个人是不太喜欢的,所以我就基于 mxgraph 二次封装成为一个数据驱动的一个组件
最近公司需要使用 mxgraph,来进行流程图的开发,由于我是第一次接触这个库,所以踩到的坑还是挺多,最坑爹的网上关于这个库的资料实在是太少了,它的文档还是英文文档。所以开发起来还是有点痛苦的。
我们来看下以下部分需求:

这是 PM 要我做的流程图,这里我会拿部份的功能和大家分享。包括新建图形,删除节点图形,响应右键菜单事件....由于 mxgraph 的套路是很固定的,只要你 GET 到这几个部分再结合文档,就基本没有问题了。
**一.创建项目**
通过 vue-cli 创建项目,这里就不多说了....,这是我生成的项目目录。我进行了一个项目目录的修改,大家也可以参考一下。
vue.config.js 配置
```javascript
module.exports = {
publicPath: "./",
outputDir: "dist",
lintOnSave: true,
chainWebpack: (config) => {
config.module
.rule("")
.test(/mxClient\.js$/)
.use("exports-loader")
.loader(
"exports-loader?mxClient,mxToolbar,mxConnectionHandler,mxEllipse,mxConnectionConstraint,mxWindow," +
"mxObjectCodec,mxGraphModel,mxActor,mxPopupMenu,mxShape,mxEventObject,mxGraph,mxPopupMenuHandler,mxPrintPreview," +
"mxEventSource,mxRectangle,mxVertexHandler,mxMouseEvent,mxGraphView,mxCodecRegistry,mxImage,mxGeometry," +
"mxRubberband,mxConstraintHandler,mxKeyHandler,mxDragSource,mxGraphModel,mxEvent,mxUtils,mxEvent,mxCodec,mxCell," +
"mxConstants,mxPoint,mxGraphHandler,mxCylinder,mxCellRenderer,mxEvent,mxUndoManager"
)
.end();
},
};
```
**二.数据驱动生成图形**
在项目开发的过程中,我使用了 mxGraph 踩了很多的坑,其中的一个大坑就是图形回显的问题,一开始我是采用官方推荐的 xml 形式,大致上就是前台生成一堆的 xml,然后后台返回。这里的问题是什么呢?就是后台的小伙伴就会很繁琐,毕竟他们要从一大堆没有规律的 xml 抽取字段,然后写进数据库。所以,我就把数据格式修改为 json 格式,我个人认为这是使用 mxGraph 最为重要的一个东西。
首先我们就先约定好数据格式
```javascript
graphData: [
{ id: "5", value: "开始", styleOptions: { shape: "rectangle", strokeColor: "#662B2B", dashed: "0", strokeWidth: 1 }, x: 100, y: 100, width: 100, height: 100,
to: [
{ id: "7", style: { strokeColor: "red", edgeStyle: "orthogonalEdgeStyle", rounded: 0, orthogonalLoop: 1 }, edgeOptions: { id: "25", value: "8888" } },
{ id: "9", edgeOptions: { id: "35", value: "9999" } }], options: { name: "add", type: "start" }
},
{ id: "7", value: "结束1", styleOptions: {shape: "cylinder"}, x: 500, y: 400, width: 100, height: 100, to: [], options: { name: "add", type: "rounded" } },
{ id: "9", value: "结束2", styleOptions: {shape: "cylinder", strokeWidth: 2, fillColor: "#ffffff", strokeColor: "black", backgroundOutline: 1, size: 15, rounded: 1}, x: 600, y: 500, width: 100, height: 100, to: [], options: { name: "add", type: "ellipse" } }
],
```
让我为 graphData 中的数据每一项做个简单的说明:
| id | 每个图形唯一的标识|
|--|--|
| value | 图形的 label 值|
| styleOptions | 图形的基本样式 |
| x | 图形的 x 轴距离|
| y | 图形的 y 轴距离|
| width | 图形的宽度|
| height | 图形的高度|
每一项的 to 作为一个数组,关联于它下面的一个节点,说明说明
| id | 目标元素的 id|
|--|--|
| options | 线条额外的属性 |
| styleOptions | 线条的样式 |
使用的方式可以[参考地址](https://github.com/whenTheMorningDark/vue-kai-admin/blob/master/src/views/mxgraph/index.vue)
**三.自定义连线规则**
在实际项目中我们需要判断那些图形可连可不连,那么我们需要在每个图形中做手脚,我们在在每个图形 options 对象中添加相对应的 type 属性,实际上,这个 options 就是专门为我们去做自定义的事情。
另外自定义的检验函数为 rules,
```javascript
// 自定义是否连线规则
rules (source, target) {
return true;
}
```
函数会返回两个参数,分别是来源和目标你可以根据这两个 type 来判断可联可不联。
**4.目前功能**
目前完善的功能点如下:
1. 数据驱动生成图形
2. 删除图形
3. 前进和后退图形
4. 自定义校验函数
5. 自定义图形
未来功能点: 1.导出功能(图片) 2.放大缩小
.......
**五.组件链接**
组件的 github 链接[mxGraph 组件](https://github.com/whenTheMorningDark/vue-kai-admin/tree/master/src/components/mxGraph)
|
e78de461bd6c755d4d4557512da2fa940acbd190
|
[
"Markdown",
"JavaScript"
] | 34 |
Markdown
|
whenTheMorningDark/vue-kai-admin
|
b4e8128d946a8652a2cff31d2a88b35c9782231b
|
bc3cb50853adfaec3fdf2c196d0fc83dd1e8545b
|
refs/heads/master
|
<repo_name>setzerbomb/apmt-server<file_sep>/server/objects/Slave.lua
function Slave()
-- Local variables of the object / Variáveis locais do objeto
local self = {}
local data
-- Global functions of the object / Funções Globais do objeto
function self.setId(id)
data.id = id
end
function self.getId()
return data.id
end
function self.setProtocol(protocol)
data.protocol = protocol
end
function self.getProtocol()
return data.protocol
end
function self.getTasks()
return data.tasks
end
function self.addTask(task)
data.tasks[task.id] = task
end
function self.subTask(task)
data.tasks[task.id] = nil
end
function self.start(tabela)
data = tabela
end
return self
end
<file_sep>/server/programs/MainApp.lua
function MainApp(root)
dofile(root .. "objects/CommonFunctions.lua")
dofile(root .. "objects/LoadPeripherals.lua")
dofile(root .. "objects/Communicator.lua")
dofile(root .. "GUI/GUIMessages.lua")
dofile(root .. "controller/DataController.lua")
dofile(root .. "programs/Configuration.lua")
self = {}
local commonF = CommonFunctions()
local guiMessages = GUIMessages()
local communicator = Communicator()
local dataController = DataController(commonF,root)
dataController.load()
local slaves = (dataController.getObjects()).slaveList.getSlaves()
local continue = true
local tasksIteratorList = {}
local protocolCallsList = {}
local callers = {}
local save = false
local selectedSlave = nil
local function taskIterator(data)
local function findNextTask(tasks)
for i,task in ipairs(tasks) do
if (not task.complete) then
return task
end
end
return nil
end
local slave = data
coroutine.yield()
while true do
if (#slave.tasks > 0) then
local task = findNextTask(slave.tasks)
if (task ~= nil) then
if (not task.sent) then
for i = 1,17 do
--print(task.execution .. ": trying for the " .. i .. " time")
rednet.send(slave.id,textutils.serialize(task),slave.protocol)
coroutine.yield()
end
task.sent = true
save = true
else
coroutine.yield()
end
end
end
coroutine.yield()
end
end
local function addSlave(protocol,id)
if (slaves[id] == nil) then
slaves[id] = {["protocol"] = protocol, ["id"] = id, ["tasks"] = {}}
tasksIteratorList[id] = coroutine.create(taskIterator)
dataController.saveData()
else
slaves[id].protocol = protocol
tasksIteratorList[id] = coroutine.create(taskIterator)
dataController.saveData()
end
end
local function protocolCalls(data)
local function executeNTimes(f,params)
local data = nil
for i = 1,10 do
data = f(params)
if data ~= nil then
return data,true
end
coroutine.yield()
end
return nil,false
end
local caller = data
local s,m,p = caller[1], caller[2], caller[3]
caller.randomKey = commonF.randomness(100,999)
caller.finished = true
caller.step = 0
caller.completed = false
local r = caller.randomKey
coroutine.yield()
local data,status = executeNTimes(
function (params)
rednet.send(params[1],r,os.getComputerID() .. params[1])
if (caller.completed) then
return "finished"
else
return nil
end
end,
{s}
)
coroutine.yield()
end
local function protocolCallsIteratorList()
while true do
if (#callers > 0) then
for k,v in ipairs(callers) do
if (coroutine.status(protocolCallsList[v[1]]) ~= "dead") then
coroutine.resume(protocolCallsList[v[1]],v)
coroutine.yield()
else
protocolCallsList[v[1]] = nil
end
end
end
coroutine.yield()
end
end
local function protocolCallsReceiver()
local s,m,p = rednet.receive(0.2)
if (s~=nil and p~=nil) then
if (p=="apmtSlaveConnection" and (protocolCallsList[s] == nil or coroutine.status(protocolCallsList[s]) == "dead")) then
callers[#callers+1] = {s,m,p}
protocolCallsList[s] = coroutine.create(protocolCalls)
end
end
if (#callers > 0) then
for k,caller in ipairs(callers) do
if (protocolCallsList[caller[1]] ~=nil) then
if (coroutine.status(protocolCallsList[caller[1]]) ~= "dead") then
if (caller.finished ~= nil) then
if (caller.finished) then
if (not caller.completed) then
if (caller.step < 10) then
if (s ~= nil) then
if (p == (os.getComputerID() .. caller[1])) then
caller.completed = true
addSlave(os.getComputerID() .. caller[1] .. (caller.randomKey * m), caller[1])
end
end
caller.step = caller.step + 1
end
end
end
end
else
callers[k] = nil
end
end
end
end
if selectedSlave ~= nil then
--print(textutils.serialize(selectedSlave))
if (tasksIteratorList[selectedSlave.id] ~= nil) then
for k,task in ipairs(selectedSlave.tasks) do
if task.sent and (not task.complete) then
--print(selectedSlave.protocol .. " " .. task.execution)
if (s~=nil) then
--print(p .. " " .. selectedSlave.protocol .. " " .. s)
if (selectedSlave.protocol == p) then
if (s == selectedSlave.id) then
local receivedTask = textutils.unserialize(m)
if receivedTask ~=nil then
--print(p .. " " .. selectedSlave.protocol .. " " .. task.execution .. " " .. receivedTask.execution)
if receivedTask.complete == true and receivedTask.execution==task.execution then
task.complete = true
task.status = receivedTask.status
save = true
end
end
end
end
end
end
end
end
end
end
local function lastCall()
end
local function slaveSelector()
while true do
for k,slave in pairs(slaves) do
selectedSlave = slave
coroutine.yield()
end
coroutine.yield()
end
end
local function slavesIterator()
while true do
for k,slave in pairs(slaves) do
if (tasksIteratorList[slave.id] ~= nil) then
coroutine.resume(tasksIteratorList[slave.id],slave)
coroutine.yield()
end
end
coroutine.yield()
end
end
local function patternAction()
local pcil = coroutine.create(protocolCallsIteratorList)
local si = coroutine.create(slavesIterator)
local ss = coroutine.create(slaveSelector)
while true do
coroutine.resume(ss)
protocolCallsReceiver()
coroutine.resume(pcil)
coroutine.resume(si)
if commonF.keyPressed(0.1) ~= 0 then
break
end
if save then
save = false
dataController.saveData()
end
end
end
local mainCase = commonF.switch{
[1] = function(x)
Configuration(root,commonF,dataController,guiMessages)
end,
[2] = function(x)
patternAction()
end,
[3] = function(x)
os.reboot()
end,
[4] = function(x)
continue = false
end,
default = function (x) continue = false end
}
local function menu()
guiMessages.showHeader("------Main Menu------")
print("1: Configure")
print("2: Applications")
print("3: Reboot")
print("4: Exit")
return commonF.limitToWrite(15)
end
function self.main()
(dataController.getObjects()).slaveList.reset()
dataController.saveData()
rednet.host("apmtSlaveConnection","apmtServer" .. os.getComputerID())
if (communicator.modemIsEnabled()) then
while continue do
patternAction()
mainCase:case(tonumber(menu()))
end
else
guiMessages.showErrorMsg("Error: This computer has no modems atached")
end
end
return self
end
<file_sep>/server/main.lua
local root = "server/"
dofile(root .. "programs/MainApp.lua")
local turnOn = true
for k,v in pairs(redstone.getSides()) do
if redstone.getInput(v) then
turnOn = false
break
end
end
if turnOn then
if os.getComputerLabel() == nil then
os.setComputerLabel("PC"..os.getComputerID())
end
local mainApp = MainApp(root)
mainApp.main()
end<file_sep>/README.md
# Almost Persistent Mining Turtle - Server
This is a server for APMT
## Getting Started
These instructions will get you a copy of the project up and running on your turtle
### Prerequisites
This project was designed to run on ComputerCraft 1.7.5 at Minecraft 1.7.10 version or superior
```
* Minecraft 1.7.10
* ComputerCraft 1.7.5
* Minecraft Forge compatible with 1.7.10 version
```
### Installing
```
pastebin get cUYTGbpb bbpack
bbpack mount https://github.com/setzerbomb/apmt-server/tree/master install
cp install\server server
mv server\startup startup
reboot
```
## Contributing
Feel free to contribute with the project, these are the guidelines:
* Create and run some tests to ensure that your code works as you espect
* The code uses prototypes and some OO concepts, make sure that your code is written similar or better
## Next Goals
- Improve the documentation
## Versioning
This project uses some core [Semantic Versioning](https://semver.org/) principles
## Authors
* **Set** - *All work until now* - [setzerbomb](https://github.com/setzerbomb)
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
<file_sep>/server/objects/Communicator.lua
function Communicator(commonF)
local self = {}
local loadPeripherals = nil
local hasModem = false
local function executeNTimes(f,params)
local data = nil
for i = 1,10 do
data = f(params)
if data ~= nil then
return data,true
end
end
return nil,false
end
local function main()
lp = LoadPeripherals()
hasModem = lp.openWirelessModem(lp.getTypes())
end
self.modemIsEnabled = function()
return hasModem
end
main()
return self
end
<file_sep>/server/controller/DataController.lua
function DataController(commonFunctions,root)
dofile(root .. "objects/TableHandler.lua")
dofile(root .. "objects/Slave.lua")
dofile(root .. "objects/SlaveList.lua")
-- Local variables of the object / Variáveis locais do objeto
local self = {}
local TableH = TableHandler()
local values = nil
local objects = {}
objects.slaveList = SlaveList()
-- Local functions of the object / Funções locais do objeto
local function fillObjects()
objects.slaveList.start(values.SlaveList)
end
-- Create a new set data if the data file is empty / Cria um novo conjunto de dados se o arquivo de dados está vazio
local function newData()
values = {}
values.SlaveList = {}
fillObjects()
self.saveData()
end
-- Global functions of the object / Funções Globais do objeto
-- Load all the data from file / Carrega todos os dados do arquivo
local function configureDataObjects()
if values ~= nil and next(values) ~= nil then
fillObjects()
else
newData()
end
end
local function tryToSave()
TableH.save(values,os.getComputerLabel())
end
-- Retrieve the data from the config file / Puxa os dados do arquivo de configuração
function self.load()
if TableH.fileExists(os.getComputerLabel()) then
values = TableH.load(os.getComputerLabel())
configureDataObjects()
else
configureDataObjects()
end
end
-- Save the data into the config file / Salva os dados no arquivo de configuração
function self.saveData()
commonFunctions.try(
tryToSave,
function(exeception) guiKP.showErrorMsg("DataController: Cautch exception while trying to save turtle data: " .. exeception) end
)
end
-- Getters
function self.getObjects()
return objects
end
return self
end
<file_sep>/server/objects/SlaveList.lua
function SlaveList()
-- Local variables of the object / Variáveis locais do objeto
local self = {}
local data
-- Global functions of the object / Funções Globais do objeto
function self.getSlaves()
return data
end
function self.addSlave(slave)
data.slaves[slave.id] = slave
end
function self.subSlave(slave)
data.slaves[slave.id] = nil
end
function self.start(tabela)
data = tabela
end
function self.reset()
if data ~= nil then
for k,slave in pairs(data) do
for i,task in ipairs(slave.tasks) do
if not task.complete then
task.sent = false
end
end
end
end
end
return self
end
<file_sep>/server/programs/Configuration.lua
function Configuration(root,commonF,dataController,guiMessages)
local slaves = (dataController.getObjects()).slaveList.getSlaves()
local continue = true
local function createTask(id,execution,params)
task = {}
task.id = id or 0
task.complete = false
task.sent = false
task.params = params or {}
task.execution = execution or ""
return task
end
local function showAvailableTurtles()
guiMessages.showSuccessMsg("Available Turtles")
for k,slave in pairs(slaves) do
io.write("[".. slave.id .."]")
end
print("")
end
local function createAndAssign()
if (next(slaves)~=nil) then
guiMessages.showHeader("------Create and Assign------")
showAvailableTurtles()
guiMessages.showInfoMsg("Select the Turtle")
local selected = tonumber(io.read())
if (selected ~= nil) then
selected = slaves[selected]
if (selected ~= nil) then
local tasks = selected.tasks
guiMessages.showInfoMsg("---Available Tasks---")
print("1: Create a Stair")
print("2: Create a Tunnel")
print("3: Go to a specific position [x,y,z]")
print("4: Quarry mode")
print("5: Diamond Quarry mode")
local resp = tonumber(io.read())
if resp == 1 then
tasks[#tasks+1]=createTask(
#tasks+1,
"Stairs",
{}
)
else
if resp == 2 then
print("Inform limit 3x3x?")
local limit = tonumber(io.read())
if limit ~= nil then
tasks[#tasks+1]=createTask(
#tasks+1,
"Tunnel",
{limit}
)
guiMessages.showSuccessMsg("Success")
else
guiMessages.showErrorMsg("Error: Limit must be a number")
end
else
if resp == 3 then
print("Type the X value")
local x = tonumber(io.read())
print("Type the Y value")
local y = tonumber(io.read())
print("Type the Z value")
local z = tonumber(io.read())
if (x~=nil and y~=nil and z~=nil) then
tasks[#tasks+1]=createTask(
#tasks+1,
"GoToPosition",
{x,y,z}
)
guiMessages.showSuccessMsg("Success")
else
guiMessages.showErrorMsg("Error: Limit must be a number")
end
else
if resp == 4 then
print("Type the X value")
local x = tonumber(io.read())
print("Type the Y value")
local y = tonumber(io.read())
if (x~=nil and y~=nil) then
tasks[#tasks+1]=createTask(
#tasks+1,
"Quarry",
{x,y}
)
guiMessages.showSuccessMsg("Success")
else
guiMessages.showErrorMsg("Error: Limit must be a number")
end
else
if resp == 5 then
print("Type the X value")
local x = tonumber(io.read())
print("Type the Y value")
local y = tonumber(io.read())
if (x~=nil and y~=nil) then
tasks[#tasks+1]=createTask(
#tasks+1,
"DiamondQuarry",
{x,y}
)
guiMessages.showSuccessMsg("Success")
else
guiMessages.showErrorMsg("Error: Limit must be a number")
end
end
end
end
end
end
end
end
dataController.saveData()
else
guiMessages.showInfoMsg("No turtles to show")
end
end
local function showTaskList()
if (next(slaves)~=nil) then
guiMessages.showHeader("------Task List------")
showAvailableTurtles()
guiMessages.showInfoMsg("Select the Turtle")
local selected = tonumber(io.read())
if (selected ~= nil) then
selected = slaves[selected]
if (selected ~= nil) then
if (#selected.tasks > 0 ) then
for i = 1,#selected.tasks do
io.write("[".. selected.tasks[i].id ..":".. selected.tasks[i].execution .."]")
end
print("")
print("1: Show detailed info of: [-1:None; ...]")
print("2: Delete all finished tasks of selected turtle")
local option = tonumber(io.read())
if option == 1 then
print("Type task number")
local action = tonumber(io.read())
if action ~= nil then
guiMessages.showInfoMsg(textutils.serialize(selected.tasks[action]))
else
guiMessages.showErrorMsg("Error: Must be a number")
end
end
if option ==2 then
local newListOfTasks = {}
for i = 1,#selected.tasks do
if selected.tasks[i].complete == false then
newListOfTasks[#newListOfTasks + 1] = selected.tasks[i]
end
end
selected.tasks = newListOfTasks
guiMessages.showInfoMsg("Deleted completed tasks of " .. selected.id)
end
else
guiMessages.showInfoMsg("Tasks of Turtle " .. selected.id .. ": None")
end
end
end
dataController.saveData()
else
guiMessages.showInfoMsg("No turtles or tasks to show")
end
end
local optionsCase = commonF.switch{
[1] = function(x)
createAndAssign()
end,
[2] = function(x)
showTaskList()
end,
[3] = function(x)
continue = false
end,
default = function (x) guiMessages.showErrorMsg("Invalid option") continue = false end
}
local function menu()
guiMessages.showHeader("------Configuration------")
print("1: Create and Assign a task to a Turtle")
print("2: Show task list of a Turtle")
print("3: Exit")
return commonF.limitToWrite(15)
end
while continue do
optionsCase:case(tonumber(menu()))
end
end
|
a49c953851e5e491bbdb8edfd6d60d53e5e3f929
|
[
"Markdown",
"Lua"
] | 8 |
Lua
|
setzerbomb/apmt-server
|
2eaa4d2007bae9eafc6cf94bd03738aab02d7e75
|
54d7647179f8e9a9ad86d6b83d147b079ffcae56
|
refs/heads/master
|
<repo_name>ongrafo/vuejs_ejemplo4<file_sep>/ejemplo4.js
const app = new Vue({
el: '#app',
data: {
mensaje: 'Hola soy Edgar',
contador: 0
},
computed: {
invertido(){
return this.mensaje.split('').reverse().join('');
},
color(){
return{
'bg-succes' : this.contador <= 10,
'bg-warning' : this.contador > 10 && this.contador < 20,
'bg-danger' : this.contador >= 20
// Prueba Git.
// Prueba Git.
// Prueba Git.
//Mensaje "Pelota" para verificar commit.
}
}
}
});
|
70e761e2a7b6359154c7108d7ce85d5abbced607
|
[
"JavaScript"
] | 1 |
JavaScript
|
ongrafo/vuejs_ejemplo4
|
a1582dfce58de7c28b9727895b03fe652aa199bf
|
6cdf32d28d259e602eb2d631f4bdf10968819906
|
refs/heads/main
|
<repo_name>erictaur/OpenFASOC<file_sep>/generators/ldo-gen/flow/design/sky130hvl/ldo/config.mk
export DESIGN_NICKNAME = ldo
export DESIGN_NAME = ldoInst
#export DESIGN_NAME = tempsenseInst_error
export PLATFORM = sky130hvl
#export VERILOG_FILES = $(sort $(wildcard ./designs/src/$(DESIGN_NICKNAME)/*.v))
# export VERILOG_FILES = ./designs/src/$(DESIGN_NICKNAME)/tempsenseInst.v \
# ./platforms/$(PLATFORM)/tempsense/tempsenseInst.blackbox.v
export VERILOG_FILES = $(sort $(wildcard ./design/src/$(DESIGN_NICKNAME)/*.v)) \
../blocks/$(PLATFORM)/ldoInst.blackbox.v
export SDC_FILE = ./design/$(PLATFORM)/$(DESIGN_NICKNAME)/constraint.sdc
export DIE_AREA = 0 0 320 320
export CORE_AREA = 10 10 310 310
#export VD1_AREA = 33.58 32.64 64.86 62.56
export PDN_CFG = ../blocks/$(PLATFORM)/pdn.cfg
export ADDITIONAL_LEFS = ../blocks/$(PLATFORM)/lef/capacitor_test_nf.lef \
../blocks/$(PLATFORM)/lef/LDO_COMPARATOR_LATCH.lef \
../blocks/$(PLATFORM)/lef/PMOS.lef \
../blocks/$(PLATFORM)/lef/PT_UNIT_CELL.lef \
../blocks/$(PLATFORM)/lef/vref_gen_nmos_with_trim.lef
export ADDITIONAL_GDS_FILES = ../blocks/$(PLATFORM)/gds/capacitor_test_nf.gds \
../blocks/$(PLATFORM)/gds/LDO_COMPARATOR_LATCH.gds \
../blocks/$(PLATFORM)/gds/PMOS.gds \
../blocks/$(PLATFORM)/gds/PT_UNIT_CELL.gds \
../blocks/$(PLATFORM)/gds/vref_gen_nmos_with_trim.gds
#export ADDITIONAL_LIBS = ../blocks/$(PLATFORM)/lib/capacitor_test_nf.lib \
../blocks/$(PLATFORM)/lib/LDO_COMPARATOR_LATCH.lib \
../blocks/$(PLATFORM)/lib/PMOS.lib \
../blocks/$(PLATFORM)/lib/PT_UNIT_CELL.lib \
../blocks/$(PLATFORM)/lib/vref_gen_nmos_with_trim.lib
export DOMAIN_INSTS_LIST = ../blocks/$(PLATFORM)/tempsenseInst_domain_insts.txt
export CUSTOM_CONNECTION = ../blocks/$(PLATFORM)/tempsenseInst_custom_net.txt
export ADD_NDR_RULE = 1
export NDR_RULE_NETS = r_VIN
export NDR_RULE = NDR_2W_2S
<file_sep>/.github/scripts/dependencies/get_tag.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 Efabless Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import subprocess
def get_tag():
tag = None
try:
tag = subprocess.check_output(["git", "describe", "--tags", "--abbrev=0"]).decode("utf8").strip()
except Exception as e:
pass
if tag is None:
try:
tag = open("./resolved_version").read()
except:
print("Please input the version of OpenLane you'd like to pull: ", file=sys.stderr)
try:
tag = input()
with open("./resolved_version", "w") as f:
f.write(tag)
except EOFError:
print("Could not resolve the version of OpenLane being used. This is a critical error.", file=sys.stderr)
exit(-1)
return tag
if __name__ == "__main__":
print(get_tag(), end="")
|
11d9573c5a82c4e9706d2a5f6108812c89f7bca4
|
[
"Python",
"Makefile"
] | 2 |
Makefile
|
erictaur/OpenFASOC
|
9ee35652e84ea33f56a9ee53c249f745bd5bdcec
|
f7990f68b6187fd6872fc06beb1bbb7aa66a67d3
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "btree.c"
void treeAdd(struct node * tree, char * key){
struct node * newnode;
printf("Adding %s\n", key);
newnode = treeSearch(tree, key);
if (newnode) {
newnode->count++;
} else {
treeInsert(tree, key);
}
}
int main(int argc, char **argv){
printf("Welcome to btree!\n");
struct node * root = makeNode("**root**");
treeAdd(root, "a");
printf("Tree height: %d Size: %d\n", treeHeight(root), treeSize(root));
treeAdd(root, "b");
printf("Tree height: %d Size: %d\n", treeHeight(root), treeSize(root));
treeAdd(root, "z");
printf("Tree height: %d Size: %d\n", treeHeight(root), treeSize(root));
treeAdd(root, "d");
treeAdd(root, "d");
treeAdd(root, "b");
treeAdd(root, "b");
treeAdd(root, "b");
printf("Tree height: %d Size: %d\n", treeHeight(root), treeSize(root));
printTreePre(root);
printf("\n");
printTreeIn(root);
printf("\n");
printTreePost(root);
printf("\n");
treeDestroy(root);
}
<file_sep>/*
stacktest.c
demonstrate stack functions
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include "stack.c"
// struct token {
// char * str;
// int type;
// double value;
// };
typedef struct token *Token;
// defined in stack.c
void * mymalloc(size_t s){
void * ptr = malloc(s);
memset(ptr, 0, s);
if (debugflag) {
printf("Mymalloc: %zu bytes: %p\n", s, ptr);
}
return ptr;
}
// defined in stack.c
// and used in stackDestroy
void myfree(void * p){
if (debugflag) {
printf("Myfree: %p \n", p);
}
free(p);
}
char *copyString(char *str)
{
int len = strlen(str);
char *tmp = mymalloc(len + 1);
if (tmp) {
strcpy(tmp, str);
//tmp[len] = '\0';
}
return tmp;
}
int main(int argc, char **argv){
debugflag = true;
if (argc == 1) {
fprintf(stderr, "Usage: stacktest numbers+\n");
exit(1);
}
Token tok;
int stacksize = 10;
stackT st;
StackInit(&st, stacksize);
char * strtmp;
int val;
for (int i=1; i < argc; i++) {
tok = mymalloc(sizeof(struct token));
tok->type = NUM;
strtmp = argv[i];
tok->str = copyString(strtmp);
val = strtod(strtmp, NULL);
tok->value = val;
StackPush(&st, tok);
}
StackPrint(&st);
tok = StackPop(&st);
myfree(tok->str);
myfree(tok);
StackPrint(&st);
StackDestroy(&st);
return(0);
}<file_sep>// This program is Cloud.c and it takes in input from
// standard input and it tabulates the frequency
// of words in the input and output those over a threshold
// Programmer: <NAME>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include "btree.h"
#define MAXSIZE 1024 // maximum size of input
bool is_int(char *s);
bool non_alpha(char *s);
int atoi(const char *str);
void to_lower(char *s);
void treeAdd(struct node * tree, char * key);
int main(int argc, char *argv[]){
// flags for command line argument
bool preorder = false;
bool postorder = false;
bool inorder = false;
bool html = false;
bool debugflag;
debugflag = false;
int threshold; // stores threshold value from command line input
threshold = 5;
for( int i = 1; i < argc ; i++){ // loop through command line input
if(!strcmp(argv[i], "-threshold")){
if(i == (argc-1)){
fprintf(stderr,"Missing threshold argment on command line.\n");
}
else if (atoi(argv[i+1]) == 1){
fprintf(stderr, "Invalid threshold value: %s\n", argv[i+1]);
i +=1; // Skip next input
}
else if( !is_int(argv[i+1])){
fprintf(stderr, "Invalid threshold value: %s\n", argv[i+1]);
i+=1; // Skip next input
}
else{
threshold = atoi(argv[i+1]);
}
}
else if(!strcmp(argv[i], "-html")){
html = true;
}
else if(!strcmp(argv[i], "-debug")){
debugflag = true;
}
else if(!strcmp(argv[i], "-preorder")){
preorder = true;
}
else if(!strcmp(argv[i], "-inorder")){
inorder = true;
}
else if(!strcmp(argv[i], "-postorder")){
postorder = true;
}
else if(is_int(argv[i])){
if (strcmp(argv[i-1], "-threshold")){
fprintf(stderr,
"Fatal error: invalid command line argument: %s\n",argv[i]);
exit(0);
}
}
else{
fprintf(stderr,
"Fatal error: invalid command line argument: %s\n", argv[i]);
exit(0);
}
}
// character buffer that stores input from fgets
char buffer[MAXSIZE+1];
char *token; // character pointer to extract tokens
struct node *cloud; // Linkedlist cloud node
cloud = NULL;
struct node * root = makeNode("**root**");
while(fgets(buffer, MAXSIZE +1 , stdin) != NULL){ // Loop through stdin
if(debugflag){
printf("Input: %s",buffer);
}
buffer[strlen(buffer) -1] = '\0';
token = strtok(buffer, " ");
while( token != NULL ){ // Process tokenized input
if( ! non_alpha(token)){
to_lower(token);
treeAdd(root, token);
if(treeSearch(root, token)->count >= threshold){
if(cloud == NULL){
cloud = treeSearch(root,token);;
cloud->next = NULL;
}
else{
struct node *e;
bool present = false;
// Check if node in linked list
for(e = cloud; e != NULL; e = e->next){
if(!strcmp(e->key, token)){
present = true;
}
}
if(!present){ // If not present, put in front of list
treeSearch(root,token)->next = cloud;
cloud = treeSearch(root,token);
}
}
}
}
token = strtok(NULL," ");
}
}
// Print output messages
if(debugflag){
printf("Tree height: %d\n", treeHeight(root));
printf("Tree size: %d\n",treeSize(root));
}
if(preorder){
printf("PREORDER\n");
printTreePre(root);
printf("\n");
}
if(inorder){
printf("INORDER\n");
printTreeIn(root);
printf("\n");
}
if(postorder){
printf("POSTORDER\n");
printTreePost(root);
printf("\n");
}
if(cloud == NULL){
printf("No words seen %d times.\n", threshold);
}
else{
struct node *e;
int i = 0;
if(!html){
printf("The Word Cloud:\n");
}
for(e = cloud; e != NULL; e = e->next){
if(!html){ // print regular output
printf("[%d] %s [%d]\n", i, e->key, e->count);
}
else{ // print html output
printf("<div style=\"font-size: %dpx\"> %s </div>\n",
e->count, e->key);
}
i++;
}
}
treeDestroy(root);
}
// This function takes in a character pointer s and returns true
// if it is an integer and false otherwise.
bool is_int(char *s){
if(atoi(s) == 0){
return false;
}
if(s[0] == '-'){
return false;
}
return true;
}
// This function takes in a character pointer s and returns true
// if it is not a non_alpha character and false otherwise.
bool non_alpha(char *s){
for(int i = 0; i < strlen(s); i++){
if( !(s[i] <= 'z' && s[i] >= 'a') && !(s[i] <= 'Z' && s[i] >= 'A')){
return true;
}
}
return false;
}
// This function takes in a character pointer s and converts
// the string to upper case form.
void to_lower(char *s){
for(int i = 0; i < strlen(s); i++){
if( (s[i] <= 'Z' && s[i] >= 'A')){
s[i] = s[i] - ('A' - 'a');
}
}
}
// This function takes in a pointer to a node (tree) and a character
// pointer (key). It creates a new node from key and calls treeSearch to
// see if it is in the tree already. If so it increments the nodes count
// and if not, it inserts the node into the tree using treeInsert.
void treeAdd(struct node * tree, char * key){
struct node * newnode;
newnode = treeSearch(tree, key);
if (newnode) {
newnode->count++;
}
else {
treeInsert(tree, key);
}
}
<file_sep>// File name: Callme.c
// This program converts alphabetic input into numbers and converts numeric
// numbers into words and checks the online dictionary if there are any
// matching words and prints them out.
// Programmer: <NAME>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include "hash.c"
int strcmp(const char *str1, const char *str2);
int tolower(int c);
size_t strlen(const char *str);
void getCombo(Hash h, int number [], int current_digit, char result[], int n);
void convertWord(char *s);
static bool match; // global flag if a word is matched in hash
int main(int argc, char *argv[]){
extern bool debugflag; // Flag for -debug argument
extern bool match;
if (argc == 1 || argc > 3){ // Check for too little or too many arguments
fprintf(stderr, "usage: Callme (digits | letters) [-debug]?\n");
exit(0);
}
else if (argc == 3){ // Check for -debug argument if two inputs
if (strcmp(*(argv+2), "-debug") == 0){
debugflag = true;
}
else{
fprintf(stderr,"Fatal error: invalid argument %s\n", *(argv + 2));
exit(0);
}
}
if ( argv[1][0] == 48 && strlen(*(argv+1)) == 1 ){ // Check for 0 case
fprintf(stderr, "Fatal error: invalid argument %s\n", *(argv + 1));
exit(0);
}
for(int j = 0; argv[1][j] != '\0'; j++){
// If not letter or digit print error
if(! (( tolower(argv[1][j]) >= 97 && tolower(argv[1][j]) <= 122 ) ||
((argv[1][j]) >= 48 && (argv[1][j]) <= 57 ))){
fprintf(stderr, "Fatal error: invalid argument %s\n", argv[1]);
exit(0);
}
}
// if first letter is a letter
if (tolower(argv[1][0]) >= 97 && tolower(argv[1][0]) <= 122 ){
for(int j = 0; argv[1][j] != '\0'; j++){ // If digit print error
if( !(tolower(argv[1][j]) >= 97 && tolower(argv[1][j])<= 122)){
fprintf(stderr,"Fatal error: invalid argument %s\n", argv[1]);
exit(0);
}
} // Output for alphabetic input
printf("alphabetic: %s => ", *(argv+1));
convertWord(*(argv +1));
printf("%s\n", *(argv +1));
}
else{ // Number input
for(int j = 0; argv[1][j] != '\0'; j++){
// If contains letter then print error
if( tolower(argv[1][j]) >= 97 && tolower(argv[1][j]) <= 122){
fprintf(stderr,"Fatal error: invalid argument %s\n", argv[1]);
exit(0);
}
}
FILE *ptr_file;
char buf[1000];
ptr_file =fopen("words.txt", "r");
Hash myHash = HashCreate();
char *point; // Pointer to get thorugh text file
point = fgets(buf,1000, ptr_file);
int len = strlen(*(argv+1)); // Length of number input
if (debugflag){
printf("Loading dictionary\n");
}
while (point !=NULL){
int index = 0;
while (*(point+index) != '\0'){
index++;
}
if (*(point+index-1) == '\n'){ // Delete newline
*(point+index-1) = '\0';
index--;
}
for(int k = 0; point[k] != '\0'; k++){
point[k] = tolower(point[k]);
}
if(index == len){
HashInsert(myHash, point);
}
point = fgets(buf,1000, ptr_file);
}
fclose(ptr_file);
if(debugflag){
printf("Word Count: %lu\n", myHash->n);
}
int number[len]; // Array of digits to store numbere
for (int k = 0; argv[1][k] != '\0'; k++){
number[k] = argv[1][k] - 48; // Convert char number to int number
}
match = false;
char result[len]; // Char array to hold resulting words
printf("numeric: %s =>", *(argv+1));
getCombo(myHash, number, 0, result, len-1);
if (!match){ // If no matches found print it out
printf(" ** no matches **");
}
printf("\n");
HashDestroy(myHash);
}
}
// This recursive function takes in a hash table (H) of words,
// array of integers (number) to make words out of, an indexing
// int (current_digit),a character array (result) to store each word
// per iteration, the length of the number array (n),
// This function obtains the different combination of words that can be made,
// checks if the word is in the hash table, and prints it out if so.
// It also changes the global variable match to true if a word is matched.
void getCombo(Hash H, int number [], int current_digit, char result[], int n)
{
const char letters[10][5] = {"", "", "abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"};
int end = 3; // Get number of possible letters for each digit
if (number[current_digit] == 7 || number[current_digit] == 9){
end = 4;
}
for(int j = 0; j< end; j++){
// Convert current digit to letter and store
result[current_digit] = letters[number[current_digit]][j];
if(current_digit < n){ // Get next digit to letter
getCombo(H, number, current_digit+1, result, n);
}
if (current_digit == n){ // If last digit store into combos
result[n+1] = '\0';
if (HashSearch(H, result)){
printf(" %s", result);
match = true;
}
}
}
}
// This function takes in a character pointer (*s) of a word,
// converts it to lower case, and replaces it with the
// corresponding number character. If the character isn't a
// valid letter, the function leaves it be.
void convertWord(char *s){
for(int j = 0; *(s+j) != '\0'; j++){
*(s+j) = tolower(*(s+j));
if (*(s+j) == 'a' ||*(s+j) == 'b' || *(s+j) == 'c'){
*(s+j) = '2';
}
else if (*(s+j) == 'd' ||*(s+j) == 'e' || *(s+j) == 'f'){
*(s+j) = '3';
}
else if (*(s+j) == 'g' ||*(s+j) == 'h' || *(s+j) == 'i'){
*(s+j) = '4';
}
else if (*(s+j) == 'j' ||*(s+j) == 'k' || *(s+j) == 'l'){
*(s+j) = '5';
}
else if (*(s+j) == 'm' ||*(s+j) == 'n' || *(s+j) == 'o'){
*(s+j) = '6';
}
else if (*(s+j) == 'p'||*(s+j) == 'q'||*(s+j) == 'r'||*(s+j) == 's'){
*(s+j) = '7';
}
else if (*(s+j) == 't' ||*(s+j) == 'u' || *(s+j) == 'v'){
*(s+j) = '8';
}
else if (*(s+j) == 'w'||*(s+j) == 'x'|| *(s+j)== 'y'||*(s+j) == 'z'){
*(s+j) = '9';
}
}
}
<file_sep>// This file contains the implementations of the methods
// outlined in the header file stack.h. The programmer
// name is <NAME>.
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include "stack.h"
// This function takes in a pointer to a stackT type (stackP)
// and the maximum size of the stackT (maxSize) and initializes
// the stackT fields. It mallocs memory for contents and
// initializes each to be 0.
void StackInit(stackT *stackP, int maxSize){
stackP->top = 0;
stackP->count = 0;
stackP->maxSize = maxSize;
stackP->contents = malloc(sizeof(Token*)*maxSize);
for(int j = 0; j<maxSize; j++){
stackP->contents[j] = 0;
}
}
// This function takes in a pointer to a stackT type (stackP) and
// frees its occupied contents.
void StackDestroy(stackT *stackP){
for(int i =0; i<stackP->count; i++){
free(stackP->contents[i]->str);
free(stackP->contents[i]);
}
free(stackP->contents);
}
// This function takes in a pointer to a stackT type (stackP) and a
// Token type (element). If the stack is full then it returns an error
// but pushes the Token onto the stack if there is space and increments
// the count variable
void StackPush(stackT *stackP, Token element){
if(!StackIsFull(stackP)){
stackP->contents[stackP->count] = element;
if (stackP->count != 0){
stackP->top++;
}
stackP->count++;
}
else{
fprintf(stderr, "Stack is full\n");
exit(0);
}
}
// This funciton takes in a pointer to a stackT type (stackP) and if
// the stack is empty, it prints an error and exits. If it is not empty
// it mallocs a Token (S) and copies the contents of the top of the stack
// into S and frees the top of the stack. It then returns S
Token StackPop(stackT *stackP){
if (!StackIsEmpty(stackP)){
Token S = malloc(sizeof(struct token));
*S = *stackP->contents[stackP->top];
free(stackP->contents[stackP->top]);
stackP->contents[stackP->top] = NULL;
stackP->count--;
if(stackP->top != 0){
stackP->top--;
}
return S;
}
fprintf(stderr, "Stack is empty\n");
exit(0);
}
// This funciton takes in a pointer to a stackT type (stackP) and returns
// true if the count is 0 and false otherwise.
bool StackIsEmpty(stackT *stackP){
if (stackP->count == 0){
return true;
}
return false;
}
// This funciton takes in a pointer to a stackT type (stackP) and returns
// true if the count of the stack is equal to its maxSize and false otherwise.
bool StackIsFull(stackT *stackP){
if (stackP->maxSize == stackP->count){
return true;
}
return false;
}
// This funciton takes in a pointer to a stackT type (stackP) and returns
// the count of the stack.
int StackCount(stackT *stackP){
return stackP->count;
}
// This funciton takes in a pointer to a stackT type (stackP) and prints
// its type and content's str and value as a tuple.
void StackPrint(stackT *stackP){
printf("Stack: size: %d :",stackP->count);
for(int k = stackP->count ; k > 0; k--){
printf("[%d %s %.1f] ", stackP->contents[k-1]->type, stackP->contents[k-1]->str, stackP->contents[k-1]->value);
}
printf("\n");
}
// This funciton takes in a pointer to a stackT type (stackP) and returns
// the top of the stack.
Token StackTop(stackT *stackP){
return stackP->contents[stackP->top];
}<file_sep>// This file is Calc.c which takes in input in prefix notation
// and uses the shunting algorithm to convert it to postfix notation
// and then evaluates it. The programmer name is <NAME>.
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include "stack.c"
#define MAXSIZE 1024 // This is the maximum a stack can hold
double atof(const char *str);
bool is_numeric(char * s);
bool is_operator(char * s);
bool is_operator1(char* s);
bool is_operator2(char* s);
bool is_left_paren(char * s);
bool is_right_paren(char * s);
bool is_error(char *s);
char *strcpy(char *dest, const char *src);
int strcmp(const char *str1, const char *str2);
int main(int argc, char *argv[]){
extern bool debugflag; // This is a boolean variable to check for -debug
debugflag = false;
if (argc == 2){
if(strcmp(argv[argc-1], "-debug") == 0){
debugflag = true;
}
else{
fprintf(stderr, "Usage: Calc [-debug]\n");
exit(0);
}
}
else if(argc > 2){
fprintf(stderr, "Usage: Calc [-debug]\n");
exit(0);
}
stackT myStack; // This is used to represent the stack
StackInit(&myStack, MAXSIZE);
Token *Queue; // This Token pointer stores all the tokens from input
// This token is used to represent the 1st argument when evaluating
// expressions.
Token arg1;
int place = 0; // This int variable tracks the place of the Queue array
char buffer[MAXSIZE]; // This char array is a buffer for taking in input
char *token; // This char pointer stores the string of the input tokens
int i; // This int variable stores the size of the token list
while(fgets(buffer, MAXSIZE , stdin) != NULL)
{
buffer[strlen(buffer) -1] = '\0';
printf("Input: %s",buffer);
Token *Tok_list = malloc(sizeof(struct token)*(MAXSIZE));
Queue = malloc(sizeof(struct token)*(MAXSIZE));
place = 0;
token = strtok(buffer, " ");
i = 0;
while( token != NULL ) // Create and place tokens in Queue
{
if(is_error(token)){
printf("\n");
StackDestroy(&myStack);
for (int k = 0; k < i; i++){
free(Tok_list[k]);
}
free(Tok_list);
free(Queue);
fprintf(stderr, "Fatal Error. Bad token: %s\n", token);
exit(0);
}
Token T = malloc(sizeof(struct token));
T->str = malloc(sizeof(char)*strlen(token) +1);
strcpy(T->str, token);
T->str[strlen(token)] = '\0';
T->value = 0;
if(is_numeric(token)){
T->type = NUM;
T->value = atof(token);
}
else if(is_operator1(token)){
T->type = OP1;
}
else if(is_operator2(token)){
T->type = OP2;
}
else if(is_left_paren(token)){
T->type = LPAR;
}
else if (is_right_paren(token)){
T->type = RPAR;
}
Tok_list[i] = T;
i++;
token = strtok(NULL," ");
}
printf("\n");
if(debugflag){
StackPrint(&myStack);
}
for (int j = 0; j< i; j++){ // Shunting yard algorithm implementation
if(debugflag){
printf("Token:%s: type: %d ",Tok_list[j]->str,Tok_list[j]->type);
printf("value: %.2f\n",Tok_list[j]->value );
}
if(Tok_list[j]->type == NUM){
Queue[place] = Tok_list[j];
place++;
}
else if(Tok_list[j]->type == OP1){
while(!StackIsEmpty(&myStack)){
if (StackTop(&myStack)->type == OP1 ||
StackTop(&myStack)->type == OP2){
Queue[place] = StackPop(&myStack);
place++;
}
else{
break;
}
}
StackPush(&myStack, Tok_list[j]);
}
else if (Tok_list[j]->type == OP2){
while(!StackIsEmpty(&myStack)){
if (StackTop(&myStack)->type == OP2){
Queue[place] = StackPop(&myStack);
place++;
}
else{
break;
}
}
StackPush(&myStack, Tok_list[j]);
}
else if(Tok_list[j]->type == LPAR){
StackPush(&myStack, Tok_list[j]);
}
else if (Tok_list[j]->type == RPAR){
free(Tok_list[j]->str);
free(Tok_list[j]);
bool lpar = false; // Flag for if left parenthesis comes up
while(!StackIsEmpty(&myStack)){
if (is_left_paren(StackTop(&myStack)->str)){
lpar = true;
Token free_this = StackPop(&myStack);
free(free_this->str);
free(free_this);
break;
}
Queue[place] = StackPop(&myStack);
place++;
}
if(!lpar){
for (int k = j; k < i; k++){
free(Tok_list[k]);
}
for (int k = 0; k < place; k++){
free(Queue[k]);
}
StackDestroy(&myStack);
free(Queue);
fprintf(stderr, "Fatal error: missing left paran\n");
exit(0);
}
}
if(debugflag){
StackPrint(&myStack);
}
}
while(!StackIsEmpty(&myStack)){
if(StackTop(&myStack)->type == LPAR ||
StackTop(&myStack)->type == RPAR){
fprintf(stderr, "Fatal error: mismatched paran\n");
exit(0);
}
Queue[place] = StackPop(&myStack);
place++;
}
if(debugflag){
printf("OUTPUT:\n");
}
// This stores the token of the 2nd argument when evaluating functions
Token arg2;
for(int j = 0; j<place; j++){ // Evaluate post fix notation
if(debugflag){
StackPrint(&myStack);
printf("Token:%s: type: %d ", Queue[j]->str, Queue[j]->type);
printf("value: %.2f\n", Queue[j]->value);
}
if(Queue[j]->type == NUM){
StackPush(&myStack,Queue[j]);
}
else if(is_operator(Queue[j]->str)){
if(myStack.count < 2){
StackDestroy(&myStack);
free(Tok_list);
free(Queue);
fprintf(stderr, "Fatal error: fewer than ");
fprintf(stderr, "2 operands available.\n");
exit(0);
}
else{
arg1 = StackPop(&myStack);
arg2 = StackPop(&myStack);
if(strcmp(Queue[j]->str,"+") == 0){
arg1->value = arg2->value + arg1->value;
}
else if(strcmp(Queue[j]->str,"-") == 0){
arg1->value = arg2->value - arg1->value;
}
else if(strcmp(Queue[j]->str,"*") == 0){
arg1->value = arg2->value * arg1->value;
}
else if(strcmp(Queue[j]->str,"/") == 0){
arg1->value = arg2->value / arg1->value;
}
free(arg2->str);
free(arg2);
free(Queue[j]->str);
free(Queue[j]);
StackPush(&myStack, arg1);
}
}
}
if(myStack.count == 1){
printf("Result: %.2f\n", StackTop(&myStack)->value);
}
else{
StackDestroy(&myStack);
free(Tok_list);
free(Queue);
fprintf(stderr, "Fatal error: Too many operands\n");
exit(0);
}
Token free_this = StackPop(&myStack);
free(free_this->str);
free(free_this);
free(Tok_list);
free(Queue);
}
StackDestroy(&myStack);
}
// This function takes in a char pointer (s) and returns true if
// it is a left parenthesis and false otherwise.
bool is_left_paren(char * s){
if(strcmp(s,"(") == 0){
return true;
}
return false;
}
// This function takes in a char pointer (s) and
// returns true if it is a right parenthesis and false otherwise.
bool is_right_paren(char * s){
if(strcmp(s,")") == 0){
return true;
}
return false;
}
// This function takes in a char pointer (s) and returns true
// if each char is a number or a decimal point.
// It returns false if at least one of the char isn't.
bool is_numeric(char * s){
int dot_count = 0;
for(int i = 0; s[i]!='\0'; i++){
if(s[i] == '-' && i == 0 && strlen(s)!= 1){
continue;
}
if(s[i] == '.'){ // count decimal
dot_count++;
}
if( !(s[i] >= '0' && s[i] <= '9') ){
if( !(s[i] == '.' && dot_count == 1)){
return false; // return false if dot appeared more than once
}
}
}
return true;
}
// This function takes in a char pointer (s) and returns true
// if it is a operator 1 type or operator 2 type and false otherwise.
bool is_operator(char * s){
if (is_operator1(s) || is_operator2(s) ){
return true;
}
return false;
}
// This function takes in a char pointer (s) and returns true
// if it is + or - symbols and false otherwise.
bool is_operator1(char * s){
if (strcmp(s,"+") == 0 || strcmp(s,"-") == 0){
return true;
}
return false;
}
// This function takes in a character pointer (s) and returns
// true if it is the * or / symbols and false otherwise.
bool is_operator2(char * s){
if (strcmp(s,"*") == 0 || strcmp(s,"/") == 0){
return true;
}
return false;
}
// This function takes in a char pointer (s) and returns true if it is not
// numeric, not a operator, and no parenthesis and false otherwise.
bool is_error(char *s){
if(!is_numeric(s) && !is_operator(s)
&& !is_right_paren(s) && !is_left_paren(s)){
return true;
}
return false;
}
<file_sep>// The file name is Words.c and it implements a 2 word
// search and dynamic programming to see if a word
// can be broken up into smaller words using an online
// dictionary.
// Programmer: <NAME>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include "/c/cs223/hw7/hash.h"
#define MAXSIZE 1024 // Max size for input line from stdin
int strcmp(const char *str1, const char *str2);
int tolower(int c);
size_t strlen(const char *str);
void check( int col, int len, int matrix[len][len], bool *success);
void dp(Hash myHash, char *token,bool debug);
void two_words(Hash myHash, char *token);
int main(int argc, char *argv[]){
bool debug_flag = false; // flag to check for debug flag in command line
char *dictionary = "words";
for(int i = 1; i < argc; i++){ // go through command line arguments
if(!strcmp(argv[i], "-debug")){
debug_flag = true;
}
else if(!strcmp(argv[i], "-dict")){
if(i == (argc-1)){
fprintf(stderr,"usage: Words [-dict filename | -debug]\n");
exit(0);
}
else{
dictionary = argv[i+1];
i++;
}
}
else{
fprintf(stderr,"usage: Words [-dict filename | -debug]\n");
exit(0);
}
}
FILE *ptr_file; // Pointer file
char buf[1000]; // character buffer
ptr_file =fopen(dictionary, "r");
if(ptr_file == 0){
fprintf(stderr, "Fatal error: dictionary not found.\n");
exit(0);
}
if(debug_flag){
printf("Loading dictionary: %s\n", dictionary);
}
Hash myHash = HashCreate();
char *point; // Pointer to get thorugh text file
point = fgets(buf,1000, ptr_file);
char buffer[MAXSIZE+1]; // buffer array for fgets
char *token; // character pointer to extract tokens
int count = 0; //word count of dictionary
while (point !=NULL){ // load hash table
count++;
int index = 0;
while (*(point+index) != '\0'){
index++;
}
if (*(point+index-1) == '\n' ){ // Delete newline
*(point+index-1) = '\0';
index--;
}
for(int k = 0; point[k] != '\0'; k++){
point[k] = tolower(point[k]);
}
HashInsert(myHash, point);
point = fgets(buf,1000, ptr_file);
}
if(debug_flag){
printf("Word Count: %d\n", count);
}
while(fgets(buffer, MAXSIZE +1 , stdin) != NULL){ // Loop through stdin
if(buffer[strlen(buffer) -1] == '\n'){
buffer[strlen(buffer) -1] = '\0';
}
if(debug_flag){
printf("Input: %s\n", buffer);
}
token = strtok(buffer, " ");
if(token != 0){
bool error = false;
for(int k = 0; token[k]!= '\0'; k++){
if( !( (token[k] >= 97 && token[k] <= 122) ||
(token[k] >=65 && token[k] <= 90) )){
fprintf(stderr,
"Non-alpha character: [%c] in %s\n", token[k], token);
error = true;
}
token[k] = tolower(token[k]);
}
if(error){
fprintf(stderr, "Error: not processing %s\n", token);
printf("Two words: FAILURE\n");
printf("---\n");
}
else{
while( token != NULL ){ // Process tokenized input
two_words(myHash, token);
dp(myHash, token, debug_flag);
token = strtok(NULL," ");
}
}
}
else{
printf("Two words: FAILURE\n");
printf("DP: SUCCESS \n\n");
printf("---\n");
}
}
HashDestroy(myHash);
}
// This function takes in a hash (myHash) and a char pointer
// called token. It prints whether a word can be broken
// down into two
void two_words(Hash myHash, char *token){
printf("Two words:");
bool success = false;
for(int j = 1; j < strlen(token); j++){ // go through token
char firstHalf[j+1];
char secondHalf[strlen(token)-j];
strncpy(firstHalf, token, j);
strncpy(secondHalf, token + j, strlen(token)-j+1);
firstHalf[j] = '\0';
secondHalf[strlen(token)-j] = '\0';
// if both halves in table
if(HashSearch(myHash, firstHalf) && HashSearch(myHash, secondHalf)){
if(success){
printf(" %s %s.", firstHalf, secondHalf);
}
else{
printf(" SUCCESS: %s %s.", firstHalf, secondHalf);
success = true;
}
}
}
if(!success){
printf(" FAILURE");
}
printf("\n");
}
// This function takes in a Hash (myhash), a char pointer token, and
// a boolean debug. It prints output depending on if the word
// can be broken down into several words and prints the corresponding
// matrix.
void dp(Hash myHash, char *token, bool debug){
int len = strlen(token); // int variable for token length
int matrix[len][len]; // matrix for dynamic programmign method
memset(matrix, -1, sizeof(matrix)); // clear memory for matrix
for(int i = 1; i <= len; i++){ // index to go through matrix columns
for( int j = 0; j < len ; j++ ){ // index for rows of matrix
if( (i +j ) <= len){
for(int k = j; k < i + j; k++){ // go through each section
if(j == k && i ==1 ){ // search one character word in dict
char strin[2];
strin[0] = token[j];
strin[1] = '\0';
if(HashSearch(myHash, strin )){// set position to j
matrix[j][j] = j; // if char is a word
}
}
else{
if(k == j ){
char entire[i+1];
strncpy(entire, token + j, i );
entire[i] = '\0';
if(HashSearch(myHash, entire)){
matrix[j][i+j-1] = j;
}
}
else if (matrix[j][k - 1] >= 0 &&
matrix[k][i + j - 1] >= 0 ){
if(matrix[j][i + j - 1] < 0){
matrix[j][i + j - 1] = k; // set spot to break
}
}
}
}
}
}
}
if(debug){ // print matrix
printf("\n");
for(int i = 0; i < len; i++){
for(int j = 0; j < len; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
printf("DP: ");
bool *success = malloc(sizeof(bool));
*success = false;
int breakpoint = 0;
check(len-1, len, matrix, success);
if(*success){ // print words
printf("SUCCESS: \n");
breakpoint = 0;
for( int i = 0; i < len; i++){
if( i == matrix[i][len-1]){
for(; i < len; i++) {
printf("%c", token[i]);
}
break;
}
if(matrix[i][len-1] > breakpoint){
for(int j = breakpoint; j < matrix[i][len-1]; j++) {
printf("%c", token[j]);
}
printf(" ");
breakpoint = matrix[i][len-1];
}
}
}
else{
printf("FAILURE");
}
printf("\n---\n");
free(success);
}
// This function takes in a integer col denoting the column of the
// matrix of integers (matrix), an integer len (denoting the
// size of the matrix), and a boolean pointer to see whether
// a word can be broken up into multiple words. It is recursive in nature.
void check(int col, int len, int matrix[len][len], bool *success){
if(!*success){
for(int i = 0; i < len; i++){
if(matrix[i][col] >= 0){
if(matrix[i][col] == 0){
*success = true;
return ;
}
else{
check( matrix[i][col] - 1, len, matrix, success);
}
}
}
}
}<file_sep>// File name: hash.c
// This program contains structures and functions to be
// used in Callme.c
// Programmer: <NAME>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <stdbool.h>
#include "hash.h"
static void grow(Hash d);
char *strdup(const char *s);
int tolower(int c);
// elt is a node in the linked list which
// contains a pointer to the next element in the
// linked list (*next) and a pointer to the
// word of the node (*key)
struct elt {
struct elt *next;
char *key;
};
// hash is a hash table structure which contains
// the number of spots in the hash table (size),
// the number of elements in the hash table (n),
// the number of spots occupied (buckets), and
// a pointer of pointers (**table) which contains
// linked lists in each spot.
struct hash {
int size;
unsigned long int n;
int buckets;
struct elt **table;
};
Hash HashCreate(void){
Hash h;
h = malloc(sizeof(*h));
h->size = INITIAL_SIZE;
h->n = 0;
h->buckets = 0;
h->table = malloc(sizeof(struct elt *) *h->size);
assert(h->table != 0);
for (int i = 0; i < h->size; i++){
h->table[i] = 0;
}
return h;
}
void HashDestroy(Hash h){
struct elt *d;
struct elt *next;
for (int i = 0; i<h->size; i++){
for ( d = h->table[i]; d!= 0; d = next){
next = d->next;
free(d->key);
free(d);
}
}
free(h->table);
free(h);
}
Hash internalHashCreate(int size)
{
Hash d;
d = malloc(sizeof(*d));
assert(d != 0);
d->size = size;
d->n = 0;
d->buckets = 0;
d->table = malloc(sizeof(struct elt *) * d->size);
assert(d->table != 0);
for(int i = 0; i < d->size; i++){
d->table[i] = 0;
}
return d;
}
// This function takes in a constant character pointer
// (*str) which points to a word and returns a number.
// Taken online (djb2 by <NAME>)
unsigned long hash_function( const char *str){
unsigned long h = 5381;
int c;
while ((c = *str++))
h = ((h << 5) + h) + c;
return h;
}
void HashInsert(Hash h, const char *key){
struct elt *e;
e = malloc(sizeof(*e));
assert(e);
e->key = strdup(key);
unsigned long hf_out = hash_function(key) % h->size;
if (h->table[hf_out] == 0){
h->buckets++;
}
e->next = h->table[hf_out];
h->table[hf_out] = e;
h->n++;
if(h->n >= h->size*MAX_LOAD_FACTOR){
grow(h);
}
}
static void grow(Hash d){
Hash d2;
struct hash swap;
struct elt *e;
extern bool debugflag;
if (debugflag){
printf("Growing to size: %d. n: %lu. ", d->size*GROWTH_FACTOR,d->n);
printf("Used buckets: %d. ", d->buckets);
printf("Occupancy rate: %.2f\n", (float)d->buckets/d->n);
}
d2 = internalHashCreate(d->size * GROWTH_FACTOR);
for(int i = 0; i < d->size; i++) {
for(e = d->table[i]; e != '\0'; e = e->next) {
HashInsert(d2, e->key);
}
}
swap = *d;
*d = *d2;
*d2 = swap;
HashDestroy(d2);
}
bool HashSearch(Hash d, char *key)
{
struct elt *e;
for(e = d->table[hash_function(key) % d->size]; e != 0; e = e->next) {
if(!strcmp(e->key, key)) {
return true;
}
}
return false;
}
void HashDisplay(Hash d){
struct elt *e;
for (int i = 0; i < d->size; i++){
for (e = d->table[i]; e!=0; e=e->next){
printf("%s in place %d\n", e->key,i );
}
}
}
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include "hash.h"
#include "hash.c"
int main(){
Hash h = HashCreate();
HashInsert(h,"one");
HashInsert(h,"two");
HashInsert(h,"three");
HashInsert(h,"four");
HashInsert(h,"five");
HashInsert(h,"six");
HashDisplay(h);
bool item;
item = HashSearch(h, "one");
if(item) {
printf("Element found: %d\n", item);
}else {
printf("Element not found\n");
}
item = HashSearch(h, "ten");
if(item){
printf("Element found: %d\n", item);
}else {
printf("Element not found\n");
}
HashDestroy(h);
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#define MAXHEAP 4
bool debugflag;
// from <NAME>, chapter 10, page 233++
typedef struct heapslot heapslot;
struct heapslot {
int key;
struct room * value;
} ;
struct heap {
int size; /* size of the pointer table */
int n; /* number of elements stored */
struct heapslot ** heap;
};
typedef struct heap *Heap;
bool empty(Heap);
void demand(int cond, char * msg);
void printHeap(Heap);
struct room * findmin(Heap);
Heap initheap();
void swap(heapslot *s1, heapslot *s2);
void insert( Heap h, int key, struct room * r);
void deletemin( Heap h);
void destroyHeap( Heap h);
<file_sep>// Filename: Inflate.c
// This program copies text from standard input to standard output
// replacing integer values incremented by 1.
// Programmer: <NAME>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ungetchar(c) ungetc(c, stdin) // Unread char read from stdin
bool isDigit(int c);
long increment(char c [], int sign, int base, int len);
bool isZero(int c);
bool checkSplice(int c);
void displayNum(int c, int sign, int base);
void putSymbols(long num, int sign, int base);
long toBase10(char c[], int base, int len);
bool isHex(int c);
bool isBinary(int c);
bool isOctal(int c);
void putDigits(long num, int base );
int main()
{
int c;
int sign = 0; // Minus sign state
while ((c = getchar()) != EOF){
if ( c== '\\'){
if(checkSplice(c)){
c = getchar();
}
else{
putchar('\\');
c = getchar();
}
if (c== '\"' ){ // Handle escaped quote case
putchar(c);
}
else{ // Handle any other character after backslash
ungetchar(c);
}
}
else if (c == '\"'){ // Handle comments
putchar('\"');
c = getchar();
while(c != '\"' && c != EOF){
if (c == '\\'){
putchar('\\');
c= getchar();
if ( c == '\"'){ // Handle escaped double quote
putchar(c);
c = getchar();
}
else{
putchar(c);
c = getchar();
}
}
else{
putchar(c);
c = getchar();
}
}
if(c != EOF){
putchar(c);
}
}
else if( c == '-'){ // Save minus state
sign = 1;
if (!(isDigit(c = getchar() ))){
putchar('-'); // Handle negative sign without number
sign = 0;
}
ungetchar(c);
}
else if( (isDigit(c) && !isZero(c)) ){ // Handle base 10 case
displayNum(c,sign,10);
}
else if(isZero(c)){ // Handle 0 character case
c = getchar();
if(checkSplice(c)){
c = getchar();
}
if (c == 'b' || c == 'B'){ // Handle binary case
c = getchar();
if(checkSplice(c)){
c = getchar();
}
displayNum(c, sign, 2);
}
else if(c == 'x' || c == 'X'){ // Handle hexadecimal case
c = getchar();
if(checkSplice(c)){
c = getchar();
}
displayNum(c, sign, 16);
}
else if (isOctal(c)){ // Handle octal case
displayNum(c, sign, 8);
}
else if(isDigit(c)){ // Handle 0 followed by 8 or 9
displayNum(c, sign, 10);
}
else{ // Handle lone 0 character case
sign = 0;
ungetchar(c);
putchar('1');
}
}
else{ // Handle other chracters
putchar(c);
sign = 0;
}
}
}
void displayNum(int c, int sign, int base){
// Takes in input character c, sign of the number (sign), and the base
// of the number (base). This function displays the incremented number
// in the specified base.
int len = 0; // Length of number (number of digits)
char digits[64] = {0};
// Get digits if valid respective to the base
while( (isBinary(c) && base == 2) || (isDigit(c) && base == 10) ||
(isOctal(c) && base == 8) || (isHex(c) && base == 16)){
digits[len] = c;
c = getchar();
if(checkSplice(c)){ // Handle line splices
c = getchar();
}
len++;
}
ungetchar(c);
long numero = increment(digits, sign, base, len);
putSymbols(numero ,sign ,base);
putDigits(numero, base);
}
long increment(char digits[], int sign, int base, int len){
// Takes in array of digits (digits), sign of the number (sign), and
// the base of the number (base), and the number of digits
// or length of the number (len).
// This function returns the incremented number.
long numero = toBase10(digits, base, len); // Number in base 10
if(sign == 0){
numero++;
}
else{
numero--;
}
return numero;
}
long toBase10(char digits[], int base, int len){
// Takes in character array of digits (digits), base of the
// number (base), and the number of digits or length of the
// number (len). It returns the number in base 10.
long result = 0; // Resulting number in base 10
for (int i=0; i< len; i++) {
result = result*base;
if (digits[i] <= '9' && digits[i] >= '0'){
result = result + (digits[i] - '0'); // Convert char to long int
}
else{ // Convert char to long int
if (digits[i] >= 'a' && digits[i] <= 'f' ){
result = result + (digits[i] - 'W');
}
else{ // Convert char to long int
result = result + (digits[i] - '7');
}
}
}
return result;
}
void putSymbols(long num, int sign, int base){
// Takes in incremented number (num), sign of the number (sign) and
// the base of the number (base). The function displays the sign and
// symbols of the specified base.
if (sign == 1 ){ // Negative number case
if(num != 0){
putchar('-');
// Put symbols for binary, octal, hex
if (base != 10)
{
putchar('0');
if (base == 2){
putchar('b');
}
else if (base == 16){
putchar('x');
}
}
}
else{ // 0 number case
putchar('0');
// Put symbols for binary and hex
if (base == 2){
putchar('b');
putchar('0');
}
else if (base == 16){
putchar('x');
putchar('0');
}
}
}
else{ // Positive number case
// Put symbols for binary, octal, hexadecimal
if(base != 10){
putchar('0');
if (base == 2){
putchar('b');
}
else if (base == 16){
putchar('x');
}
}
}
}
void putDigits(long num, int base ){
// Takes in incremented number (num) and base of the number (base)
// and displays the digits in the specified base.
int converted_number[64];
char digits[16] ={'0', '1', '2', '3', '4', '5', '6',
'7','8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
int i =0;
while(num != 0){ // Convert into different base
converted_number[i] = num%base; // Note: number is written backwards
num = num/base;
i++;
}
i--;
for( ; i>=0; i--) // Go backwards through array and display the digits
{
putchar(digits[converted_number[i]]);
}
}
bool isDigit(int c){
// Takes in input character c and returns true if c is a digit
if(c <= '9' && c >= '0'){
return true;
}
return false;
}
bool isZero(int c){
// Takes in input character c and returns true if c is 0
if (c == '0'){
return true;
}
return false;
}
bool isBinary(int c){
// Takes in input character c, returns true if c is a binary digit
if (c == '0' || c == '1'){
return true;
}
return false;
}
bool isOctal(int c){
// Takes in input character c, returns true if c is a octal digit
for( int i = 0; i < 8; i++){
if (i == (c- '0')){
return true;
}
}
return false;
}
bool isHex(int c){
// Takes in input character c, returns true if it is hexadeimcal
char hex_digits[22] ={'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
'a', 'b', 'c', 'd', 'e', 'f'};
for (int i = 0; i < 22; i++)
{
if ( hex_digits[i] == c){
return true;
}
}
return false;
}
bool checkSplice(int c){
// Takes in input character c, returns true if there is a line splice
if(c == '\\'){
c = getchar();
if(c == '\n'){
return true;
}
ungetchar(c);
}
return false;
}<file_sep>// This file name is heap.c and it implements the functions
// outlined in heap.h
// Programmer: <NAME>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include "/c/cs223/hw6/heap.h"
#define GROWTH_FACTOR (2)
#define MAX_LOAD_FACTOR (1)
// from Van Wyk, chapter 10, page 233++
// typedef struct heapslot heapslot;
// struct heapslot {
// int key;
// struct room * value;
// } ;
// struct heap {
// int size; /* size of the pointer table */
// int n; /* number of elements stored */
// struct heapslot ** heap;
// };
// #define MAXHEAP 4
// bool debugflag;
//typedef struct heap *Heap;
void internaldestroyHeap( Heap h){
for( int i = 0; i < h->size; i++){
free(h->heap[i]);
}
free(h->heap);
free(h);
}
Heap internalHeapCreate(int size){
Heap myHeap = malloc(sizeof(struct heap));
myHeap->size = size;
myHeap->n = 0;
myHeap->heap = malloc(sizeof(struct heapslot*)*myHeap->size);
for(int i = 0; i < myHeap->size; i++){
myHeap->heap[i] = malloc(sizeof(struct heapslot));
}
return myHeap;
}
void growHeap(Heap h){
Heap h2;
struct heap swap;
h2 = internalHeapCreate(h->size*GROWTH_FACTOR);
for(int i = 0; i < h->n; i++) {
insert(h2, h->heap[i]->key,h->heap[i]->value);
}
swap = *h;
*h = *h2;
*h2 = swap;
internaldestroyHeap(h2);
}
bool empty(Heap h){
if(h!=0){
return h->n == 0;
}
return 0;
}
void demand(int cond, char * msg){
if(cond){
printf("%s\n", msg);
return;
}
}
void printHeap(Heap h){
for(int i = 0 ; i < h->n; i++){
printf("key: %d\n", h->heap[i]->key);
}
}
struct room * findmin(Heap h){
if(h!= 0){
return h->heap[0]->value;
}
return 0;
}
Heap initheap(){
Heap myHeap = malloc(sizeof(struct heap));
myHeap->size = MAXHEAP;
myHeap->n = 0;
myHeap->heap = malloc(sizeof(struct heapslot*)*myHeap->size);
for(int i = 0; i < myHeap->size; i++){
myHeap->heap[i] = malloc(sizeof(struct heapslot));
}
return myHeap;
}
void swap(heapslot *s1, heapslot *s2){
heapslot temp;
temp = *s1;
*s1 = *s2;
*s2 = temp;
}
void insert( Heap h, int key, struct room * r){
if(h != 0){
int cur;
int parent;
cur = h->n;
h->n++;
h->heap[cur]->key = key;
h->heap[cur]->value = r;
parent = cur/2;
while(h->heap[parent]->key > h->heap[cur]->key ){
swap(h->heap[parent], h->heap[cur]);
cur = parent;
parent = cur/2;
}
if(h->n >= h->size * MAX_LOAD_FACTOR) {
growHeap(h);
}
}
}
void deletemin(Heap h){
if(h != 0){
int cur;
int child;
*h->heap[0] = *h->heap[h->n-1];
h->n--;
cur = 0;
child = 1;
while(child<= h->n-1){
if(child < h->n-1 && h->heap[child+1]->key < h->heap[child]->key){
child++;
}
if(h->heap[cur]->key > h->heap[child]->key){
swap(h->heap[cur], h->heap[child]);
cur = child;
child = 2*cur+1;
}
else{
break;
}
}
}
}
void destroyHeap( Heap h){
if(h!=0){
for( int i = 0; i < h->size; i++){
if(i < h->n){ // only delete if occupied
free(h->heap[i]->value);
}
free(h->heap[i]);
}
free(h->heap);
free(h);
}
}
<file_sep>// This file is btree.c which implements the
// functions in btree.h
// Programmer: <NAME>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "btree.h"
struct node *makeNode(char * key){
struct node *newNode;
newNode = malloc(sizeof(struct node));
assert(newNode);
newNode->key = malloc(strlen(key)+1);
// set variables
newNode->key[strlen(key)] = '\0';
strcpy(newNode->key, key);
newNode->count = 1;
newNode->left = NULL;
newNode->right = NULL;
newNode->next = NULL;
newNode->height = 0;
newNode->parent = NULL;
return newNode;
}
int treeSize(struct node *root){
if(root == NULL){
return 0;
}
else{
return 1 + treeSize(root->left) + treeSize(root->right);
}
}
int treeHeight(struct node *root){
int lh;
int rh;
if(root ==NULL){
return -1;
}
else{
lh = treeHeight(root->left);
rh = treeHeight(root->right);
if(lh>rh){
return 1 + lh;
}
else{
return 1 + rh;
}
}
}
struct node * treeSearch(struct node *root, char * target){
if( !root){
return NULL;
}
if(strcmp(root->key, target) == 0){ // found
return root;
}
else if (strcmp(root->key, target) > 0){
return treeSearch(root->left, target);
}
else{
return treeSearch(root->right, target);
}
}
void treeInsert(struct node *root, char * key){
if(root != NULL){
struct node *newNode;
newNode = makeNode(key);
for(;;) {
if(strcmp(root->key, key) > 0) {
if(root->left) {
root = root->left;
}
else {
root->left = newNode;
return;
}
}
else {
if(root->right) {
root = root->right;
}
else {
root->right = newNode;
return;
}
}
}
}
}
void printTreePre(struct node * tree){
if(tree!= NULL){
printf("%s [%d / %d] ", tree->key, tree->count, treeHeight(tree));
printTreePre(tree->left);
printTreePre(tree->right);
}
}
void printTreeIn(struct node * tree){
if(tree!= NULL){
printTreeIn(tree->left);
printf("%s [%d / %d] ", tree->key, tree->count, treeHeight(tree));
printTreeIn(tree->right);
}
}
void printTreePost(struct node * tree){
if(tree!= NULL){
printTreePost(tree->left);
printTreePost(tree->right);
printf("%s [%d / %d] ", tree->key, tree->count, treeHeight(tree));
}
}
void treeDestroy(struct node * tree){
if (tree != NULL){
treeDestroy(tree->right);
treeDestroy(tree->left);
free(tree->key);
free(tree);
}
}
<file_sep>// file: Pack.c
// Programmer: <NAME>
// This program solves the bin packing problem by
// implementing the next, first, best, ffd, and bfd algorithms
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
int next(float sizes[], int len, int trace);
int first(float sizes[], int len, int trace);
int best( float sizes[], int len, int trace);
int strcmp(const char *str1, const char *str2);
bool isValid(char *param);
double atof(const char *s);
float nround (float n, unsigned int c);
void exit(int status);
void sort(float *nums, int len);
int main( int argc, char *argv[] ) {
// Indicators for -trace and each bin packing algorithm
int trace = 0;
int next_flag = 0;
int first_flag = 0;
int best_flag= 0;
int ffd_flag=0;
int bfd_flag = 0;
for (int j = 0; j < argc; j++){
if (strcmp((*(argv + j)), "-trace") ==0){
trace = 1;
}
}
if (argc == 1){
fprintf(stderr, "usage: Pack [sizes]* [-next ");
fprintf(stderr, "| -first | -best | -ffd | -bfd]+ -trace*\n");
}
else{
int i = 1;
while((atof(*(argv+i))) != 0 || (strcmp((*(argv+i)), "-trace") == 0)){
// If number is less than 0 or greater than 1 then print error
// Don't print error if string is -trace
if ( ((atof(*(argv+i)) <= 0) || (nround(atof(*(argv+i)), 5) > 1)) ) {
// Check if parameter not trace or a method
if (!isValid(*(argv+i))){
fprintf(stderr, "Fatal error: ");
// Print size error if number invalid
if ((atof(*(argv+i)) != 0)){
fprintf(stderr, "Invalid size: %f\n",
atof(*(argv+i)));
exit(0);
}
// Print bad argument error if argument not valid
fprintf(stderr, "bad argument: %s\n", *(argv+i));
exit(0);
}
}
// Check if number is too small and if so print error
if( nround(atof(*(argv+i)),5) == 0){
fprintf(stderr, "Fatal error: bad argument: %s\n", *(argv+i));
exit(0);
}
i++;
// If argument is the last one in argv, print error and exit
if ( i == argc ){
fprintf(stderr, "Fatal error: no algorithm specified.\n");
exit(0);
}
}
// If last argument isn't trace or a bin packing method, print error
if(!isValid(*(argv+i))){
fprintf(stderr, "Fatal error: bad argument: %s\n", *(argv+i));
}
else{
// Indicator variable to check whether number is greater than 0
// and less than or equal to 1.
int valid = 0;
float numbers [i-1];
float sorted_numbers[i-1];
// Store each size in argv into numbers and sorted_numbers
for ( int j = 1; j < i; j++){
numbers[j-1] = atof(*(argv+j));
numbers[j-1] = nround(numbers[j-1], 5);
sorted_numbers[j-1] = numbers[j-1];
// If number in valid range, note it
if (numbers[j-1] != 0 && numbers[j-1]<=1){
valid = 1;
}
}
sort(sorted_numbers,i-1);
// Check for numbers and if so, print error and exit
for(int k = i; k < argc; k++){
if ( atof(*(argv + k)) != 0){
if ((atof(*(argv+k)) <= 0) || (atof(*(argv+k)) > 1) ){
fprintf(stderr, "Fatal error: Invalid size: ");
fprintf(stderr, "%f\n", atof(*(argv + k)));
exit(0);
}
fprintf(stderr, "Fatal error: Size option");
fprintf(stderr, " out of order: %f\n", atof(*(argv + k)));
exit(0);
}
}
// Flags to check whether each algorithm is called
int next_bin, first_bin, best_bin, ffd_bin, bfd_bin = 0;
// Array of chars to store in order which algorithm is called
char pos [argc-i];
int p = 0;
for(int k = i; k < argc; k++){
if (strcmp((*(argv + k)), "-next" ) == 0){
pos[p] = 'n';
p++;
next_flag = 1;
}
else if (strcmp((*(argv + k)), "-first" ) == 0 ){
pos[p] = 'f';
p++;
first_flag = 1;
}
else if (strcmp((*(argv + k)), "-best" ) == 0 ){
pos[p] = 'b';
p++;
best_flag = 1;
}
else if (strcmp((*(argv + k)), "-ffd" ) == 0 ){
pos[p] = 'd';
p++;
ffd_flag = 1;
}
else if (strcmp((*(argv + k)), "-bfd" ) == 0){
pos[p] = 'e';
p++;
bfd_flag = 1;
}
else if(!isValid(*(argv + k))){ //
fprintf(stderr, "Fatal error: ");
fprintf(stderr, "bad argument: %s\n", *(argv +k));
exit(0);
}
}
// Check flags for each method, if so run method and store
// the number of bins
printf("%d\n", next_flag);
if (next_flag == 1){
if (trace == 1 && valid == 1){
printf("Trace -next\n");
}
next_bin = next(numbers,i, trace);
}
if (first_flag == 1){
if (trace == 1 && valid == 1){
printf("Trace -first\n");
}
first_bin = first(numbers,i,trace);
}
if(best_flag == 1){
if (trace == 1 && valid == 1){
printf("Trace -best\n");
}
best_bin = best(numbers,i,trace);
}
if (ffd_flag == 1){
if (trace == 1 && valid == 1){
printf("Trace -ffd\n");
}
ffd_bin = first(sorted_numbers,i, trace);
}
if (bfd_flag == 1){
if (trace == 1 && valid ==1){
printf("Trace -bfd\n");
}
bfd_bin = best(sorted_numbers,i, trace);
}
// Go through array of char that stores whether each
// method is called and print the result if called
for (int y = 0; y < p ; y++){
switch(pos[y]) {
case 'n':
printf("-next: %d\n", next_bin);
break;
case 'f':
printf("-first: %d\n", first_bin);
break;
case 'b':
printf("-best: %d\n", best_bin);
break;
case 'd':
printf("-ffd: %d\n", ffd_bin);
break;
case 'e':
printf("-bfd: %d\n", bfd_bin);
break;
default:
break;
}
}
}
}
}
// This function takes in a pointer (param) that points to an array
// of string parameters. It returns true if the strings are "-next",
// "-first", "-best", "-ffd", "-bfd", or "-trace" and false otherwise.
bool isValid(char *param){
if ( (strcmp(param, "-next") == 0) || (strcmp(param, "-first") == 0)) {
return true;
}
else if ((strcmp(param, "-best") == 0) || (strcmp(param, "-ffd") == 0)){
return true;
}
else if ( (strcmp(param, "-bfd") == 0) || (strcmp(param, "-trace") == 0)){
return true;
}
return false;
}
// This function takes in a array of floats (sizes), the length of the
// of the array (len), and an indicator variable for -trace (trace)
// and returns the number of bins needed to pack sizes. The algorithm
// checks if the number fits in the same bin as the last item. If none
// fit a new bin is started.
int next(float sizes[], int len, int trace){
int isValue = 0; // Indicator variable if valid number is present
int countBins = 0; // Number of bins used
float currentBin = 0;
int count = -1;
for ( int i = 0; i < len-1; i++){ // Loop through sizes
if(sizes[i] != 0)
{
count++;
isValue = 1;
currentBin += sizes[i];
if (nround(currentBin,5) > 1.0){
countBins++;
currentBin = 0;
i--; // Stay on current bin if fits
count--;
}
else{ // Print results for the size after fitted
if (trace == 1){
printf("arg: %d val: %f bin: %d total: %f\n",
count, sizes[i], countBins, currentBin );
}
}
}
}
if(isValue == 1){
countBins++;
}
return (countBins);
}
// This function takes in a array of floats (sizes), the length of the
// of the array (len), and an indicator variable for -trace (trace)
// and returns the number of bins needed to pack sizes. The algorithm
// processes each number and places it into the first bin that fits.
// If none fit, a new bin is started.
int first(float sizes[], int len, int trace){
int countBins = 0; // Number of bins used
float bins[len];
int count = -1;
for( int i = 0; i < len; i++){
bins[i] = 0;
}
// Loop through sizes
for ( int i = 0; i < len-1; i++){
if (sizes[i] != 0){
count++;
int j = 0;
while( nround(bins[j] + sizes[i],5) > 1.0 ){
j++;
}
bins[j] += sizes[i];
if (trace == 1 && sizes[i] !=0 ){
printf("arg: %d val: %f bin: %d total: %f\n",
count, sizes[i], j, bins[j] );
}
}
}
for(int i = 0; i < len; i++){
if (bins[i] > 0){
countBins++;
}
}
return countBins;
}
// This function takes in a array of floats (sizes), the length of the
// of the array (len), and an indicator variable for -trace (trace)
// and returns the number of bins needed to pack sizes. The algorithm
// processes each number and places it into the one with tightest fit.
// If none fit, then a new bin is started.
int best( float sizes[], int len, int trace){
int countBins = 0; // Number of bins used
float bins[len];
int count = -1;
for( int i = 0; i < len; i++){
bins[i] = 0;
}
for ( int i = 0; i < len-1; i++){ // Loop through sizes
int j = 0;
int h = 0; // Index variable to identify best bin
int best = 0;
float min = 1.0;
if (sizes[i] != 0)
{
count++;
// Loop through bins to check for tightest fit
while (bins[j] != 0){
if ( (nround(1 - sizes[i] - bins[j],5) <= min) &&
(nround(sizes[i] + bins[j],5) < 1.0) ){
min = 1 - sizes[i] - bins[j];
h = j;
best = 1;
}
j++;
}
if (best == 1){
bins[h] += sizes[i];
if (trace == 1 && sizes[i] !=0 ){
printf("arg: %d val: %f bin: %d total: %f\n",
count, sizes[i], h, bins[h] );
}
}
else{
bins[j] += sizes[i];
if (trace == 1 && sizes[i] !=0 ){
printf("arg: %d val: %f bin: %d total: %f\n",
count, sizes[i], j, bins[j] );
}
}
}
}
for(int i = 0; i < len; i++){
if (bins[i] > 0){
countBins++;
}
}
return countBins;
}
// This function takes in an array of floats (nums) and the
// length of the array (len) and sorts the array in decreasing order
void sort(float *nums, int len){
bool swaps = true;
float temp;
while (swaps){ // Loop until no swaps occur in array
swaps = false;
// Loop through nums and swap consecutive elements if needed
for(int i = 0; i < len-1; i++){
if( *(nums+i) < *(nums+i+1)){
swaps = true;
temp = *(nums+i);
*(nums+i) = *(nums+i+1);
*(nums+i+1) = temp;
}
}
}
}
// This function takes in an double value (n) and an integer signifying
// how many decimal places to round to (dec) and returns the rounded number
float nround (float n, unsigned int dec)
{
float power = pow (10, dec);
float product = n * power;
float rounded_num = round (product) / power;
return rounded_num;
}
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include "hash.h"
#include "hash.c"
char * rand_string(char * str, int size)
{
const char charset[26] = "abcdefghijklmnopqrstuvwxyz";
if (size) {
--size;
for (size_t n = 0; n < size; n++) {
int key = rand() % 26;
str[n] = charset[key];
}
str[size] = '\0';
}
return str;
}
int main(){
Hash h = HashCreate();
int size = 5;
char * str = malloc(size);
for (int i=0; i < 1000; i++){
HashInsert(h, rand_string(str, size));
}
free(str);
HashInsert(h,"one");
HashInsert(h,"two");
HashInsert(h,"three");
HashInsert(h,"four");
HashInsert(h,"five");
HashInsert(h,"six");
HashDisplay(h);
bool item;
item = HashSearch(h, "one");
if(item) {
printf("Element found: %d\n", item);
}else {
printf("Element not found\n");
}
item = HashSearch(h, "ten");
if(item){
printf("Element found: %d\n", item);
}else {
printf("Element not found\n");
}
HashDestroy(h);
}<file_sep>#include <stdio.h>
#include <string.h>
const char hashTable[10][5] = {"", "", "abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"};
void printWordsUtil(int number [], int current_digit, char output[], int n)
{
int i = current_digit;
int end = 3;
if (number[current_digit] == 9){
end = 4;
}
for(int j = 0; j< end; j++){
output[i] = hashTable[number[i]][j];
if(i < n){
printWordsUtil(number, i+1, output, n);
}
if (i == n){
printf("%s\n", output);
}
}
}
int main(void)
{
int number[] = {9,2,2};
int n = 3;
char result[n+1];
result[n] ='\0';
printWordsUtil(number, 0, result, n-1);
return 0;
}<file_sep>#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include "/c/cs223/hw6/dict.h"
#include "/c/cs223/hw6/heap.h"
#define MAXSIZE 1024 // Max size of input line through stdin
int undir(Dict d);
void best(Dict d, const char *key);
void bfs(Dict d, const char *key);
void dfs(Dict d, const char *key, int *count, bool conn);
void mark_unvisited(Dict d);
// global variable to check whether burning room found
bool success = false;
int main(int argc, char *argv[]){
char *roomkey; // variable to hold the room key from command line
// Initialize command line flags
bool dfs_flag = false;
bool bfs_flag = false;
bool best_flag = false;
bool conn_flag = false;
bool dir_flag = false;
bool room_flag = false;
// check if no methods given
bool default_flag = true;
extern bool success;
for(int i = 1; i < argc; i++){ // go through command line arguments
if(!strcmp("-dfs", argv[i])){
dfs_flag = true;
default_flag = false;
}
else if(!strcmp("-bfs", argv[i])){
bfs_flag = true;
default_flag = false;
}
else if(!strcmp("-best", argv[i])){
best_flag = true;
default_flag = false;
}
else if(!strcmp("-conn", argv[i])){
conn_flag = true;
default_flag = false;
}
else if(!strcmp("-dir", argv[i])){
dir_flag = true;
default_flag = false;
}
else if(!strcmp("-room", argv[i])){
if(argc-1 == i){
fprintf(stderr, "Fatal error: no room given.\n");
fprintf(stderr, "Usage: Fire -room value ");
fprintf(stderr, "[-dfs | -bfs | -best | -conn | -dir]\n");
exit(0);
}
else{
room_flag = true;
roomkey = argv[i+1];
}
}
}
if(!room_flag){
fprintf(stderr, "Fatal error: no room given.\n");
fprintf(stderr, "Usage: Fire -room value ");
fprintf(stderr, "[-dfs | -bfs | -best | -conn | -dir]\n");
exit(0);
}
if(default_flag){ // if no commandline flags, dfs is the default method
dfs_flag = true;
}
struct dict *d; //dictionary for hash table
d = DictCreate();
char buffer[MAXSIZE+1]; // buffer array for fgets
char *token; // character pointer to extract tokens
int index;
int total = 0; // total count of input rooms
while(fgets(buffer, MAXSIZE +1 , stdin) != NULL){ // Loop through stdin
if(buffer[strlen(buffer) -1] == '\n'){
buffer[strlen(buffer) -1] = '\0';
}
token = strtok(buffer, " ");
index = 0;
struct room *r = malloc(sizeof(struct room));
r->visited = 0;
r->ncount = 0;
while( token != NULL ){ // Process tokenized input
if(index == 0){ // get room key
strncpy(r->room, token, 4);
r->room[3] = '\0';
}
else if(index == 1){ // get temperature
r->temp = atoi(token);
}
else{ //get neighbors
strncpy(r->neighbors[index-2], token,4);
r->neighbors[index-2][3] = '\0';
r->ncount++;
}
index++;
token = strtok(NULL," ");
}
if(DictSearch(d,r->room) != 0){ // if room already in dict from before
fprintf(stderr,"Room %s already in graph. ", r->room);
fprintf(stderr, "Replacing it.\n");
DictDelete(d, r->room);
}
else{
total++;
}
DictInsert(d, r->room, r);
}
struct elt *e; // struct to go through dict
for(int i=0; i<d->size; i++) {
if (d->table[i]) {
for (e = d->table[i];e != NULL; e = e->next){ // go through table
int place = 0;
char badneighbors[10][4]; //2D array to hold neighbors not in dict
memset(badneighbors, 0, sizeof(badneighbors));
for(int j = 0; j< e->value->ncount; j++){ // go through neighbors
if(DictSearch(d, e->value->neighbors[j]) == 0){
int repeat = 0;
for(int l = 0; l < 10; l++){ // check if in 2D array
if( !strcmp(badneighbors[l],e->value->neighbors[j] )){
repeat = 1;
}
}
if(repeat != 1){
fprintf(stderr, "Warning: room %s has neighbor ",
e->value->room);
fprintf(stderr,"%s which is not in the dictionary.\n",
e->value->neighbors[j] );
strncpy(badneighbors[place],
e->value->neighbors[j], 4);
badneighbors[place][3] = '\0';
place++;
}
}
}
}
}
}
int *count = malloc(sizeof(int)); // room count variable for dfs
*count = 0;
if(dfs_flag){
bool conn = false; // boolean for dfs to run dfs and not conn
printf("Starting depth first search:");
dfs(d, roomkey, count, conn);
if(!success){
printf(" FAILED\n");
}
else{
success = true;
}
mark_unvisited(d); // reset rooms in dict to be not visited
}
if(bfs_flag){
printf("Starting breadth first search:");
bfs(d, roomkey);
if(!success){
printf(" FAILED\n");
}
else{
success = true;
}
mark_unvisited( d); // reset rooms in dict to be not visited
}
if(best_flag){
printf("Starting best first search:");
best(d, roomkey);
if(!success){
printf(" FAILED\n");
}
else{
success = true;
}
mark_unvisited( d); // reset rooms in dict to be not visited
}
if(conn_flag){
*count = 0;
dfs(d, roomkey, count, conn_flag);
if(*count == total){
printf("Graph is connected.\n");
}
else{
printf("Graph is NOT connected.\n");
}
mark_unvisited( d); // reset rooms in dict to be not visited
}
if(dir_flag){
if (undir(d)){
printf("Graph is undirected.\n");
}
else{
printf("Graph is directed.\n");
}
mark_unvisited( d); // reset rooms in dict to be not visited
}
free(count);
DictDestroy(d);
}
void dfs(Dict d, const char *key, int *count, bool conn){
struct room *r;
r = DictSearch(d, key);
extern bool success;
if(r != 0){
if(r->visited == 0){
(*count)++;
r->visited = 1;
if(!success){ // print room if burning room not found yet
if(!conn){
printf(" %s", r->room);
}
}
if(r->temp > 400 && !success ){ // if found for first time
if(!conn){
printf(" SUCCESS!\n");
}
success = true;
return;
}
else{
for(int h = 0; h < r->ncount; h++){ // go through neighbors
dfs(d, r->neighbors[h],count, conn); // recursively
}
}
}
}
}
void bfs(Dict d, const char *key){
extern bool success;
Heap h;
h = initheap();
// create malloced room to put in heap
struct room *r = malloc(sizeof(struct room));
struct room *hold; //create pointer to room in dict
hold = DictSearch(d, key);
hold->visited = 1;
*r = *hold;
int order = 0; // int key for order of rooms in heap
if(r!=0){
insert(h, order ,r);
order++;
while(!empty(h)){
struct room *v; // evaluate min-key room
v = findmin(h);
printf(" %s", v->room);
if(v->temp > 400){ // burning room found
destroyHeap(h);
printf(" SUCCESS!\n");
success = true;
return;
}
for(int i = 0; i < v->ncount; i++){ // go through neighbors
//create malloced room to put in heap
struct room *neigh = malloc(sizeof(struct room));
struct room *h2; //create pointer to room in dict
h2 = DictSearch(d,v->neighbors[i] );
*neigh = *h2;
if(neigh != 0 ){
if(neigh->visited == 0){
h2->visited = 1;
insert( h, order, neigh);
order++;
}
else{
free(neigh);
}
}
}
free(v);
deletemin(h);
}
}
destroyHeap(h);
}
void best(Dict d, const char *key){
extern bool success;
Heap h;
h = initheap();
// create malloced room to put in heap
struct room *r = malloc(sizeof(struct room));
struct room *hold; //create pointer to room in dict
hold = DictSearch(d, key);
hold->visited = 1;
*r = *hold;
if(r!=0){
insert(h, -1*r->temp ,r);
while(!empty(h)){
// evaluate min-key room
struct room *v = malloc(sizeof(struct room));
*v = *findmin(h);
free(findmin(h));
deletemin(h);
printf(" %s", v->room);
if(v->temp > 400){ //burning room
free(v);
destroyHeap(h);
printf(" SUCCESS!\n");
success = true;
return;
}
for(int i = 0; i < v->ncount; i++){ // go through neighbors
// create malloced room to put in heap
struct room *neigh = malloc(sizeof(struct room));
struct room *h2; //create pointer to room in dict
h2 = DictSearch(d,v->neighbors[i] );
*neigh = *h2;
if(neigh != 0 ){
if(neigh->visited == 0){
h2->visited = 1;
// use negative temperature as key in heap
insert( h, -1*neigh->temp, neigh);
}
else{
free(neigh);
}
}
}
free(v);
}
}
destroyHeap(h);
}
int undir(Dict d){
struct elt *e; // struct to go through dict
bool undirected = true; // bool to check if undirected or directed
for(int i=0; i<d->size; i++) { // go through hash table
if (d->table[i]) {
for (e = d->table[i];e != NULL; e = e->next){ //go through linked list
for(int j = 0; j< e->value->ncount; j++){ // go through neighbors
struct room *r;
r = DictSearch(d, e->value->neighbors[j]);
int is_neighbor = 0;
if(r != 0){
for( int k = 0; k < r->ncount; k++){ // go through neighbors
if(!strcmp(r->neighbors[k],e->value->room )){
is_neighbor = 1;
}
}
}
else{ // if neighbor not in dictionary then undirected
undirected = false;
printf("Rooms %s and %s are not symmetric.\n",
r->room, e->key);
}
if(is_neighbor == 0){ // if neighbor's list does not original
undirected = false; // then undirected
printf("Rooms %s and %s are not symmetric.\n",
r->room, e->key);
}
}
}
}
}
if(undirected){
return 1;
}
return 0;
}
void mark_unvisited(Dict d){
struct elt *e; // struct to go through dict
for(int i=0; i<d->size; i++) { // go through dict
if (d->table[i]) {
for (e = d->table[i];e != NULL; e = e->next){ //go through linked list
e->value->visited = 0;
}
}
}
}
|
2dff3d91f75a051c6afd5c6cddf37dc3b15d3751
|
[
"C"
] | 17 |
C
|
bpark738/Data_Structures
|
03b95589e0e2454450d2794924257f6c76e03810
|
c13ac7f310b405fac4d9ca183e342b9c44ad166b
|
refs/heads/master
|
<repo_name>edeiver/WeatherApp-React.js<file_sep>/src/components/WeatherLocation/WeatherData/index.js
import React from 'react';
import WeatherTemperature from './WeatherTemperature';
import WeatherExtraInfo from './WeatherExtraInfo';
import { WINDY} from './../../../constants/weathers'
import './style.css';
const WeatherData = () =>(
<div className="card-text">
<WeatherTemperature temperature={35} weatherState={WINDY}/>
<WeatherExtraInfo humidity={80} wind={'10m/s'}/>
</div>
);
export default WeatherData;<file_sep>/src/components/WeatherLocation/index.js
import React from 'react';
import Location from './Location';
import WeatherData from './WeatherData'
import PropTypes from 'prop-types';
const WeatherLocation = () =>(
<div className="row">
<div className="col-lg-12 col-sm-12 col-md-12">
<div className="card">
<div className="card-header">
<h4>WheatherLoaction</h4>
<Location city={'Barranquilla'}/>
</div>
<div className="card-body">
<WeatherData/>
</div>
</div>
</div>
</div>
);
Location.propTypes={
city: PropTypes.string.isRequired,
};
export default WeatherLocation;<file_sep>/src/components/WeatherLocation/WeatherData/WeatherExtraInfo.js
import React from 'react';
import PropTypes from 'prop-types';
import './style.css';
const WeatherExtraInfo = (props) =>{
return (
<div className="weatherExtraInfoCont">
<span>{`${props.humidity} % - `}</span>
<span>{props.wind}</span>
</div>
)
};
WeatherExtraInfo.propTypes={
humidity: PropTypes.number.isRequired,
wind: PropTypes.string.isRequired,
};
export default WeatherExtraInfo;
|
79a3825461d49a7e5fc5ac2ffc337deb1f17c844
|
[
"JavaScript"
] | 3 |
JavaScript
|
edeiver/WeatherApp-React.js
|
216bc87985a886d96f0bce64d2129c68bfdfbd15
|
48c5d640042ab87f484125dd9d0769330e32552d
|
refs/heads/master
|
<file_sep>use std::fs::File;
use std::io::prelude::*;
pub struct Lua {
pub lua: rlua::Lua,
}
impl Lua {
pub fn new() -> Lua {
Lua {
lua: rlua::Lua::new(),
}
}
pub fn get(&mut self) -> &rlua::Lua {
&self.lua
}
pub fn read(path: &str) -> String {
let mut file_handle = File::open(path).expect(&format!("Cannot read lua file \"{}\"", path));
let mut file_contents = String::new();
file_handle.read_to_string(&mut file_contents).expect(&format!("Could not convert lua script \"{}\" to string.", path));
file_contents
}
}
<file_sep>#! /bin/bash
path=$1
./$1 &
pid=$!
# If this script is killed, kill the `cp'.
trap "kill $pid 2> /dev/null" EXIT
counter=1
mkdir profiler
# While copy is running...
while kill -0 $pid 2> /dev/null; do
echo q | htop --sort-key=PERCENT_MEM | aha --black --line-fix > profiler/htop-$counter.html
((++counter))
sleep 1
done
# Disable the trap on a normal exit.
trap - EXIT<file_sep>use std::fs::File;
use std::io::prelude::*;
pub struct Json {
pub file_path: String,
file_handle: File,
content: String,
pub json: serde_json::Value,
}
impl Json {
pub fn new(path: &str) -> Json {
Json {
file_path: path.to_string(),
file_handle: File::open(path).expect("Json file not found"),
content: String::new(),
json: serde_json::Value::default()
}
}
pub fn load_json(&mut self) {
self.file_handle.read_to_string(&mut self.content).expect("Could not read json file");
self.json = serde_json::from_str(&self.content).unwrap();
}
}
<file_sep>#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
pub use self::model::Model;
pub mod model;
<file_sep>[package]
name = "platformer-rust"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
[dependencies]
sfml = "0.14.0"
serde_json = "1.0"
walkdir = "2"
rlua = "0.15.3"
[lib]
name = "platformer"
path = "src/lib.rs"
[[bin]]
name = "runtime"
path = "src/runtime/main.rs"
<file_sep>pub use self::json::Json;
pub use self::lua::Lua;
pub mod json;
pub mod lua;
<file_sep>extern crate platformer;
use std::ffi::OsStr;
use platformer::bindings::Json;
use platformer::bindings::Lua;
fn read_directory(path: &str) -> Vec<String> {
let mut vec: Vec<String> = Vec::new();
for entry in walkdir::WalkDir::new(path) {
let entry = entry.unwrap();
if entry.path().extension() == Some(OsStr::new("lua")) {
vec.push(entry.path().to_str().unwrap().to_string())
}
}
vec
}
fn main() {
{
let mut win = platformer::engine::Window::new_with(1024, 768, "Platformer Rust");
let mut scene = platformer::engine::Scene::new(&mut win);
// Read config file
let mut config = Json::new("game/config.json");
config.load_json();
let config_scripts_path = &config.json["scripts_folders"];
let config_data_path = &config.json["data_folder"].as_str();
let script_path_one = config_scripts_path[0].as_str().unwrap();
println!("Scripts directory: {}", script_path_one);
println!("Data directory: {}", config_data_path.unwrap());
let lua_paths: Vec<String> = read_directory(&format!("game/{}", script_path_one));
let mut lua = Lua::new();
let lua_ptr = lua.get();
for path in lua_paths {
let content: String = Lua::read(&path);
let function = lua_ptr.load(&content, Some(&path)).unwrap();
function.call::<_, ()>(()).unwrap();
}
// Load backgrounds
let mut backgrounds_tex: Vec<sfml::graphics::Texture> = Vec::new();
let mut tex_ptr: *mut sfml::graphics::Texture;
let mut model: platformer::containers::Model;
for i in 0..50 {
backgrounds_tex.push(sfml::graphics::Texture::from_file(&format!("game/{}{}{}.jpg", config_data_path.unwrap(), "assets/backgrounds/", (i + 1).to_string())).unwrap());
tex_ptr = backgrounds_tex.as_mut_ptr();
unsafe {
model = platformer::containers::Model {
name: format!("{}{}", i, ".jpg"),
model: Box::new(sfml::graphics::Sprite::with_texture(&*tex_ptr.add(i))),
hidden: false
};
}
scene.add_model(model);
}
println!("Running Platformer Rust for 10 seconds...");
scene.render();
println!("Cleaning resources...");
}
println!("Cleaned all the assets. Waiting for 30 seconds...");
std::thread::sleep(std::time::Duration::from_secs(30));
}<file_sep>#![allow(dead_code)]
#![allow(unused_variables)]
pub use self::window::Window;
pub use self::scene::Scene;
pub mod window;
pub mod scene;
<file_sep>extern crate sfml;
use std::boxed::Box;
use sfml::window::{Event, Key, Style, VideoMode};
use sfml::graphics::{RenderWindow, RenderTarget};
use super::super::containers;
#[derive(Debug)]
pub struct Window {
m_window_width: u32,
m_window_height: u32,
m_window_title: String,
m_fullscreen: bool,
m_fps: f32,
m_initial_aspect_ratio: f32,
m_event: sfml::window::Event,
m_window_handle: Box<RenderWindow>
}
impl Window {
pub fn new() -> Window {
Window::new_with(1024, 768, "Main Window (Rust)")
}
pub fn new_with(width: u32, height: u32, title: &str) -> Window {
let desktop_mode = VideoMode::desktop_mode();
Window {
m_window_width: width,
m_window_height: height,
m_window_title: title.to_string(),
m_fullscreen: false,
m_initial_aspect_ratio: (width as f32) / (height as f32),
m_fps: 60.0,
m_event: Event::GainedFocus,
m_window_handle: Box::new(
RenderWindow::new(
VideoMode::new(width as u32, height as u32, desktop_mode.bits_per_pixel),
title, Style::CLOSE, &Default::default())
)
}
}
pub fn poll_events(&mut self) {
while let Some(event) = self.m_window_handle.poll_event() {
self.m_event = event;
match self.m_event {
Event::Closed | Event::KeyPressed { code: Key::Escape, .. } => {
self.m_window_handle.close();
},
Event::KeyPressed { code: Key::F5, .. } => { }, // Toggle fullscreen,
Event::Resized {width: new_width, height: new_height} => { }, // Resized event
Event::LostFocus => { },
Event::GainedFocus => { },
_ => { }
}
}
}
pub fn is_open(&self) -> bool {
self.m_window_handle.is_open()
}
pub fn set_fullscreen(&mut self, fullscreen: bool) {
let desktop_mode = VideoMode::desktop_mode();
if !self.m_fullscreen && fullscreen {
self.m_window_handle.close();
self.m_window_handle = Box::new(
RenderWindow::new(
VideoMode::new(desktop_mode.width, desktop_mode.height, desktop_mode.bits_per_pixel),
&self.m_window_title, Style::FULLSCREEN, &Default::default())
)
} else if self.m_fullscreen && !fullscreen {
self.m_window_handle.close();
let new_width = (desktop_mode.height as f32) * self.m_initial_aspect_ratio;
self.m_window_handle = Box::new(
RenderWindow::new(
VideoMode::new(new_width.floor() as u32, desktop_mode.height, desktop_mode.bits_per_pixel),
&self.m_window_title, Style::CLOSE, &Default::default())
)
} else {
// Nothing
}
}
pub fn set_fps(&mut self, fps: f32) {
self.m_fps = fps;
}
pub fn get_size(&self) -> (u32, u32) {
(self.m_window_width, self.m_window_height)
}
pub fn get_title(&self) -> &str {
&self.m_window_title
}
pub fn clear(&mut self, color: sfml::graphics::Color) {
self.m_window_handle.clear(&color);
}
pub fn display(&mut self) {
self.m_window_handle.display();
}
pub fn draw(&mut self, model: &mut Box<containers::Model>) {
self.m_window_handle.draw(&*model.model)
}
}
<file_sep>extern crate sfml;
use std::boxed::Box;
use super::window::Window;
use super::super::containers::model::Model;
pub struct Scene<'a, 'b> {
elapsed_time: sfml::system::Time,
window: &'b mut Window,
models: Vec<Box<Model<'a>>>,
clock: sfml::system::Clock,
frame_time: f32
}
impl<'a, 'b> Drop for Scene<'a, 'b> {
fn drop(&mut self) {}
}
impl<'a, 'b> Scene<'a, 'b> {
pub fn new(window: &'b mut Window) -> Scene<'a, 'b> {
Scene {
elapsed_time: sfml::system::Time::ZERO,
window: window,
models: Vec::new(),
clock: sfml::system::Clock::default(),
frame_time: 1.0 / 60.0
}
}
pub fn render(&mut self) {
let clock = sfml::system::Clock::start();
while self.window.is_open() && clock.elapsed_time().as_seconds() < 10.0 {
self.pre_frame();
self.on_frame();
self.post_frame();
self.restart_clock();
}
}
fn pre_frame(&mut self) {
// Call draw function on all objects
self.window.poll_events();
self.window.clear(sfml::graphics::Color::BLACK);
for model in &mut self.models {
if model.is_visible() {
self.window.draw(model);
}
}
}
fn on_frame(&mut self) {
if self.elapsed_time.as_seconds() > self.frame_time {
self.window.display();
self.elapsed_time -= sfml::system::Time::seconds(self.frame_time)
}
}
fn post_frame(&self) { }
pub fn add_model(&mut self, model: Model<'a>) {
self.models.push(Box::new(model))
}
pub fn add_model_ptr(&mut self, model: Box<Model<'a>>) {
self.models.push(model)
}
pub fn get_model(&mut self, name: &str) -> Option<Box<Model<'a>>> {
for model in &self.models {
if model.get_name() == name {
Some(model);
}
}
println!("Could not find a model named \"{}\"", name);
None
}
pub fn make_sprite(name: &str, sprite: sfml::graphics::Sprite<'a>) -> Model<'a> {
Model::new_sprite(name, sprite)
}
fn get_elapsed_time(&self) -> sfml::system::Time {
self.elapsed_time
}
fn restart_clock(&mut self) {
self.elapsed_time += self.clock.restart()
}
}
<file_sep>extern crate sfml;
use std::boxed::Box;
use std::fmt;
pub struct Model<'a> {
pub name: String,
pub model: Box<sfml::graphics::Sprite<'a>>,
pub hidden: bool
}
impl<'a> fmt::Debug for Model<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Name: {0}\nModel: SFML Drawable", self.name)
}
}
impl<'a> fmt::Display for Model<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Name: {0}\nModel: SFML Drawable", self.name)
}
}
impl<'a> Model<'a> {
pub fn new_sprite(name: &str, model: sfml::graphics::Sprite<'a>) -> Model<'a> {
Model {
name: name.to_string(),
model: Box::new(model),
hidden: false
}
}
pub fn get_name(&self) -> &str {
&self.name
}
pub fn set_name(&mut self, name: &str) {
self.name = name.to_string()
}
pub fn set_model(&mut self, model: sfml::graphics::Sprite<'a>) {
self.model = Box::new(model)
}
pub fn set_hidden(&mut self, hidden: bool) {
self.hidden = hidden;
}
pub fn is_hidden(&self) -> bool {
self.hidden
}
pub fn set_visible(&mut self, visible: bool) {
self.set_hidden(!visible)
}
pub fn is_visible(&self) -> bool {
!self.is_hidden()
}
}
<file_sep>extern crate serde_json;
pub mod containers;
pub mod bindings;
pub mod engine;
|
bd06c4592720434eabf4db33ebccb4d3b59e2831
|
[
"TOML",
"Rust",
"Shell"
] | 12 |
Rust
|
Borderliner/platformer-rust
|
4bd7f344ee16f513dbf098817fae6ffcff406819
|
2e2d60c8d8c12f4f8afb3c56426f6c590ccf0ebb
|
refs/heads/master
|
<repo_name>niedzielnyaniol/niedzielnyaniol.github.io<file_sep>/README.md
This is readme.md
This is text from repo1
dwadw
dwdwdw<file_sep>/js/scripts.js
$('.skill').hover(function(){
var prBar = $(this).children('.progressbar');
prBar.fadeIn(300)
console.log('hello from repo1');
prBar.children('.percent-20').addClass('percent-20-animation');
prBar.children('.percent-40').addClass('percent-40-animation');
prBar.children('.percent-60').addClass('percent-60-animation');
prBar.children('.percent-80').addClass('percent-80-animation');
prBar.children('.percent-100').addClass('percent-100-animation');
console.log('hello from repo2');
});
$('.env').hover(function(){
$(this).children('.logo-80x80')
.addClass('env-logo-animation')
.delay(1000)
.queue(function () {
$(this).removeClass('env-logo-animation')
.dequeue();
})
});
$('header').height($(window).height());
console.log( 'hello and hi' );
|
58aa291daa2c8e892985172be5a25557e87efe69
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
niedzielnyaniol/niedzielnyaniol.github.io
|
53ec2195198189433ef575e1290bd90109e7f38c
|
19adb93e74735da8dcb3a0bd20b63d3d4900ebce
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import webapp2, jinja2, os, re
from google.appengine.ext import db
from cgi import escape
#Constants lol no caps
template_dir = os.path.join(os.path.dirname(__file__), "templates")
#that auto escape tho
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape=True)
def render_temp(template_name, **kargs):
""" render jinja templates with less typing """
template = jinja_env.get_template(template_name)
return template.render(**kargs)
def get_posts(limit, offset):
return db.GqlQuery("SELECT * FROM Posts ORDER BY created DESC LIMIT " +
"{} OFFSET {}".format(limit, offset))
class Posts(db.Model):
title = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
class NewPost(webapp2.RequestHandler):
'''new post handler'''
def get(self):
#handle title error
t_error = self.request.get('t_error')
c_error = self.request.get('c_error')
content = self.request.get("content")
title = self.request.get("title")
title = escape(title)
content = escape(content)
self.response.write(render_temp('newpost.html', t_error=t_error,
c_error=c_error, content=content,
title=title, ptitle="New Entry"))
class AddPost(webapp2.RequestHandler):
def post(self):
title = self.request.get('post_title')
text = self.request.get('post_content')
# this chunk does the error handling
error = ""
if not title:
error += "t_error=Enter A Title"
else:
error += "title=" + title
if not text:
error += "&c_error=Enter Content for Your Post"
else:
if "t_error" in error:
error += "&content=" + text
print(error)
if error != "title=" + title:
self.redirect("/newpost?" + error)
elif (title and title.strip() != "") and (text and text.strip() != ""):
p = Posts(title=title, content=text)
p.put()
self.redirect("/blog")
else:
self.response.write("you broke it")
class Blog(webapp2.RequestHandler):
''' handler for /blog '''
def get(self):
page = self.request.get("page")
page = page if page and int(page) else 1
page = int(page)
if page == 1:
offset = 0
else:
offset = page * 5 - 5
posts = get_posts(5, offset)
total_posts = posts.count()
tpages = total_posts / 5 + 1
print("{} total posts, {} pages".format(total_posts, tpages))
self.response.write(render_temp('blog.html', posts=posts, ptitle="Blog", page=page, tpages=tpages))
class ViewPostHandler(webapp2.RequestHandler):
''' handler for /blog/id instances '''
def get(self, post_id):
post_id = post_id if post_id and int(post_id) else ""
post = Posts.get_by_id(int(post_id))
#this is me being lazy
self.response.write(""" <div style="font-family:sans-serif;">"""
"""<h1> {} </h1> {}</div<""".format(post.title, post.content))
#testing something
app = webapp2.WSGIApplication([
('/', Blog),
('/add', AddPost),
('/blog', Blog),
('/newpost', NewPost),
#weird why did i have to add the extra bit
webapp2.Route('/blog/<post_id:\d+>', ViewPostHandler)
], debug=True)
|
25e9bc2d2d4ee090630b6c367423b4160f1e0477
|
[
"Python"
] | 1 |
Python
|
KerstingJ/build-a-blog
|
675d576053974b5ceabeeeb8e4dee741f84d0b20
|
4264143a3aad8a0de7f343652a7f858b51d752dc
|
refs/heads/master
|
<repo_name>timbear00/Shooting<file_sep>/Assets/Scripts/Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
public int hpSetting;
public static float attackDamage;
public static float attackSpeed;
public static string playerName;
public static float playerSpeed;
public static bool playerdead;
public static bool playerClear;
public static int hp;
public static bool shield;
public static bool powerUp;
public static float shieldTime;
public static float powerUpTime;
// Start is called before the first frame update
void Start()
{
hp = hpSetting;
playerdead = false;
shield = false;
powerUp = false;
}
void FixedUpdate()
{
//Debug.Log(hp);
PlayerDie();
itemCheck();
}
private void PlayerDie()
{
if (hp < 1)
{
gameObject.SetActive(false);
playerdead = true;
}
}
private void itemCheck()
{
if( powerUp == true )
{
Debug.Log("Hello");
powerUpTime -= Time.deltaTime;
if( powerUpTime <= 0 )
{
powerUp = false;
if (Player.playerName == "Jack")
{
Player.attackDamage = 20;
Player.attackSpeed = 0.8f;
Player.playerSpeed = 2;
}
else if (Player.playerName == "Jessica")
{
Player.attackDamage = 10;
Player.attackSpeed = 0.3f;
Player.playerSpeed = 3;
}
gameObject.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f);
}
else
{
if ( Player.playerName == "Jack" )
{
Player.attackDamage = 40;
Player.attackSpeed = 0.2f;
Player.playerSpeed = 4f;
}
else if ( Player.playerName == "Jessica" )
{
Player.attackDamage = 20;
Player.attackSpeed = 0.05f;
Player.playerSpeed = 6f;
}
gameObject.GetComponent<SpriteRenderer>().color = new Color(1f, 0, 0);
}
}
else if ( shield )
{
shieldTime -= Time.deltaTime;
gameObject.GetComponent<SpriteRenderer>().color = new Color(0, 1f, 1f);
if ( shieldTime <= 0 )
{
shield = false;
gameObject.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f);
}
}
else if ( !shield ) gameObject.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f);
}
}
<file_sep>/Assets/Scripts/Bgm.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bgm : MonoBehaviour
{
public AudioClip newMusic;
public bool changeMusic = true;
// Start is called before the first frame update
void Awake()
{
if (changeMusic)
{
var go = GameObject.Find("StartBGM"); //Finds the game object called Game Music, if it goes by a different name, change this.
go.GetComponent<AudioSource>().clip = newMusic; //Replaces the old audio with the new one set in the inspector.
go.GetComponent<AudioSource>().Play(); //Plays the audio.
}
DontDestroyOnLoad(gameObject);
}
// Update is called once per frame
void Update()
{
}
}
<file_sep>/Assets/Scripts/ShieldItem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShieldItem : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "player")
{
Player.shield = true;
Player.shieldTime = 30.0f;
GameManager.itemCount--;
Destroy(gameObject);
}
}
}
<file_sep>/Assets/Scripts/Boss.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Boss : MonoBehaviour
{
private Transform target;
public float speed;
public float bossHp;
public int demage;
private bool enemyHit;
// Start is called before the first frame update
void Start()
{
enemyHit = false;
if (!Player.playerdead && !Player.playerClear)
target = GameObject.FindGameObjectWithTag("player").GetComponent<Transform>();
}
// Update is called once per frame
void FixedUpdate()
{
float step = speed * Time.deltaTime;
if (!Player.playerdead && !Player.playerClear)
{
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
if (gameObject.transform.position.x - target.transform.position.x > 0)
gameObject.GetComponent<SpriteRenderer>().flipX = true;
}
if (enemyHit)
{
bossHp -= Player.attackDamage;
enemyHit = false;
}
BossDead();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Bullet")
{
gameObject.GetComponent<SpriteRenderer>().color = new Color(1f, 0, 0);
enemyHit = true;
StartCoroutine(BossColorBack());
}
}
IEnumerator BossColorBack()
{
yield return new WaitForSeconds(1.0f);
gameObject.GetComponent<SpriteRenderer>().color = new Color(0, 0, 0);
}
void BossDead()
{
if (bossHp <= 0)
{
Variables.GameClear = true;
Destroy(gameObject);
SceneManager.LoadScene("Ending");
}
}
}
<file_sep>/Assets/Scripts/bullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bullet : MonoBehaviour
{
public float bulletSpeed;
public Rigidbody2D bulletBody;
private Vector3 target = new Vector3();
private float moveSpeed = 5f;
// Start is called before the first frame update
void Start()
{
Vector2 target = Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
Vector2 myPos = new Vector2(transform.position.x, transform.position.y);
Vector2 direction = target - myPos;
direction.Normalize();
bulletBody.velocity = direction * moveSpeed;
StartCoroutine(DeleteBullet());
}
IEnumerator DeleteBullet()
{
yield return new WaitForSeconds(3);
this.enabled = false;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "enemy")
Destroy(gameObject);
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Boundary")
Destroy(gameObject);
}
}
<file_sep>/Assets/Scripts/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public List<GameObject> enemies;
public List<Transform> enemySpawnPos;
public GameObject Jack;
public GameObject Jessica;
public Text nameText;
public Slider HealthBar;
public Text hpText;
public Text timeTable;
public string stageName;
public GameObject clearPanel;
public GameObject MenuPanel;
public float LastTime;
public float timeLeft = 1.0f;
private int spawnNum = 0;
private GameObject player;
public GameObject powerUpItem;
public GameObject hpItem;
public GameObject shieldItem;
private float itemTimeLeft;
private int itemType;
public static int itemCount;
// Start is called before the first frame update
private void Awake()
{
itemCount = 0;
itemTimeLeft = Random.Range(3.0f, 5.0f);
Debug.Log(itemTimeLeft);
if (Player.playerName == "Jack")
{
player = Instantiate<GameObject>(Jack, new Vector3 (0,0,0), transform.rotation);
player.SetActive(true);
}
else
{
player = Instantiate<GameObject>(Jessica, new Vector3(0, 0, 0), transform.rotation);
player.SetActive(true);
}
Player.playerClear = false;
Variables.currentScene = stageName;
nameText.text = "Name : " + Player.playerName;
HealthBar.value = Player.hp;
hpText.text = Player.hp + "/100";
clearPanel.SetActive(false);
MenuPanel.SetActive(false);
}
// Update is called once per frame
void FixedUpdate()
{
LastTime -= Time.deltaTime;
if(Input.GetKeyDown(KeyCode.Escape))
{
MenuPanel.SetActive(true);
Time.timeScale = 0;
}
if(LastTime > 0)
timeTable.text = "남은 시간 : " + LastTime.ToString();
else
timeTable.text = "남은 시간 : " + 0;
timeLeft -= Time.deltaTime;
if( timeLeft <= 0 )
{
Instantiate(enemies[Random.Range(0, enemies.Capacity)], enemySpawnPos[Random.Range(0, enemySpawnPos.Capacity)].position, Quaternion.identity);
Instantiate(enemies[Random.Range(0, enemies.Capacity)], enemySpawnPos[Random.Range(0, enemySpawnPos.Capacity)].position, Quaternion.identity);
timeLeft = 1.5f;
}
#region item spawn
itemTimeLeft -= Time.deltaTime;
if (itemTimeLeft <= 0 && itemCount <= 10)
{
itemType = Random.Range(0, 3);
if (itemType == 0)
{
Instantiate(powerUpItem, new Vector3(Random.Range(-20.0f, 20.0f), Random.Range(-10.0f, 10.0f), 0), Quaternion.identity);
}
else if (itemType == 1)
{
Instantiate(hpItem, new Vector3(Random.Range(-20.0f, 20.0f), Random.Range(-10.0f, 10.0f), 0), Quaternion.identity);
}
else if (itemType == 2)
{
Instantiate(shieldItem, new Vector3(Random.Range(-20.0f, 20.0f), Random.Range(-10.0f, 10.0f), 0), Quaternion.identity);
}
itemCount++;
itemTimeLeft = Random.Range(3.0f, 5.0f);
//Debug.Log("Item type : " + Item.itemName + ", Item Count : " + itemCount+", TimeLeft : "+itemTimeLeft);
}
#endregion
HealthBar.value = Player.hp;
hpText.text = Player.hp + "/100";
Clear();
GameOver();
}
void GameOver()
{
if(Player.playerdead)
{
player.SetActive(false);
SceneManager.LoadScene("BadEnding");
}
else if(stageName == "Boss" && LastTime <= 0)
{
player.SetActive(false);
SceneManager.LoadScene("BadEnding");
}
}
void Clear()
{
if (LastTime <= 0 && stageName != "Boss" && !Player.playerdead)
{
player.SetActive(false);
clearPanel.SetActive(true);
Player.playerClear = true;
}
else if(stageName == "Boss" && Variables.GameClear)
{
SceneManager.LoadScene("Ending");
player.SetActive(false);
}
}
}
<file_sep>/Assets/Scripts/Enemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
private Transform target;
public float speed;
public float enemyHp;
public int demage;
public bool enemyDead;
private bool enemyHit;
private Vector2 movementDirection;
private Vector2 movementPerSecond;
// Start is called before the first frame update
void Start()
{
enemyDead = false;
enemyHit = false;
movementDirection = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
movementPerSecond = movementDirection * speed;
if (!Player.playerdead && !Player.playerClear)
target = GameObject.FindGameObjectWithTag("player").GetComponent<Transform>();
}
// Update is called once per frame
void FixedUpdate()
{
float step = speed * Time.deltaTime;
if (!Player.playerdead && !Player.playerClear)
{
if (Vector3.Distance(target.position, gameObject.transform.position) < 10f)
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
else
transform.position = new Vector3(transform.position.x + (movementPerSecond.x * Time.deltaTime), transform.position.y + (movementPerSecond.y * Time.deltaTime), 0);
if (gameObject.transform.position.x - target.transform.position.x > 0)
gameObject.GetComponent<SpriteRenderer>().flipX = true;
}
if (enemyHit)
{
enemyHp -= Player.attackDamage;
if (enemyHp <= 20) speed *= 2;
enemyHit = false;
}
Enemydead();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "player")
{
if (Player.shield)
{
Player.shield = false;
}
else
{
Player.hp -= demage;
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Bullet")
{
gameObject.GetComponent<SpriteRenderer>().color = new Color(1f, 0, 0);
enemyHit = true;
}
}
private void Enemydead()
{
if(enemyHp <= 0)
{
enemyDead = true;
Destroy(gameObject);
}
}
}
<file_sep>/Assets/Scripts/SceneChange.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SceneChange : MonoBehaviour
{
public GameObject panel;
public void Jack()
{
SceneManager.LoadScene("Stage1");
Player.playerName = "Jack";
Player.attackDamage = 20;
Player.attackSpeed = 0.8f;
Player.playerSpeed = 2;
Player.hp = 100;
}
public void Jessica()
{
SceneManager.LoadScene("Stage1");
Player.playerName = "Jessica";
Player.attackDamage = 10;
Player.attackSpeed = 0.3f;
Player.playerSpeed = 3;
Player.hp = 100;
}
public void GoToStage2()
{
SceneManager.LoadScene("Stage2");
}
public void GoToBossStage()
{
SceneManager.LoadScene("Boss");
}
public void GoToMain()
{
SceneManager.LoadScene("Main");
Time.timeScale = 1;
}
public void ContinueGame()
{
Time.timeScale = 1;
panel.SetActive(false);
}
public void StartGame()
{
SceneManager.LoadScene("CharacterSelect");
Variables.GameClear = false;
}
public void ContinuePlay()
{
if(Variables.currentScene == null)
{
Variables.GameClear = false;
SceneManager.LoadScene("CharacterSelect");
}
else
SceneManager.LoadScene(Variables.currentScene);
}
public void HowToPlay()
{
SceneManager.LoadScene("HowToPlay");
Player.playerName = "Jack";
Player.attackDamage = 20;
Player.attackSpeed = 0.8f;
Player.playerSpeed = 2;
Player.hp = 100;
}
}
<file_sep>/Assets/Scripts/PowerUpItem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerUpItem : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
if( collision.gameObject.tag == "player" )
{
Player.powerUp = true;
Player.powerUpTime = 10.0f;
GameManager.itemCount--;
Destroy(gameObject);
}
}
}
<file_sep>/Assets/Scripts/HpItem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HpItem : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "player")
{
Player.hp += 25;
if (Player.hp > 100)
{
Player.hp = 100;
}
GameManager.itemCount--;
Destroy(gameObject);
}
}
}
<file_sep>/Assets/Scripts/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public GameObject bullet;
public Transform GunPosition;
float timeT;
bool fireLocked;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos);
lookPos = lookPos - transform.position;
float angle = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
if (angle < 90 && angle > -90)
{
gameObject.GetComponent<SpriteRenderer>().flipY = false;
}
else
{
gameObject.GetComponent<SpriteRenderer>().flipY = true;
}
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
timeT += Time.deltaTime;
if (timeT > Player.attackSpeed && fireLocked)
fireLocked = false;
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
transform.position += new Vector3(0, Player.playerSpeed * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
transform.position += new Vector3(0, Player.playerSpeed * (-1) * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
transform.position += new Vector3(Player.playerSpeed * (-1) * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
transform.position += new Vector3(Player.playerSpeed * Time.deltaTime, 0, 0);
}
if ( Input.GetMouseButtonDown(0) )
{
if (!fireLocked)
{
GameObject instantiatedProjectile = Instantiate(bullet, GunPosition.position, bullet.transform.rotation);
Object.Destroy(instantiatedProjectile, 2.0f);
fireLocked = true;
timeT = 0;
}
}
}
}
|
fda9042fbd86fc64c88fea59db614396ebc4fe5c
|
[
"C#"
] | 11 |
C#
|
timbear00/Shooting
|
ca39f298c9398d66a627f035e23c7c6137e99250
|
50d4ceb6ec2ea2e8fe23fce85915bc66a663e5c6
|
refs/heads/master
|
<repo_name>lumoslabs/pronto-brakeman<file_sep>/lib/pronto/brakeman/version.rb
module Pronto
module BrakemanVersion
VERSION = '0.4.0'
end
end
<file_sep>/spec/pronto/brakeman_spec.rb
require 'spec_helper'
module Pronto
describe Brakeman do
let(:brakeman) { Brakeman.new }
describe '#run' do
subject { brakeman.run(patches, nil) }
context 'patches are nil' do
let(:patches) { nil }
it { should == [] }
end
context 'no patches' do
let(:patches) { [] }
it { should == [] }
end
context 'patches with a single unsafe redirect' do
let(:repo) { Git::Repository.new('spec/fixtures/test.git') }
let(:patches) { repo.diff('da70127') }
its(:count) { should == 1 }
its(:'first.msg') do
should ==
'Possible security vulnerability: Possible unprotected redirect'
end
end
end
end
end
<file_sep>/lib/pronto/brakeman.rb
require 'pronto'
require 'brakeman'
module Pronto
class Brakeman < Runner
def run(patches, _)
return [] unless patches
ruby_patches = patches.select { |patch| patch.additions > 0 }
.select { |patch| ruby_file?(patch.new_file_full_path) }
files = ruby_patches.map { |patch| patch.new_file_full_path.to_s }
if files.any?
output = ::Brakeman.run(app_path: ruby_patches.first.repo.path,
output_formats: [:to_s],
rails3: true)
messages_for(ruby_patches, output).compact
else
[]
end
end
def messages_for(ruby_patches, output)
output.checks.all_warnings.map do |warning|
patch = patch_for_warning(ruby_patches, warning)
if patch
line = patch.added_lines.find do |added_line|
added_line.new_lineno == warning.line
end
new_message(line, warning) if line
end
end
end
def new_message(line, warning)
Message.new(line.patch.delta.new_file[:path], line, :warning,
"Possible security vulnerability: #{warning.message}")
end
def patch_for_warning(ruby_patches, warning)
ruby_patches.find do |patch|
patch.new_file_full_path.to_s == warning.file
end
end
end
end
<file_sep>/README.md
# Pronto runner for Brakeman
[](https://codeclimate.com/github/mmozuras/pronto-brakeman)
[](https://travis-ci.org/mmozuras/pronto-brakeman)
[](http://badge.fury.io/rb/pronto-brakeman)
[](https://gemnasium.com/mmozuras/pronto-brakeman)
Pronto runner for [Brakeman](https://github.com/presidentbeef/brakeman), security vulnerability scanner for RoR. [What is Pronto?](https://github.com/mmozuras/pronto)
|
d3a05c242fe405f0773c9a8c968426cb8e0cfea2
|
[
"Markdown",
"Ruby"
] | 4 |
Ruby
|
lumoslabs/pronto-brakeman
|
843760cbe1350cb39544bc89768106159f7598a1
|
c4ea9715da5f4627ee4ab6fdb7e2b59e096c51e4
|
refs/heads/master
|
<repo_name>reactNoobie/animations<file_sep>/scripts/index.js
const render = () => {
const toggleRainButton = document.querySelector('#toggle-rain-btn');
toggleRainButton.onclick = () => {
const rains = document.querySelectorAll('.rain');
rains.forEach(rain => rain.classList.toggle('raining'));
}
const rainContainer = document.querySelector('.rain-container');
for (let i = 0; i < 50; i++) {
const rain = document.createElement('div');
rain.classList.add('rain');
rainContainer.appendChild(rain);
}
const pausables = document.querySelectorAll('.pausable');
pausables.forEach(pausable => {
pausable.onclick = (e) => {
e.stopPropagation();
pausable.classList.toggle('paused');
}
});
};
const clickbait = document.querySelector('.clickbait');
clickbait.onclick = () => {
clickbait.classList.toggle('clicked');
};
const getRandom = (max, min) => Math.floor(Math.random() * (min - max + 1)) + max;
const containerGrid = document.querySelector('.container-grid');
containerGrid.onclick = () => {
const emergingBox = document.createElement('div');
emergingBox.style.backgroundColor = `rgb(${getRandom(0, 256)}, ${getRandom(0, 256)}, ${getRandom(0, 256)})`;
emergingBox.classList.add('emerging-box');
emergingBox.classList.add('pausable');
containerGrid.appendChild(emergingBox);
render();
};
const animateJsAnimation = () => {
const jsAnimation = document.querySelector('.js-animation');
jsAnimation.animate([{ backgroundColor: 'turquoise' }, { backgroundColor: 'teal' }], 3000);
};
const animateJsAnimationButton = document.querySelector('.js-animation-btn');
animateJsAnimationButton.onclick = animateJsAnimation;
const animateTweenMaxExample = () => {
const tweenMaxExample = document.querySelector('.tweenmax-example');
TweenMax.to(
tweenMaxExample,
2,
{
y: '100%',
ease: 'Elastic.easeOut',
repeat: 1,
yoyo: true,
},
);
};
const tweenMaxExampleButton = document.querySelector('.tweenmax-example-btn');
tweenMaxExampleButton.onclick = animateTweenMaxExample;
const itemNames = document.querySelectorAll('.item-name');
itemNames.forEach((itemName, index) => {
itemName.onclick = () => {
document.querySelector('.item-list').style.transform = 'translateX(-100%)';
document.querySelector(`.item-description:nth-of-type(${index + 1})`).style.transform = 'translateX(0)';
}
});
const itemDescriptions = document.querySelectorAll('.item-description');
itemDescriptions.forEach(itemDescription => {
itemDescription.onclick = () => {
itemDescription.style.transform = 'translateX(100%)';
document.querySelector('.item-list').style.transform = 'translateX(0)';
}
});
const CAROUSEL_ITEM_COUNT = 5;
const updateCarouselControlButtons = () => {
slideLeftButton.disabled = carouselIndex === 0;
slideRightButton.disabled = carouselIndex === CAROUSEL_ITEM_COUNT - 1;
};
const carouselItems = document.querySelectorAll('.carousel-container>div');
const slide = slideTo => {
if (slideTo === 'right') carouselIndex++;
else carouselIndex--;
updateCarouselControlButtons();
carouselItems.forEach(item => item.style.transform = `translateX(calc(-100% * ${carouselIndex}))`);
};
let carouselIndex = 0;
const slideLeftButton = document.querySelector('.slide-left-btn');
slideLeftButton.onclick = slide.bind(null, 'left');
const slideRightButton = document.querySelector('.slide-right-btn');
slideRightButton.onclick = slide.bind(null, 'right');
updateCarouselControlButtons();
document.querySelector('.show-modal-btn').onclick = () => {
document.querySelector('.modal-container').classList.add('shown');
};
document.querySelector('.dismiss-modal').onclick = () => {
document.querySelector('.modal-container').classList.remove('shown');
};
render();
<file_sep>/README.md
# Animations
Learning how to animate stuffs on the web
<file_sep>/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animations</title>
<link rel="stylesheet" href="styles/style.css">
<script src="scripts/index.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
</head>
<body>
<button id="toggle-rain-btn">Toggle rain</button>
<div class="rain-container"></div>
<pre>.rain-container {
display: grid;
grid-template-columns: repeat(auto-fill, 20px);
grid-auto-rows: 20px;
gap: 5px;
}
.rain {
border-radius: 0 10px 10px 10px;
background-image: linear-gradient(to right, lightblue, cyan);
}
.raining {
animation: rain 3s infinite ease-in-out alternate;
}
@keyframes rain {
to {
transform: translate(0, 100vh) skewY(90deg);
}
}
/* JS */
const toggleRainButton = document.querySelector('#toggle-rain-btn');
toggleRainButton.onclick = () => {
const rains = document.querySelectorAll('.rain');
rains.forEach(rain => rain.classList.toggle('raining'));
}
const rainContainer = document.querySelector('.rain-container');
for (let i = 0; i <= 30; i++) {
const rain = document.createElement('div');
rain.classList.add('rain');
rainContainer.appendChild(rain);
}</pre>
<hr>
Starting
<a href="https://www.youtube.com/watch?v=zHUpx90NerM">
CSS3 Animation & Transitions Crash Course by Traverst Media
</a>
<h1 class="pausable">Let's animate stuffs!</h1>
<p>
In CSS, there are 2 main ways to move things around the page:
</p>
<ul>
<li>Transition Property</li>
<li>Animation Property + Keyframes</li>
</ul>
<pre>h1 {
position: relative;
text-align: center;
width: 50%;
animation-name: main-header;
animation-duration: 5s;
animation-iteration-count: infinite;
animation-delay: 3s;
animation-direction: alternate;
animation-timing-function: ease-out;
}
@keyframes main-header {
0% {
background-color: hotpink;
transform: translate(0, 0);
}
25% {
background-color: thistle;
transform: translate(100%, 0);
}
50% {
background-color: lime;
transform: translate(100%, 10vh);
}
75% {
background-color: cyan;
transform: translate(0, 10vh);
}
100% {
background-color: hotpink;
transform: translate(0, 0);
}
}</pre>
<div class="centered-circle pausable" id="morphing-circle"></div>
<pre>#morphing-circle {
background-image: linear-gradient(to right, darkcyan, cyan);
position: relative;
left: calc(50% - 10vw);
height: 20vw;
width: 20vw;
animation-name: morphing-circle;
animation-duration: 5s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: ease-out;
}
@keyframes morphing-circle {
0% {border-radius: 0 0 0 0;}
25% {border-radius: 50% 0 0 0;}
50% {border-radius: 50% 50% 0 0;}
75% {border-radius: 50% 50% 50% 0;}
100% {border-radius: 50% 50% 50% 50%;}
}</pre>
<div class="centered-circle" id="transition-1">Hold</div>
<pre>#transition-1 {
transition-property: background-color, border-radius, transform;
transition-duration: 2s, 3s, 4s;
}
#transition-1:active {
background-color: limegreen;
border-radius: 50%;
transform: rotateZ(180deg);
}</pre>
End of
<a href="https://www.youtube.com/watch?v=zHUpx90NerM">
CSS3 Animation & Transitions Crash Course by Traverst Media
</a>
<hr>
Starting
<a href="https://www.youtube.com/watch?v=8kK-cA99SA0">CSS Transitions</a>
Syntax for applying transition:
<pre id="one-line-transform">.element {
/* transition: [property] [duration] [ease] [delay]; */
#one-line-transform {
transition: opacity 1s ease-in 100ms;
}
#one-line-transform:hover {
opacity: 0;
}
}</pre>
<p>
We declare the transition property on the element that we want to move. Note that every element is not
animatable. Things we can animate include:
</p>
<ul>
<li>font-size</li>
<li>background-color</li>
<li>width</li>
<li>left</li>
</ul>
<p>
These things do not cause a repaint, or reflow of the layout. Things we can't animate:
</p>
<ul>
<li>display</li>
<li>font-family</li>
<li>position</li>
</ul>
<p>
If you animate anything other than translation, scale, rotation and opacity, you are at risk of not hitting
60fps mark.
</p>
<p>
Main ways of triggering these transitions are to hover over things and use classes. Remember
<code>pointer-events</code>. Its a big one.
</p>
<div class="centered-circle clickbait">
<div>Clickbait!</div>
</div>
<pre>.clickbait {
border: 10px double orange;
display: flex;
background-color: pink;
}
.clickbait div {
flex: 1;
transition: background-color 500ms ease-in, transform 500ms ease-in;
pointer-events: none;
}
.clickbait.clicked div {
transform: translate(50px, 50px) rotate(90deg);
background-color: darkseagreen;
}
/* JS */
const clickbait = document.querySelector('.clickbait');
clickbait.onclick = () => {
clickbait.classList.toggle('clicked');
};</pre>
<p>
In order to use the <code>animation</code> property, we need to use something called <code>keyframe</code>.
Keyframes don't have any selectors on them, they are not nested inside anything, they are placed at the root of
the css file.
</p>
<div class="one-line-animation pausable">Ease</div>
<pre>.one-line-animation {
animation: expand-width 4s ease-in infinite alternate;
transform-origin: 0 0;
background-color: plum;
}
@keyframes expand-width {
from {
transform: scaleX(0);
}
to {
transform: scaleX(1);
}
}</pre>
<div class="container-grid"></div>
<pre>.container-grid {
display: grid;
grid-template-columns: repeat(auto-fill, 10vw);
grid-auto-rows: 10vw;
gap: 10px;
min-height: 100px;
}
.emerging-box {
animation: emerging-box 1s ease-in infinite alternate;
}
@keyframes emerging-box {
from {transform: scale(0);}
to {transform: scale(1);}
}
/* JS */
const containerGrid = document.querySelector('.container-grid');
containerGrid.onclick = () => {
const emergingBox = document.createElement('div');
emergingBox.style.backgroundColor = `rgb(${getRandom(0, 256)}, ${getRandom(0, 256)}, ${getRandom(0, 256)})`;
emergingBox.classList.add('emerging-box');
emergingBox.classList.add('pausable');
containerGrid.appendChild(emergingBox);
}</pre>
End of
<a href="https://www.youtube.com/watch?v=8kK-cA99SA0">CSS Transitions</a>
<hr>
Beginning
<a href="https://www.youtube.com/watch?v=Nloq6uzF8RQ">Animating with CSS transitions</a>
<div class="timing-functions">
Various <code>animation-timing-function</code>s:
<dl>
<dt>ease</dt>
<dd></dd>
<dt>ease-in</dt>
<dd></dd>
<dt>ease-out</dt>
<dd></dd>
<dt>ease-in-out</dt>
<dd></dd>
<dt>linear</dt>
<dd></dd>
</dl>
</div>
End of
<a href="https://www.youtube.com/watch?v=Nloq6uzF8RQ">Animating with CSS transitions</a>
<hr>
Starting
<a href="https://developers.google.com/web/fundamentals/design-and-ux/animations/css-vs-javascript">
CSS animations vs JS animations
</a>
<br>
<p>
Some properties are more expensive to change than others, and are therefore more likely to make things stutter.
So, for example, changing the box-shadow of an element requires a much more expensive paint operation than
changing, say, its text color. Similarly, changing the width of an element is likely to be more expensive than
changing its transform. If you want the TL;DR, stick to transforms and opacity changes, and use will-change.
</p>
<ul>
<li>
CSS transitions and animations are ideal for bringing a navigation menu in from the side, or showing a
tooltip. You may end up using JavaScript to control the states, but the animations themselves will be in
your CSS.
</li>
<li>
Use JavaScript when you need significant control over your animations. The Web Animations API is the
standards-based approach, available today in most modern browsers. This provides real objects, ideal for
complex object-oriented applications. JavaScript is also useful when you need to stop, pause, slow down, or
reverse your animations.
</li>
<li>
Use requestAnimationFrame directly when you want to orchestrate an entire scene by hand.
</li>
</ul>
<p>
Animating with CSS is the simplest way to get something moving on screen. This approach is described as
declarative, because you specify what you'd like to happen.
</p>
<p>
Keyframes are an old term from hand-drawn animations. Animators would create specific frames for a piece of
action, called key frames, which would capture things like the most extreme part of some motion, and then they
would set about drawing all the individual frames in between the keyframes. We have a similar process today with
CSS animations, where we instruct the browser what values CSS properties need to have at given points, and it
fills in the gaps.
</p>
<p>
Creating animations with JavaScript is, by comparison, more complex than writing CSS transitions or animations,
but it typically provides developers significantly more power. You can use the Web Animations API to either
animate specific CSS properties or build composable effect objects.
</p>
<p>
JavaScript animations are imperative, as you write them inline as part of your code. You can also encapsulate
them inside other objects.
</p>
<div class="js-animation"></div>
<button class="js-animation-btn">Animate</button>
<pre>const animateJsAnimation = () => {
const jsAnimation = document.querySelector('.js-animation');
jsAnimation.animate([{ backgroundColor: 'turquoise' }, { backgroundColor: 'teal' }], 3000);
};
const animateJsAnimationButton = document.querySelector('.js-animation-btn');
animateJsAnimationButton.onclick = animateJsAnimation;</pre>
<p>
By default, Web Animations only modify the presentation of an element. If you'd like to have your object remain
at the location it has moved to, then you should modify its underlying styles when the animation has finished.
</p>
<p>
With JavaScript animations, you're in total control of an element's styles at every step. This means you can
slow down animations, pause them, stop them, reverse them, and manipulate elements as you see fit. This is
especially useful if you're building complex, object-oriented applications, because you can properly encapsulate
your behavior.
</p>
<p>
Easing makes your animations feel more natural. Choose ease-out animations for UI elements. Avoid ease-in or
ease-in-out animations unless you can keep them short; they tend to feel sluggish to end users.
</p>
<p>
With linear motion, things tend to feel robotic and unnatural, and this is something that users find jarring.
Generally speaking, you should avoid linear motion.
</p>
<p>
Sometimes you need even more control than a cubic Bézier curve can provide. If you wanted an elastic bounce
feel, you might consider using a JavaScript framework, because this is a difficult effect to achieve with either
CSS or Web Animations. One powerful framework is GreenSock’s TweenMax (or TweenLite if you want to keep things
really lightweight), because you get a lot of control from it in a small JavaScript library, and it’s a very
mature codebase.
</p>
<div class="tweenmax-example"></div>
<button class="tweenmax-example-btn">Animate with TweenMax</button>
<pre>[script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"][/script]
const animateTweenMaxExample = () => {
const tweenMaxExample = document.querySelector('.tweenmax-example');
TweenMax.to(
tweenMaxExample,
2,
{
y: '100%',
ease: 'Elastic.easeOut',
repeat: 1,
yoyo: true,
},
);
};</pre>
<p>
Ensure that any animating element has will-change set for anything you plan to change well ahead of the
animation starting. For view transitions, it’s highly likely you will want to use will-change: transform.
</p>
<div class="slide-in-example">
<ul class="item-list">
<li class="item-name">Item 1</li>
<li class="item-name">Item 2</li>
<li class="item-name">Item 3</li>
</ul>
<div class="item-description">Item 1 description</div>
<div class="item-description">Item 2 description</div>
<div class="item-description">Item 3 description</div>
</div>
<pre>.slide-in-example {
position: relative;
height: 100px;
overflow: hidden;
}
.item-list, .item-description {
position: absolute;
height: 100%;
width: 100%;
transition: transform 3s ease-out;
}
.item-description {
transform: translateX(100%);
}
/* JS */
const itemNames = document.querySelectorAll('.item-name');
itemNames.forEach((itemName, index) => {
itemName.onclick = () => {
document.querySelector('.item-list').style.transform = 'translateX(-100%)';
document.querySelector(`.item-description:nth-of-type(${index + 1})`).style.transform = 'translateX(0)';
}
});
const itemDescriptions = document.querySelectorAll('.item-description');
itemDescriptions.forEach(itemDescription => {
itemDescription.onclick = () => {
itemDescription.style.transform = 'translateX(100%)';
document.querySelector('.item-list').style.transform = 'translateX(0)';
}
});</pre>
<div class="carousel-container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="carousel-controls">
<button class="slide-left-btn"><</button>
<button class="slide-right-btn">></button>
</div>
<pre>.carousel-container {
height: 100px;
display: flex;
overflow: hidden;
}
.carousel-container>div {
flex: 1;
min-width: 100%;
transition: transform 2s ease-out;
}
.carousel-container>div:nth-of-type(1) {
background-color: lime;
}
...
/* JS */
const CAROUSEL_ITEM_COUNT = 5;
const updateCarouselControlButtons = () => {
slideLeftButton.disabled = carouselIndex === 0;
slideRightButton.disabled = carouselIndex === CAROUSEL_ITEM_COUNT - 1;
};
const carouselItems = document.querySelectorAll('.carousel-container>div');
const slide = slideTo => {
if (slideTo === 'right') carouselIndex++;
else carouselIndex--;
updateCarouselControlButtons();
carouselItems.forEach(item => item.style.transform = `translateX(calc(-100% * ${carouselIndex}))`);
};
let carouselIndex = 0;
const slideLeftButton = document.querySelector('.slide-left-btn');
slideLeftButton.onclick = slide.bind(null, 'left');
const slideRightButton = document.querySelector('.slide-right-btn');
slideRightButton.onclick = slide.bind(null, 'right');</pre>
<div class="modal-container">
<div class="modal-content">
Haha!
<button class="dismiss-modal">Dismiss</button>
</div>
</div>
<button class="show-modal-btn">Show Modal</button>
<pre>.modal-container {
display: flex;
justify-content: center;
align-items: center;
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
background-color: rgba(239, 239, 239, 0.741);
pointer-events: none;
opacity: 0;
transform: scale(1.1);
transition: transform 100ms ease-in, opacity 100ms ease-in;
}
.modal-content {
padding: 10rem;
background-color: white;
color: black;
}
.modal-container.shown {
pointer-events: auto;
opacity: 1.0;
transform: scale(1.0);
transition: transform 200ms ease-in, opacity 200ms ease-in;
}
/* JS */
document.querySelector('.show-modal-btn').onclick = () => {
document.querySelector('.modal-container').classList.add('shown');
};
document.querySelector('.dismiss-modal').onclick = () => {
document.querySelector('.modal-container').classList.remove('shown');
};</pre>
<p>
Note that the different transition values let us make the modal appear slower but go faster. Woahwoahwoah!
</p>
<p>
Where you can, you should avoid animating properties that trigger layout or paint. For most modern browsers,
this means limiting animations to opacity or transform, both of which the browser can highly optimize; it
doesn’t matter if the animation is handled by JavaScript or CSS.
</p>
<ul>
<li>
CSS-based animations, and Web Animations where supported natively, are typically handled on a thread known
as the "compositor thread". This is different from the browser's "main thread", where styling, layout,
painting, and JavaScript are executed. This means that if the browser is running some expensive tasks on the
main thread, these animations can keep going without being interrupted.
</li>
<li>
Other changes to transforms and opacity can, in many cases, also be handled by the compositor thread.
</li>
<li>
If any animation triggers paint, layout, or both, the "main thread" will be required to do work. This is
true for both CSS- and JavaScript-based animations, and the overhead of layout or paint will likely dwarf
any work associated with CSS or JavaScript execution.
</li>
</ul>
End of
<a href="https://developers.google.com/web/fundamentals/design-and-ux/animations/css-vs-javascript">
CSS animations vs JS animations
</a>
<hr>
Starting
<a href="https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/">
High performance animations
</a>
<p>
The process that the browser goes through is pretty simple: calculate the styles that apply to the elements
(Recalculate Style), generate the geometry and position for each element (Layout), fill out the pixels for each
element into layers (Paint Setup and Paint) and draw the layers out to screen (Composite Layers).
</p>
<p>
To achieve silky smooth animations you need to avoid work, and the best way to do that is to only change
properties that affect compositing -- transform and opacity. The higher up you start on the timeline waterfall
the more work the browser has to do to get pixels on to the screen.
</p>
<p>
When you change elements, the browser may need to do a layout, which involves calculating the geometry (position
and size) of all the elements affected by the change. If you change one element, the geometry of other elements
may need to be recalculated. For example, if you change the width of the [html] element any of its children may
be affected. Due to the way elements overflow and affect one another, changes further down the tree can
sometimes result in layout calculations all the way back up to the top.
</p>
<p>
The larger the tree of visible elements, the longer it takes to perform layout calculations, so you must take
pains to avoid animating properties that trigger layout. Styles that affect layout:
</p>
<table>
<tbody>
<tr>
<td>width</td>
<td>height</td>
</tr>
<tr>
<td>padding</td>
<td>margin</td>
</tr>
<tr>
<td>display</td>
<td>border-width</td>
</tr>
<tr>
<td>border</td>
<td>top</td>
</tr>
<tr>
<td>position</td>
<td>font-size</td>
</tr>
<tr>
<td>float</td>
<td>text-align</td>
</tr>
<tr>
<td>overflow-y</td>
<td>font-weight</td>
</tr>
<tr>
<td>overflow</td>
<td>left</td>
</tr>
<tr>
<td>font-family</td>
<td>line-height</td>
</tr>
<tr>
<td>vertical-align</td>
<td>right</td>
</tr>
<tr>
<td>clear</td>
<td>white-space</td>
</tr>
<tr>
<td>bottom</td>
<td>min-height</td>
</tr>
</tbody>
</table>
<p>
Take a look at
<a
href="https://docs.google.com/spreadsheets/u/1/d/1Hvi0nu2wG3oQ51XRHtMv-A_ZlidnwUYwgQsPQUg1R2s/pub?single=true&gid=0&output=html">
this great page for details
</a>. Styles that affect paint:
</p>
<table>
<tbody>
<tr>
<td>color</td>
<td>border-style</td>
</tr>
<tr>
<td>visibility</td>
<td>background</td>
</tr>
<tr>
<td>text-decoration</td>
<td>background-image</td>
</tr>
<tr>
<td>background-position</td>
<td>background-repeat</td>
</tr>
<tr>
<td>outline-color</td>
<td>outline</td>
</tr>
<tr>
<td>outline-style</td>
<td>border-radius</td>
</tr>
<tr>
<td>outline-width</td>
<td>box-shadow</td>
</tr>
<tr>
<td>background-size</td>
<td></td>
</tr>
</tbody>
</table>
End of
<a href="https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/">
High performance animations
</a>
<hr>
</body>
</html>
|
edf05a68b5bf1e40c0f859cb6006ec536527588c
|
[
"JavaScript",
"HTML",
"Markdown"
] | 3 |
JavaScript
|
reactNoobie/animations
|
7305a75c2a12a6644f2a18989cef01e0ddd0ab01
|
d6280cbcccbc98394e4cd2dd7f04cd9345fe907d
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from recorder.recorder import main
# allow this script to be executed as a child of another script (lsprofcalltree, for example)
sys.path.insert(0, '.')
if __name__ == '__main__':
main()
|
18afe564eea78b4d9d5b82012f52ea4b6f164120
|
[
"Python"
] | 1 |
Python
|
moliqingwa/Recorder
|
ccd14f4bd893590182a0998ac8b378c6f02082cc
|
5f9df32958d5948cdb6b27ddcf73ffc39457f70e
|
refs/heads/master
|
<file_sep>var express = require("express");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var session = require("express-session");
const User = require('./models/User')
const Images = require('./models/Images')
const router = express.Router();
var rememberBox = false;
router.use(bodyParser.urlencoded({ extended: true }))
router.use(cookieParser());
router.use(
session({
key: 'user_sid',
secret: "thisIsSecret",
resave: true,
saveUninitialized: true
})
);
router.use(express.static(__dirname + '/webpages'));
// This middleware will check if user's cookie is still saved in browser and user is not set, then automatically log the user out.
// This usually happens when you stop your express server after login, your cookie still remains saved in the browser.
router.use((req, res, next) => {
if (req.cookies.user_sid && !req.session.user) {
res.clearCookie("user_sid");
}
next();
});
var sessionChecker = (req, res, next) => {
if (req.session.user && req.cookies.user_sid) {
res.redirect("/");
} else {
next();
}
};
// router.use(
// function (req, res, next) {
// var data = "";
// req.on('data', function (chunk) { data += chunk });
// req.on('end', function () {
// req.rawBody = data;
// next();
// });
// });
router.get("/session_info", (req, res) => {
var user_info = {
username: "",
email: "",
remember: false,
last_time: ""
};
if (req.session.user && req.cookies.user_sid) {
user_info.username = req.session.user.username
user_info.remember = req.session.remember;
user_info.email = req.session.user.email;
}
res.send(user_info);
});
router.get('/', (req,res) =>{
res.sendFile(__dirname + '/views/webpages/home.html')
})
//login page
router.route('/login').get(sessionChecker,(req, res) => {
//who does only this work and no /login
res.sendFile(__dirname + '/views/webpages/login.html');
}).post(async (req, res) => {
console.log(req.body.password);
var email = req.body.email,
password = <PASSWORD>,
remember = req.body.remember;
//remember me set the maxAge
if (remember == "on") {
rememberBox = true;
req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 6;
}
else {
rememberBox = false;
}
try {
const user = await User.findOne({ email: email }).exec();
if (!user) {
res.redirect("/login");
}
user.comparePassword(password, (error, match) => {
if (!match) {
res.redirect("/login");
}
});
req.session.user = user;
req.session.remember = rememberBox;
res.redirect("/");
} catch (error) {
console.log(error)
}
});
//registration page
router.route('/registration').get(sessionChecker,(req, res) => {
res.sendFile(__dirname + '/views/webpages/registration.html');
})
.post((req, res) => {
console.log("here")
var user = new User({
username: req.body.username,
email: req.body.email,
password: <PASSWORD>,
});
console.log(req.body.username);
user.save((err, docs) => {
if (err) {
res.redirect("/registration");
} else {
res.redirect("/");
}
});
});
//contact us
router.route('/contact').get((req, res) => {
res.sendFile(__dirname + '/views/webpages/contact-us.html');
});
//get all photos from database
//should this change the return object
router.get("/photos", async (req, res) => {
Images.find({}).sort({date: -1}).exec((err, photo_list) => {
if (err) {
console.log(err);
return handleError(err);
}
else {
photo_list.forEach(photo_list => photo_list.image = photo_list.image.toString('base64'))
res.render('webpages/photos', { database: photo_list })
}
});
});
//logout
router.get("/logout", (req, res) => {
if (req.session.user && req.cookies.user_sid) {
res.clearCookie("user_sid")
req.session.destroy();
res.redirect("/");
} else {
res.redirect("/error");
}
});
router.route('/configuration').get(async(req,res) =>{
const configuration = await Config.find()
res.send(configuration);
})
.post(async (req, res) => {
var song = req.body.music;
if(song == ''){
song = 'default song/album'
}
var config = new Config({
frequency: req.body.frequency,
start_time: req.body.start_time,
end_time: req.body.end_time,
music: song,
});
config.save((err) => {
if (err) {
console.log(err);
return handleError(err);
} else {
console.log("successfully saved config")
}
});
});
// route for handling 404 requests(unavailable routes)
// router.use(function (req, res, next) {
// res.sendFile(__dirname + "/views/error.html")
// });
module.exports = router;
<file_sep>
const mqttConfig = {
"host": "localhost",
"port": 9001,
"url": '',
"topic": {
"subscribe": "config"
}
}
// Create a client instance
client = new Paho.MQTT.Client(mqttConfig.host, mqttConfig.port, mqttConfig.url, '');
client.connect({
timeout: 3,
onSuccess: function () {
console.log("mqtt connected");
client.subscribe("config", { qos: 2 });
},
onFailure: function (message) {
console.log("Connection failed: " + message.errorMessage);
}
});
// called when the client loses its connection
client.onConnectionLost = function (responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
// called when a message arrives
client.onMessageArrived = function (message) {
console.log(message);
location.reload();
};
<file_sep># 
IoT smart home appliance that captures candid photos of your family’s special moments using a combination of emotion detection and phrase detection. This app is a great appliance for families to capture fun moments between family members or improve your mood by playing happy songs when you are sad.
# Built with
* NodeJs
* Mosquito
* Node-red
* MongoDB
* Flutter
# Getting started
To run the application, you will need Node JS, MongoDB, Mosquito, Node red and Futter installed on your machine.
- Clone this repo
- Navigate to the server folder, install the required dependencies and run `node app.js` to start the local server
- Import `Node-red/spotify_flow.json` into your Node-RED instance from the node-red folder.
- Navigate to the fultter folder to run the Flutter app.
## Using node-red's Spotify integration
- To use the Spotify tool in node red you will have to make an account on Spotify.
- After creating your account go to [Spotify Developers](https://developer.spotify.com/dashboard/) to login and create an App to get a Client ID and Secret.
- Enter your Client ID and Client Secret in the Spotify Node.
- This is the scope to [Start/Resume a Users Playback](https://developer.spotify.com/documentation/web-api/reference/player/start-a-users-playback/); `user-modify-playback-state`.
- After authorizing you Select the API "play" and you are done with setting up the Spotify node.
- Please refer to the Spotify's [Web API](https://developer.spotify.com/documentation/web-api/reference/) reference to know about utilizing other API's.
<b> Please note: to use the 'Play' functionality you must have Spotify premium activated </b>
## Using MQTT
Websockets are used on the edge device using port 9001. Add the following configration to the mosquitto.conf file.
```
listener 443
protocol websockets
```
# Views
## Smart home edge device running on Browser
Our smart home application runs on the Chrome Browser where it does facial emotion detection, take picture with voice command and blur detection.

## Candid Capture Website
The candid capture website allows users to login and view their photos.

## Candid Capture flutter app
The flutter app has two activities, one to show the pictures taken of the user and the other to deal with the configurations/Settings.

# Overall Architecture
## Edge-device functionalities
The following diagram shows the functionalities of the browser which acts as our edge device.

## Configuration
Users can modify the various settings of their home system such as; <b> Camera on/off, camera timmings, camera frequency, spotify album</b>. The following is the pictorial representation of changing the configuration.

## Handling Images
The following flow diagram outlines how the edge device, server, browser and flutter are integrated when the appropriate picture is taken.

## License
MIT
## Authors
Project was build was part of our University Internet of Things course at AUS by
- [<NAME>](https://github.com/JeremyDsilva)
- [<NAME>](https://github.com/dhritix1999)
- [<NAME>](https://github.com/skampala1)
<file_sep>
var cam_state, cam_freq;
function getTimeDifference(time) {
return
}
$(document).ready(function () {
var canvas = document.getElementById('canvas');
console.log('start');
/**
* write ajax call save config in a variable
*
*/
$.get("/config", function (data) {
//get todays time
var load_time = new Date()
load_time = (load_time.getHours()*60) + load_time.getMinutes();
cam_state = data.cam_state
cam_freq = data.cam_freq
start_time = data.start_time
end_time = data.end_time
console.log(data)
startDifference = getTimeDifference(start_time);
endDifference = getTimeDifference(end_time);
// if camera on
if (cam_state) {
//if within on time
if (start_time <= load_time && end_time > load_time && cam_state) {
try {
faceDetectionStartup();
} catch (error) {
}
try {
phraseDetectionStartup();
} catch (error) {
}
} else {
setInterval(async => location.reload(), (1440 + start_time) * 1000); // reload page without hitting the server
}
}
});
// goes within call back of ajax call
// start time
if (true) {
// refresh page when end time
} else {
// start time refresh the page
}
});
function postImage() {
console.log('Posting image...');
$.post('/image', canvas.toDataURL('image/png'));
}
function playSong(){
console.log('Play song because im sad');
$.get('/play_song');
}
function faceDetectionStartup() {
var streaming = false;
var tinyFaceDetector = null;
var width = 720;
var height = 0;
const video = document.getElementById('video');
var streaming = false;
var context;
const url = 'https://raw.githubusercontent.com/justadudewhohacks/face-api.js/master/weights/';
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri(url),
faceapi.nets.faceLandmark68Net.loadFromUri(url),
faceapi.nets.faceRecognitionNet.loadFromUri(url),
faceapi.nets.faceExpressionNet.loadFromUri(url)]
).then(() => {
navigator.getWebcam = (navigator.getUserMedia || navigator.webKitGetUserMedia || navigator.moxGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia)
navigator.mediaDevices.getUserMedia({ audio: false, video: true })
.then((stream) => video.srcObject = stream)
.catch((e) => console.log);
else
navigator.getWebcam({ audio: false, video: true }, (stream) => video.srcObject = stream, () => logError("Web cam is not accessible."));
tinyFaceDetector = new faceapi.TinyFaceDetectorOptions();
})
video.addEventListener('canplay', function (ev) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
// Firefox currently has a bug where the height can't be read from
// the video, so we will make assumptions if this happens.
if (isNaN(height)) {
height = width / (4 / 3);
}
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
context = canvas.getContext('2d');
setInterval(async () => {
console.log('Evaluting...')
// if there is a measure blur dont compute
var blur = measureBlur(context.getImageData(0, 0, width, height)).avg_edge_width_perc;
if (1 < blur)
return;
const detections = await faceapi.detectAllFaces(video, tinyFaceDetector).withFaceLandmarks().withFaceExpressions();
context.drawImage(video, 0, 0, width, height);
for (let i = 0; i < detections.length; ++i)
if (detections[i].expressions.happy > 0.7) {
postImage();
break;
}
else if(detections[i].expressions.sad > 0.8){
playSong();
break;
}
},cam_freq * 1000)
}
}, false);
}
function phraseDetectionStartup() {
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition
var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList
var SpeechRecognitionEvent = SpeechRecognitionEvent || webkitSpeechRecognitionEvent
const phrase = 'take a picture';
var grammar = '#JSGF V1.0; grammar phrase; public <phrase> = ' + phrase + ';';
var recognition = new SpeechRecognition();
var speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
recognition.continuous = false;
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
var bg = document.querySelector('html');
recognition.onresult = function (event) {
var phraseRecieved = event.results[0][0].transcript;
console.log('Result received: ' + phraseRecieved + '.');
if (phraseRecieved == phrase) {
postImage();
}
console.log('Confidence: ' + event.results[0][0].confidence);
}
recognition.onspeechend = function () {
recognition.stop();
setTimeout(async () => { recognition.start() }, 2000);
}
recognition.onnomatch = function (event) {
console.log("I didn't recognise that color.");
setTimeout(async () => { recognition.start() }, 2000);
}
recognition.onerror = function (event) {
console.log('Error occurred in recognition: ' + event.error);
setTimeout(async () => { recognition.start() }, 2000);
}
recognition.start();
}
/**
*
* Configure mqtt to refresh when message is recieved
*
*/
// location.reload()
<file_sep>const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/CandidCapture', { useNewUrlParser: true, useUnifiedTopology: true });
const imageSchema = new mongoose.Schema({
date: {
type: Date,
required: true
},
image: {
type: Buffer,
required: true
}
})
const imageModel = mongoose.model('images', imageSchema)
module.exports = imageModel<file_sep>var express = require('express');
var mongoose = require('mongoose')
var mqtt = require('mqtt')
const Config = require('./models/Config')
const router = express.Router();
var client = mqtt.connect('mqtt://localhost:1883')
client.on('connect', function () {
client.subscribe('config', function (err) {
if (err)
console.log(err);
else
console.log('connected to mqtt succesffully 2')
})
});
router.get("/play_song", (req, res) => {
var id = 'spotify:playlist:37i9dQZF1DX3rxVfibe1L0'
//get from database
Config.find().limit(1).exec((err, conf) => {
if (err) {
console.log(err);
return handleError(err);
}
else {
var song = conf[0].album;
console.log(song)
res.redirect('http://127.0.0.1:1880/play_spotify?song=' + song)
}
});
});
router.get("/config", (req, res) => {
//get from database
Config.find().limit(1).exec((err, conf) => {
if (err) {
console.log(err);
return handleError(err);
}
else {
res.send(conf[0]);
}
});
});
router.post('/config', function (req, res, next) {
var data = "";
req.on('data', function (chunk) { data += chunk })
req.on('end', function () {
req.body = JSON.parse(data);
next();
})
}, async (req, res) => {
//delete all records
Config.deleteMany({}).then(function () {
console.log("Data deleted"); // Success
//add new config
console.log(req.body.cam_state);
if (!req.body.cam_freq || req.body.cam_freq == null)
req.body.cam_freq = 2;
if (!req.body.cam_state || req.body.cam_state == null)
req.body.cam_state = true;
if (!req.body.start_time || req.body.start_time == null)
req.body.start_time = 0;
if (!req.body.end_time || req.body.end_time == null)
req.body.end_time = 24 * 60;
Config({
cam_state: req.body.cam_state,
cam_freq: req.body.cam_freq,
start_time: req.body.start_time,
end_time: req.body.end_time,
album: req.body.album,
}).save((err) => {
if (err) {
console.log(err);
return handleError(err);
} else {
console.log("successfully saved config")
client.publish("config", "new configuration added");
res.send();
}
});
}).catch(function (error) {
console.log(error); // Failure
});
});
module.exports = router;<file_sep>var express = require('express');
var mongoose = require('mongoose')
var app = express();
mongoose.connect('mongodb://localhost:27017/CandidCapture', { useNewUrlParser: true, useUnifiedTopology: true });
app.set("port", 3000);
app.set("view engine", "ejs")
app.use(express.static(__dirname + '/views'));
// Import my test routes into the path '/test'
var websiteRoutes = require('./web')
var imageRoutes = require('./image');
var configRoutes = require('./config')
app.use('/', imageRoutes);
app.use('/', websiteRoutes);
app.use('/', configRoutes);
// app.use('/web', websiteRoutes);
app.listen(3000, () =>
console.log(`App started on port ${app.get("port")}`)
);<file_sep>function detectEdges(imageData) {
var greyscaled, sobelKernel;
if (imageData.width >= 360) {
greyscaled = Filters.luminance(Filters.gaussianBlur(imageData, 5.0));
} else {
greyscaled = Filters.luminance(imageData);
}
sobelKernel = Filters.getFloat32Array(
[1, 0, -1,
2, 0, -2,
1, 0, -1]);
return Filters.convolve(greyscaled, sobelKernel, true);
}
// Reduce imageData from RGBA to only one channel (Y/luminance after conversion to greyscale)
// since RGB all have the same values and Alpha was ignored.
function reducedPixels(imageData) {
var i, x, y, row,
pixels = imageData.data,
rowLen = imageData.width * 4,
rows = [];
for (y = 0; y < pixels.length; y += rowLen) {
row = new Uint8ClampedArray(imageData.width);
x = 0;
for (i = y; i < y + rowLen; i += 4) {
row[x] = pixels[i];
x += 1;
}
rows.push(row);
}
return rows;
}
// pixels = Array of Uint8ClampedArrays (row in original image)
function detectBlur(pixels) {
var x, y, value, oldValue, edgeStart, edgeWidth, bm, percWidth,
width = pixels[0].length,
height = pixels.length,
numEdges = 0,
sumEdgeWidths = 0,
edgeIntensThresh = 20;
for (y = 0; y < height; y += 1) {
// Reset edge marker, none found yet
edgeStart = -1;
for (x = 0; x < width; x += 1) {
value = pixels[y][x];
// Edge is still open
if (edgeStart >= 0 && x > edgeStart) {
oldValue = pixels[y][x - 1];
// Value stopped increasing => edge ended
if (value < oldValue) {
// Only count edges that reach a certain intensity
if (oldValue >= edgeIntensThresh) {
edgeWidth = x - edgeStart - 1;
numEdges += 1;
sumEdgeWidths += edgeWidth;
}
edgeStart = -1; // Reset edge marker
}
}
// Edge starts
if (value == 0) {
edgeStart = x;
}
}
}
if (numEdges === 0) {
bm = 0;
percWidth = 0;
} else {
bm = sumEdgeWidths / numEdges;
percWidth = bm / width * 100;
}
return {
width: width,
height: height,
num_edges: numEdges,
avg_edge_width: bm,
avg_edge_width_perc: percWidth
};
}
function measureBlur(imageData) {
return detectBlur(reducedPixels(detectEdges(imageData)));
}<file_sep>const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/CandidCapture', { useNewUrlParser: true, useUnifiedTopology: true });
const configSchema = new mongoose.Schema({
cam_state: {
type: Boolean,
required: true
},
cam_freq: {
type: Number,
required: true
},
start_time: {
type: Number,
required: true
},
end_time: {
type: Number,
required: true
},
album: {
type: String
}
})
const configModel = mongoose.model('config', configSchema)
module.exports = configModel
|
2d3effb6b6ba1938525c1000f4ea011932ea16c4
|
[
"JavaScript",
"Markdown"
] | 9 |
JavaScript
|
JeremyDsilva/Candid-Capture
|
a87b61578755d2ac9cbd5f04b68cbe308c2b40bc
|
df8bc14531567ba776370f89ece24a0a3c8ec1e7
|
refs/heads/master
|
<repo_name>RTaylor31415/ProjectEuler<file_sep>/src/problem25/Problem25.java
package problem25;
import java.math.BigInteger;
public class Problem25 {
public static void main(String[] args)
{
System.out.println(Fibonacci(1000));
}
public static int Fibonacci(int max)
{
BigInteger n = BigInteger.valueOf(1);
BigInteger k= BigInteger.valueOf(2);
BigInteger j= BigInteger.valueOf(3);
int digits=0;
int count = 4;
while(digits<max-1)
{
BigInteger temp1=j;
j=j.add(k);
n=k;
k=temp1;
count++;
digits=j.toString().length()-1;
}
return count;
}
}
<file_sep>/src/problem15/Problem15.java
package problem15;
public class Problem15 {
public static long l=0;
public static void main(String[] args)
{
System.out.println(LatticePaths(20));
}
private static long LatticePaths(int i) {
PathstoEndRecursive(0,0,i);
return l;
}
private static void PathstoEndRecursive(int i, int j, int k) {
if(i<k&&j<k)
{
PathstoEndRecursive(i+1,j,k);
PathstoEndRecursive(i,j+1,k);
}
else if(i<k)
{
PathstoEndRecursive(i+1,j,k);
}
else if(j<k)
{
PathstoEndRecursive(i,j+1,k);
}
if(i==k&&j==k)
{
l++;
}
}
}
<file_sep>/src/problem8/Problem8.java
package problem8;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Problem8 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(LargestProduct(4));
}
public static int LargestProduct(int n) throws FileNotFoundException
{
int mult=0;
Scanner s = new Scanner(new File("numbers.txt"));
ArrayList<Integer> al = new ArrayList<Integer>();
arrayfromfile(s);
return mult;
}
public static ArrayList<Integer> arrayfromfile(Scanner s)
{
ArrayList<Integer> al = new ArrayList<Integer>();
s.useDelimiter("");
while(s.hasNext())
{
al.add(Integer.parseInt(s.next()));
}
return al;
}
}
<file_sep>/src/problem18/Problem18.java
package problem18;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Problem18 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(MaximumPathSum(15));
}
private static int MaximumPathSum(int n) throws FileNotFoundException {
Scanner s = new Scanner(new File("C:\\Users\\RAT\\workspace\\Euler\\src\\problem18\\numbers.txt"));
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
al = arrayfromfile2d(s);
for(int i=n-1;i>0;i--)
{
for(int j=0;j<al.get(i).size()-1;j++)
{
int currentnode = al.get(i).get(j);
int nextnode = al.get(i).get(j+1);
int abovenode = al.get(i-1).get(j);
if(currentnode>=nextnode)
{
al.get(i-1).set(j, abovenode+currentnode);
}
else
{
al.get(i-1).set(j, abovenode+nextnode);
}
}
}
return al.get(0).get(0);
}
public static ArrayList<ArrayList<Integer>> arrayfromfile2d(Scanner s)
{
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
while(s.hasNextLine())
{
String t = s.nextLine();
String[] splitStr = t.split("\\s+");
ArrayList<Integer> al2 = new ArrayList<Integer>();
for(int i=0;i<splitStr.length;i++)
{
try{
al2.add(Integer.parseInt(splitStr[i]));
}
catch(NumberFormatException e)
{
}
}
al.add(al2);
}
return al;
}
}
<file_sep>/src/problem5/Problem5.java
package problem5;
import java.util.ArrayList;
import java.util.Collections;
public class Problem5 {
public static void main(String[] args) {
System.out.println(SmallestMultiple(20));
}
public static int SmallestMultiple(int num)
{
int mult=1;
ArrayList unusedprimes = new ArrayList();
for(int i=1;i<num;i++)
{
ArrayList al = primefactors(i);
for(Object prime: al)
{
if(!unusedprimes.contains(prime))
{
unusedprimes.add(prime);
}
if(unusedprimes.contains(prime))
{
int temp =(Collections.frequency(al, prime)-Collections.frequency(unusedprimes, prime));
for(int j=0;j<temp;j++)
{
unusedprimes.add(prime);
}
}
}
}
for(int i=0;i<unusedprimes.size()-1;i++)
{
System.out.println(unusedprimes.get(i));
mult*=(Integer)unusedprimes.get(i);
}
return mult;
}
public static ArrayList primefactors(int num)
{
ArrayList al=new ArrayList();
int i=1;
while(num>1)
{
if(num%i==0)
{
num=num/i;
al.add(i);
i=1;
}
i++;
}
return al;
}
}
<file_sep>/src/problem17/Problem17.java
package problem17;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Problem17 {
static List<String> numbers = new ArrayList<>(Arrays.asList("zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"));
static List<String> numbers2 = new ArrayList<>(Arrays.asList("zero","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"));
static String hundred = "hundred";
static String hundredand = "hundredand";
static String onethousand = "onethousand";
public static void main(String[] args)
{
System.out.println(lettercounts(1000));
}
public static int lettercounts(int num)
{
int sum=0;
for(int i=1;i<=num;i++)
{
sum+=lettercount(i);
}
return sum;
}
public static int lettercount(int num)
{
int count=0;
int tempnum=0;
if(num==1000)
{
return onethousand.length();
}
if(num>=100)
{
tempnum=num/100;
count+=numbers.get(tempnum).length();
if(num%100==0)
{
count+=hundred.length();
}
else
{
count+=hundredand.length();
}
num=num%100;
}
if(num>20)
{
tempnum=num/10;
count+=numbers2.get(tempnum).length();
num=num%10;
}
if(num<=20&&num>=1)
{
count+=numbers.get(num).length();
}
return count;
}
}
<file_sep>/src/problem27/Problem27.java
package problem27;
import java.util.ArrayList;
public class Problem27 {
static ArrayList checkedprimes = new ArrayList();
public static void main(String[] args)
{
System.out.println(QuadraticPrimes(1000));
}
public static int QuadraticPrimes(int n)
{
int maxprimes=0;
int maxi=0;
int maxj=0;
for(int i=-n;i<n;i++)
{
for(int j=-n;j<n;j++)
{
int count=numprimes(i,j);
if(count-1>maxprimes)
{
maxprimes=count-1;
maxi=i;
maxj=j;
System.out.println(maxi);
System.out.println(maxj);
System.out.println(maxprimes);
}
}
}
System.out.println(maxi);
System.out.println(maxj);
return maxi*maxj;
}
public static boolean IsPrime(long n)
{
if(n<=1)
{
return false;
}
for(int i=2;i<n/2;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
public static int numprimes(int i, int j)
{
boolean prime=true;
int count=0;
while(prime)
{
prime=IsPrime((count*count)+(i*count)+j);
count++;
}
return count-1;
}
}
<file_sep>/src/problem23/Problem23.java
package problem23;
import java.util.ArrayList;
public class Problem23 {
public static void main(String[] args)
{
System.out.println(NonAbundantSums(28123));
}
public static long NonAbundantSums(int num)
{
ArrayList<Integer> al=abundantlist(num);
ArrayList<Integer> al2=abundantlistsum(al);
long sum=0;
for(int i=1;i<=num;i++)
{
if(!al2.contains(i))
{
sum+=i;
}
}
return sum;
}
public static boolean Abundant(int num)
{
ArrayList<Integer> al = factors(num);
int sum = ArraySum(al);
return (sum>num);
}
public static ArrayList<Integer> factors(int num)
{
ArrayList al=new ArrayList();
for(int i=1;i<=num/2+1;i++)
{
if(num%i==0)
{
if(!al.contains(i))
{
al.add(i);
}
if(!al.contains(num/i))
{
al.add(num/i);
}
}
}
al.remove((Integer) num);
return al;
}
public static int ArraySum(ArrayList<Integer> al)
{
int sum=0;
for(int i=0;i<al.size();i++)
{
sum+=al.get(i);
}
return sum;
}
public static ArrayList<Integer> abundantlist(int num)
{
ArrayList al=new ArrayList();
for(int i=2;i<=num;i++)
{
if(Abundant(i))
{
al.add(i);
}
}
return al;
}
public static ArrayList<Integer> abundantlistsum(ArrayList<Integer> al)
{
ArrayList<Integer> al2 = new ArrayList<Integer>();
System.out.println(al.size());
for(int i=0;i<al.size();i++)
{
if(i%100==0)
{
System.out.println(i);
}
for(int j=0;j<al.size();j++)
{
if(!al2.contains(al.get(i)+al.get(j)))
{
al2.add(al.get(i)+al.get(j));
}
}
}
return al2;
}
}
<file_sep>/src/problem14/Problem14.java
package problem14;
public class Problem14 {
public static void main(String[] args)
{
System.out.println(LargestCollatzSequence(1000000));
}
private static int LargestCollatzSequence(int n) {
int longest=1;
int num=1;
for(int i=1;i<n;i++)
{
if(CollatzSequence(i)>longest)
{
longest=CollatzSequence(i);
num=i;
System.out.println(num);
System.out.println(longest);
}
}
return num;
}
private static int CollatzSequence(long n)
{
int count=0;
while(n>1)
{
if(n%2==0)
{
n/=2;
}
else
{
n = n*3+1;
}
count++;
}
return count+1;
}
}
<file_sep>/src/problem2/Problem2.java
package problem2;
public class Problem2 {
public static void main(String[] args) {
System.out.println(sumofevens(4000000));
}
public static int sumofevens(int max)
{
int n=1;
int k=2;
int j=3;
int sum=0;
while(j<max)
{
int temp1=j;
if(j%2==0)
{
sum+=j;
}
j=j+k;
n=k;
k=temp1;
}
return sum+2;
}
}
|
94c56bfb24001b01776a7e71b81a414cb4093f76
|
[
"Java"
] | 10 |
Java
|
RTaylor31415/ProjectEuler
|
8bb22e8d0c11e695825b6dc5ef2573bace08f7d5
|
97d6680e3dcf3c10d3d078c097d61a81e4e191a5
|
refs/heads/master
|
<repo_name>jerbbive/Git-Test<file_sep>/Git_Working/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Git_Working
{
class Program
{
static void Main(string[] args)
{
int int_choice;
int int_min;
int int_max;
Console.WriteLine("Please pick a low number.");
string min = Console.ReadLine();
int.TryParse(min, out int_min);
Console.WriteLine("Please pick a high number.");
string max = Console.ReadLine();
int.TryParse(max, out int_max);
Random random = new System.Random();
int num = random.Next(int_min, int_max);
Console.WriteLine(num);
Console.WriteLine("Please guess a number.");
string choice = Console.ReadLine();
int.TryParse(choice, out int_choice);
while (int_choice != num)
{
if(int_choice > num)
{
Console.WriteLine("Guess too high.");
}
else
{
Console.WriteLine("Guess too low");
}
Console.WriteLine("Please another guess a number.");
choice = Console.ReadLine();
int.TryParse(choice, out int_choice);
}
Console.WriteLine("You Guessed Correctly!");
Console.WriteLine("Push any key to exit.");
Console.ReadKey();
}
}
}
|
913accf2b85ebd003ab9d1a171831844f76780a6
|
[
"C#"
] | 1 |
C#
|
jerbbive/Git-Test
|
0bcbbf3fed8b73b933b817d28e635489cd1dd285
|
23322fa4abec6791bae5568618fe5eb8a1e6ba0f
|
refs/heads/master
|
<repo_name>comac-chen/ParameterManagement<file_sep>/management/apps.py
from __future__ import unicode_literals
from django.apps import AppConfig
from suit.apps import DjangoSuitConfig
#import sys
#sys.setrecursionlimit(1000000) #例如这里设置为一百万
class SuitConfig(DjangoSuitConfig):
layout = 'horizontal'
#class ManagementConfig(AppConfig):
# name = 'management'
<file_sep>/README.md
测试参数管理系统
<<<<<<< HEAD
2018.3.27
=======
>>>>>>> 01b26d4bceacf0d6506b19eb56dce6cb53218ad1
<file_sep>/management/migrations/0020_auto_20180314_1353.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('management', '0019_delete_sensorinfomanager'),
]
operations = [
migrations.AlterModelOptions(
name='parameter',
options={'verbose_name': '模拟量参数', 'verbose_name_plural': '模拟量参数'},
),
migrations.AlterModelOptions(
name='sensorinfo',
options={'verbose_name': '传感器', 'verbose_name_plural': '传感器'},
),
migrations.AddField(
model_name='myuser',
name='employee_id',
field=models.CharField(verbose_name='工号', max_length=15, blank=True),
),
migrations.AlterField(
model_name='parameter',
name='identifier',
field=models.CharField(verbose_name='参数符号', null=True, max_length=64),
),
migrations.AlterField(
model_name='parameter',
name='name',
field=models.CharField(verbose_name='参数名称', null=True, max_length=64),
),
migrations.AlterField(
model_name='parameter',
name='name_output',
field=models.CharField(verbose_name='输出符号', null=True, max_length=64),
),
migrations.AlterField(
model_name='parameter',
name='range_max',
field=models.CharField(verbose_name='量程最大值', null=True, max_length=16, blank=True),
),
migrations.AlterField(
model_name='parameter',
name='range_min',
field=models.CharField(verbose_name='量程最小值', null=True, max_length=16, blank=True),
),
migrations.AlterField(
model_name='parameter',
name='samplerate',
field=models.CharField(verbose_name='采样率', max_length=16, blank=True),
),
migrations.AlterField(
model_name='sensorinfo',
name='power',
field=models.CharField(verbose_name='功耗', max_length=16),
),
migrations.AlterField(
model_name='sensorinfo',
name='sensor_type',
field=models.CharField(verbose_name='传感器型号', max_length=32),
),
migrations.AlterField(
model_name='sensorinfo',
name='weight',
field=models.CharField(verbose_name='重量', max_length=16),
),
]
|
7d4b7a625bf4773f213a23d6264a854b13a3d9fe
|
[
"Markdown",
"Python"
] | 3 |
Python
|
comac-chen/ParameterManagement
|
3da950bedca2fb57dc7cf72e03a054965a1969c8
|
691080afbfc2177669cbd7ffeb0afc30cb905d87
|
refs/heads/master
|
<repo_name>darwright/building<file_sep>/app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
def index
@projects = Project.all
end
def show
@project = Project.find_by_id(params[:id])
end
def new
@project = Project.new
end
def create
@project = Project.new
@project.description = params[:description]
@project.responsible = params[:responsible]
@project.priority = params[:priority]
@project.status = params[:status]
@project.due_date = params[:due_date]
@project.reminder = params[:reminder]
if @project.save
redirect_to projects_url
else
render 'new'
end
end
def edit
@project = Project.find_by_id(params[:id])
end
def update
@project = Project.find_by_id(params[:id])
@project.description = params[:description]
@project.responsible = params[:responsible]
@project.priority = params[:priority]
@project.status = params[:status]
@project.due_date = params[:due_date]
@project.reminder = params[:reminder]
if @project.save
redirect_to projects_url
else
render 'edit'
end
end
def destroy
@project = Project.find_by_id(params[:id])
@project.destroy
redirect_to projects_url
end
end
<file_sep>/db/migrate/20130513211933_fix_type_column.rb
class FixTypeColumn < ActiveRecord::Migration
def change
rename_column :contractors, :type, :job
end
end
<file_sep>/app/controllers/contractors_controller.rb
class ContractorsController < ApplicationController
def index
@contractors = Contractor.all
end
def show
@contractor = Contractor.find_by_id(params[:id])
end
def new
@contractor = Contractor.new
end
def create
@contractor = Contractor.new
@contractor.business = params[:business]
@contractor.name = params[:name]
@contractor.type = params[:type]
@contractor.email = params[:email]
@contractor.phone = params[:phone]
@contractor.address = params[:address]
if @contractor.save
redirect_to contractors_url
else
render 'new'
end
end
def edit
@contractor = Contractor.find_by_id(params[:id])
end
def update
@contractor = Contractor.find_by_id(params[:id])
@contractor.business = params[:business]
@contractor.name = params[:name]
@contractor.type = params[:type]
@contractor.email = params[:email]
@contractor.phone = params[:phone]
@contractor.address = params[:address]
if @contractor.save
redirect_to contractors_url
else
render 'edit'
end
end
def destroy
@contractor = Contractor.find_by_id(params[:id])
@contractor.destroy
redirect_to contractors_url
end
end
|
5041fb9681813b0bbd7caa14c9ade9b89f60e8f8
|
[
"Ruby"
] | 3 |
Ruby
|
darwright/building
|
be7534948138e924944225378c794641fe3017eb
|
54f63a19651b36c878b6a81abf1e8dfdd126d73b
|
refs/heads/master
|
<file_sep>//choose a computer random number between 19 and 120
//assign random number to html
//choose 4 random numbers for 4 jewels between 1 and 12
//assign these to 4 crystals
//create variables -- wins, losses and total score
//assign variables to html
//on clicking crystals -- random numbers adding into totalscore
//if totalscore is equal to computer random number
//show youwin image
//wins increase by one
//reset game by pressing space
//winsound play
//if total score > computer random number
//loses increase by one
//lose sound play
//show you lose image
//reset game by pressing space
//reset game
//wins = 0
//loses = 0
//userTotal = 0
//win image display none
//lose image display none
$(function(){
// Computer chooses random number betwen 19 and 120
var randomNumber = Math.floor(Math.random()*(120-19)+19);
//Four random numbers between 1 and 12 for four crystals
var num1 = Math.floor(Math.random()*(12-1)+1);
var num2 = Math.floor(Math.random()*(12-1)+1);
var num3 = Math.floor(Math.random()*(12-1)+1);
var num4 = Math.floor(Math.random()*(12-1)+1);
//Defining variables for scores
var userTotal = 0;
var wins = 0;
var loses = 0;
//Defining game sounds
var clickSound = new Audio("./assets/sounds/keyboard_tap.mp3");
var wonSound = new Audio("./assets/sounds/you-win.wav");
var lostSound = new Audio("./assets/sounds/you-lose.wav");
$(".totalScore").text("Press SPACE to start the Game!");
// Adding functions
function resetGame() {
randomNumber = Math.floor(Math.random()*(120-19)+19);
$(".randNum").text("Random Number: " + randomNumber);
num1 = Math.floor(Math.random()*(12-1)+1);
num2 = Math.floor(Math.random()*(12-1)+1);
num3 = Math.floor(Math.random()*(12-1)+1);
num4 = Math.floor(Math.random()*(12-1)+1);
userTotal = 0;
$(".wins").text("Wins: 0");
$(".loses").text("Loses: 0");
$(".totalScore").text(userTotal);
};
function won() {
wonSound.play();
wins++;
alert("You Win");
$(".wins").text("Wins: " + wins);
resetGame();
};
function lost() {
lostSound.play();
loses++;
alert("You Lost");
$(".loses").text("Loses: " + loses);
resetGame();
};
function check() {
if (userTotal == randomNumber) {
won();
} else if (userTotal > randomNumber) {
lost();
}
};
// Adding click events for each crystal
$(".num1").on("click", function() {
clickSound.play();
userTotal += num1;
$(".totalScore").text(userTotal);
check();
});
$(".num2").on("click", function() {
clickSound.play();
userTotal += num2;
$(".totalScore").text(userTotal);
check();
})
$(".num3").on("click", function() {
clickSound.play();
$(".totalScore").text(userTotal);
check();
userTotal += num3;
})
$(".num4").on("click", function() {
clickSound.play();
$(".totalScore").text(userTotal);
check();
userTotal += num4;
})
//Press space to reset the game
$(window).keypress(function (x) {
if (x.keyCode == 0 || x.keyCode == 32) {
x.preventDefault();
resetGame();
}
})
});
|
559511f00189395e39dadbc04e4899a5142f1c4d
|
[
"JavaScript"
] | 1 |
JavaScript
|
docvvk/unit-4-game
|
103769bc8be66bbd1c6087b9cb6b422200329e57
|
9debbd08ee47de4beeb3a8cf85fee0dc036d89d6
|
refs/heads/master
|
<repo_name>Igorkh106/blogpage<file_sep>/src/js/partials/functions.js
function addEditForm(text){
var formLayout = "<div class='col-md-10'>";
formLayout += "<form>";
formLayout += "<textarea name='comment-message' id='comment-message' placeholder='Your message' rows='3'>" + text + "</textarea>";
formLayout += "<input type='submit' class='btn btn-lg btn-submit pull-right' name='leave-comment' value='Send'/>";
formLayout += "</form></div>";
return formLayout;
}
function addReplyForm(person){
var formLayout = "<div class='col-md-10 comment-reply'>";
formLayout += "<div class='comment-meta'>";
formLayout += "<span class='comment-option comment-option-edit pull-left'><i class='fa fa-mail-forward' aria-hidden='true'></i>" + person + "</span>";
formLayout += "<button class='comment-option comment-option-close pull-right'><i class='fa fa-close' aria-hidden='true'></i> Close</span>";
formLayout += "</div>";
formLayout += "<form>";
formLayout += "<textarea name='comment-message' id='comment-message' placeholder='Your message' rows='3'></textarea>";
formLayout += "<input type='submit' class='btn btn-lg btn-submit pull-right' name='leave-comment' value='Send'/>";
formLayout += "</form></div>";
return formLayout;
}
<file_sep>/src/js/main.js
/*
Third party
*/
//= ../../bower_components/jquery/dist/jquery.min.js
/*
Custom
*/
//= partials/functions.js
$(document).ready(function(){
"use strict";
//show options on hover
$(".comment").hover(function(){
$(this).find(".comment-options").slideToggle();
});
//delete comment
$(".comment-option-delete").click(function(){
var parentComment = $(this).closest(".comment");
parentComment.hide();
});
//open edit form for a comment
$(".comment-option-edit").click(function(){
var parentComment = $(this).closest(".comment");
var commentText = parentComment.find("p").text();
var editForm = addEditForm(commentText);
!parentComment.find("form").length ? parentComment.append(editForm) : false;
});
//open reply form for a comment
$(".comment-option-reply").click(function(){
var parentComment = $(this).closest(".comment");
var replyTo = parentComment.find(".comment-author-name").text();
var replyForm = addReplyForm(replyTo);
!parentComment.find("form").length ? parentComment.append(replyForm) : false;
});
});<file_sep>/README.md
# Test Blog Page
Compiled project is in the /build directory.
Seems like the Stag font is paid and I didn't found it with the task, so replaced with Helvetica.
Also font-awesome is used for the icons.
The main coding part is not ready for now, only a few interface features like show form on reply or edit your comment and delete it.
Hope this is enough :)
|
103be2dd149349dbd6553507ef301619d38fd0f7
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
Igorkh106/blogpage
|
b33a18ec14c071d9c0e6caf2916d8a914d46deb5
|
d6e0bc1f05335449883db3cd973c63ac9368b34d
|
refs/heads/master
|
<repo_name>ramyapabbu/localstorage<file_sep>/local.js
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);
var butt = document.querySelector("button");
var table = document.getElementById("myTable");
document.getElementById('datePicker').valueAsDate = new Date();
var data = JSON.parse(localStorage.getItem('data') || '[]');
readJsonFile(data, function(data)
{
console.log(JSON.stringify(data));
arr = data;
for(i=0; i<arr.length; i++) {
var row = table.insertRow(i+1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = arr[i].fName;
cell2.innerHTML = arr[i].lName;
cell3.innerHTML = arr[i].tInput;
};
});
butt.addEventListener("click", function(){
var fName = document.getElementById("title").value;
var lName = document.getElementById("datePicker").value;
var tInput = document.getElementById("textField").value;
arr.push({fName, lName, tInput})
document.getElementById("title").value = "";
document.getElementById("datePicker").value="";
document.getElementById("textField").value="";
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = fName;
cell2.innerHTML = lName;
cell3.innerHTML = tInput;
localStorage.setItem('data', JSON.stringify(arr));
});
function readJsonFile(jsonData, callback)
{
callback(jsonData);
}
|
2b7140eda11c67f6fbb6af033e26aef8eced4976
|
[
"JavaScript"
] | 1 |
JavaScript
|
ramyapabbu/localstorage
|
4e3751b5511aa7cb26981cfc19086b5ed23343d4
|
bd7cd0eba93086c50575906b655b68f8a5f01d2e
|
refs/heads/master
|
<repo_name>Surinder07/spring-first<file_sep>/src/main/java/io/pragra/learning/springfirst/domain/Car.java
package io.pragra.learning.springfirst.domain;
// Tight coupling
public class Car {
private String make;
private IEngine engine;
public Car(String make, IEngine engine) {
this.make = make;
this.engine = engine;
}
@Override
public String toString() {
return "Car{" +
"make='" + make + '\'' +
", engine=" + engine +
'}';
}
}
|
aca1325d6d0b4bf5404832fe8f06b46954f7ba4e
|
[
"Java"
] | 1 |
Java
|
Surinder07/spring-first
|
e67fc47182fd399c9ce55ebfb92526c59577dd7f
|
83e5c4aa3574f357c6c6c7371fef81372621f383
|
refs/heads/master
|
<repo_name>sretundijr/portfolio<file_sep>/README.md
Live site here, currently under construction
[Portfolio](https://happy-brown-896133.netlify.com/)
This is my portfolio page built using Gatsby js. More info coming soon.
<file_sep>/src/__tests__/header.js
/* global describe it */
import React from 'react';
import { shallow } from 'enzyme';
import Header from '../components/header';
describe('testing Index page component', () => {
it('should render without crashing', () => {
shallow(<Header />);
});
});
<file_sep>/src/layouts/index.js
import React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
// css
import './index.css';
import './child-container.css';
// components
import Footer from '../components/footer';
import Header from '../components/header';
const TemplateWrapper = ({ children }) => (
<div>
<Helmet
title="<NAME> Jr."
meta={[
{ name: 'description', content: 'Sample' },
{ name: 'keywords', content: 'sample, something' },
]}
/>
<div>
<Header />
</div>
<div className="child-container">
{children()}
</div>
<div>
<Footer />
</div>
</div>
);
TemplateWrapper.propTypes = {
children: PropTypes.func,
};
export default TemplateWrapper;
<file_sep>/src/__tests__/index-page.js
/* global describe it */
import React from 'react';
import { shallow } from 'enzyme';
import IndexPage from '../pages/index';
describe('testing Index page component', () => {
it('should render without crashing', () => {
shallow(<IndexPage />);
});
});
<file_sep>/src/components/nav-bar.js
import React from 'react';
import { navigateTo } from 'gatsby-link';
// css
import './nav-bar.css';
const NavBar = () => (
<div className="nav-btn-container">
<button onClick={() => navigateTo('/about-me')} className="nav-btn">About</button>
<button onClick={() => navigateTo('/Projects')} className="nav-btn">Projects</button>
</div>
);
export default NavBar;
<file_sep>/src/components/tech-list.js
import React from 'react';
import TechLogo from './tech-logo';
import './tech-logo.css';
const TechList = (props) => {
const listOfTech = props.list.map((item) => {
if (item.image) {
return (<TechLogo key={item.type} src={item.image} alt={item.type} />);
}
});
return (
<div className="tech-logo-container">
{listOfTech}
</div>
);
};
export default TechList;
<file_sep>/src/components/tech-logo.js
import React from 'react';
// css
import './tech-logo.css';
const TechLogo = (props) => {
return (
<div>
<img className="tech-logo" src={props.src} alt={`${props.alt} logo`} />
</div>
);
};
export default TechLogo;
<file_sep>/src/pages/index.js
import React from 'react';
import aboutMe from '../personal-info';
// css
import './index.css';
import './placeHolder.css';
const IndexPage = () => (
<div>
<div className="index-container">
<p className="index-content">{aboutMe().about}</p>
<div className="first-image large-square" />
</div>
<div className="second-image xLarge-square" />
</div>
);
export default IndexPage;
<file_sep>/src/components/footer.js
import React from 'react';
import aboutMe from '../personal-info';
// css
import './footer.css';
const Footer = () => (
<div className="footer-container">
<p className="contact-me">
Contact Me @
</p>
<p className="contact-me">
<a className="email-tag" href={`mailto:${aboutMe().contactInfo.email}`}>{aboutMe().contactInfo.email}</a>
</p>
</div >
);
export default Footer;
<file_sep>/src/__tests__/projects-page.js
/* global describe it */
import React from 'react';
import { shallow } from 'enzyme';
import Projects from '../pages/projects';
describe('testing Index page component', () => {
it('should render without crashing', () => {
shallow(<Projects />);
});
});
<file_sep>/src/pages/projects.js
import React from 'react';
import Card from '../components/card';
import aboutMe from '../personal-info';
import './projects.css';
const Projects = () => {
const listOfCards = aboutMe().projects.map(item => <Card key={item.title} project={item} />);
return (
<div className="projects">
{listOfCards}
</div>
);
};
export default Projects;
|
bc4796d04b2face5c0144e3e78a60c8e3feab413
|
[
"Markdown",
"JavaScript"
] | 11 |
Markdown
|
sretundijr/portfolio
|
500ba8b9cb585cf5c844210a6effc1874663cd3f
|
474ba6b7db67c3e80b0af0c57fd68e173fc85e6d
|
refs/heads/master
|
<file_sep>package ru.agolovin.settings;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class Settings {
/**
* Properties.
*/
private Properties properties = new Properties();
/**
* load properties.
*
* @param inputStream InputStream
*/
public void load(InputStream inputStream) {
try {
this.properties.load(inputStream);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Get property value.
*
* @param key String
* @return property value
*/
public String getValue(String key) {
return this.properties.getProperty(key);
}
}
<file_sep>package ru.agolovin;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author agolovin (<EMAIL>)
* @version $
* @since 0.1
*/
public class Config {
/**
* Properties.
*/
private final Properties prop = new Properties();
/**
* Url database.
*/
private String url;
/**
* Create script.
*/
private String create;
/**
* Clear script.
*/
private String clear;
/**
* Insert script.
*/
private String insert;
/**
* Select script.
*/
private String select;
/**
* Constructor.
*
* @param file string filename
*/
public Config(String file) {
load(file);
}
/**
* get select script.
*
* @return String
*/
public String getSelect() {
return select;
}
/**
* Get url.
*
* @return string
*/
public String getUrl() {
return this.url;
}
/**
* Get create.
*
* @return string.
*/
public String getCreate() {
return this.create;
}
/**
* Get clear.
*
* @return String.
*/
public String getClear() {
return this.clear;
}
/**
* Get insert.
*
* @return String
*/
public String getInsert() {
return this.insert;
}
/**
* Load config from property file.
*
* @param file File
*/
private void load(String file) {
try (InputStream in = getClass().getClassLoader().getResourceAsStream(file)) {
prop.load(in);
this.url = prop.getProperty("url");
this.create = prop.getProperty("create");
this.clear = prop.getProperty("clear");
this.insert = prop.getProperty("insert");
this.select = prop.getProperty("select");
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>package ru.agolovin.start;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;
/**
* Test methods for ConsoleInput class.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class ConsoleInputTest {
/**
* Test method ask.
*/
@Test
public final void whenUserInputThenResultIs() {
String result = "testWord";
InputStream in = new ByteArrayInputStream(result.getBytes());
System.setIn(in);
ConsoleInput console = new ConsoleInput();
String answer = console.ask("sss");
assertThat(result, is(answer));
}
}<file_sep>package ru.agolovin;
/**
* Create Read Only array.
*/
public class ArrayReadOnly {
/**
* Original array.
*/
private final int[] readOnlyArray;
/**
* copy of original array.
*/
private final int[] tempReadOnlyArray;
/**
* Constructor.
*
* @param array integer array
*/
public ArrayReadOnly(int[] array) {
readOnlyArray = new int[array.length];
tempReadOnlyArray = new int[array.length];
System.arraycopy(array, 0, readOnlyArray, 0, array.length);
}
/**
* get method.
*
* @return original array
*/
public int[] getReadOnlyArray() {
System.arraycopy(readOnlyArray, 0, tempReadOnlyArray, 0, readOnlyArray.length);
return tempReadOnlyArray;
}
}
<file_sep># Курс обучения [job4j.ru](http://job4j.ru/)
### Цель курса
Получение работы программистом
### Срок выполнения
В 2017 году.
### Пройденные темы
1. Базовый синтаксис.
2. ООП.
3. Ввод-вывод
4. Collections lite
<file_sep>package ru.agolovin;
import java.math.BigInteger;
public class Factorial {
public BigInteger factorial(int t) {
BigInteger result = BigInteger.valueOf(1);
if (t < 0)
result = result.valueOf(0);
else if (t > 0)
for (int i = 1; i <= t; i++)
result = result.multiply(BigInteger.valueOf(i));
return result;
}
}<file_sep>package ru.agolovin.server;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
abstract class BaseAction {
/**
* String name.
*/
private String name;
/**
* @param sName String
*/
BaseAction(String sName) {
this.name = sName;
}
/**
* Key.
* @return key String
*/
abstract String key();
/**
* @return info about menu line
*/
String info() {
return String.format(" %s. %s", this.key(), this.name);
}
/**
* Action.
*/
abstract void execute();
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class SortArrayCollectionProTest {
/**
* Test methods works.
*/
@Test
public void whenFirstEndSecondThenResultIs() {
SortArrayCollectionPro sort = new SortArrayCollectionPro();
Integer[] arrOne = {1, 5, 6};
Integer[] arrTwo = {4, 2, 3};
Integer[] res = {1, 2, 3, 4, 5, 6};
Integer[] answer = sort.createNewArrayFromEntry(arrOne, arrTwo);
assertThat(answer, is(res));
}
}<file_sep>package ru.agolovin;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class User implements Comparable<User> {
/**
* User name.
*/
private String name;
/**
* User age.
*/
private int age;
/**
* Constructor.
*
* @param name String.
* @param age String.
*/
public User(String name, int age) {
this.name = name;
this.age = age;
}
/**
* Getter Name.
*
* @return name String.
*/
public String getName() {
return this.name;
}
/**
* Getter age.
*
* @return age int.
*/
public int getAge() {
return this.age;
}
/**
* Compare user by ascending age.
*
* @param user User
* @return 1 if older, -1 if younger, 0 - if same.
*/
@Override
public int compareTo(User user) {
return Integer.compare(this.age, user.age);
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import java.util.NoSuchElementException;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class EvenNumberTest {
/**
* 2.
*/
private final int two = 2;
/**
* 3.
*/
private final int three = 3;
/**
* 4.
*/
private final int four = 4;
/**
* Test array.
*/
private int[] array = {1, two, three, four};
/**
* Test class.
*/
private EvenNumber en = new EvenNumber(array);
/**
* Test get even number from array.
*/
@Test
public void whenNextReturnEvenNumberThenResultIs() {
en.hasNext();
assertThat(en.next(), is(two));
en.hasNext();
assertThat(en.next(), is(four));
}
/**
* Test work hasNext() method.
*/
@Test
public void whenTestHasNextThenResultIs() {
assertThat(en.hasNext(), is(true));
en.next();
en.hasNext();
en.next();
assertThat(en.hasNext(), is(false));
}
/**
* Test out from array.
*/
@Test(expected = NoSuchElementException.class)
public void whenTestExceptionThenResultIs() {
for (int i = 0; i < three; i++) {
en.hasNext();
en.next();
}
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class UserTest {
/**
* Test when user1 equals user2.
*/
@Test
public void whenUserIsSameThenResultTrue() {
User user1 = new User("Name1", 0);
User user2 = new User("Name1", 0);
boolean result = user1.equals(user2);
assertThat(result, is(true));
}
/**
* Test when user1 not equals user2.
*/
@Test
public void whenUserNotTheSameThenResultFalse() {
User user1 = new User("Name1", 0);
User user2 = new User("Name2", 1);
boolean result = user1.equals(user2);
assertThat(result, is(false));
}
}<file_sep><project>
<parent>
<artifactId>chapter_001</artifactId>
<groupId>ru.agolovin</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>task132</artifactId>
</project><file_sep>jdbc.driver=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost:5432/tracker
jdbc.username=postgres
jdbc.password=<PASSWORD>
create = CREATE TABLE IF NOT EXISTS parser (id serial primary key, description text, url text, date timestamp)
insert = INSERT INTO parser(description, url, date)<file_sep>package ru.agolovin.start;
import org.junit.Test;
import ru.agolovin.models.Filter;
import ru.agolovin.models.Item;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test methods for StartUI.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class StartUITest {
/**
* Test for paragraph 1 in menu StartUI.
*/
@Test
public final void whenUserSet1inMenuThenResultIs() {
final long timeCreate = 15;
Tracker tracker = new Tracker();
String[] answer = {"1", "ss", "d", "15", "6"};
StartUI stUI = new StartUI(new StubInput(answer));
stUI.init(tracker);
Item item = new Item("ss", "d", timeCreate);
Item[] res = stUI.getTracker().getByFilter(new Filter("ss"));
assertThat(res[0].getName(), is(item.getName()));
}
/**
* Test for paragraph 2 in menu StartUI.
*/
@Test
public final void whenUserSet2inMenuThenResultIs() {
final long timecreate1 = 9;
final long timecreate2 = 8;
Tracker tracker = new Tracker();
Item item1 = new Item("ss", "desc", timecreate1);
Item item2 = new Item("ss2", "dd2", timecreate2);
tracker.add(item1);
tracker.add(item2);
String idItem = tracker.findById(item2.getId()).getId();
String[] answer = {"2", idItem, "6"};
StartUI stUI = new StartUI(new StubInput(answer));
stUI.init(tracker);
Item item = new Item("ss", "desc", timecreate1);
Item[] res = stUI.getTracker().getByFilter(new Filter("ss"));
assertThat(res[0].getName(), is(item.getName()));
}
/**
* Test for paragraph 2 in menu StartUI.
*/
@Test
public final void whenUserSet3inMenuThenResultIs() {
Tracker tracker = new Tracker();
Item item = new Item("testName", "testDescription", 1);
Item updateItem = new Item("updateName", "updateDescription", 2);
Item[] result = new Item[1];
tracker.add(item);
updateItem.setId(tracker.findById(item.getId()).getId());
String idItem = updateItem.getId();
result[0] = updateItem;
String[] answer = {
"3", idItem, "updateName", "updateDescription", "2", "6"};
StartUI stUI = new StartUI(new StubInput(answer));
stUI.init(tracker);
Item[] res =
stUI.getTracker().getByFilter(new Filter("updateDescription"));
assertThat(res[0].getName(), is(updateItem.getName()));
}
/**
* Test for paragraph 4 in menu StartUI.
*/
@Test
public final void whenUserSet4inMenuThenResultIs() {
Tracker tracker = new Tracker();
Item itemOne = new Item("testName", "testDescription", 1);
Item itemTwo = new Item("updateName", "updateDescription", 2);
tracker.add(itemOne);
tracker.add(itemTwo);
String[] answer = {"4", "testName", "6"};
StartUI stUI = new StartUI(new StubInput(answer));
stUI.init(tracker);
Item[] res = stUI.getTracker().getByFilter(new Filter("testName"));
assertThat(res[0].getName(), is(itemOne.getName()));
}
/**
* Test for paragraph 5 in menu StartUI.
*/
@Test
public final void whenUserSet5inMenuThenResultIs() {
Tracker tracker = new Tracker();
Item itemOne = new Item("testName", "testDescription", 1);
Item itemTwo = new Item("updateName", "updateDescription", 2);
tracker.add(itemOne);
tracker.add(itemTwo);
String[] answer = {"5", "6"};
StartUI stUI = new StartUI(new StubInput(answer));
stUI.init(tracker);
Item[] res = stUI.getTracker().getAll();
assertThat(res.length, is(tracker.getAll().length));
}
}
<file_sep>CREATE.SQL
CREATE TABLE roles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(50) NOT NULL UNIQUE
);
CREATE TABLE rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(50) NOT NULL UNIQUE
);
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
login VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(50),
role_id INTEGER REFERENCES roles (id) NOT NULL
);
CREATE TABLE state (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(50) NOT NULL UNIQUE
);
CREATE TABLE categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(50) NOT NULL UNIQUE
);
CREATE TABLE item (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(50) NOT NULL,
description TEXT NOT NULL,
user_id INTEGER REFERENCES users (id) NOT NULL,
category_id INTEGER REFERENCES categories (id) NOT NULL,
state_id INTEGER REFERENCES state (id) NOT NULL
);
CREATE TABLE attaches (
id INTEGER PRIMARY KEY AUTOINCREMENT,
description TEXT NOT NULL,
item_id INTEGER REFERENCES item (id) NOT NULL
);
CREATE TABLE comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
description TEXT NOT NULL,
item_id INTEGER REFERENCES item (id) NOT NULL
);
INSERT INTO roles (name) VALUES ('root'), ('user'), ('guest');
INSERT INTO rules (name) VALUES ('create'), ('read'), ('update'), ('delete');
INSERT INTO users (login, password, role_id) VALUES
('root', 'root', (SELECT id
FROM roles
WHERE name = 'root')),
('user', 'user', (SELECT id
FROM roles
WHERE name = 'user')),
('guest', 'guest', (SELECT id
FROM roles
WHERE name = 'guest'));
INSERT INTO state (name) VALUES ('new'), ('in work'), ('close');
INSERT INTO categories (name) VALUES ('S1'), ('S2'), ('S3');
INSERT INTO item (name, description, user_id, category_id, state_id) VALUES
(
'item_1',
'desc One',
(SELECT id
FROM users
WHERE login = 'user'),
(SELECT id
FROM categories
WHERE name = 'S1'),
(SELECT id
FROM state
WHERE name = 'new')
),
(
'item_2',
'desc Two',
(SELECT id
FROM users
WHERE login = 'user'),
(SELECT id
FROM categories
WHERE name = 'S2'),
(SELECT id
FROM state
WHERE name = 'close')
);
INSERT INTO comments (description, item_id) VALUES
(
'Comment short',
(SELECT id
FROM item
WHERE name = 'item_1')
),
(
'Comment',
(SELECT id
FROM item
WHERE name = 'item_2')
);
INSERT INTO attaches (description, item_id) VALUES (
'attach', (SELECT id
FROM item
WHERE name = 'item_2')
)<file_sep>package ru.agolovin;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class ConvertXSQTTest {
private final File file = new File("test.xml");
private final File dest = new File("destTest.xml");
@Test
public void methodTest() {
File scheme = new File(getClass()
.getClassLoader().getResource("scheme.xsl").getFile());
List<StoreXML.Entry> methodData = new ArrayList<>();
for (int i = 0; i < 2; i++) {
methodData.add(new StoreXML.Entry(i));
}
StoreXML storeXML = new StoreXML(file);
storeXML.save(methodData);
ConvertXSQT convertXSQT = new ConvertXSQT();
convertXSQT.convert(this.file, this.dest, scheme);
StringBuilder result = new StringBuilder();
try (Scanner scan = new Scanner(this.dest)) {
while (scan.hasNext()) {
result.append(scan.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String expect = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entries>"
+ " <entry field=\"0\"/>"
+ " <entry field=\"1\"/>"
+ "</entries>";
assertThat(result.toString(), is(expect));
}
@After
public void clean() {
this.dest.delete();
this.file.delete();
}
}<file_sep>package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class FindSubStringInStringTest {
@Test
public void whenStringContainsSubStringThanResultIs() {
FindSubStringInString fnd = new FindSubStringInString();
String orig = "abcabca";
String sub = "bcab";
boolean result = fnd.contains(orig, sub);
assertThat(result, is(true));
}
@Test
public void whenStringNotContainsSubStringThanResultIs() {
FindSubStringInString fnd = new FindSubStringInString();
String orig = "abcabca";
String sub = "lk";
boolean result = fnd.contains(orig, sub);
assertThat(result, is(false));
}
}
<file_sep>package ru.agolovin;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
import java.util.List;
import java.util.Objects;
/**
* @author agolovin (<EMAIL>)
* @version $
* @since 0.1
*/
public class StoreXML {
/**
* File.
*/
private final File file;
/**
* Constructor.
*
* @param file File
*/
public StoreXML(File file) {
this.file = file;
}
/**
* Save to XML.
*
* @param list List
*/
void save(List<Entry> list) {
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(Entries.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(new Entries(list), this.file);
} catch (JAXBException e) {
e.printStackTrace();
}
}
@XmlRootElement
public static class Entry {
private int field;
public Entry() {
}
public Entry(int field) {
this.field = field;
}
public int getField() {
return this.field;
}
public void setField(int field) {
this.field = field;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Entry entry = (Entry) o;
return field == entry.field;
}
@Override
public int hashCode() {
return Objects.hash(field);
}
}
@XmlRootElement
public static class Entries {
private List<Entry> entry;
public Entries() {
}
public Entries(List<Entry> entry) {
this.entry = entry;
}
public List<Entry> getEntry() {
return entry;
}
public void setEntry(List<Entry> entry) {
this.entry = entry;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Entries entries = (Entries) o;
return Objects.equals(entry, entries.entry);
}
@Override
public int hashCode() {
return Objects.hash(entry);
}
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class TaskStringTest {
String sOne = "2222222222";
String sTwo = "3333333333";
@Test
public void testTaskStringThreadOneRepeat() {
TaskString task = new TaskString();
task.start();
String expect = task.getString();
String result = sOne + sTwo;
assertThat(expect, is(result));
}
@Test
public void testTaskStringThreadFourRepeat() {
int repeat = 4;
int rep = repeat - 1;
TaskString task = new TaskString();
task.setRepeatString(repeat);
task.start();
String expect = task.getString();
StringBuilder result = new StringBuilder(sOne + sTwo);
for (int i = 0; i < rep; i++) {
result.append(sOne).append(sTwo);
}
assertThat(expect, is(result.toString()));
}
}<file_sep>package ru.agolovin.models;
import org.junit.Test;
/**
* unHandle exception for menu class.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class FigureNotFoundExceptionTest {
/**
* Test FigureNotFoundException.
*/
@Test (expected = RuntimeException.class)
public final void whenSomethingThen() {
throw new FigureNotFoundException("test");
}
}
<file_sep>package ru.agolovin;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class Time implements Runnable {
/**
* Thread.
*/
private Thread threadIn;
/**
* Constructor.
*
* @param threadIn Thread
*/
Time(Thread threadIn) {
this.threadIn = threadIn;
}
/**
* Main method.
*
* @param args String[]
*/
public static void main(String[] args) {
String str = "Incoming string";
CountChar countChar = new CountChar(str);
Thread threadChar = new Thread(countChar);
Time time = new Time(threadChar);
Thread timeThread = new Thread(time);
timeThread.start();
}
@Override
public void run() {
long startTime = System.currentTimeMillis();
threadIn.start();
try {
threadIn.join(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (threadIn.isAlive()) {
if (threadIn.isAlive() && ((startTime - System.currentTimeMillis()) > 1000)) {
threadIn.interrupt();
}
}
}
}
<file_sep>package ru.agolovin;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class ThreadPool {
/**
* Lock object for threads.
*/
private final Object lock = new Object();
/**
* Queue for threads work.
*/
private final Queue<Work> queue = new LinkedBlockingQueue<>();
/**
* Monitor.
*/
private boolean flag = false;
/**
* main method.
*
* @param args String[]
*/
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool();
threadPool.init(30);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadPool.stopWork();
}
/**
* Init all threads.
*
* @param amount int
*/
private void init(int amount) {
int coreNumber = Runtime.getRuntime().availableProcessors();
System.out.println(String.format("Available processors %s", coreNumber));
Thread[] threads = new Thread[coreNumber];
for (int i = 0; i < coreNumber; i++) {
threads[i] = this.createThread();
threads[i].start();
}
for (int i = 0; i < amount; i++) {
this.addWork(new Work(i));
}
}
/**
* Create thread.
*
* @return thread
*/
private Thread createThread() {
return new Thread(() -> {
Work work;
while (!this.flag) {
synchronized (this.lock) {
while (this.queue.isEmpty() && !this.flag) {
try {
this.lock.wait(300);
System.out.println(String.format("Thread %s don`t work", Thread.currentThread().getId()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
work = this.queue.poll();
if (work != null) {
work.run();
}
}
});
}
/**
* Add Work to Queue.
*
* @param work Work
*/
private void addWork(Work work) {
this.queue.add(work);
synchronized (this.lock) {
this.lock.notifyAll();
}
}
/**
* Stop program evolution.
*/
private void stopWork() {
synchronized (this.lock) {
this.lock.notifyAll();
}
this.flag = true;
}
/**
* Some task.
*/
private class Work implements Runnable {
/**
* Part number.
*/
private int number;
/**
* Constructor.
*
* @param number int
*/
Work(int number) {
this.number = number;
}
/**
* Information about current work.
*/
@Override
public void run() {
System.out.println(String.format("Thread %s counting Task %s", Thread.currentThread().getId(), this.number));
}
}
}
<file_sep>package ru.agolovin;
public class Square {
public float a;
public float b;
public float c;
public void setParameters(float a, float b, float c) {
this.a = a;
this.b = b;
this.c = c;
}
public float calculate(int x) {
float result =a * x * x + b * x + c;
return result;
}
public void show(int st, int fin, int stp) {
for (int i = st; i <= fin; i += stp) {
System.out.println(calculate(i));
}
}
}<file_sep>package ru.agolovin;
import org.junit.Test;
import java.util.NoSuchElementException;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class CustomStackTest {
/**
* Test normal work.
*/
@Test
public void whenAddLastThenLastOut() {
CustomStack cs = new CustomStack();
cs.push(1);
cs.push(2);
cs.push(3);
assertThat(cs.poll(), is(3));
assertThat(cs.poll(), is(2));
assertThat(cs.poll(), is(1));
}
/**
* Test throw Exception.
*/
@Test(expected = NoSuchElementException.class)
public void whenNoElementAndPollThenThrowException() {
CustomStack cs = new CustomStack();
cs.poll();
}
}<file_sep>package ru.agolovin;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
class Counter {
/**
* Expected result.
*/
private static final int LIMIT = 100_000_000;
/**
* Count.
*/
private static int anInt = 0;
/**
* Count hits.
*/
private AtomicInteger lim = new AtomicInteger();
/**
* Main method.
*
* @param args String[]
*/
public static void main(String[] args) {
Counter problem = new Counter();
Thread thread = new Thread(() -> {
while (!problem.stop()) {
anInt++;
}
});
Thread thread2 = new Thread(() -> {
while (!problem.stop()) {
anInt++;
}
});
thread.start();
thread2.start();
try {
thread.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("Expected %s", LIMIT));
System.out.println(String.format("Result %s", anInt));
}
/**
* Stop.
*
* @return boolean result
*/
private boolean stop() {
return lim.incrementAndGet() > LIMIT;
}
}
<file_sep>package ru.agolovin;
import java.util.Arrays;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
class SortArrayCollectionPro {
/**
* main array.
*/
private Integer[] mainArray;
/**
* Create one sorted array from two sorted.
*
* @param arrOne Array
* @param arrTwo Array
* @return array
*/
Integer[] createNewArrayFromEntry(Integer[] arrOne, Integer[] arrTwo) {
mainArray = new Integer[arrOne.length + arrTwo.length];
Arrays.sort(arrTwo);
int mainLength = mainArray.length;
int i = 0;
int j = 0;
int n;
for (n = 0; n < mainLength; n++) {
if (arrOne[i] < arrTwo[j]) {
mainArray[n] = arrOne[i];
if (i < arrOne.length - 1) {
i++;
} else {
System.arraycopy(arrTwo, j, mainArray, n, arrTwo.length - 1);
break;
}
} else {
mainArray[n] = arrTwo[j];
if (j < arrTwo.length - 1) {
j++;
} else {
System.arraycopy(arrOne, i, mainArray, n + 1, arrOne.length - 1);
break;
}
}
}
return this.mainArray;
}
}
<file_sep>package ru.agolovin;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class StoreXMLTest {
private final File file = new File("StoreXMLTest.xml");
@Test
public void methodTest() {
List<StoreXML.Entry> methodData = new ArrayList<>();
for (int i = 0; i < 2; i++) {
methodData.add(new StoreXML.Entry(i));
}
StoreXML storeXML = new StoreXML(file);
storeXML.save(methodData);
StringBuilder result = new StringBuilder();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
result.append(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
StringBuilder correctAnswer = new StringBuilder();
correctAnswer
.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
.append("<entries>")
.append(" <entry>")
.append(" <field>0</field>")
.append(" </entry>")
.append(" <entry>")
.append(" <field>1</field>")
.append(" </entry>")
.append("</entries>");
assertThat(result.toString(), is(correctAnswer.toString()));
}
@After
public void delete() {
this.file.delete();
}
}
<file_sep>package ru.agolovin;
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
@ThreadSafe
class Count {
/**
* Expected result.
*/
private static final int LIMIT = 100_000_000;
/**
* Count.
*/
@GuardedBy("This")
private int anInt = 0;
/**
* Count hits.
*/
private AtomicInteger lim = new AtomicInteger();
/**
* Main method.
*
* @param args String[]
*/
public static void main(String[] args) {
Count count = new Count();
Thread thread = new Thread(() -> {
while (!count.stop()) {
count.increment();
}
});
Thread thread2 = new Thread(() -> {
while (!count.stop()) {
count.increment();
}
});
thread.start();
thread2.start();
try {
thread.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("Expected %s", LIMIT));
System.out.println(String.format("Result %s", count.anInt));
}
/**
* Stop.
*
* @return boolean result
*/
private boolean stop() {
return lim.incrementAndGet() > LIMIT;
}
/**
* Increment value.
*/
private void increment() {
synchronized (this) {
this.anInt++;
}
}
}
<file_sep>CREATE TABLE Transmission (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trans_name VARCHAR(50) NOT NULL
);
CREATE TABLE Engine (
id INTEGER PRIMARY KEY AUTOINCREMENT,
eng_name VARCHAR(50) NOT NULL
);
CREATE TABLE Gear_box (
id INTEGER PRIMARY KEY AUTOINCREMENT,
box_name VARCHAR(50) NOT NULL
);
CREATE TABLE Car (
id INTEGER PRIMARY KEY AUTOINCREMENT,
car_name VARCHAR(50) NOT NULL,
trans_id INTEGER REFERENCES Transmission (id),
engine_id INTEGER REFERENCES Engine (id),
gear_box_id INTEGER REFERENCES Gear_box (id)
);
INSERT INTO Transmission (trans_name) VALUES ('Race');
INSERT INTO Transmission (trans_name) VALUES ('Road');
INSERT INTO Transmission (trans_name) VALUES ('Off-road');
INSERT INTO Transmission (trans_name) VALUES ('Golf');
INSERT INTO Engine (eng_name) VALUES ('Gasoline');
INSERT INTO Engine (eng_name) VALUES ('Diesel');
INSERT INTO Engine (eng_name) VALUES ('Electric');
INSERT INTO Engine (eng_name) VALUES ('Sun');
INSERT INTO Gear_box (box_name) VALUES ('Automatic');
INSERT INTO Gear_box (box_name) VALUES ('Manual');
INSERT INTO Gear_box (box_name) VALUES ('Robot');
INSERT INTO Gear_box (box_name) VALUES ('Driver');
INSERT INTO Car (car_name, trans_id, engine_id, gear_box_id) VALUES ('Race Car', 1, 1, 2);
INSERT INTO Car (car_name, trans_id, engine_id, gear_box_id) VALUES ('Road Car', 2, 2, 1);
INSERT INTO Car (car_name, trans_id, engine_id, gear_box_id) VALUES ('Sport Car', 1, 1, 3);
SELECT
table_car.car_name,
trans_table.trans_name,
engine_table.eng_name,
box_table.box_name
FROM Car AS table_car
LEFT OUTER JOIN Transmission AS trans_table ON table_car.trans_id = trans_table.id
LEFT OUTER JOIN Engine AS engine_table ON table_car.engine_id = engine_table.id
LEFT OUTER JOIN Gear_box AS box_table ON table_car.gear_box_id = box_table.id;
SELECT
trans_name,
'Transmission' AS 'PART'
FROM Transmission
LEFT OUTER JOIN Car ON Transmission.id = Car.trans_id
WHERE Car.id ISNULL
UNION
SELECT
eng_name,
'Engine' AS 'PART'
FROM Engine
LEFT OUTER JOIN Car ON Engine.id = Car.trans_id
WHERE Car.id ISNULL
UNION
SELECT
box_name,
'Gear Box' AS 'PART'
FROM Gear_box
LEFT OUTER JOIN Car ON Gear_box.id = Car.gear_box_id
WHERE Car.id ISNULL;<file_sep>package ru.agolovin.models;
import java.util.Objects;
/**
* Base Item methods.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class Item {
/**
* variable class Item.
* <p>
* id String.
*/
private String id;
/**
* variable class Item.
* <p>
* name String.
*/
private String name;
/**
* variable class Item.
* <p>
* description String.
*/
private String description;
/**
* variable class Item.
* <p>
* timeCreate long.
*/
private long timeCreate;
/**
* base method Item.
*/
public Item() {
}
/**
* base method Item.
*
* @param sName name
* @param sDescription description
* @param sTimeCreate timeCreate
*/
public Item(
final String sName,
final String sDescription,
final long sTimeCreate) {
this.name = sName;
this.description = sDescription;
this.timeCreate = sTimeCreate;
}
/**
* @return name
*/
public final String getName() {
return this.name;
}
/**
* @param sName name
*/
final void setName(final String sName) {
this.name = sName;
}
/**
* @return description
*/
public final String getDescription() {
return this.description;
}
/**
* @param sDescription description
*/
final void setDescription(final String sDescription) {
this.description = sDescription;
}
/**
* @return timeCreate
*/
public final long getTimeCreate() {
return this.timeCreate;
}
/**
* @return id
*/
public final String getId() {
return this.id;
}
/**
* @param sId id
*/
public final void setId(final String sId) {
this.id = sId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Item item = (Item) o;
return timeCreate == item.timeCreate
&& Objects.equals(id, item.id)
&& Objects.equals(name, item.name)
&& Objects.equals(description, item.description);
}
@Override
public int hashCode() {
return Objects.hash(id, name, description, timeCreate);
}
}
<file_sep><project>
<parent>
<groupId>ru.agolovin</groupId>
<artifactId>Java-course</artifactId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>package_1</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<modules>
<module>chapter_002</module>
<module>chapter_005</module>
</modules>
</project><file_sep>package ru.agolovin;
import java.util.Objects;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class Order {
/**
* Order id.
*/
private int id;
/**
* order volume.
*/
private int volume;
/**
* order price.
*/
private float price;
/**
* order type.
*/
private String type;
/**
* Constructor.
*
* @param id int
* @param volume int
* @param price float
* @param type String
*/
Order(int id, int volume, float price, String type) {
this.id = id;
this.volume = volume;
this.price = price;
this.type = type;
}
/**
* Get order Id.
*
* @return int Id
*/
int getId() {
return id;
}
/**
* get order volume.
*
* @return int volume.
*/
int getVolume() {
return volume;
}
/**
* Set order volume.
*
* @param volume int.
*/
void setVolume(int volume) {
this.volume = volume;
}
/**
* get order price.
*
* @return float price.
*/
float getPrice() {
return price;
}
/**
* get order type,
*
* @return string type
*/
String getType() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return id == order.id &&
volume == order.volume &&
Float.compare(order.price, price) == 0 &&
Objects.equals(type, order.type);
}
@Override
public int hashCode() {
return Objects.hash(id, volume, price, type);
}
}
<file_sep>package ru.agolovin.server;
import com.google.common.base.Joiner;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Socket;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class ServerTest {
/**
* Line separator.
*/
private static final String LN = System.getProperty("line.separator");
/**
* Test single server ask.
*
* @throws Exception Exception
*/
@Test
public void whenSetExitServerThenServerStopWork() throws Exception {
String word = "exit";
String result = "";
testServer(word, result);
}
/**
* Test ask server twice.
*
* @throws Exception Exception
*/
@Test
public void whenAskHelloServerThenServerAnswerIt() throws Exception {
String word = Joiner.on(LN).join(
"hello", "exit");
String result = Joiner.on(LN).join("Hello, dear friend, I'm a oracle.", "", "");
testServer(word, result);
}
/**
* Test ask server multiple.
*
* @throws Exception Exception
*/
@Test
public void whenAskSomeWordsServerThenHisAnswer() throws Exception {
String word = Joiner.on(LN).join(
"hello", "Give me first answer", "second answer", "next answer please", "exit");
String result = Joiner.on(LN).join("Hello, dear friend, I'm a oracle.", "",
"simple question", "", "difficult", "question", "", "simple question", "", ""
);
testServer(word, result);
}
/**
* Base method.
*
* @param incoming String
* @param result String
* @throws IOException Exception
*/
private void testServer(String incoming, String result) throws IOException {
Socket socket = mock(Socket.class);
Server server = new Server(socket);
ByteArrayInputStream in = new ByteArrayInputStream(incoming.getBytes());
ByteArrayOutputStream out = new ByteArrayOutputStream();
when(socket.getInputStream()).thenReturn(in);
when(socket.getOutputStream()).thenReturn(out);
server.init();
assertThat(result, is(out.toString()));
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test methods for Check amount bracket.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class CheckTest {
/**
* Test for correct qun ().
*/
@Test
public final void whenCorrectThenResult() {
String test = "()()()()()";
Check ch = new Check();
boolean result = ch.validate(test);
assertThat(result, is(true));
}
/**
* Test for not correct qun ().
*/
@Test
public final void whenNotCorrectThenResult() {
String test = "((())()))";
Check ch = new Check();
boolean result = ch.validate(test);
assertThat(result, is(false));
}
}
<file_sep>package ru.agolovin;
public class BubbleSortMas {
public void bubbleSort(int[] t) {
for (int i = t.length - 1; i >= 0; i--)
for (int j = 0; j < i; j++)
if (t[j] > t[j + 1]) {
int tmp = t[j];
t[j] = t[j + 1];
t[j + 1] = tmp;
}
}
}<file_sep>url=jdbc:sqlite:xslt.db
create=CREATE TABLE IF NOT EXISTS entry(field INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT)
clear=DELETE FROM entry
insert=INSERT INTO entry VALUES (?)
select=SELECT * FROM entry<file_sep>package ru.agolovin;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class NodeCycle {
/**
* Check if node has cycle.
*
* @param first Node
* @return true if node has cycle
*/
boolean hasCycle(Node first) {
boolean result = false;
Node temp = first;
if (temp == null || temp.getNext() == null) {
result = false;
} else {
boolean flag = true;
do {
if (temp.getNext() != null) {
temp = temp.getNext();
if (first.equals(temp)) {
result = true;
flag = false;
}
} else {
flag = false;
}
} while (flag);
}
return result;
}
/**
* Node.
*
* @param <T> Generic
*/
static class Node<T> {
/**
* Node value.
*/
private T value;
/**
* Next node.
*/
private Node<T> next;
/**
* Constructor.
*
* @param value Generic
*/
Node(T value) {
this.value = value;
}
/**
* Get next node.
*
* @return Node
*/
public Node<T> getNext() {
return next;
}
/**
* Set node value.
*
* @param next Node.
*/
public void setNext(Node<T> next) {
this.next = next;
}
}
}
<file_sep><project>
<parent>
<groupId>ru.agolovin</groupId>
<artifactId>Java-course</artifactId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>package_2</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<modules>
<module>chapter_005_pro</module>
<module>multithreading</module>
<module>sql</module>
</modules>
</project><file_sep>package ru.agolovin;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test file sort class.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class FileSortTest {
/**
* Line separator.
*/
private String separator = System.getProperty("line.separator");
/**
* Test sorting method.
*
* @throws IOException Exception
*/
@Test
public void whenCheckExistFileThenResultTrue() throws IOException {
FileSort fileSort = new FileSort();
String income = "bb" + separator
+ "a" + separator + "ddd" + separator + "e";
File source = new File("test1.txt");
File distance = new File("distance.txt");
RandomAccessFile rafSource = new RandomAccessFile(source, "rw");
rafSource.seek(0);
fileSort.write(rafSource, income);
fileSort.sort(source, distance);
RandomAccessFile rafDistance = new RandomAccessFile(distance, "r");
assertThat(distance.exists(), is(true));
assertThat(rafDistance.readLine().equals("a"), is(true));
assertThat(rafDistance.readLine().equals("e"), is(true));
assertThat(rafDistance.readLine().equals("bb"), is(true));
assertThat(rafDistance.readLine().equals("ddd"), is(true));
rafDistance.close();
rafSource.close();
source.delete();
}
}<file_sep>package ru.agolovin;
import java.util.Calendar;
import java.util.Objects;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class User {
/**
* User name.
*/
private String name;
/**
* Qunat user child.
*/
private int children;
/**
* User birthday.
*/
private Calendar birthday;
/**
* Constructor.
*
* @param name String
* @param children int
* @param birthday Calendar
*/
public User(String name, int children, Calendar birthday) {
this.name = name;
this.children = children;
this.birthday = birthday;
}
/**
* Get user name.
*
* @return name String.
*/
public String getName() {
return name;
}
/**
* Get user childs.
*
* @return child int
*/
public int getChildren() {
return children;
}
/**
* Get user birthday.
*
* @return birthday Calendar
*/
public Calendar getBirthday() {
return birthday;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + children;
result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return children == user.children
&& Objects.equals(name, user.name)
&& Objects.equals(birthday, user.birthday);
}
}
<file_sep>package ru.agolovin;
import java.util.concurrent.Semaphore;
/**
* @author agolovin (<EMAIL>)
* @version $
* @since 0.1
*/
public class TaskString {
private final int LIMIT = 10;
private StringBuffer buffer = new StringBuffer();
private Semaphore semaphore = new Semaphore(1);
private int repeat = 1;
public void setRepeatString(int number) {
this.repeat = number;
}
public String getString() {
return this.buffer.toString();
}
public void start() {
Thread threadOne = new Thread(new StringThread(2));
Thread threadTwo = new Thread(new StringThread(3));
threadOne.start();
threadTwo.start();
try {
threadTwo.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class StringThread implements Runnable {
private int anInt;
public StringThread(int number) {
this.anInt = number;
}
@Override
public void run() {
int repeatAmount = LIMIT * repeat;
try {
semaphore.acquire();
for (int i = 1; i <= repeatAmount; i++) {
buffer.append(anInt);
if ((i % LIMIT) == 0) {
semaphore.release();
Thread.yield();
semaphore.acquire();
}
}
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
<file_sep>package ru.agolovin.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class Server {
/**
* Private socket server.
*/
private Socket socket;
/**
* Arrays of the bot answers.
*/
private String[] botAnswers = {"simple question", "", "difficult", "question", ""};
/**
* Default index.
*/
private int index = 0;
/**
* Constructor.
* @param socket Socket
*/
Server(Socket socket) {
this.socket = socket;
}
/**
* main method.
*
* @param args String
*/
public static void main(String[] args) {
final int port = 23451;
try (Socket socket = new ServerSocket(port).accept()) {
new Server(socket).init();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Initialization.
*/
void init() {
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String ask;
do {
System.out.println("wait command ...");
ask = in.readLine();
System.out.println(ask);
if ("hello".equals(ask)) {
out.println("Hello, dear friend, I'm a oracle.");
out.println();
} else {
if (!"exit".equals(ask)) {
String[] answers = takeAnswer();
for (String element : answers) {
out.println(element);
}
}
if (this.index == this.botAnswers.length) {
this.index = 0;
}
}
} while (!("exit".equals(ask)));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Local answers.
*
* @return Array of the answers.
*/
private String[] takeAnswer() {
int stopIndex = this.index;
for (int i = index; i < this.botAnswers.length; i++) {
if (!this.botAnswers[i].isEmpty()) {
stopIndex++;
} else {
stopIndex++;
break;
}
}
String[] answer = new String[stopIndex - this.index];
for (int i = 0; i < answer.length; i++) {
answer[i] = this.botAnswers[this.index++];
}
return answer;
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import java.util.Iterator;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class CustomArrayListTest {
/**
* Test iterator for CustomArrayList.
*/
@Test
public void whenTestIterator() {
CustomArrayList<Integer> customArrayList = new CustomArrayList<>(2);
customArrayList.add(1);
customArrayList.add(2);
Integer[] answer = new Integer[2];
answer[0] = customArrayList.get(0);
answer[1] = customArrayList.get(1);
Integer[] res = new Integer[2];
int pos = 0;
Iterator<Integer> element = customArrayList.iterator();
while (element.hasNext()) {
res[pos++] = element.next();
}
assertThat(res, is(answer));
}
/**
* Test add and get method from CustomArrayList.
*/
@Test
public void whenAddTwoThenGetTwoByIndex() {
CustomArrayList<Integer> customArrayList = new CustomArrayList<>();
customArrayList.add(1);
customArrayList.add(2);
assertThat(customArrayList.get(0), is(1));
assertThat(customArrayList.get(1), is(2));
}
/**
* Test dynamically rise.
*/
@Test
public void whenRiseArraySizeThenResultIs() {
CustomArrayList<Integer> customArrayList = new CustomArrayList<>(1);
customArrayList.add(1);
customArrayList.add(2);
assertThat(customArrayList.get(0), is(1));
assertThat(customArrayList.get(1), is(2));
}
}<file_sep>package ru.agolovin;
import java.util.Iterator;
/**
* @param <E> Generic
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class ThreadSafeLinkedList<E> {
/**
* LinkedList size.
*/
private int size = 0;
/**
* Node to first.
*/
private Node<E> first;
/**
* Node to last.
*/
private Node<E> last;
/**
* Iterator.
*
* @return <E> Object
*/
public synchronized Iterator<E> iterator() {
return new Iterator<E>() {
private int iterIndex = 0;
private Node<E> iterNode = first;
@Override
public boolean hasNext() {
return iterIndex < size;
}
@Override
public E next() {
Node<E> node = this.iterNode;
E item = node.getItem();
if (hasNext()) {
this.iterNode = node.getNext();
iterIndex++;
} else {
throw new IndexOutOfBoundsException();
}
return item;
}
};
}
/**
* Add element to LinkedList.
*
* @param element E
*/
public synchronized void add(E element) {
final Node<E> node = this.last;
final Node<E> newNode = new Node<>(node, element, null);
this.size++;
this.last = newNode;
if (node == null) {
first = newNode;
} else {
node.setNext(newNode);
}
}
/**
* Get object from LinkedList.
*
* @param index int
* @return E object
*/
public synchronized E get(int index) {
Node<E> node = this.first;
if (index >= 0 && index <= this.size) {
for (int i = 0; i < index; i++) {
node = node.getNext();
}
} else {
throw new IndexOutOfBoundsException();
}
return node.getItem();
}
/**
* Node.
*
* @param <E> Generic
*/
public static class Node<E> {
/**
* Current element.
*/
private E item;
/**
* Next node.
*/
private Node<E> next;
/**
* Previous node.
*/
private Node<E> prev;
/**
* Constructor.
*
* @param prev Node
* @param element Generic
* @param next Node
*/
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
/**
* Get element.
*
* @return element <E>
*/
E getItem() {
return item;
}
/**
* Get nex node.
*
* @return E object
*/
Node<E> getNext() {
return next;
}
/**
* Set node next.
*
* @param next Node.
*/
void setNext(Node<E> next) {
this.next = next;
}
}
}
<file_sep>package ru.agolovin;
import java.util.HashMap;
import java.util.List;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class UserConvert {
/**
* Convert List<user> to HashMap<Integer, User>. Key - user Id.
*
* @param list List<User>
* @return HashMap<Integer, User>
*/
public HashMap<Integer, User> process(List<User> list) {
HashMap<Integer, User> map = new HashMap<>();
for (User user : list) {
map.put(user.getId(), user);
}
return map;
}
}
<file_sep><project>
<parent>
<groupId>ru.agolovin</groupId>
<artifactId>package_1</artifactId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chapter_005</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<modules>
<module>task512</module>
<module>task513</module>
<module>task522</module>
<module>task531</module>
<module>testTaskBank</module>
<module>additionalTestTask</module>
</modules>
</project><file_sep>package ru.agolovin;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class Cell {
/**
* X crd.
*/
private int xCell;
/**
* Y crd.
*/
private int yCell;
/**
* Marker busy cell.
*/
private volatile boolean isStop = false;
/**
* Possible figure.
*/
private Figure figure;
/**
* Constructor.
*
* @param xCell int
* @param yCell int
*/
Cell(int xCell, int yCell) {
this.xCell = xCell;
this.yCell = yCell;
}
/**
* Get for isStop.
*
* @return boolean result
*/
public boolean getIsStop() {
return !this.isStop;
}
/**
* Change isStop value.
*
* @param stop boolean
*/
public void setIsStop(boolean stop) {
this.isStop = stop;
}
/**
* Get X crd value.
*
* @return int X crd.
*/
public int getXCell() {
return this.xCell;
}
/**
* Get Y crd value.
*
* @return int yCell
*/
public int getYCell() {
return this.yCell;
}
/**
* Get figure type.
*
* @return Figure figure
*/
public Figure getFigure() {
synchronized (this) {
return figure;
}
}
/**
* Set figure type.
*
* @param figure Figure.
*/
public void setFigure(Figure figure) {
this.figure = figure;
}
}
<file_sep>package ru.agolovin;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class CountChar implements Runnable {
/**
* String for parse.
*/
private String str;
/**
* Constructor.
*
* @param str String.
*/
CountChar(String str) {
this.str = str;
}
/**
* Count whiteSpaces.
*/
private void countWhiteSpaces() {
int count = 0;
char[] arr = str.toCharArray();
for (char element : arr) {
if (element == ' ') {
count++;
}
if (Thread.currentThread().isInterrupted()) {
System.out.println("Thread interrupted");
return;
}
}
System.out.println(String.format("Whitespace count: %s", count));
}
@Override
public void run() {
countWhiteSpaces();
countChar();
}
/**
* Count char.
*/
private void countChar() {
boolean flag = false;
char[] arr = str.toCharArray();
int count = 0;
for (char element : arr) {
if ((element != ' ') && !flag) {
count++;
flag = true;
}
if (element == ' ') {
flag = false;
}
if (Thread.currentThread().isInterrupted()) {
System.out.println("Thread interrupted");
return;
}
}
System.out.println(String.format("Words count: %s", count));
}
}
<file_sep><project>
<parent>
<groupId>ru.agolovin</groupId>
<artifactId>package_1</artifactId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chapter_002</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>Chess</module>
<module>ControlQuestions</module>
<!--<module>task220</module>-->
<!--<module>task230</module>-->
<!--<module>task240</module>-->
<!--<module>task250</module>-->
<!--<module>task260</module>-->
</modules>
</project><file_sep>package ru.agolovin;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*
* @param <T> extends Base
*/
public class MainStore<T extends Base> implements Store<Base> {
/**
* Container.
*/
private SimpleArray<Base> simpleArray;
/**
* Constructor.
*
* @param size int.
*/
MainStore(int size) {
this.simpleArray = new SimpleArray<>(size);
}
@Override
public void add(Base item) {
this.simpleArray.add(item);
}
@Override
public void delete(String id) {
this.simpleArray.delete(getIndexById(id));
}
@Override
public void update(String id, Base newItem) {
this.simpleArray.update(getIndexById(id), newItem);
}
@Override
public Base get(String id) {
return this.simpleArray.get(getIndexById(id));
}
/**
* Get index in container by identification.
*
* @param id String
* @return index int
*/
private int getIndexById(String id) {
Base element;
int i = 0;
int result = -1;
try {
element = this.simpleArray.get(i);
while (element != null) {
if (id.equals(element.getId())) {
result = i;
break;
}
element = this.simpleArray.get(++i);
}
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
return result;
}
}
<file_sep>package ru.agolovin;
public class Triangle {
public Point a;
public Point b;
public Point c;
public Triangle(Point a, Point b, Point c) {
this.a = a;
this.b = b;
this.c = c;
}
public double area() {
double area;
double ab = a.distanceTo(b);
double ac = a.distanceTo(c);
double bc = b.distanceTo(c);
if ((ab + ac > bc) && (ac + bc > ab) && (bc + ab > ac)) {
double per = (ab + ac + bc) / 2;
area = Math.sqrt(per * (per - ab) * (per - ac) * (per - bc));
} else {
area = 0.0;
}
return area;
}
}<file_sep>/**
* //TODO add comments.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
package ru.agolovin.start;
<file_sep>package ru.agolovin;
/**
* Method to input from case.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class StubInput implements Input {
/**
* answers String array.
*/
private String[] answers;
/**
* position int.
*/
private int position = 0;
/**
* @param sAnswers String array
*/
StubInput(final String[] sAnswers) {
this.answers = sAnswers;
}
/**
* @param question String
* @return answers String
*/
public final String ask(final String question) {
return answers[position++];
}
}
<file_sep>package ru.agolovin;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class ProducerCustomer {
/**
* Queue.
*/
private final Queue<Integer> queue = new LinkedBlockingQueue<>();
/**
* Element amount.
*/
private int amount;
/**
* Marker.
*/
private boolean flag = false;
/**
* Constructor.
*
* @param amount int
*/
public ProducerCustomer(int amount) {
this.amount = amount;
}
/**
* Main method.
*
* @param args String[]
*/
public static void main(String[] args) {
new ProducerCustomer(20).init();
}
/**
* ProducerCustomer start.
*/
private void init() {
Thread threadOne = this.producer();
Thread threadTwo = this.customer();
threadOne.start();
threadTwo.start();
}
/**
* Thread producer.
*
* @return Thread.
*/
private Thread producer() {
Thread thread = new Thread(() -> {
int i = 0;
while (i < amount) {
queue.add(i);
queue.notify();
System.out.println(String.format(
"Added %s by producer", i));
i++;
if (i == (amount - 1)) {
flag = true;
}
try {
Thread.sleep(35);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
return thread;
}
/**
* Thread customer.
*
* @return Thread
*/
private Thread customer() {
Thread thread = new Thread(() -> {
while (!flag) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(String.format("Removed %s by customer", queue.remove()));
}
});
return thread;
}
}
<file_sep>url=jdbc:postgresql://localhost:5432/tracker
username=postgres
password=<PASSWORD><file_sep>package ru.agolovin;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class StorageSQLTest {
@Test
public void thenGenerate100ThenExpectGetThem() {
Config config = new Config("xslt.properties");
StorageSQL sql = new StorageSQL(config);
sql.init();
sql.createTable();
int limit = 5;
sql.generate(limit);
List<StoreXML.Entry> answer = new ArrayList<>();
for (int i = 1; i <= limit; i++) {
answer.add(new StoreXML.Entry(i));
}
List<StoreXML.Entry> res = sql.getData();
assertThat(res, is(answer));
}
}<file_sep>package ru.agolovin;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
* <p>
* Нужно осуществлять обход файловой системы и поиск заданного текста в файловой системе.
* public class ParallerSearch(String root, String text, List<String> exts) {
* }
* ,где
* root - путь до папки откуда надо осуществлять поиск.
* text - заданных текст.
* exts - расширения файлов в которых нужно делать поиск.
* <p>
* Приложения должно искать тесты в файле и сохранять адрес файла.
* <p>
* List<String> result(); - возвращает список всех файлов.
* <p>
* Логика приложения.
* <p>
* 1. Запустить код.
* 2. Внутри запустить несколько потоков. Объяснить для чего нужно делать потоки.
* 3. Долждатся завершения поиска.
* 4. Вывести на консоль результат.
*/
public class ParallelSearch {
/**
* Result list.
*/
private List<String> result = new CopyOnWriteArrayList<>();
/**
* Temp file list.
*/
private List<String> listFiles = new ArrayList<>();
/**
* Main method.
*
* @param args String[]
*/
public static void main(String[] args) {
ParallelSearch search = new ParallelSearch();
String root = "D:\\Project\\Java-course\\package_2\\multithreading";
String text = "check";
List<String> ext = new ArrayList<>();
ext.add(".txt");
search.parallelSearch(root, text, ext);
search.showResult();
}
/**
* @param root String Start directory
* @param text String Search text
* @param ext List<String> extensions to find
*/
private void parallelSearch(String root, String text, List<String> ext) {
searchInDirectories(root, ext);
Thread threadOne = new Thread(() -> {
for (int i = 0; i < listFiles.size() / 2; i++) {
if (searchTextInFile(text, listFiles.get(i))) {
result.add(listFiles.get(i));
}
}
});
Thread threadTwo = new Thread(() -> {
for (int i = listFiles.size() / 2; i < listFiles.size(); i++) {
if (searchTextInFile(text, listFiles.get(i))) {
result.add(listFiles.get(i));
}
}
});
threadOne.start();
threadTwo.start();
try {
threadOne.join();
threadTwo.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Recursive find directories with valid file
*
* @param directory String
* @param ext List<String>
*/
private void searchInDirectories(String directory, List<String> ext) {
File file = new File(directory);
for (File element : file.listFiles()) {
if (element.isDirectory()) {
searchInDirectories(element.getAbsolutePath(), ext);
} else {
for (String name : ext) {
if (element.getName().endsWith(name)) {
this.listFiles.add(element.getAbsolutePath());
}
}
}
}
}
/**
* Search text in file.
*
* @param text String
* @param path String file path
* @return boolean result
*/
private boolean searchTextInFile(final String text, final String path) {
File file = new File(path);
boolean flag = false;
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (scanner != null) {
try {
while (scanner.hasNextLine()) {
if (scanner.nextLine().contains(text)) {
flag = true;
break;
}
}
} finally {
scanner.close();
}
}
return flag;
}
/**
* Show work result.
*/
private void showResult() {
for (String str : this.result) {
System.out.println(str);
}
}
}
<file_sep>package ru.agolovin.start;
import org.junit.Test;
import ru.agolovin.start.MenuOutException;
/**
* unHandle exception for menu class.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class MenuOutExceptionTest {
/**
* Test MenuOutException.
*/
@Test (expected = RuntimeException.class)
public final void whenSomethingThen() {
throw new MenuOutException("test");
}
}<file_sep><project>
<parent>
<groupId>ru.agolovin</groupId>
<artifactId>package_1</artifactId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chapter_001</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>task121</module>
<module>task131</module>
<module>task132</module>
<module>task141</module>
<module>task142</module>
<module>task151</module>
<module>task152</module>
<module>task153</module>
<module>task161</module>
</modules>
</project><file_sep>-- 1. Написать запрос получение всех продуктов с типом "СЫР"
SELECT *
FROM product
WHERE type_id = (
SELECT type.id
FROM type
WHERE name = 'Сыр');
-- 2. Написать запрос получения всех продуктов, у кого в имени есть слово "мороженное
SELECT *
FROM product
WHERE name LIKE '%мороженное%';
-- 3. Написать запрос, который выводит все продукты, срок годности которых заканчивается в следующем месяце.
SELECT *
FROM product
WHERE expired_date BETWEEN date('now', 'start of month', '+1 month') AND date('now', 'start of month', '+2 month');
-- 4. Написать запрос, который вывод самый дорогой продукт.
SELECT *
FROM product
WHERE price = (
SELECT MAX(price)
FROM product
);
-- 5. Написать запрос, который выводит количество всех продуктов определенного типа.
SELECT COUNT(type_id)
FROM product
WHERE type_id = (
SELECT type.id
FROM type
WHERE type.name = 'Сыр'
);
-- 6. Написать запрос получение всех продуктов с типом "СЫР" и "МОЛОКО"
SELECT *
FROM product
WHERE type_id = (
SELECT type.id
FROM type
WHERE type.name = 'Сыр') OR type_id = (
SELECT type.id
FROM type
WHERE type.name = 'Молоко');
-- 7. Написать запрос, который выводит тип продуктов, которых осталось меньше 10 штук.
SELECT type.name
FROM product
INNER JOIN type ON product.type_id = type.id
GROUP BY type_id
HAVING count(*) < 10;
-- 8. Вывести все продукты и их тип.
SELECT *
FROM product
INNER JOIN type ON product.type_id = type.id;<file_sep>package ru.agolovin.start;
/**
* Methods for User Interface.
* Contains initialization, user menu.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public final class StartUI {
/**
* tracker Tracker.
*/
private Tracker tracker = new Tracker();
/**
* input Input.
*/
private Input input;
/**
* len user menu.
*/
private int len;
/**
* Array of possible range for input.
*/
private int[] ranges = fillRanges();
/**
* Base method.
*
* @param sInput Input
*/
StartUI(final Input sInput) {
this.input = sInput;
}
/**
* main method.
*
* @param args String[]
*/
public static void main(final String[] args) {
Tracker tracker = new Tracker();
Input input = new ValidateInput();
new StartUI(input).init(tracker);
}
/**
* Initialization.
*
* @param nTracker Tracker
*/
void init(final Tracker nTracker) {
this.tracker = nTracker;
MenuTracker menu = new MenuTracker(this.input, this.tracker);
menu.fillActions();
len = menu.getLengthUserActions();
ranges = fillRanges();
do {
menu.show();
menu.select(input.ask("Select: ", ranges));
} while (!"y".equals(this.input.ask("Exit? y ")));
}
/**
* @return tracker
*/
Tracker getTracker() {
return this.tracker;
}
/**
* @return array of length user menu
*/
private int[] fillRanges() {
int ln = len;
int[] array = new int[ln];
for (int i = 0; i < ln; i++) {
array[i] = i;
}
return array;
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Check number in the input stream class.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class CheckNumberTest {
/**
* Test then input even number, then method return true.
*/
@Test
public final void whenInputEvenNumberThenReturnTrue() {
CheckNumber check = new CheckNumber();
InputStream in = new ByteArrayInputStream("6".getBytes());
boolean result = check.isNumber(in);
assertThat(result, is(true));
}
/**
* Test then input not even number, then method return false.
*/
@Test
public final void whenInputNotEvenNumberThenReturnTrue() {
CheckNumber check = new CheckNumber();
InputStream in = new ByteArrayInputStream("5".getBytes());
boolean result = check.isNumber(in);
assertThat(result, is(false));
}
/**
* Test then input not Number, then method return false.
*/
@Test
public final void whenInputNotNumberThenResultFalse() {
CheckNumber check = new CheckNumber();
InputStream in = new ByteArrayInputStream("e".getBytes());
boolean result = check.isNumber(in);
assertThat(result, is(false));
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import java.util.Random;
import static java.lang.String.format;
import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class FastArraySimpleSetTest {
/**
* Test work fasSet.
*/
@Test
public void thenAddThenGetElement() {
FastArraySimpleSet<Integer> fastSet = new FastArraySimpleSet<>();
fastSet.add(22);
fastSet.add(22);
fastSet.add(44);
fastSet.add(44);
assertThat(fastSet.get(0), is(22));
assertThat(fastSet.get(1), is(44));
}
/**
* Test adding time.
*/
@Test
public void testSetAddTime() {
final int iterations = 1000000;
final int bound = 900;
Random rnd = new Random();
long startTime = System.currentTimeMillis();
FastArraySimpleSet<Integer> fastSet = new FastArraySimpleSet<>();
for (int i = 0; i < iterations; i++) {
fastSet.add(rnd.nextInt(bound));
}
long endFastTime = System.currentTimeMillis();
System.out.println(format("Fast time is: %s", endFastTime - startTime));
long startTimeSet = System.currentTimeMillis();
ArraySimpleSet<Integer> set = new ArraySimpleSet<>(0);
for (int i = 0; i < iterations; i++) {
set.add(rnd.nextInt(bound));
}
long endSetTime = System.currentTimeMillis();
System.out.println(format("Set time is: %s", endSetTime - startTimeSet));
}
}<file_sep>package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.hamcrest.number.IsCloseTo.*;
public class TriangleTest {
@Test
public void whenTriangleExistThenResultIs() {
Point point1 = new Point(1, 4);
Point point2 = new Point(7, 9);
Point point3 = new Point(6, 10);
Triangle triangle = new Triangle(point1, point2, point3);
double area = triangle.area();
assertThat(area, is(closeTo(5.500, 0.0005)));
}
@Test
public void whenTriangleNotExistThenResultIs() {
Point point1 = new Point(9, 4);
Point point2 = new Point(4, 9);
Point point3 = new Point(6, 7);
Triangle triangle = new Triangle(point1, point2, point3);
double area = triangle.area();
assertThat(area, is(0.0));
}
}
<file_sep>package ru.agolovin.start;
import ru.agolovin.models.Task;
/**
* Prepare for UI.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public final class StartUI {
/**
* base method Item.
*/
protected StartUI() {
}
/**
* variable class Item.
*
* @param args args
*/
public static void main(final String[] args) {
Tracker tracker = new Tracker();
tracker.add(new Task("first task", "first desc"));
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test methods for ArrayReadOnly class.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class ArrayReadOnlyTest {
/**
* Test for readOnly class.
*/
@Test
public final void whenArrayReadThen() {
final int first = 1;
final int second = 5;
final int third = 8;
ArrayReadOnly ar = new ArrayReadOnly(
new int[]{first, second, third}
);
final int test = 4;
ar.getReadOnlyArray()[0] = test;
assertThat(ar.getReadOnlyArray()[0], is(1));
}
}
<file_sep>package ru.agolovin;
//Симулятор лифта
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class Elevator implements Runnable {
/**
* Высота этажа.
*/
private final int height;
/**
* Скорость лифта.
*/
private final int speed;
/**
* Время между открытием и закрытием дверей
*/
private final int stopTime;
/**
* Текущий этаж.
*/
private int currentFloor;
/**
* Текущий этаж.
*/
private boolean allowed;
/**
* Очередь заявок.
*/
private PriorityBlockingQueue<Integer> calls;
/**
* Конструктор.
*
* @param height int
* @param speed int
* @param stopTime int
* @param calls PriorityBlockingQueue
*/
Elevator(int height, int speed, int stopTime, PriorityBlockingQueue<Integer> calls) {
this.height = height;
this.speed = speed;
this.stopTime = stopTime;
this.calls = calls;
this.allowed = true;
}
/**
* Инициализация метода.
*/
private void init() {
this.currentFloor = 1;
do {
try {
if (!calls.isEmpty()) {
move(calls.take());
Thread.sleep(200);
} else {
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (allowed);
}
@Override
public void run() {
init();
}
/**
* Перемещение лифта между этажами.
*
* @param targetFloor int
*/
private void move(int targetFloor) {
try {
if (targetFloor == 0) {
this.allowed = false;
}
if (targetFloor == currentFloor) {
turnDoor();
} else {
if (targetFloor > currentFloor) {
moveUP(targetFloor);
turnDoor();
this.currentFloor = targetFloor;
} else {
moveDown(targetFloor);
turnDoor();
this.currentFloor = targetFloor;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Смещение лифта вниз.
*
* @param targetFloor int
* @throws InterruptedException Exception
*/
private void moveDown(int targetFloor) throws InterruptedException {
for (int i = currentFloor; i >= targetFloor; i--) {
messageCurrentFloor(i);
TimeUnit.MICROSECONDS.sleep(speedDelay());
}
}
/**
* Смещение лифта вверх.
*
* @param targetFloor int
* @throws InterruptedException Exception
*/
private void moveUP(int targetFloor) throws InterruptedException {
for (int i = currentFloor; i <= targetFloor; i++) {
messageCurrentFloor(i);
TimeUnit.MICROSECONDS.sleep(speedDelay());
}
}
/**
* Временная пауза.
*
* @return int
*/
private int speedDelay() {
return height / speed;
}
/**
* Открытие/закрытие дверей.
*/
private void turnDoor() {
System.out.println("Лифт открывает двери");
try {
TimeUnit.SECONDS.sleep(stopTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Лифт закрывает двери");
}
/**
* Отображение текущего этажа.
*
* @param i int
*/
private void messageCurrentFloor(int i) {
System.out.println(String.format("Лифт проехал %d этаж", i));
}
}
<file_sep>package ru.agolovin;
import java.util.concurrent.CountDownLatch;
public class DeadLockCDL {
public static void main(String[] args) {
Object object1 = new Object();
Object object2 = new Object();
CountDownLatch cdl = new CountDownLatch(2);
System.out.println("All object:");
System.out.println(object1.toString());
System.out.println(object2.toString());
System.out.println("Start thread:");
new Thread(new Lock(object1, object2, cdl)).start();
new Thread(new Lock(object2, object1, cdl)).start();
}
}
class Lock implements Runnable {
final Object object1;
final Object object2;
CountDownLatch cdl;
Lock(Object object1, Object object2, CountDownLatch cdl) {
this.object1 = object1;
this.object2 = object2;
this.cdl = cdl;
}
@Override
public void run() {
synchronized (object1) {
System.out.println(object1.toString() + "is locked by " + Thread.currentThread().getName());
cdl.countDown();
try {
cdl.await();
} catch (Exception e) {
e.printStackTrace();
}
synchronized (object2) {
System.out.println("Thread finished");
}
}
}
}<file_sep>package ru.agolovin;
import org.junit.Test;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class FileSortExceptionTest {
/**
* Test FileSortException.
*/
@Test(expected = RuntimeException.class)
public final void whenSomethingThen() {
throw new FileSortException("test");
}
}<file_sep>package ru.agolovin;
import org.junit.Test;
import java.util.NoSuchElementException;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class PrimeNumberIteratorTest {
/**
* Test work next & hasNext methods.
*/
@Test
public void whenGivePrimeNumberFromArrayThenResultIs() {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8};
PrimeNumberIterator it = new PrimeNumberIterator(array);
it.hasNext();
assertThat(it.next(), is(2));
it.hasNext();
assertThat(it.next(), is(3));
it.hasNext();
assertThat(it.next(), is(5));
assertThat(it.hasNext(), is(true));
assertThat(it.next(), is(7));
assertThat(it.hasNext(), is(false));
}
/**
* Test exception.
*/
@Test(expected = NoSuchElementException.class)
public void whenNoPrimeNumberThenException() {
int[] array = {1, 4, 6, 8};
PrimeNumberIterator it = new PrimeNumberIterator(array);
it.hasNext();
it.next();
}
}<file_sep>package ru.agolovin;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class NonBlocking {
/**
* Concurent map.
*/
private final ConcurrentMap<Integer, Model> map = new ConcurrentHashMap<>();
/**
* add data.
*
* @param model Model
*/
public void add(Model model) {
this.map.put(model.getId(), model);
}
/**
* delete data.
*
* @param model Model
*/
public void delete(Model model) {
this.map.remove(model.getId());
}
/**
* Update data.
*
* @param newModel Model
*/
public void update(Model newModel) {
this.map.computeIfPresent(newModel.getId(), (integer, oldModel) -> {
if (oldModel.getVersion() == newModel.getVersion()) {
newModel.update();
return newModel;
} else {
throw new OplimisticException("Busy by another thread");
}
});
}
}
<file_sep><project>
<parent>
<groupId>ru.agolovin</groupId>
<artifactId>package_2</artifactId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chapter_005_pro</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<modules>
<module>iterator</module>
<module>generic</module>
<module>list</module>
<module>set</module>
<module>map</module>
<module>tree</module>
<module>testTaskCollectionPro</module>
<module>testTaskOrderBook</module>
</modules>
</project><file_sep>package ru.agolovin;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
* @param <T> Generic
*/
public class ThreadSafeArrayList<T> {
/**
* Array capacity.
*/
private static final int DEFAULT_CAPACITY = 100;
/**
* Array.
*/
private Object[] array;
/**
* Last index in array.
*/
private int index;
/**
* Constructor.
*/
public ThreadSafeArrayList() {
this.array = new Object[DEFAULT_CAPACITY];
}
/**
* Constructor. Custom array size.
*
* @param size int
*/
public ThreadSafeArrayList(int size) {
this.array = new Object[size];
}
/**
* Rise array capacity.
*/
private void riseArray() {
this.array = Arrays.copyOf(this.array, this.index + 10);
}
/**
* Iterator.
* @return T object
*/
public synchronized Iterator<T> iterator() {
return new Iterator<T>() {
private int current = 0;
@Override
public boolean hasNext() {
return current != index;
}
@Override
public T next() {
if (hasNext()) {
return (T) array[current++];
} else {
throw new IndexOutOfBoundsException();
}
}
};
}
/**
* Add element to array.
*
* @param e Object
*/
public synchronized void add(Object e) {
if (this.array.length > index) {
this.array[index++] = e;
} else {
riseArray();
this.array[index++] = e;
}
}
/**
* Get element from array.
*
* @param index int
* @return Element Object
*/
public synchronized T get(int index) {
Object result;
if (index < this.index && index >= 0) {
result = this.array[index];
} else {
throw new NoSuchElementException();
}
return (T) result;
}
}<file_sep>package ru.agolovin;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class SortUserTest {
/**
* User 1.
*/
private User user1 = new User("Name11", 2);
/**
* User 2.
*/
private User user2 = new User("Name", 1);
/**
* User 3.
*/
private User user3 = new User("Name333", 0);
/**
* Test class.
*/
private SortUser sortUser = new SortUser();
/**
* List users.
*/
private List<User> users = new ArrayList<>();
/**
* Add users to list.
* @param list list.
*/
private void collectionsAdd(List<User> list) {
list.add(user1);
list.add(user2);
list.add(user3);
}
/**
* Sort user by age.
*/
@Test
public void whenAddSomeUserToListThenGiveSortedTreeMap() {
collectionsAdd(users);
Set<User> result = sortUser.sort(users);
Set<User> answer = new LinkedHashSet<>();
answer.add(user3);
answer.add(user2);
answer.add(user1);
assertThat(result, is(answer));
}
/**
* Sort List<Users> by hashCode.
*/
@Test
public void whenAddSomeUserToListThenSortItByHashCode() {
collectionsAdd(users);
List<User> result = sortUser.sortHash(users);
List<User> answer = new ArrayList<>();
collectionsAdd(answer);
for (int i = 0; i < answer.size() - 1; i++) {
for (int j = i + 1; j < answer.size(); j++) {
if (answer.get(i).hashCode() > answer.get(j).hashCode()) {
User temp = answer.get(i);
answer.set(i, answer.get(j));
answer.set(j, temp);
}
}
}
assertThat(result, is(answer));
}
/**
* Sort List<Users> by Name length.
*/
@Test
public void whenAddSomeUserToListThenSortItByNameLength() {
collectionsAdd(users);
List<User> result = sortUser.sortLength(users);
List<User> answer = new ArrayList<>();
collectionsAdd(answer);
for (int i = 0; i < answer.size() - 1; i++) {
for (int j = i + 1; j < answer.size(); j++) {
if (answer.get(i).getName().length() > answer.get(j).getName().length()) {
User temp = answer.get(i);
answer.set(i, answer.get(j));
answer.set(j, temp);
}
}
}
assertThat(result, is(answer));
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Создать класс User с полями id, name, city.
* Cоздать клаcc UserConvert.
* В классе UserConvert написать метод public HashMap<Integer, User> process(List<User> list) {},
* который принимает в себя список пользователей и конвертирует его в Map с ключом Integer id и
* соответствующим ему User.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class UserConvertTest {
/**
* Test convert List<User> to HashMap<Integer, User>. Key - user.Id.
*
* @throws Exception Exception
*/
@Test
public void whenConvertUserListToHashMapThenItConvert() throws Exception {
int index = 0;
User user1 = new User(index++, "Name1", "City1");
User user2 = new User(index++, "Name2", "City2");
User user3 = new User(index, "Name3", "City3");
List<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
users.add(user3);
UserConvert userConvert = new UserConvert();
HashMap<Integer, User> result;
result = userConvert.process(users);
HashMap<Integer, User> answer = new HashMap<>();
answer.put(user1.getId(), user1);
answer.put(user2.getId(), user2);
answer.put(user3.getId(), user3);
assertThat(result, is(answer));
}
}<file_sep>ip_address=127.0.0.1
port=25432
home.path=./<file_sep>package ru.agolovin;
import org.junit.Test;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class BookTest {
/**
* Test method work.
*
* @throws Exception exception
*/
@Test
public void testBook() throws Exception {
long startTime = System.currentTimeMillis();
Map<String, Book> book = new HashMap<>();
File file = new File("D:\\Project\\orders.xml");
ReadFromXML reader = new ReadFromXML(book);
reader.fillFromXML(file);
for (String element : book.keySet()) {
System.out.println("Order book: " + element);
book.get(element).init();
}
long elapsed = System.currentTimeMillis() - startTime;
System.out.println(String.format("Elapsed time: %s (s)", elapsed / 1000));
}
}<file_sep>package ru.agolovin;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class User {
/**
* Identification.
*/
private int id = 0;
/**
* User name.
*/
private String name;
/**
* User city.
*/
private String city;
/**
* Constructor.
*
* @param id int.
* @param name String.
* @param city String.
*/
public User(int id, String name, String city) {
this.id = id;
this.name = name;
this.city = city;
}
/**
* getter Id.
*
* @return id int
*/
public int getId() {
return this.id;
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class ArrayIteratorTest {
/**
* Start array value.
*/
private int index = 1;
/**
* Test array.
*/
private int[][] array = {{index++, index++}, {index++, index++}};
/**
* Test class.
*/
private ArrayIterator it = new ArrayIterator(array);
/**
* testing data.
*/
@Test
public void whenArrayIteratorReturnArrayThrnResultIs() {
for (int[] anArray : array) {
for (int anAnArray : anArray) {
int result = it.next();
assertThat(result, is(anAnArray));
}
}
}
/**
* Testing method has next.
*/
@Test
public void whenTestOutFromNexThenResultIs() {
boolean result;
for (int[] anArray : array) {
for (int anAnArray : anArray) {
result = it.hasNext();
assertThat(result, is(true));
it.next();
}
}
boolean result2 = it.hasNext();
assertThat(result2, is(false));
}
/**
* test out from array.
*/
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void whenOutFromArrayThenException() {
for (int[] anArray : array) {
for (int anAnArray : anArray) {
it.next();
}
}
it.next();
}
}<file_sep>package ru.agolovin;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class Role extends Base {
/**
* Constructor.
*
* @param id String.
*/
public Role(String id) {
setId(id);
}
}
<file_sep>package ru.agolovin;
/**
* @param <E> generic
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class CustomQueue<E> implements StackQueue<E> {
/**
* Base Linked list.
*/
private CustomLinkedList<E> baseList = new CustomLinkedList<>();
@Override
public void push(E e) {
baseList.add(e);
}
@Override
public E poll() {
return baseList.removeFirst();
}
}
<file_sep>package ru.agolovin.start;
/**
* interface for input.
*/
public interface Input {
/**
* @param question String
* @return ask User answer String
*/
String ask(String question);
/**
* @param question String
* @param range int
* @return user ask int
*/
int ask(String question, int[] range);
}
<file_sep>package ru.agolovin;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* @param <E> Generic.
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class ArraySimpleSet<E> implements Iterable<E> {
/**
* Array capacity.
*/
private static final int DEFAULT_CAPACITY = 100;
/**
* Array.
*/
private Object[] array;
/**
* Last index in array.
*/
private int index;
/**
* Constructor.
*/
ArraySimpleSet() {
this.array = new Object[DEFAULT_CAPACITY];
}
/**
* Constructor. Custom array size.
*
* @param size int
*/
ArraySimpleSet(int size) {
this.array = new Object[size];
}
/**
* Get array.
*
* @return array
*/
Object[] getArray() {
return array;
}
/**
* Set new array.
*
* @param array array
*/
void setArray(Object[] array) {
this.array = array;
}
/**
* Get index.
*
* @return int index
*/
int getIndex() {
return index;
}
/**
* Set index.
*
* @param index int
*/
void setIndex(int index) {
this.index = index;
}
/**
* Set value to array item.
*
* @param pos int
* @param value Generic
*/
void setValue(int pos, E value) {
this.array[pos] = value;
}
/**
* Rise array capacity.
*/
void riseArray() {
this.array = Arrays.copyOf(this.array, (this.index * 3) / 2 + 1);
}
/**
* Chech if element alredy contains in array.
*
* @param e Generic
* @return check result.
*/
private boolean contains(E e) {
boolean result = false;
if (e != null) {
for (Object anArray : this.array) {
if (e.equals(anArray)) {
result = true;
break;
}
}
}
return result;
}
/**
* Add element to array.
*
* @param e Generic
*/
public void add(E e) {
if (!contains(e)) {
if (this.array.length > index) {
this.array[index++] = e;
} else {
riseArray();
this.array[index++] = e;
}
}
}
/**
* Get element from array.
*
* @param index int
* @return Element
*/
public E get(int index) {
Object result;
if (index < this.index && index >= 0) {
result = this.array[index];
} else {
throw new NoSuchElementException();
}
return (E) result;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
/**
* Iter index.
*/
private int current = 0;
@Override
public boolean hasNext() {
return index > current;
}
@Override
public E next() {
if (hasNext()) {
return (E) array[current++];
} else {
throw new IndexOutOfBoundsException();
}
}
};
}
}
<file_sep>package ru.agolovin.start;
/**
* Abstract class for UserAction.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public abstract class BaseAction implements UserAction {
/**
* String name.
*/
private String name;
/**
* @param sName String
*/
public BaseAction(String sName) {
this.name = sName;
}
/**
* @return key value int
*/
public abstract int key();
/**
* @param input Input
* @param tracker Tracker
*/
public abstract void execute(Input input, Tracker tracker);
/**
* @return info about menu line
*/
public String info() {
return String.format(" %s. %s", this.key(), this.name);
}
}
<file_sep>package ru.agolovin;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Вам необходимо создать класс ConvertList.
* В нём написать 2 метода:
* public List<Integer> toList (int[][] array) {} - в метод прходит двумерный массив целых чисел,
* необходимо пройтись по всем элементам массива и добавить их в List<Integer>
* public int[][] toArray (List<Integer> list, int rows) {} - метод toArray должен равномерно разбить лист
* на количество строк двумерного массива. В методе toArray должна быть проверка - если количество элементов
* не кратно количеству строк - оставшиеся значения в массиве заполнять нулями
* Например в результате конвертации листа со значениями (1,2,3,4,5,6,7) с разбиением на 3 строки должен
* получиться двумерный массив {{1, 2, 3} {4, 5, 6} {7, 0 ,0}}
*
* В классе ConvertList написать метод:
* public List<Integer> convert (List<int[]> list)
* В этом методе вы должны пройтись по всем элементам всех массивов в списке list и добавить их в один
* общий лист Integer
* Массивы в списке list могут быть разного размера
*
* Например:
* list.add(new int[]{1, 2})
* list.add(new int[]{3, 4, 5, 6})
* List<Integer> result = convertList.convert(list)
* List<Integer> result будет содержать элементы: (1, 2, 3, 4, 5, 6)
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
class ConvertList {
/**
* Convert int[][] array to List<Integer>.
*
* @param array int[][]
* @return list List<Integer>
*/
public List<Integer> toList(int[][] array) {
ArrayList<Integer> arrayList = new ArrayList<>();
for (int[] element : array) {
for (int sub : element) {
arrayList.add(sub);
}
}
return arrayList;
}
/**
* Convert List<Integer> to int[][] array With the number of lines. Free elements are replaced by 0.
*
* @param list List<Integer>
* @param rows int
* @return array int[][]
*/
public int[][] toArray(List<Integer> list, int rows) {
int[][] array;
int listSize = list.size();
int lines = listSize % rows == 0 ? listSize / rows : listSize / rows + 1;
array = new int[lines][rows];
Iterator<Integer> iterator = list.iterator();
for (int i = 0; i < lines; i++) {
for (int j = 0; j < rows; j++) {
if (iterator.hasNext()) {
array[i][j] = iterator.next();
} else {
array[i][j] = 0;
}
}
}
return array;
}
/**
* Convert List<int[]> to List<Integer>.
* @param list List<int[]>
* @return List<Integer>
*/
public List<Integer> convert(List<int[]> list) {
ArrayList<Integer> arrayList = new ArrayList<>();
for (int[] element : list) {
for (int sub : element) {
arrayList.add(sub);
}
}
return arrayList;
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class UserStoreTest {
/**
* Test add user to store.
*/
@Test
public void whenAddUsersToStoreAndGetIt() {
UserStore userStore = new UserStore(3);
String idUser1 = "idOne";
String idUser2 = "idTwo";
User user1 = new User(idUser1);
User user2 = new User(idUser2);
userStore.add(user1);
userStore.add(user2);
assertThat(userStore.get(idUser1), is(user1));
assertThat(userStore.get(idUser2), is(user2));
}
/**
* Test update user.
*/
@Test
public void whenUpdateUserThenItUpdate() {
UserStore userStore = new UserStore(3);
String idUser1 = "idOne";
String idUser2 = "idTwo";
User user1 = new User(idUser1);
User user2 = new User(idUser2);
userStore.add(user1);
userStore.update(idUser1, user2);
assertThat(userStore.get(idUser2), is(user2));
}
/**
* Test delete user.
*/
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void whenDeleteUser2FromStoreThen() {
UserStore userStore = new UserStore(3);
String idUser1 = "idOne";
String idUser2 = "idTwo";
User user1 = new User(idUser1);
User user2 = new User(idUser2);
userStore.add(user1);
userStore.add(user2);
userStore.delete(idUser2);
assertEquals(userStore.get(idUser2), null);
}
}<file_sep>package ru.agolovin.models;
/**
* Base Item methods.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class Item {
/**
* variable class Item.
*
* @param id String
*/
private String id;
/**
* variable class Item.
*
* @param name String
*/
private String name;
/**
* variable class Item.
*
* @param description String
*/
private String description;
/**
* variable class Item.
*
* @param timeCreate long
*/
private long timeCreate;
/**
* base method Item.
*
*/
public Item() {
}
/**
* base method Item.
*
* @param sName name
* @param sDescription description
* @param sTimeCreate timeCreate
*/
public Item(
final String sName,
final String sDescription,
final long sTimeCreate) {
this.name = sName;
this.description = sDescription;
this.timeCreate = sTimeCreate;
}
/**
* @return name
*/
public final String getName() {
return this.name;
}
/**
* @param sName name
*/
public final void setName(final String sName) {
this.name = sName;
}
/**
* @return description
*/
public final String getDescription() {
return this.description;
}
/**
* @param sDescription description
*/
public final void setDescription(final String sDescription) {
this.description = sDescription;
}
/**
* @return timeCreate
*/
public final long getTimeCreate() {
return this.timeCreate;
}
/**
* @param sTimeCreate timeCreate
*/
public final void setTimeCreate(final long sTimeCreate) {
this.timeCreate = sTimeCreate;
}
/**
* @return id
*/
public final String getId() {
return this.id;
}
/**
* @param sId id
*/
public final void setId(final String sId) {
this.id = sId;
}
}
<file_sep>package ru.agolovin.start;
import org.junit.Test;
import ru.agolovin.models.Task;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test methods for Task class.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class TaskTest {
/**
* Test for Task class.
*/
@Test
public final void whenAddInTaskThenResultIs() {
Task task = new Task("taskName", "taskDesc");
String resultName = "taskName";
String resultDesc = "taskDesc";
assertThat(task.getName(), is(resultName));
assertThat(task.getDescription(), is(resultDesc));
}
}
<file_sep>package ru.agolovin;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class IteratorIterators implements ConvertIterator, Iterator<Integer> {
/**
* Private iterator.
*/
private Iterator<Iterator<Integer>> source;
/**
* Inner iterator.
*/
private Iterator<Integer> current;
@Override
public Iterator<Integer> convert(Iterator<Iterator<Integer>> it) {
this.source = it;
if (this.source.hasNext()) {
this.current = this.source.next();
}
return this;
}
@Override
public boolean hasNext() {
return this.current.hasNext() || this.source.hasNext();
}
@Override
public Integer next() {
Integer result;
if (current.hasNext()) {
result = current.next();
} else if (source.hasNext()) {
current = source.next();
result = current.next();
} else {
throw new NoSuchElementException();
}
return result;
}
}
<file_sep>package ru.agolovin;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class EvenNumber implements Iterator<Integer> {
/**
* Private class array.
*/
private int[] array;
/**
* Index last even number.
*/
private int index = 0;
/**
* index event number.
*/
private int indexEvNumber;
/**
* Constructor.
*
* @param array int[]
*/
EvenNumber(int[] array) {
this.array = array;
}
@Override
public boolean hasNext() {
return indexEvenNumber() != -1;
}
@Override
public Integer next() throws NoSuchElementException {
int result;
if (this.indexEvNumber != -1) {
result = this.array[this.indexEvNumber];
this.index = this.indexEvNumber + 1;
} else {
throw new NoSuchElementException();
}
return result;
}
/**
* Get index even number.
*
* @return index int
*/
private int indexEvenNumber() {
int result = -1;
if (this.index < this.array.length) {
for (int i = index; i < this.array.length; i++) {
if (this.array[i] % 2 == 0) {
result = i;
this.indexEvNumber = i;
break;
}
}
} else {
indexEvNumber = -1;
}
return result;
}
}
<file_sep>package ru.agolovin;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.IOException;
/**
* @author agolovin (<EMAIL>)
* @version $
* @since 0.1
*/
public class ParseXML {
/**
* Total count from XML field.
*/
private int count;
/**
* Constructor.
*
* @param file File.
*/
public ParseXML(File file) {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
try {
SAXParser parser = parserFactory.newSAXParser();
Handler handler = new Handler();
parser.parse(file, handler);
} catch (SAXException | ParserConfigurationException | IOException e) {
e.printStackTrace();
}
}
/**
* Get total count.
*
* @return int result
*/
public int getCount() {
return count;
}
/**
* Handler.
*/
public class Handler extends DefaultHandler {
@Override
public void startElement(String url, String localName, String name,
Attributes attributes) {
int length = attributes.getLength();
for (int i = 0; i < length; i++) {
String atrName = attributes.getQName(i);
if (atrName != null && atrName.equals("field")) {
count += Integer.parseInt(attributes.getValue(i));
}
}
}
}
}
<file_sep>package ru.agolovin;
/**
* @param <E> generic
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public interface StackQueue<E> {
/**
* Add object.
*
* @param e Generic
*/
void push(E e);
/**
* Get object.
*
* @return Object
*/
E poll();
}
<file_sep>package ru.agolovin;
public class MaxTriangleSide {
public static double maxSide(double ... args) {
double max = 0.0;
for (double x : args)
if (x > max) max = x;
return max;
}
}
<file_sep><project>
<parent>
<groupId>ru.agolovin</groupId>
<artifactId>Java-course</artifactId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>chapter_003</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<modules>
<module>task1</module>
<module>task2</module>
<module>task3</module>
<module>task4</module>
<module>task5</module>
<module>task6</module>
<module>task7</module>
<module>controlTask_3</module>
</modules>
</project><file_sep>package ru.agolovin;
import java.util.Random;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class Bomberman {
/**
* Game marker.
*/
private static volatile boolean stop;
/**
* Game board.
*/
private final Cell[][] board;
/**
* Game board size [size][size].
*/
private final int size;
/**
* Number of warriors.
*/
private final int bots;
/**
* Number of blocks on board.
*/
private final int blocks;
/**
* Warriors array.
*/
private Figure[] warriors;
/**
* For Random number.
*/
private Random random;
/**
* Player thread.
*/
private Thread player;
/**
* Constructor.
*
* @param size int
* @param bots int
* @param blocks int
*/
private Bomberman(int size, int bots, int blocks) {
this.size = size;
this.board = new Cell[size][size];
this.bots = bots;
this.blocks = blocks;
stop = false;
this.random = new Random();
}
/**
* Get game marker.
*
* @return boolean result.
*/
public synchronized static boolean isStop() {
return stop;
}
/**
* Change game marker.
*
* @param stop boolean
*/
public static void setStop(boolean stop) {
Bomberman.stop = stop;
}
/**
* Main method.
*
* @param args String[]
*/
public static void main(String[] args) {
new Bomberman(3, 3, 1).init();
}
/**
* Initialization.
*/
private void init() {
prepareBoard();
setUpBlockCell();
setUpWarriors();
createThreads();
try {
player.join();
System.out.println("Game over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Prepare board.
*/
private void prepareBoard() {
for (int i = 0; i < this.size; i++) {
for (int j = 0; j < this.size; j++) {
this.board[i][j] = new Cell(i, j);
}
}
}
/**
* Set blocks on board.
*/
private void setUpBlockCell() {
int count = this.blocks;
while (count != 0) {
int x = getRandomNumber();
int y = getRandomNumber();
if (this.board[x][y].getIsStop()) {
this.board[x][y].setIsStop(true);
System.out.println(
String.format(
"Block setUp in %s, %s",
this.board[x][y].getXCell(), this.board[x][y].getYCell()));
count--;
}
}
}
/**
* Initialize warriors.
*/
private void setUpWarriors() {
this.warriors = new Warrior[this.bots];
Warrior warrior;
int count = 0;
while (count != this.bots) {
int x = getRandomNumber();
int y = getRandomNumber();
if (this.board[x][y].getIsStop() && this.board[x][y].getFigure() == null) {
warrior = new Warrior(String.valueOf(count), this.board, this.board[x][y]);
this.warriors[count] = warrior;
count++;
}
}
}
/**
* Prepare player figure.
*
* @return Player player.
*/
private Player createBomberman() {
Player player = null;
boolean result = false;
while (!result) {
int x = getRandomNumber();
int y = getRandomNumber();
if (this.board[x][y].getIsStop() && this.board[x][y].getFigure() == null) {
player = new Player("0", this.board, this.board[x][y]);
System.out.println(
String.format("Bomberman %s start game in %d %d", player.type(),
this.board[x][y].getXCell(), this.board[x][y].getYCell())
);
result = true;
}
}
return player;
}
/**
* get random number in allowed range.
*
* @return int result
*/
private int getRandomNumber() {
return random.nextInt(this.size);
}
/**
* Create threads.
*/
private void createThreads() {
this.player = new Thread(this.createBomberman());
this.player.start();
for (Figure warrior : this.warriors) {
new Thread(warrior).start();
}
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/**
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class RoleStoreTest {
/**
* Test add role to store.
*/
@Test
public void whenAddRoleToStoreAndGetIt() {
RoleStore roleStore = new RoleStore(2);
String idRole1 = "idOne";
String idRole2 = "idTwo";
Role role1 = new Role(idRole1);
Role role2 = new Role(idRole2);
roleStore.add(role1);
roleStore.add(role2);
assertThat(roleStore.get(idRole1), is(role1));
assertThat(roleStore.get(idRole2), is(role2));
}
/**
* Test update role.
*/
@Test
public void whenUpdateRoleThenItUpdate() {
RoleStore roleStore = new RoleStore(3);
String idRole1 = "idOne";
String idRole2 = "idTwo";
Role role1 = new Role(idRole1);
Role role2 = new Role(idRole2);
roleStore.add(role1);
roleStore.update(idRole1, role2);
assertThat(roleStore.get(idRole2), is(role2));
}
/**
* Test delete role2.
*/
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void whenDeleteRole2FromStoreThen() {
RoleStore roleStore = new RoleStore(3);
String idRole1 = "idOne";
String idRole2 = "idTwo";
Role role1 = new Role(idRole1);
Role role2 = new Role(idRole2);
roleStore.add(role1);
roleStore.add(role2);
roleStore.delete(idRole2);
assertEquals(roleStore.get(idRole2), null);
}
}<file_sep>package ru.agolovin;
import java.util.Arrays;
/**
* @param <E> Generic
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class FastArraySimpleSet<E> extends ArraySimpleSet<E> {
@Override
public void add(E e) {
if (contains(e) < 0) {
int ind = getIndex();
if (getArray().length >= ind) {
riseArray();
}
setValue(ind, e);
Arrays.sort(getArray());
setIndex(++ind);
}
}
/**
* Rise array.
*/
void riseArray() {
setArray(Arrays.copyOf(getArray(), (getIndex() + 1)));
}
/**
* Check if element already contains in array.
*
* @param e Generic
* @return index element in array. Return -1 if not contains
*/
private int contains(E e) {
int low = 0;
int high = getIndex() - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
@SuppressWarnings("rawtypes")
Comparable midVal = (Comparable) getArray()[mid];
@SuppressWarnings("unchecked")
int cmp = midVal.compareTo(e);
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
return mid;
}
}
return -(low + 1); // key not found.
}
}
<file_sep>package ru.agolovin;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class SquareTest {
@Test
public void whenAllExistThenResult() {
Square sq = new Square();
sq.setParameters(5, 10, 15);
float result = sq.calculate(5);
assertThat(result, is(190.0F));
}
@Test
public void whenShowResultThenResultIs() {
Square sq = new Square();
sq.setParameters(5, 10, 15);
sq.calculate(5);
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
sq.show(5, 8, 1);
assertThat(out.toString(), is("190.0\r\n255.0\r\n330.0\r\n415.0\r\n"));
}
}<file_sep>package models :
класс Item
содержит переменные экземпляра: имя, описание, время создания, комментарий,
содержит методы: получения значения имени, описания, времени создания, комментария;
редактирования комментария;
класс Task наследуется от Item
содержит методы создания объекта item, редактирования и удаления.
класс Filter необходим для поиска элемента по заданному условию.
содержит переменные экземпляря: параметр для поиска;
содержит метод поиска по заданному условию.
класс UI
содержит методы необходимые для работы и отображению меню программы
package start
класс Tracker
содержит главный метод программы
содержит метод включающий логику работы<file_sep>/**
*
* В течении дня в банк заходят люди, у каждого человека есть время захода в банк и время выхода.
* Всего за день у банка было N посетителей. Банк работает с 8:00 до 20:00.
* Человек посещает банк только один раз за день.
* Написать программу, которая определяет периоды времени,.
* когда в банке было максимальное количество посетителей.
*
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
package ru.agolovin;<file_sep>package ru.agolovin.start;
import org.junit.Test;
import ru.agolovin.models.Filter;
import ru.agolovin.models.Item;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test methods for Tracker.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class TrackerTest {
/**
* Test for adding new Item in tracker.
*/
@Test
public final void whetAddNewItemThenResultIs() {
Tracker tracker = new Tracker();
Item item = new Item("testName", "testDescription", 1);
Item[] result = new Item[1];
tracker.add(item);
result[0] = item;
assertThat(tracker.getAll(), is(result));
}
/**
* Test for update exist Item in tracker.
*/
@Test
public final void whenUpdateItemThenResultIs() {
Tracker tracker = new Tracker();
Item item = new Item("testName", "testDescription", 1);
Item updateItem = new Item("updateName", "updateDescription", 2);
Item[] result = new Item[1];
tracker.add(item);
updateItem.setId(tracker.findById(item.getId()).getId());
tracker.updateItem(updateItem);
result[0] = updateItem;
assertThat(tracker.getAll(), is(result));
}
/**
* Test for delete exist Item in tracker.
*/
@Test
public final void whenDeleteItemThenResultIs() {
Tracker tracker = new Tracker();
Item itemOne = new Item("testName", "testDescription", 1);
Item itemTwo = new Item("updateName", "updateDescription", 2);
Item[] result = new Item[2];
tracker.add(itemOne);
tracker.add(itemTwo);
tracker.deleteItem(itemOne);
result[1] = itemTwo;
assertThat(tracker.getAll(), is(result));
}
/**
* Test for find by filter Item in tracker.
*/
@Test
public final void whenFindByFilterThenResultIs() {
Tracker tracker = new Tracker();
Item itemOne = new Item("testName", "testDescription", 1);
Item[] result = new Item[1];
tracker.add(itemOne);
result[0] = itemOne;
Filter filter = new Filter("testName");
assertThat(tracker.getByFilter(filter), is(result));
}
}
<file_sep>package ru.agolovin;
public class ArrRotate {
public void arrRotate(int[][] arr) {
int n = arr.length;
int[][] temp = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
temp[i][j] = arr[j][n - i - 1];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
arr[i][j] = temp[i][j];
}
}<file_sep>package ru.agolovin.start;
/**
* Method to input from case.
*
* @author agolovin (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class StubInput implements Input {
/**
* nswers String array.
*/
private String[] answers;
/**
* position int.
*/
private int position = 0;
/**
* @param sAnswers String array
*/
StubInput(final String[] sAnswers) {
this.answers = sAnswers;
}
/**
* @param question String
* @return answers String
*/
public final String ask(final String question) {
return answers[position++];
}
/**
* @param question String
* @param range int
* @return new UnsupportedOperationException
*/
public int ask(String question, int[] range) {
int key = Integer.valueOf(this.ask(question));
boolean exist = false;
for (int value : range) {
if (value == key) {
exist = true;
break;
}
}
return exist ? key : -1;
}
}
|
d6cfd644c9791525e8d97949134dd4c3c7e7b76b
|
[
"SQL",
"Markdown",
"Maven POM",
"INI",
"Java",
"Text"
] | 103 |
Java
|
MorpG/Java-course
|
ec9ce77be1e7429fa0a1210a6df7d10b3348b615
|
1a9b8d4163fc80ac063eafb80d3fd37f1c723049
|
refs/heads/master
|
<file_sep>package function;
import function.Operator;
import java.lang.IllegalArgumentException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import precisemath.DecimalGenerator;
import precisemath.DecimalGenerator.RoundedDecimal;
import precisemath.PreciseMath;
import utility.ParenthResolver;
/**
* Represents a function consisting of an alternating string of numerical values and operators.
*/
public class Function {
private static final String REGEX_DECIMAL = "(?<Operand>(^-)?+(\\d++(\\.\\d++)?+)|(\\.\\d++))";
private static final String OPERATOR = "(?<Operator>(?!^-)(?=\\D)[^.])";
private static final String FUNCTION_MOULD = "(" + REGEX_DECIMAL + OPERATOR + "?+)++";
private final DecimalGenerator dcmlControl;
//default operators
private Operator[] operators = new Operator[] {
new Operator('^', 0, (lOperand, rOperand) -> PreciseMath.pow(lOperand, rOperand)),
new Operator('*', 1, (lOperand, rOperand) -> PreciseMath.multiply(lOperand, rOperand)),
new Operator('/', 1, (lOperand, rOperand) -> PreciseMath.divide(lOperand, rOperand)),
new Operator('%', 1, (lOperand, rOperand) -> PreciseMath.remainder(lOperand, rOperand)),
new Operator('+', 2, (lOperand, rOperand) -> PreciseMath.add(lOperand, rOperand)),
new Operator('-', 2, (lOperand, rOperand) -> PreciseMath.subtract(lOperand, rOperand))
};
private final List<Object> fstack = new ArrayList<Object>();
private final Stack<Operator> opstack = new Stack<Operator>();
private final boolean verbose;
/**
* The constructor for this function.
*
* @param canidate The input to be evaluated if it is a valid function.
* @param verbose To print the solution verbosly.
*/
public Function(String canidate, boolean verbose, DecimalGenerator generator) {
dcmlControl = generator;
this.verbose = verbose;
if(canidate.indexOf('(') != -1) {
canidate = simplifyInner(canidate);
}
if(!isFunction(canidate)) {
throw new IllegalArgumentException(canidate + " is invalid or contains invalid characters");
}
parseTerms(canidate);
}
private void setOperators(Operator[] operators) {
this.operators = operators;
}
private void parseTerms(String canidate) {
Matcher operandParser = Pattern.compile(REGEX_DECIMAL).matcher(canidate);
Matcher operatorParser = Pattern.compile(OPERATOR).matcher(canidate);
while(operandParser.find()) {
fstack.add(dcmlControl.valueOf(operandParser.group()));
if(operatorParser.find()) {
fstack.add(getMatchingOp(operatorParser.group().charAt(0)));
}
}
ArrayList<Object> tmp = (ArrayList)fstack;
tmp = (ArrayList)tmp.clone();
tmp.removeIf((x) -> x.getClass() != Operator.class);
ArrayList<Operator> toStack = (ArrayList)tmp;
toStack.sort(Operator.COMPARATOR);
ListIterator<Operator> reverseIterate = toStack.listIterator(toStack.size());
while(reverseIterate.hasPrevious()) {
opstack.push(reverseIterate.previous());
}
}
private Operator getMatchingOp(char op) {
for(Operator operator : operators) {
if(operator.symbol == op) {
return operator;
}
}
throw new IllegalArgumentException(op + " is not a valid operator");
}
/**
* Returns true if the string represents a Function.
*/
public static boolean isFunction(String canidate) {
return canidate.matches(FUNCTION_MOULD);
}
private String simplifyInner(String canidate) {
for(int i = canidate.indexOf('('); i != -1; i = canidate.indexOf('(')) {
String inner = ParenthResolver.resolveInner(i, canidate);
String soltn = new Function(inner, verbose, dcmlControl).solve().toString();
inner = "(" + inner + ")";
canidate = canidate.replace(inner, soltn);
}
return canidate;
}
/**
* Reduces the Function by one level of complexity.
*/
public boolean simplify() {
if(opstack.isEmpty()) {
return false;
}
Operator toConsume = opstack.pop();
int opIndex = fstack.indexOf(toConsume);
RoundedDecimal lHand = (RoundedDecimal)fstack.get(opIndex - 1);
RoundedDecimal rHand = (RoundedDecimal)fstack.get(opIndex + 1);
RoundedDecimal simplified = toConsume.execute(lHand, rHand);
fstack.set(opIndex - 1, simplified);
fstack.remove(rHand);
fstack.remove(toConsume);
return true;
}
/**
* Returns the solution of this function.
*/
public RoundedDecimal solve() {
do {
if(verbose) {
System.out.println(toString());
}
} while(simplify());
return (RoundedDecimal)(fstack.get(0));
}
/**
* Returns a string representing the current state of this Function.
*/
@Override
public String toString() {
String ret = new String();
for(Object term : fstack) {
ret = ret.concat(term.toString());
}
return ret;
}
}
<file_sep>package qcalc;
@FunctionalInterface
public interface Procedure {
/**
* Runs a method that is accepts no value and returns no value.
*/
void run();
}
<file_sep>package plugin;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.lang.IllegalArgumentException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import utility.ParenthResolver;
public final class UserDef implements UserPlugin {
private static String UDEF_PATH;
private static final ArrayList<String> definitions = new ArrayList<String>();
private static final String PARAM = "(?<params>(\\p{Alpha}++,\\s)*+\\p{Alpha}++)";
private static final String HEADER = "(?<methodName>\\p{Alpha}++)\\(" + PARAM + "\\)\\s";
private static final String LAMDA = "\\-\\>\\s";
private static final String BLUEPRINTF = HEADER + LAMDA + "(?<function>.++)";
private static final String CONSTANT_HEADER = "^(?<constName>\\p{Upper}++)\\s";
private static final String BLUEPRINTC = CONSTANT_HEADER + LAMDA + "(?<value>.++)";
private static Pattern VALIDATEF = Pattern.compile(BLUEPRINTF);
private static Pattern VALIDATEC = Pattern.compile(BLUEPRINTC);
static {
BufferedReader readIn = null;
try {
String path = UserDef.class.getProtectionDomain().getCodeSource()
.getLocation().toURI().getPath();
path = path.substring(0, path.lastIndexOf(System.getProperty("file.separator").charAt(0)));
path += "/udefs.clc";
UDEF_PATH = path;
readIn = new BufferedReader(new FileReader(path));
readIn.lines().forEach(definitions::add);
} catch(Exception e) {
;
} finally {
close(readIn);
if(UDEF_PATH == null) {
throw new java.lang.RuntimeException("path loading failed!!!");
}
}
}
private static void close(BufferedReader reader) {
if(reader == null) {
return;
}
try {
reader.close();
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* Writes a user defined function to the plugin script.
*/
@Override
public void writeDefinition(String canidate) {
Matcher checkF = VALIDATEF.matcher(canidate);
Matcher checkC = VALIDATEC.matcher(canidate);
if(checkF.matches() || checkC.matches()) {
try(PrintWriter writer = new PrintWriter(new FileWriter(UDEF_PATH, true), true)) {
writer.println(canidate);
} catch(Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Regex user function mould failed!!!\t" + canidate);
}
}
/**
* Returns true if the function appears to contain a user definiton.
*/
@Override
public boolean hasDefinition(String udef) {
Matcher defParser = Pattern.compile("\\p{Alpha}++").matcher(udef);
return defParser.find();
}
private String getDefName(String header) {
Pattern methodName = Pattern.compile("\\p{Alpha}++");
Matcher findLName = methodName.matcher(header);
String lName;
if(findLName.find()) {
lName = findLName.group();
} else {
throw new IllegalArgumentException("invalid def name in " + header);
}
return lName;
}
/**
* Reduces to the definition to the series of operations that makes it up.
*
* @return actual The constituent string of operands and operators.
*/
@Override
public String mapToActual(String udef) {
if(!hasDefinition(udef)) {
return udef;
}
String prototype = getMatching(udef);
if(prototype == null) {
throw new IllegalArgumentException("Unrecognized definition:" + getDefName(udef));
}
Matcher getConst = Pattern.compile(BLUEPRINTC).matcher(prototype);
if(getConst.matches()) {
String name = getDefName(udef);
return mapToActual(udef.replaceAll(name, getConst.group("value")));
}
String localParams = getParams(udef);
Scanner localParser = new Scanner(localParams);
localParser.useDelimiter(",\\s");
String remoteParams = getParams(prototype);
Scanner remoteParser = new Scanner(remoteParams);
remoteParser.useDelimiter(",\\s");
Matcher getFunc = Pattern.compile(BLUEPRINTF).matcher(prototype);
getFunc.matches();
String function = getFunc.group("function");
while(localParser.hasNext() && remoteParser.hasNext()) {
String localParam = localParser.next();
String remoteParam = remoteParser.next();
function = function.replaceAll(remoteParam, localParam);
}
localParser.close();
remoteParser.close();
return mapToActual(function);
}
private String getMatching(String udef) {
String localName = getDefName(udef);
boolean match = false;
for(String def : definitions) {
if(def.matches(localName + ".++")) {
match = true;
}
}
if(!match) {
return null;
}
if(localName.matches(".*\\p{Upper}++(?!\\()")) {
for(String remoteC : definitions) {
if(remoteC.matches("^" + localName + ".*")) {
return remoteC;
}
}
}
int localParamCount = paramCount(udef);
for(String remoteH : definitions) {
if(remoteH.indexOf('(') == -1) {
continue;
}
int remoteParamCount = paramCount(remoteH);
String remoteName = getDefName(remoteH);
if(localParamCount == remoteParamCount && localName.equals(remoteName)) {
return remoteH;
}
}
return null;
}
private String getParams(String udef) {
String params = ParenthResolver.resolveInner(udef.indexOf('('), udef);
Scanner parser = new Scanner(params);
parser.useDelimiter(",\\s");
ArrayList<String> tmp = new ArrayList<String>();
while(parser.hasNext()) {
tmp.add(parser.next());
}
parser.close();
return String.join(", ", tmp);
}
private int paramCount(String header) {
String params = ParenthResolver.resolveInner(header.indexOf('('), header);
Scanner parser = new Scanner(params);
parser.useDelimiter(",\\s");
int i = 0;
while(parser.hasNext()) {
i++;
parser.next();
}
parser.close();
return i;
}
/**
* Returns a list of all user definitions.
*/
public List<String> getDefinitions() {
return definitions;
}
/**
* Removes the specified user definition.
*/
public void removeDefinition(int line) {
definitions.remove(line);
try(PrintWriter writer = new PrintWriter(new FileWriter(UDEF_PATH, false), true)) {
definitions.forEach(writer::println);
} catch(Exception e) {
e.printStackTrace();
}
}
}
<file_sep># qcalc
A Java TUI calculator.
Qcalc is a TUI calculator with a friendly user interface and custom definition support. It takes flags and a function as arguments,
and outputs the result. Qcalc is licensed under the MIT license. See [LICENSE](/LICENSE) for more details. For pre-built releases, look [here](https://github.com/paroxayte/qcalc/releases). For detailed documentation check the [docs page](https://paroxayte.github.io/qcalc/).
<br />
<br />
**syntax:** [optional flags] "function". Eg `qcalc -v "sqrt(5^2+8^2)"`
**supported flags:**
- -v Verbose. Prints out each state change of the function as it is being solved.
- -D Define. Defines a function which can be used in functions.
**Syntax:** -D "funcName(arbitary, number, ofparams) -> arbitary*number*ofparams"
- -h Help. Prints the manual.
- -l List. Lists all user definitions.
- -rm Remove. Removes the definition contained on a given line. Use -l to get the line number. **Syntax:** -rm lineNumber.
eg `qcalc -rm 2`
- -p Precision. Species the maximum number of significant figures to display in the solution. Rounds half up. Default 16. **Special Note** `-p 0` will set the precison to **infinity** for some operations such as division. However this will cause an error if the value cannot be dispalyed precicely. `-p 0` may behave unpredictably on operations such as pow. *Use with caution.*
The plugin script is saved in the directory the jar is placed in.
<br />
**Build command:** `mvn install`
<br />
**Installation(linux, mac, chromeos, unix-like):**
- `chmod +x qcalc`
- move somewhere on your PATH or use softlink. Eg `mv ./qcalc /usr/local/lib/qcalc/` `ln -s /usr/local/lib/qcalc/qcalc /usr/local/bin`
# screenshots


<file_sep>package main;
import java.lang.Integer;
import java.util.List;
import java.util.Optional;
import plugin.UserDef;
import plugin.UserPlugin;
import precisemath.DecimalGenerator.RoundedDecimal;
import qcalc.Calculator;
import qcalc.Flag;
public class Main {
/**
* Creates and configures a calculator for users to interact with.
*/
public static void main(String[] args) {
if(args.length == 0) {
printHelp();
}
//set up calculator**********************************************
Calculator calc = new Calculator(new UserDef());
UserPlugin plugin = calc.getPlugin();
calc.addFlag(new Flag("v", () -> calc.setVerbosity(true)));
calc.addFlag(new Flag("D", () -> {
int paramIndex = calc.getArgs().indexOf("-D") + 1;
String param = calc.getArgs().get(paramIndex);
plugin.writeDefinition(param);
calc.getArgs().remove(paramIndex);
}));
calc.addFlag(new Flag("l", () -> {
List<String> lines = plugin.getDefinitions();
for(int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
System.out.println(i + ": " + line);
}
}));
calc.addFlag(new Flag("rm", () -> {
int paramIndex = calc.getArgs().indexOf("-rm") + 1;
String param = calc.getArgs().get(paramIndex);
plugin.removeDefinition(new Integer(param));
calc.getArgs().remove(paramIndex);
}));
calc.addFlag(new Flag("p", () -> {
int paramIndex = calc.getArgs().indexOf("-p") + 1;
String param = calc.getArgs().get(paramIndex);
calc.setMaxFig(new Integer(param));
calc.getArgs().remove(paramIndex);
}));
calc.addFlag(new Flag("h", () -> printHelp()));
//*****************************************************************
Optional<RoundedDecimal> soltn = calc.proccess(args);
soltn.ifPresent((x) -> System.out.println(x));
}
/**
* Prints a help man.
*/
private static void printHelp() {
int col2 = 24;
printRow("-D [@param]",
"Define. The Definition to be used. Format: "
+ "\"funcName(params, go, here) -> params*go*here\"", col2);
printRow("-h", "Help. Print help menu.", col2);
printRow("-l", "List. Lists all user definitions.", col2);
printRow("-p [@param]", "Precision. The integer qauntity of sig figs to display.", col2);
printRow("-rm [@param]", "Remove. Remove the user definition # specifcied", col2);
printRow("-v", "Verbose. Preforms operations verbosely.", col2);
System.exit(0);
}
/**
* Normalizes table style tui printing.
*/
private static void printRow(String flag, String msg, int colStart) {
String toPrint = flag;
toPrint = flag + new String(new char[colStart - flag.length()]).replace("\0", " ");
toPrint += msg;
System.out.println(toPrint);
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>qcalc</groupId>
<artifactId>qcalc</artifactId>
<version>1.1-beta</version>
<packaging>jar</packaging>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.google.code.findbugs/jsr305 -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>com.github.paroxayte</groupId>
<artifactId>PreciseMath</artifactId>
<version>v1.0</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<checkstyle.config.location>checkstyle-checker.xml</checkstyle.config.location>
</properties>
<build>
<finalName>qcalc</finalName>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>${basedir}</directory>
<includes>
<include>LICENSE</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifest>
<mainClass>main.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<reportOutputDirectory>docs/</reportOutputDirectory>
<failOnError>false</failOnError>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.0.0</version>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>8.8</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>checkstyle</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
<configuration>
<failOnViolation>true</failOnViolation>
</configuration>
</execution>
</executions>
<configuration>
<configLocation>checkstyle-checker.xml</configLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>false</failsOnError>
<linkXRef>false</linkXRef>
<violationSeverity>warning</violationSeverity>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<configuration>
<tasks>
<exec executable="./appendJar.sh">
</exec>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project><file_sep>package function;
import java.util.Comparator;
import java.util.function.BiFunction;
import precisemath.DecimalGenerator.RoundedDecimal;
public class Operator {
/**
* The symbol which represents this Operator.
*/
public final char symbol;
/**
* The priority of this operator. (0-inf). 0 is the greatest priority.
*/
private final int priority;
private final BiFunction<RoundedDecimal, RoundedDecimal, RoundedDecimal> operation;
/**
* Allows for Operators to be sorted by their priority.
*/
public static final Comparator<Operator> COMPARATOR = new Comparator<Operator>() {
public int compare(Operator thisOp, Operator thatOp) {
int delta = thisOp.priority - thatOp.priority;
if(delta == 0) {
return 0;
} else {
return delta > 0 ? 1 : -1;
}
}
};
/**
* The constructor for Operator instances.
*
* @param symbol The character representation of the operator.
* @param priority The priority of the operator.
* @param operation The operation to be carried about by Operation.execute().
*/
Operator(char symbol, int priority, BiFunction<RoundedDecimal, RoundedDecimal,
RoundedDecimal> operation) {
this.priority = priority;
this.symbol = symbol;
this.operation = operation;
}
/**
* Returns the RoundedDecimal value of the operation represented by this operator.
*/
public RoundedDecimal execute(RoundedDecimal lOperand, RoundedDecimal rOperand) {
return operation.apply(lOperand, rOperand);
}
/**
* Returns the symbol representation of this operator.
*/
public String toString() {
return new String(new char[] {symbol});
}
}
<file_sep>package qcalc;
import function.Function;
import java.lang.IllegalArgumentException;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import plugin.UserPlugin;
import precisemath.DecimalGenerator;
import precisemath.DecimalGenerator.RoundedDecimal;
/**
* Calculates a <code>function</code>.
*/
public class Calculator {
private List<Flag> flags;
private UserPlugin udef;
private List<String> args;
private boolean verbose = false;
private int maxFig = 16;
/**
* The constructor for this calculator object.
*/
public Calculator(UserPlugin plugin) {
udef = plugin;
}
/**
* Adds flags to be executed before function is processed.
*/
public void addFlag(Flag newFlag) {
if(!Optional.ofNullable(flags).isPresent()) {
flags = new ArrayList<Flag>();
}
for(Flag defined : flags) {
if(defined.name.equals(newFlag.name)) {
throw new IllegalArgumentException(defined.name + " cannot be defined twice");
}
}
flags.add(newFlag);
}
private void consumeFlag(Flag flag) {
flag.execute();
}
/**
* Processes the input. Prints the solution to the function if any was passed.
*/
public Optional<RoundedDecimal> proccess(String[] tmp) {
args = new ArrayList<String>(Arrays.asList(tmp));
List<Flag> detected = flags.stream().filter((flag) -> args.contains(flag.name))
.collect(Collectors.toList());
detected.forEach(this::consumeFlag);
detected.forEach((x) -> args.remove(x.toString()));
if(args.isEmpty()) {
return Optional.empty();
}
String finalArg = args.get(args.size() - 1);
if(Function.isFunction(finalArg) || udef.hasDefinition(finalArg)) {
String rawFunction = udef.mapToActual(finalArg);
return Optional.of(new Function(rawFunction, verbose,
new DecimalGenerator(new MathContext(maxFig, RoundingMode.HALF_UP))).solve());
}
throw new IllegalArgumentException("unable to proccess " + finalArg);
}
public UserPlugin getPlugin() {
return udef;
}
public void setVerbosity(boolean verbose) {
this.verbose = verbose;
}
public List<String> getArgs() {
return args;
}
public void setMaxFig(int max) {
maxFig = max;
}
public int getMaxFig() {
return maxFig;
}
}
<file_sep>#!/bin/bash
cat ./stubMould ./target/qcalc-jar-with-dependencies.jar > ./target/qcalc && chmod +x ./target/qcalc
|
a59aba6eae48e70f54425e4ca5a201c6278dc3c1
|
[
"Markdown",
"Java",
"Maven POM",
"Shell"
] | 9 |
Java
|
paroxayte/qcalc
|
1679babaaea9f244cd739e604b3f93b3dd01d268
|
53fc271850a3904e7e1618878dbddb987a9010a6
|
refs/heads/master
|
<file_sep># byrestrepo
Portfolio
<file_sep>// Sliders
var testimonials = {};
testimonials.slider = (function(){
var currentItemIndex = 0,
prevBtn = $('.prev-testimonial'),
nextBtn = $('.next-testimonial'),
items = (function(){
var items = [];
$('.testimonial').each(function(){
items.push($(this));
});
return items;
})();
function getCurrent(){
$('.testimonial').each(function(index){
$(this).removeClass('current');
});
$('.testimonial').eq(currentItemIndex).addClass('current');
}
function greyOut(prevBtn, nextBtn){
if($(prevBtn).hasClass('grey-out')){
$(prevBtn).removeClass('grey-out');
}
if($(nextBtn).hasClass('grey-out')){
$(nextBtn).removeClass('grey-out');
}
if(currentItemIndex == 0){
$(prevBtn).addClass('grey-out');
}
if(currentItemIndex == items.length -1){
$(nextBtn).addClass('grey-out');
}
}
return{
init: function(prevBtn, nextBtn){
items[currentItemIndex].addClass('current');
greyOut(prevBtn, nextBtn);
$(prevBtn).click(function(){
if(currentItemIndex > 0){
currentItemIndex--;
}
getCurrent();
greyOut(prevBtn, nextBtn);
});
$(nextBtn).click(function(){
if(currentItemIndex < items.length - 1){
currentItemIndex++;
}
getCurrent();
greyOut(prevBtn, nextBtn);
});
}
};
})();
/*
By <NAME>, www.osvaldas.info
Available for use under the MIT License
*/
;( function( $, window, document, undefined )
{
'use strict';
var cssTransitionSupport = function()
{
var s = document.body || document.documentElement, s = s.style;
if( s.WebkitTransition == '' ) return '-webkit-';
if( s.MozTransition == '' ) return '-moz-';
if( s.OTransition == '' ) return '-o-';
if( s.transition == '' ) return '';
return false;
},
isCssTransitionSupport = cssTransitionSupport() === false ? false : true,
cssTransitionTranslateX = function( element, positionX, speed )
{
var options = {}, prefix = cssTransitionSupport();
options[ prefix + 'transform' ] = 'translateX(' + positionX + ')';
options[ prefix + 'transition' ] = prefix + 'transform ' + speed + 's linear';
element.css( options );
},
hasTouch = ( 'ontouchstart' in window ),
hasPointers = window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
wasTouched = function( event )
{
if( hasTouch )
return true;
if( !hasPointers || typeof event === 'undefined' || typeof event.pointerType === 'undefined' )
return false;
if( typeof event.MSPOINTER_TYPE_MOUSE !== 'undefined' )
{
if( event.MSPOINTER_TYPE_MOUSE != event.pointerType )
return true;
}
else
if( event.pointerType != 'mouse' )
return true;
return false;
};
$.fn.imageLightbox = function( options )
{
var options = $.extend(
{
selector: 'id="imagelightbox"',
animationSpeed: 250,
preloadNext: true,
enableKeyboard: true,
quitOnEnd: false,
quitOnImgClick: false,
quitOnDocClick: true,
onStart: false,
onEnd: false,
onLoadStart: false,
onLoadEnd: false
},
options ),
targets = $([]),
target = $(),
image = $(),
imageWidth = 0,
imageHeight = 0,
swipeDiff = 0,
inProgress = false,
setImage = function()
{
if( !image.length ) return true;
var screenWidth = $( window ).width() * 0.8,
screenHeight = $( window ).height() * 0.9,
tmpImage = new Image();
tmpImage.src = image.attr( 'src' );
tmpImage.onload = function()
{
imageWidth = tmpImage.width;
imageHeight = tmpImage.height;
if( imageWidth > screenWidth || imageHeight > screenHeight )
{
var ratio = imageWidth / imageHeight > screenWidth / screenHeight ? imageWidth / screenWidth : imageHeight / screenHeight;
imageWidth /= ratio;
imageHeight /= ratio;
}
image.css(
{
'width': imageWidth + 'px',
'height': imageHeight + 'px',
'top': ( $( window ).height() - imageHeight ) / 2 + 'px',
'left': ( $( window ).width() - imageWidth ) / 2 + 'px'
});
};
},
loadImage = function( direction )
{
if( inProgress ) return false;
direction = typeof direction === 'undefined' ? false : direction == 'left' ? 1 : -1;
if( image.length )
{
if( direction !== false && ( targets.length < 2 || ( options.quitOnEnd === true && ( ( direction === -1 && targets.index( target ) == 0 ) || ( direction === 1 && targets.index( target ) == targets.length - 1 ) ) ) ) )
{
quitLightbox();
return false;
}
var params = { 'opacity': 0 };
if( isCssTransitionSupport ) cssTransitionTranslateX( image, ( 100 * direction ) - swipeDiff + 'px', options.animationSpeed / 1000 );
else params.left = parseInt( image.css( 'left' ) ) + 100 * direction + 'px';
image.animate( params, options.animationSpeed, function(){ removeImage(); });
swipeDiff = 0;
}
inProgress = true;
if( options.onLoadStart !== false ) options.onLoadStart();
setTimeout( function()
{
image = $( '<img ' + options.selector + ' />' )
.attr( 'src', target.attr( 'href' ) )
.on( 'load', function()
{
image.appendTo( 'body' );
setImage();
var params = { 'opacity': 1 };
image.css( 'opacity', 0 );
if( isCssTransitionSupport )
{
cssTransitionTranslateX( image, -100 * direction + 'px', 0 );
setTimeout( function(){ cssTransitionTranslateX( image, 0 + 'px', options.animationSpeed / 1000 ) }, 50 );
}
else
{
var imagePosLeft = parseInt( image.css( 'left' ) );
params.left = imagePosLeft + 'px';
image.css( 'left', imagePosLeft - 100 * direction + 'px' );
}
image.animate( params, options.animationSpeed, function()
{
inProgress = false;
if( options.onLoadEnd !== false ) options.onLoadEnd();
});
if( options.preloadNext )
{
var nextTarget = targets.eq( targets.index( target ) + 1 );
if( !nextTarget.length ) nextTarget = targets.eq( 0 );
$( '<img />' ).attr( 'src', nextTarget.attr( 'href' ) );
}
})
.on( 'error', function()
{
if( options.onLoadEnd !== false ) options.onLoadEnd();
});
var swipeStart = 0,
swipeEnd = 0,
imagePosLeft = 0;
image.on( hasPointers ? 'pointerup MSPointerUp' : 'click', function( e )
{
e.preventDefault();
if( options.quitOnImgClick )
{
quitLightbox();
return false;
}
if( wasTouched( e.originalEvent ) ) return true;
var posX = ( e.pageX || e.originalEvent.pageX ) - e.target.offsetLeft;
target = targets.eq( targets.index( target ) - ( imageWidth / 2 > posX ? 1 : -1 ) );
if( !target.length ) target = targets.eq( imageWidth / 2 > posX ? targets.length : 0 );
loadImage( imageWidth / 2 > posX ? 'left' : 'right' );
})
.on( 'touchstart pointerdown MSPointerDown', function( e )
{
if( !wasTouched( e.originalEvent ) || options.quitOnImgClick ) return true;
if( isCssTransitionSupport ) imagePosLeft = parseInt( image.css( 'left' ) );
swipeStart = e.originalEvent.pageX || e.originalEvent.touches[ 0 ].pageX;
})
.on( 'touchmove pointermove MSPointerMove', function( e )
{
if( !wasTouched( e.originalEvent ) || options.quitOnImgClick ) return true;
e.preventDefault();
swipeEnd = e.originalEvent.pageX || e.originalEvent.touches[ 0 ].pageX;
swipeDiff = swipeStart - swipeEnd;
if( isCssTransitionSupport ) cssTransitionTranslateX( image, -swipeDiff + 'px', 0 );
else image.css( 'left', imagePosLeft - swipeDiff + 'px' );
})
.on( 'touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel', function( e )
{
if( !wasTouched( e.originalEvent ) || options.quitOnImgClick ) return true;
if( Math.abs( swipeDiff ) > 50 )
{
target = targets.eq( targets.index( target ) - ( swipeDiff < 0 ? 1 : -1 ) );
if( !target.length ) target = targets.eq( swipeDiff < 0 ? targets.length : 0 );
loadImage( swipeDiff > 0 ? 'right' : 'left' );
}
else
{
if( isCssTransitionSupport ) cssTransitionTranslateX( image, 0 + 'px', options.animationSpeed / 1000 );
else image.animate({ 'left': imagePosLeft + 'px' }, options.animationSpeed / 2 );
}
});
}, options.animationSpeed + 100 );
},
removeImage = function()
{
if( !image.length ) return false;
image.remove();
image = $();
},
quitLightbox = function()
{
if( !image.length ) return false;
image.animate({ 'opacity': 0 }, options.animationSpeed, function()
{
removeImage();
inProgress = false;
if( options.onEnd !== false ) options.onEnd();
});
},
addTargets = function( newTargets )
{
newTargets.each( function()
{
targets = targets.add( $( this ) );
});
newTargets.on( 'click.imageLightbox', function( e )
{
e.preventDefault();
if( inProgress ) return false;
inProgress = false;
if( options.onStart !== false ) options.onStart();
target = $( this );
loadImage();
});
};
$( window ).on( 'resize', setImage );
if( options.quitOnDocClick )
{
$( document ).on( hasTouch ? 'touchend' : 'click', function( e )
{
if( image.length && !$( e.target ).is( image ) ) quitLightbox();
});
}
if( options.enableKeyboard )
{
$( document ).on( 'keyup', function( e )
{
if( !image.length ) return true;
e.preventDefault();
if( e.keyCode == 27 ) quitLightbox();
if( e.keyCode == 37 || e.keyCode == 39 )
{
target = targets.eq( targets.index( target ) - ( e.keyCode == 37 ? 1 : -1 ) );
if( !target.length ) target = targets.eq( e.keyCode == 37 ? targets.length : 0 );
loadImage( e.keyCode == 37 ? 'left' : 'right' );
}
});
}
addTargets( $( this ) );
this.switchImageLightbox = function( index )
{
var tmpTarget = targets.eq( index );
if( tmpTarget.length )
{
var currentIndex = targets.index( target );
target = tmpTarget;
loadImage( index < currentIndex ? 'left' : 'right' );
}
return this;
};
this.addToImageLightbox = function( newTargets )
{
addTargets( newTargets );
};
this.quitImageLightbox = function()
{
quitLightbox();
return this;
};
return this;
};
})( jQuery, window, document );
/*!
hey, [be]Lazy.js - v1.6.2 - 2016.05.09
A fast, small and dependency free lazy load script (https://github.com/dinbror/blazy)
(c) <NAME> - @bklinggaard - http://dinbror.dk/blazy
*/
;
(function(root, blazy) {
if (typeof define === 'function' && define.amd) {
// AMD. Register bLazy as an anonymous module
define(blazy);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = blazy();
} else {
// Browser globals. Register bLazy on window
root.Blazy = blazy();
}
})(this, function() {
'use strict';
//private vars
var _source, _viewport, _isRetina, _attrSrc = 'src',
_attrSrcset = 'srcset';
// constructor
return function Blazy(options) {
//IE7- fallback for missing querySelectorAll support
if (!document.querySelectorAll) {
var s = document.createStyleSheet();
document.querySelectorAll = function(r, c, i, j, a) {
a = document.all, c = [], r = r.replace(/\[for\b/gi, '[htmlFor').split(',');
for (i = r.length; i--;) {
s.addRule(r[i], 'k:v');
for (j = a.length; j--;) a[j].currentStyle.k && c.push(a[j]);
s.removeRule(0);
}
return c;
};
}
//options and helper vars
var scope = this;
var util = scope._util = {};
util.elements = [];
util.destroyed = true;
scope.options = options || {};
scope.options.error = scope.options.error || false;
scope.options.offset = scope.options.offset || 100;
scope.options.success = scope.options.success || false;
scope.options.selector = scope.options.selector || '.b-lazy';
scope.options.separator = scope.options.separator || '|';
scope.options.container = scope.options.container ? document.querySelectorAll(scope.options.container) : false;
scope.options.errorClass = scope.options.errorClass || 'b-error';
scope.options.breakpoints = scope.options.breakpoints || false; // obsolete
scope.options.loadInvisible = scope.options.loadInvisible || false;
scope.options.successClass = scope.options.successClass || 'b-loaded';
scope.options.validateDelay = scope.options.validateDelay || 25;
scope.options.saveViewportOffsetDelay = scope.options.saveViewportOffsetDelay || 50;
scope.options.srcset = scope.options.srcset || 'data-srcset';
scope.options.src = _source = scope.options.src || 'data-src';
_isRetina = window.devicePixelRatio > 1;
_viewport = {};
_viewport.top = 0 - scope.options.offset;
_viewport.left = 0 - scope.options.offset;
/* public functions
************************************/
scope.revalidate = function() {
initialize(this);
};
scope.load = function(elements, force) {
var opt = this.options;
if (elements.length === undefined) {
loadElement(elements, force, opt);
} else {
each(elements, function(element) {
loadElement(element, force, opt);
});
}
};
scope.destroy = function() {
var self = this;
var util = self._util;
if (self.options.container) {
each(self.options.container, function(object) {
unbindEvent(object, 'scroll', util.validateT);
});
}
unbindEvent(window, 'scroll', util.validateT);
unbindEvent(window, 'resize', util.validateT);
unbindEvent(window, 'resize', util.saveViewportOffsetT);
util.count = 0;
util.elements.length = 0;
util.destroyed = true;
};
//throttle, ensures that we don't call the functions too often
util.validateT = throttle(function() {
validate(scope);
}, scope.options.validateDelay, scope);
util.saveViewportOffsetT = throttle(function() {
saveViewportOffset(scope.options.offset);
}, scope.options.saveViewportOffsetDelay, scope);
saveViewportOffset(scope.options.offset);
//handle multi-served image src (obsolete)
each(scope.options.breakpoints, function(object) {
if (object.width >= window.screen.width) {
_source = object.src;
return false;
}
});
// start lazy load
setTimeout(function() {
initialize(scope);
}); // "dom ready" fix
};
/* Private helper functions
************************************/
function initialize(self) {
var util = self._util;
// First we create an array of elements to lazy load
util.elements = toArray(self.options.selector);
util.count = util.elements.length;
// Then we bind resize and scroll events if not already binded
if (util.destroyed) {
util.destroyed = false;
if (self.options.container) {
each(self.options.container, function(object) {
bindEvent(object, 'scroll', util.validateT);
});
}
bindEvent(window, 'resize', util.saveViewportOffsetT);
bindEvent(window, 'resize', util.validateT);
bindEvent(window, 'scroll', util.validateT);
}
// And finally, we start to lazy load.
validate(self);
}
function validate(self) {
var util = self._util;
for (var i = 0; i < util.count; i++) {
var element = util.elements[i];
if (elementInView(element) || hasClass(element, self.options.successClass)) {
self.load(element);
util.elements.splice(i, 1);
util.count--;
i--;
}
}
if (util.count === 0) {
self.destroy();
}
}
function elementInView(ele) {
var rect = ele.getBoundingClientRect();
return (
// Intersection
rect.right >= _viewport.left && rect.bottom >= _viewport.top && rect.left <= _viewport.right && rect.top <= _viewport.bottom
);
}
function loadElement(ele, force, options) {
// if element is visible, not loaded or forced
if (!hasClass(ele, options.successClass) && (force || options.loadInvisible || (ele.offsetWidth > 0 && ele.offsetHeight > 0))) {
var dataSrc = ele.getAttribute(_source) || ele.getAttribute(options.src); // fallback to default 'data-src'
if (dataSrc) {
var dataSrcSplitted = dataSrc.split(options.separator);
var src = dataSrcSplitted[_isRetina && dataSrcSplitted.length > 1 ? 1 : 0];
var isImage = equal(ele, 'img');
// Image or background image
if (isImage || ele.src === undefined) {
var img = new Image();
// using EventListener instead of onerror and onload
// due to bug introduced in chrome v50
// (https://productforums.google.com/forum/#!topic/chrome/p51Lk7vnP2o)
var onErrorHandler = function() {
if (options.error) options.error(ele, "invalid");
addClass(ele, options.errorClass);
unbindEvent(img, 'error', onErrorHandler);
unbindEvent(img, 'load', onLoadHandler);
};
var onLoadHandler = function() {
// Is element an image
if (isImage) {
setSrc(ele, src); //src
handleSource(ele, _attrSrcset, options.srcset); //srcset
//picture element
var parent = ele.parentNode;
if (parent && equal(parent, 'picture')) {
each(parent.getElementsByTagName('source'), function(source) {
handleSource(source, _attrSrcset, options.srcset);
});
}
// or background-image
} else {
ele.style.backgroundImage = 'url("' + src + '")';
}
itemLoaded(ele, options);
unbindEvent(img, 'load', onLoadHandler);
unbindEvent(img, 'error', onErrorHandler);
};
bindEvent(img, 'error', onErrorHandler);
bindEvent(img, 'load', onLoadHandler);
setSrc(img, src); //preload
} else { // An item with src like iframe, unity, simpelvideo etc
setSrc(ele, src);
itemLoaded(ele, options);
}
} else {
// video with child source
if (equal(ele, 'video')) {
each(ele.getElementsByTagName('source'), function(source) {
handleSource(source, _attrSrc, options.src);
});
ele.load();
itemLoaded(ele, options);
} else {
if (options.error) options.error(ele, "missing");
addClass(ele, options.errorClass);
}
}
}
}
function itemLoaded(ele, options) {
addClass(ele, options.successClass);
if (options.success) options.success(ele);
// cleanup markup, remove data source attributes
ele.removeAttribute(options.src);
each(options.breakpoints, function(object) {
ele.removeAttribute(object.src);
});
}
function setSrc(ele, src) {
ele[_attrSrc] = src;
}
function handleSource(ele, attr, dataAttr) {
var dataSrc = ele.getAttribute(dataAttr);
if (dataSrc) {
ele[attr] = dataSrc;
ele.removeAttribute(dataAttr);
}
}
function equal(ele, str) {
return ele.nodeName.toLowerCase() === str;
}
function hasClass(ele, className) {
return (' ' + ele.className + ' ').indexOf(' ' + className + ' ') !== -1;
}
function addClass(ele, className) {
if (!hasClass(ele, className)) {
ele.className += ' ' + className;
}
}
function toArray(selector) {
var array = [];
var nodelist = document.querySelectorAll(selector);
for (var i = nodelist.length; i--; array.unshift(nodelist[i])) {}
return array;
}
function saveViewportOffset(offset) {
_viewport.bottom = (window.innerHeight || document.documentElement.clientHeight) + offset;
_viewport.right = (window.innerWidth || document.documentElement.clientWidth) + offset;
}
function bindEvent(ele, type, fn) {
if (ele.attachEvent) {
ele.attachEvent && ele.attachEvent('on' + type, fn);
} else {
ele.addEventListener(type, fn, false);
}
}
function unbindEvent(ele, type, fn) {
if (ele.detachEvent) {
ele.detachEvent && ele.detachEvent('on' + type, fn);
} else {
ele.removeEventListener(type, fn, false);
}
}
function each(object, fn) {
if (object && fn) {
var l = object.length;
for (var i = 0; i < l && fn(object[i], i) !== false; i++) {}
}
}
function throttle(fn, minDelay, scope) {
var lastCall = 0;
return function() {
var now = +new Date();
if (now - lastCall < minDelay) {
return;
}
lastCall = now;
fn.apply(scope, arguments);
};
}
});
|
ac84d9e41d4cc58bb34e0ab060b361d4206ce5bf
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
byrestrepo/byrestrepo.github.io
|
0c2d622d676e0f5f64ebfe763429781ac0770b87
|
86411f06b3ba87ade7980cee7355dd394083e580
|
refs/heads/master
|
<repo_name>rr-/imgdup<file_sep>/README.md
imgdup
======
A command-line utility that allows you to discover visually similar images.
Features:
- Hash caching for speeding up the hash computation
- Manipulationg duplicate detection threshold to detect more or fewer pictures
- `stdin` integration
How it works
------------
- For each image:
- resize the image to 16x16 pixels,
- convert the image to grayscale,
- compute the average brightness,
- start creating hash H.
- For each pixel in the image:
- append 1 to H if the pixel is above average, 0 otherwise.
- For each pair of hashes H1 and H2:
- compute Hamming distance between them
- if the distance is below threshold, it means the images are most probably
visually similar.
Dependencies
------------
- GraphicsMagick++
- boost
Licensing
---------
Please see file named `LICENSE.md`.
<file_sep>/src/BaseApplication.cpp
#include <algorithm>
#include <iostream>
#include <thread>
#include <vector>
#include "BaseApplication.h"
#include "Worker.h"
BaseApplication::BaseApplication(const UserInput &_user_input)
: user_input(_user_input), hash_cache(nullptr)
{
if (user_input.cache_path != "")
hash_cache = new HashCache(user_input.cache_path, file_hashes);
}
int BaseApplication::run()
{
switch (user_input.action)
{
case ProgramAction::RUN:
load_hash_cache_if_needed();
search_for_files();
if (file_list.size() == 0)
{
std::cerr << "No files supplied." << std::endl;
return 1;
}
compute_hashes();
search_for_duplicates();
save_hash_cache_if_needed();
return 0;
case ProgramAction::HELP:
show_help();
return 0;
}
throw std::runtime_error("Unrecognized program action");
}
void BaseApplication::show_help() const
{
std::cout << R"END(imgdup v0.1
Searches for similar images amongst specified files.
Usage: imgdup [OPTIONS] PATH1 [PATH2...]
PATH can be either a folder, or a file.
Additionally, imgdup checks in stdin for any extra PATHs to scan, so you can
pipe to it anything you want:
find . -iname '*.jpg' -type f | imgdup
Supported OPTIONS:
-h, --help
Shows this help.
-t, --threshold NUM
Sets the value of minimum difference between a pair files after which
they are no longer considered duplicates. In other words, --threshold 0
will match only perfect duplicates, while --threshold 255 will match
every pair.
Defaults to 10.
-c, --cache FILE
Sets path to cache file. Used in order to speed up hash computations when
run repetetively on similar file sets.
By default, imgdup doesn't use cache.
)END";
}
void BaseApplication::compute_hashes()
{
size_t worker_count = 4;
std::cerr << "Computing file hashes using " << worker_count << " worker threads..." << std::endl;
Worker **workers = new Worker*[worker_count];
std::mutex mutex;
std::vector<std::thread> threads;
for (size_t i = 0; i < worker_count; i ++)
{
workers[i] = new Worker(file_list, file_hashes, mutex);
threads.push_back(std::thread([&workers, i](){
workers[i]->compute_hashes();
}));
}
for (auto& thread : threads)
thread.join();
for (size_t i = 0; i < worker_count; i ++)
{
for (auto error : workers[i]->errors)
std::cerr << "Warning: " << error << std::endl;
delete workers[i];
}
delete[] workers;
}
void BaseApplication::search_for_duplicates()
{
std::cerr << "Searching for duplicates..." << std::endl;
for (auto it = file_hashes.begin(); it != file_hashes.end(); it ++)
{
auto it2 = it;
++ it2;
for (; it2 != file_hashes.end(); it2 ++)
{
auto difference = (it->second ^ it2->second).count();
if (difference > user_input.threshold)
continue;
std::cout
<< it->first << std::endl
<< it2->first << std::endl
<< "Diff: " << difference << std::endl
<< std::endl;
}
}
}
void BaseApplication::search_for_files()
{
std::cerr << "Searching for files..." << std::endl;
for (auto path : user_input.paths)
file_list.add_path(path);
}
void BaseApplication::load_hash_cache_if_needed()
{
if (hash_cache == nullptr)
return;
std::cerr << "Loading hash cache..." << std::endl;
hash_cache->load();
hash_cache->purge_non_existing();
}
void BaseApplication::save_hash_cache_if_needed()
{
if (hash_cache == nullptr)
return;
std::cerr << "Saving hash cache..." << std::endl;
hash_cache->save();
}
<file_sep>/src/Hash.h
#ifndef HASH_H_
#define HASH_H_
#include <bitset>
typedef std::bitset<256> Hash;
#endif
<file_sep>/src/imgdup.cpp
#include <Magick++.h>
#include <exception>
#include <iostream>
#include "BaseApplication.h"
int main(int argc, char **argv)
{
Magick::InitializeMagick(*argv);
try
{
UserInput user_input(argc, argv);
BaseApplication app(user_input);
return app.run();
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
return 1;
}
}
<file_sep>/src/Hasher.h
#ifndef HASHER_H_
#define HASHER_H_
#include "Hash.h"
class Hasher
{
public:
Hash get_hash(std::string path) const;
};
#endif
<file_sep>/src/ProgramAction.h
#ifndef PROGRAM_ACTION_H_
#define PROGRAM_ACTION_H_
enum class ProgramAction
{
RUN,
HELP
};
#endif
<file_sep>/src/UserInput.cpp
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <unistd.h>
#include "UserInput.h"
UserInput::UserInput(int argc, char **argv)
: threshold(10),
action(ProgramAction::RUN)
{
parse_arguments(argc, argv);
parse_stdin();
}
void UserInput::parse_arguments(int argc, char **argv)
{
for (int i = 1; i < argc; i ++)
{
auto arg = std::string(argv[i]);
if (i + 1 < argc)
{
if (arg == "-c" || arg == "--cache")
{
cache_path = argv[++ i];
continue;
}
else if (arg == "-t" || arg == "--threshold")
{
threshold = boost::lexical_cast<int>(argv[++ i]);
continue;
}
}
else
{
if (arg == "-h" || arg == "--help")
{
action = ProgramAction::HELP;
continue;
}
}
paths.push_back(argv[i]);
}
}
void UserInput::parse_stdin()
{
std::string line;
if (!isatty(STDIN_FILENO))
while (std::getline(std::cin, line))
{
paths.push_back(line);
}
}
<file_sep>/src/FileList.h
#ifndef FILE_LIST_H_
#define FILE_LIST_H_
#include <string>
#include <vector>
class FileList
{
public:
void add_path(std::string path);
size_t size() const;
void pop_back();
std::string back() const;
private:
void list_directory(std::string initial_directory);
std::vector<std::string> file_list;
};
#endif
<file_sep>/src/Worker.cpp
#include <boost/progress.hpp>
#include <iostream>
#include "Worker.h"
boost::progress_display *progress_display = nullptr;
static size_t worker_count = 0;
Worker::Worker(
FileList &_file_list,
std::map<std::string, Hash> &_file_hashes,
std::mutex &_mutex)
: file_list(_file_list),
file_hashes(_file_hashes),
mutex(_mutex),
hasher(Hasher()),
worker_number(++ worker_count)
{
if (worker_number == 1)
{
progress_display = new boost::progress_display(file_list.size(), std::cerr);
}
}
void Worker::compute_hashes()
{
mutex.lock();
mutex.unlock();
while (true)
{
std::string file_path;
mutex.lock();
if (file_list.size() == 0)
{
mutex.unlock();
break;
}
file_path = file_list.back();
file_list.pop_back();
if (progress_display != nullptr)
++ *progress_display;
if (file_hashes.find(file_path) != file_hashes.end())
{
mutex.unlock();
continue;
}
mutex.unlock();
Hash hash;
try
{
hash = hasher.get_hash(file_path);
}
catch (const std::exception &e)
{
errors.push_back(e.what());
continue;
}
mutex.lock();
file_hashes[file_path] = hash;
mutex.unlock();
}
}
<file_sep>/src/UserInput.h
#ifndef USER_INPUT_H_
#define USER_INPUT_H_
#include <string>
#include <vector>
#include "ProgramAction.h"
class UserInput
{
public:
std::string cache_path;
std::vector<std::string> paths;
size_t threshold;
ProgramAction action;
UserInput(int argc, char **argv);
private:
void parse_arguments(int argc, char **argv);
void parse_stdin();
};
#endif
<file_sep>/src/HashCache.h
#ifndef HASH_CACHE_H_
#define HASH_CACHE_H_
#include <map>
#include <string>
#include "Hash.h"
class HashCache
{
public:
HashCache(std::string path, std::map<std::string, Hash> &file_hashes);
void load();
void save() const;
void purge_non_existing();
private:
const std::string path;
std::map<std::string, Hash> &file_hashes;
};
#endif
<file_sep>/Makefile
SRCDIR := src/
OBJDIR := obj/
BINDIR := bin/
EXECUTABLE := imgdup
SOURCES := $(wildcard $(SRCDIR)/*.cpp)
CXXFLAGS := $(shell GraphicsMagick++-config --cppflags --cxxflags) -Wall --pedantic -std=c++11 -O5
LFLAGS := $(shell GraphicsMagick++-config --libs --ldflags) -lboost_filesystem -lboost_system -lboost_serialization
OBJECTS := $(SOURCES:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o)
debug: CXX += -DDEBUG -g
debug: $(EXECUTABLE)
all: $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CXX) $(CXXFLAGS) $(OBJECTS) $(LFLAGS) -o $(BINDIR)/$(EXECUTABLE)
$(OBJECTS): $(OBJDIR)/%.o : $(SRCDIR)/%.cpp
$(CXX) $(CXXFLAGS) -c $< -o $@
clean:
-rm -f $(BINDIR)/*
-rm -f $(OBJDIR)/*.o
<file_sep>/src/Worker.h
#ifndef WORKER_H_
#define WORKER_H_
#include <map>
#include <mutex>
#include <string>
#include <vector>
#include "FileList.h"
#include "Hash.h"
#include "Hasher.h"
class Worker {
public:
Worker(
FileList &file_list,
std::map<std::string, Hash> &file_hashes,
std::mutex &mutex);
std::vector<std::string> errors;
void compute_hashes();
private:
FileList &file_list;
std::map<std::string, Hash> &file_hashes;
std::mutex &mutex;
const Hasher hasher;
const size_t worker_number;
};
#endif
<file_sep>/src/HashCache.cpp
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/filesystem.hpp>
#include <boost/serialization/bitset.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/serialization.hpp>
#include <fstream>
#include "HashCache.h"
HashCache::HashCache(
std::string _path,
std::map<std::string, Hash> &_file_hashes)
: path(_path), file_hashes(_file_hashes)
{
}
void HashCache::load()
{
if (boost::filesystem::exists(path))
{
std::ifstream input_file(path, std::ifstream::in | std::ofstream::binary);
boost::archive::binary_iarchive input_archive(input_file);
input_archive >> file_hashes;
input_file.close();
}
}
void HashCache::save() const
{
std::ofstream output_file(path, std::ofstream::out | std::ofstream::binary);
boost::archive::binary_oarchive output_archive(output_file);
output_archive << file_hashes;
output_file.close();
}
void HashCache::purge_non_existing()
{
auto it = file_hashes.begin();
while (it != file_hashes.end())
{
if (!boost::filesystem::exists(it->first))
{
it = file_hashes.erase(it);
}
else
{
++ it;
}
}
}
<file_sep>/src/BaseApplication.h
#ifndef BASE_APPLICATION_H_
#define BASE_APPLICATION_H_
#include "FileList.h"
#include "Hash.h"
#include "HashCache.h"
#include "UserInput.h"
class BaseApplication
{
private:
const UserInput &user_input;
HashCache *hash_cache;
FileList file_list;
std::map<std::string, Hash> file_hashes;
void load_hash_cache_if_needed();
void save_hash_cache_if_needed();
void compute_hashes();
void search_for_files();
void search_for_duplicates();
void show_help() const;
public:
BaseApplication(const UserInput &user_input);
int run();
};
#endif
<file_sep>/src/FileList.cpp
#include <boost/filesystem.hpp>
#include <set>
#include "FileList.h"
struct ci_char_comparer
: public std::binary_function<unsigned char, unsigned char, bool>
{
bool operator() (
const unsigned char &c1,
const unsigned char &c2) const
{
return tolower(c1) < tolower(c2);
}
};
struct ci_string_comparer
: std::binary_function<std::string, std::string, bool>
{
bool operator() (const std::string &s1, const std::string &s2) const
{
return std::lexicographical_compare(
s1.begin(), s1.end(),
s2.begin(), s2.end(),
ci_char_comparer());
}
};
void FileList::add_path(std::string initial_path)
{
if (!boost::filesystem::exists(initial_path))
{
std::cerr << "Warning: " << initial_path << " does not exist" << std::endl;
}
else if (boost::filesystem::is_regular_file(initial_path))
{
file_list.push_back(initial_path);
}
else
{
list_directory(initial_path);
}
}
void FileList::list_directory(std::string initial_path)
{
std::set<std::string, ci_string_comparer> extensions = {".jpg", ".gif", ".png"};
boost::filesystem::recursive_directory_iterator rdi(initial_path);
boost::filesystem::recursive_directory_iterator end_rdi;
for (; rdi != end_rdi; rdi++)
{
if (extensions.find(rdi->path().extension().string()) != extensions.end())
{
file_list.push_back(rdi->path().string());
}
}
}
size_t FileList::size() const
{
return file_list.size();
}
std::string FileList::back() const
{
return file_list.back();
}
void FileList::pop_back()
{
file_list.pop_back();
}
<file_sep>/src/Hasher.cpp
#include <Magick++.h>
#include "Hasher.h"
Hash Hasher::get_hash(std::string path) const
{
const size_t target_size = 16;
Magick::Image image;
image.read(path);
Magick::Geometry geometry = Magick::Geometry(target_size, target_size);
geometry.aspect(true);
image.scale(geometry);
const Magick::PixelPacket *pixels =
image.getConstPixels(
0,
0,
image.size().width(),
image.size().height());
const Magick::PixelPacket *source = pixels;
unsigned char monochrome[target_size * target_size];
unsigned char *target = monochrome;
float multiplier = 255.0f / (1 << QuantumDepth);
uint64_t average = 0;
for (size_t i = 0; i < target_size * target_size; i ++)
{
*target =
0.3 * source->red * multiplier +
0.59 * source->green * multiplier +
0.11 * source->blue * multiplier;
average += *target;
++ source;
++ target;
}
average /= target_size * target_size;
Hash hash = 0;
target = monochrome;
for (size_t i = 0; i < target_size * target_size; i ++)
{
hash <<= 1;
if (*target > average)
hash |= 1;
target ++;
}
return hash;
}
|
0335f378d9e916797e8a25dd347dcdadff112c41
|
[
"Markdown",
"C",
"Makefile",
"C++"
] | 17 |
Markdown
|
rr-/imgdup
|
2636f9a309cbb729655d9797715a7f39c722ea9a
|
f511ba85e749d7e4fbb1b67d201d2cd8e99567ed
|
refs/heads/master
|
<repo_name>Black13Flash/TrabajoFinal<file_sep>/src/Vistas/myFrame.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 Vistas;
/**
*
* @author Brujo
*/
public class myFrame extends javax.swing.JFrame {
/**
* Creates new form myFrame
*/
public myFrame() {
initComponents();
this.setLocationRelativeTo(null);
this.setResizable(false);
}
/**
* 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() {
myPanel = new javax.swing.JPanel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
itemInsertar = new javax.swing.JMenuItem();
menuBorrar = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
menuModificar = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
mnuBusca = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
jMenu4 = new javax.swing.JMenu();
jMenuItem6 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout myPanelLayout = new javax.swing.GroupLayout(myPanel);
myPanel.setLayout(myPanelLayout);
myPanelLayout.setHorizontalGroup(
myPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1164, Short.MAX_VALUE)
);
myPanelLayout.setVerticalGroup(
myPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 676, Short.MAX_VALUE)
);
jMenu1.setText("Insertar/Eliminar");
itemInsertar.setText("Insertar");
itemInsertar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
itemInsertarActionPerformed(evt);
}
});
jMenu1.add(itemInsertar);
menuBorrar.setText("Borrar");
menuBorrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuBorrarActionPerformed(evt);
}
});
jMenu1.add(menuBorrar);
jMenuBar1.add(jMenu1);
jMenu2.setText("Modificar");
menuModificar.setText("Modificar");
menuModificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuModificarActionPerformed(evt);
}
});
jMenu2.add(menuModificar);
jMenuBar1.add(jMenu2);
jMenu3.setText("Búsqueda");
mnuBusca.setText("Busca / Patente");
mnuBusca.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mnuBuscaActionPerformed(evt);
}
});
jMenu3.add(mnuBusca);
jMenuItem5.setText("Mostrar Todos");
jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem5ActionPerformed(evt);
}
});
jMenu3.add(jMenuItem5);
jMenuBar1.add(jMenu3);
jMenu4.setText("Edición");
jMenuItem6.setText("Salir");
jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem6ActionPerformed(evt);
}
});
jMenu4.add(jMenuItem6);
jMenuBar1.add(jMenu4);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(myPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(myPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void itemInsertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemInsertarActionPerformed
// ITEM MENU 1 : Insertar
if (venInsertar == null || venInsertar.isClosed()) {
venInsertar = new ventanaInsertar();
myPanel.add(venInsertar);
venInsertar.show();
venInsertar.focoPatente();
}else{
venInsertar.show();
venInsertar.focoPatente();
}
}//GEN-LAST:event_itemInsertarActionPerformed
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
// MOSTRAR TODO
if (venMostrarTodo == null || venMostrarTodo.isClosed()) {
venMostrarTodo = new ventanaMostrarTodo();
myPanel.add(venMostrarTodo);
venMostrarTodo.show();
}else{
venMostrarTodo.show();
}
}//GEN-LAST:event_jMenuItem5ActionPerformed
private void menuBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuBorrarActionPerformed
//BORRAR
if (venBorrar == null || venBorrar.isClosed()) {
venBorrar = new ventanaBorrar();
myPanel.add(venBorrar);
venBorrar.show();
}else{
venBorrar.show();
}
}//GEN-LAST:event_menuBorrarActionPerformed
private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
this.dispose();
}//GEN-LAST:event_jMenuItem6ActionPerformed
private void mnuBuscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuBuscaActionPerformed
if (MosUn == null || MosUn.isClosed()) {
MosUn = new MostrarUno();
myPanel.add(MosUn);
MosUn.show();
}else{
MosUn.show();
}
}//GEN-LAST:event_mnuBuscaActionPerformed
private void menuModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuModificarActionPerformed
// MODIFICAR
if (venModificar == null || venModificar.isClosed()) {
venModificar = new ventanaModificar();
myPanel.add(venModificar);
venModificar.show();
}else{
venModificar.show();
}
}//GEN-LAST:event_menuModificarActionPerformed
/**
* @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(myFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(myFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(myFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(myFrame.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 myFrame().setVisible(true);
}
});
}
ventanaInsertar venInsertar;
ventanaMostrarTodo venMostrarTodo;
ventanaBorrar venBorrar;
MostrarUno MosUn;
ventanaModificar venModificar;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem itemInsertar;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuItem menuBorrar;
private javax.swing.JMenuItem menuModificar;
private javax.swing.JMenuItem mnuBusca;
public static javax.swing.JPanel myPanel;
// End of variables declaration//GEN-END:variables
}
<file_sep>/src/Modelos/Vehiculo.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 Modelos;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author <NAME> (Brujo)
*/
public class Vehiculo {
private String Patente; // Primary KEY
private Vehiculo(String Patente, String Marca, String Modelo, String Color, int Ano, int Precio) {
}
public Vehiculo(String Patente) {
this.Patente = Patente;
}
public String getPatente() {
return Patente;
}
public void setPatente(String Patente) {
this.Patente = Patente;
}
public String getMarca() {
return Marca;
}
public void setMarca(String Marca) {
this.Marca = Marca;
}
public String getModelo() {
return Modelo;
}
public void setModelo(String Modelo) {
this.Modelo = Modelo;
}
public String getColor() {
return Color;
}
public void setColor(String Color) {
this.Color = Color;
}
public int getAno() {
return Ano;
}
public void setAno(int Ano) {
this.Ano = Ano;
}
public int getPrecio() {
return Precio;
}
public void setPrecio(int Precio) {
this.Precio = Precio;
}
public Vehiculo() {
}
// Las demas variables
private String Marca;
private String Modelo;
private String Color;
private int Ano;
private int Precio;
private Statement state; // Ejecuta la querys
private ResultSet res; // Guarda una consulta SELECT
public boolean insertaVehiculo(Vehiculo v){
Conexion con=new Conexion();
String query = "INSERT INTO Vehiculo VALUES('"+v.getPatente()+"','"
+v.getMarca()+"','"
+v.getModelo()+"','"
+v.getColor()+"','"
+v.getAno()+"','"
+v.getPrecio()
+"')";
try {
state = con.usaConexion().createStatement();
if(state.executeUpdate(query) > 0)
return true;
} catch (SQLException ex) {
Logger.getLogger(Vehiculo.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
con.cierraConexion();
}
return false;
}
public boolean eliminarVehiculo(Vehiculo v){
Conexion con=new Conexion();
String query ="DELETE FROM Vehiculo WHERE patente='"+v.getPatente()+"'";
try {
state = con.usaConexion().createStatement();
if (state.execute(query)) {
return true;
}
} catch (SQLException ex) {
Logger.getLogger(Vehiculo.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
con.cierraConexion();
}
return false;
}
// BUSCA 1
public Vehiculo buscaUno(Vehiculo v){
String query="SELECT * FROM Vehiculo WHERE Patente='"+v.getPatente()+"'";
Conexion con = new Conexion();
Vehiculo ve=null;
try {
state = con.usaConexion().createStatement();
res = state.executeQuery(query);
while(res.next()){
ve = new Vehiculo();
ve.setPatente(res.getString("Patente"));
ve.setMarca(res.getString("Marca"));
ve.setModelo(res.getString("Modelo"));
ve.setColor(res.getString("Color"));
ve.setAno(res.getInt("Ano"));
ve.setPrecio(res.getInt("Precio"));
}
} catch (SQLException ex) {
Logger.getLogger(Vehiculo.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
con.cierraConexion();
}
return ve;
}
// BUSCA TODOS
public ArrayList<Vehiculo> buscarTodos(){
String query="SELECT * FROM Vehiculo";
Conexion con = new Conexion();
ArrayList<Vehiculo> vei=null;
try {
state = con.usaConexion().createStatement();
res = state.executeQuery(query);
vei = new ArrayList<>();
while(res.next()){
Vehiculo objTemp = new Vehiculo();
objTemp.setPatente(res.getString("Patente"));
objTemp.setMarca(res.getString("Marca"));
objTemp.setModelo(res.getString("Modelo"));
objTemp.setColor(res.getString("Color"));
objTemp.setAno(res.getInt("Ano"));
objTemp.setPrecio(res.getInt("Precio"));
vei.add(objTemp);
}
return vei;
} catch (SQLException ex) {
Logger.getLogger(Vehiculo.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
con.cierraConexion();
}
return vei;
}
public boolean modificaVehiculo(Vehiculo v){
String query="UPDATE Vehiculo SET Marca='"+v.getMarca()+"' , "
+ "Modelo='"+v.getModelo()+"' , Color='"+v.getColor()+"' , "
+ "Ano='"+v.getAno()+"' , Precio='"+v.getPrecio()+"' "
+ "WHERE Patente='"+v.getPatente()+"' ";
Conexion con = new Conexion();
try {
state = con.usaConexion().createStatement();
if (state.executeUpdate(query)>0) {
return true;
}
} catch (SQLException ex) {
Logger.getLogger(Vehiculo.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
con.cierraConexion();
}
return false;
}
}
<file_sep>/nbproject/private/private.properties
compile.on.save=true
user.properties.file=/Users/Brujo/Library/Application Support/NetBeans/8.0.2/build.properties
<file_sep>/README.md
# TrabajoFinal
Proyecto : Taller de Programación 1
### Checklist Nº1
1: Crear Base de datos "TrabajoFinal" <b>[OK]</b>
2: Crear Tabla "Vehiculo" con atributos: <b>[OK]</b>
3: Crear Frame central <b>[OK]</b>
4: Crear Internal Frame "INSERTAR" <b>[OK]</b>
5: Crear Internal Frame "BORRAR"<b>[OK]</b>
6: Crear Internal Frame "MODIFICA" <b>[OK]</b>
7: Crear Internal Frame "BUSCA/PATENTE"<b>[OK]</b>
8: Crear Internal Frame "MOSTRAR TODOS" <b>[OK]</b>
9: Programar Item Menu "SALIR"<b>[OK]</b>
<file_sep>/src/Modelos/Conexion.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 Modelos;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author <NAME> (Brujo)
*/
public class Conexion {
private Connection con;
public Conexion() {
try {
String url="jdbc:mysql://localhost:3306/TrabajoFinal?zeroDateTimeBehavior=convertToNull";
Class.forName("com.mysql.jdbc.Driver"); // Driver de Conexión
con = DriverManager.getConnection(url, "admin_TrabajoFinal", ""); // URL,user,pass
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Connection usaConexion(){
return con;
}
public void cierraConexion(){
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<file_sep>/src/Vistas/MostrarUno.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 Vistas;
import Modelos.Vehiculo;
import javax.swing.JOptionPane;
/**
*
* @author G
*/
public class MostrarUno extends javax.swing.JInternalFrame {
/**
* Creates new form MostrarUno
*/
public MostrarUno() {
initComponents();
}
/**
* 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() {
lblTitulo = new javax.swing.JLabel();
txtPatente = new javax.swing.JTextField();
lblPatente = new javax.swing.JLabel();
lblMarca = new javax.swing.JLabel();
lblModelo = new javax.swing.JLabel();
lblColor = new javax.swing.JLabel();
lblAno = new javax.swing.JLabel();
lblPrecio = new javax.swing.JLabel();
lblCPatente = new javax.swing.JLabel();
lblCMarca = new javax.swing.JLabel();
lblCModelo = new javax.swing.JLabel();
lblCColor = new javax.swing.JLabel();
lblCAno = new javax.swing.JLabel();
lblCPrecio = new javax.swing.JLabel();
btnSalir = new javax.swing.JButton();
btnAceptar = new javax.swing.JButton();
setClosable(true);
setTitle("Buscar Vehiculo");
lblTitulo.setText("Ingrese Patente a buscar:");
lblPatente.setText("Patente:");
lblMarca.setText("Marca:");
lblModelo.setText("Modelo:");
lblColor.setText("Color:");
lblAno.setText("Año:");
lblPrecio.setText("Precio:");
lblCPatente.setText(" ");
lblCMarca.setText(" ");
lblCModelo.setText(" ");
lblCColor.setText(" ");
lblCAno.setText(" ");
lblCPrecio.setText(" ");
btnSalir.setText("Salir");
btnSalir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSalirActionPerformed(evt);
}
});
btnAceptar.setText("Aceptar");
btnAceptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAceptarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(111, 111, 111)
.addComponent(lblTitulo))
.addGroup(layout.createSequentialGroup()
.addGap(93, 93, 93)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblPatente)
.addComponent(lblMarca)
.addComponent(lblModelo)
.addComponent(lblColor)
.addComponent(lblAno)
.addComponent(lblPrecio)
.addComponent(btnAceptar))
.addGap(53, 53, 53)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblCPrecio)
.addComponent(lblCAno)
.addComponent(lblCColor)
.addComponent(lblCModelo)
.addComponent(lblCMarca)
.addComponent(lblCPatente)
.addComponent(btnSalir)))
.addGroup(layout.createSequentialGroup()
.addGap(125, 125, 125)
.addComponent(txtPatente, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(102, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblTitulo)
.addGap(18, 18, 18)
.addComponent(txtPatente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblPatente)
.addComponent(lblCPatente))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblMarca)
.addComponent(lblCMarca))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblModelo)
.addComponent(lblCModelo))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblColor)
.addComponent(lblCColor))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblAno)
.addComponent(lblCAno))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblPrecio)
.addComponent(lblCPrecio))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSalir)
.addComponent(btnAceptar))
.addGap(33, 33, 33))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
String patente = txtPatente.getText();
if(patente.equals("")||patente==null)
{
JOptionPane.showMessageDialog(this, "Ingrese patente");
}
else
{
Vehiculo v=new Vehiculo(patente);
Vehiculo ve=v.buscaUno(v);
if(ve==null)
{
JOptionPane.showMessageDialog(this, "Vehiculo no encontrado");
}
else
{
lblCPatente.setText(ve.getPatente());
lblCMarca.setText(ve.getMarca());
lblCModelo.setText(ve.getModelo());
lblCColor.setText(ve.getColor());
lblCAno.setText(String.valueOf(ve.getAno()));
lblCPrecio.setText(String.valueOf(ve.getPrecio()));
}
}
}//GEN-LAST:event_btnAceptarActionPerformed
private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
this.dispose();
}//GEN-LAST:event_btnSalirActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAceptar;
private javax.swing.JButton btnSalir;
private javax.swing.JLabel lblAno;
private javax.swing.JLabel lblCAno;
private javax.swing.JLabel lblCColor;
private javax.swing.JLabel lblCMarca;
private javax.swing.JLabel lblCModelo;
private javax.swing.JLabel lblCPatente;
private javax.swing.JLabel lblCPrecio;
private javax.swing.JLabel lblColor;
private javax.swing.JLabel lblMarca;
private javax.swing.JLabel lblModelo;
private javax.swing.JLabel lblPatente;
private javax.swing.JLabel lblPrecio;
private javax.swing.JLabel lblTitulo;
private javax.swing.JTextField txtPatente;
// End of variables declaration//GEN-END:variables
}
<file_sep>/TrabajoFinal.sql
create database TrabajoFinal;
use TrabajoFinal;
create table Vehiculo
(
Patente varchar(10),
Marca varchar(30),
Modelo varchar(30),
Color varchar(30),
Ano int,
Precio int,
primary key (Patente)
);
use mysql;
create user 'admin_TrabajoFinal'@'localhost' identified by '';
grant all privileges on TrabajoFinal.* to 'admin_TrabajoFinal'@'localhost';
flush privileges
|
64ad44a3ae590b3bc230b0a6c072d9c557d3d779
|
[
"Markdown",
"Java",
"SQL",
"INI"
] | 7 |
Java
|
Black13Flash/TrabajoFinal
|
2fcb014f48b095f7a2bda9e116c618e762edafad
|
31ef60dddb061555dea059a7d3899899a3792a93
|
refs/heads/master
|
<file_sep>require_relative '../spec_helper_lite'
require_relative '../../app/exhibits/animal_profile_exhibit'
describe AnimalProfileExhibit do
subject { AnimalProfileExhibit.new(->{data}) }
let(:data) {
{"Colour"=>"Yellow",
"CreatedDate"=>1333112400000,
"Gender"=>"",
"ImageUrl"=>"",
"LastSighting"=>1334277559280,
"Name"=>"CockaStu",
"Tag"=>23,
"id"=>"16"}
}
it 'initializes from a hash' do
puts data
subject.Colour.must_equal "Yellow"
#@new_exhibit = AnimalProfileExhibit.new(@data)
#@new_exhibit.Colour.must_equal "Yellow"
end
end
<file_sep>class Animal
include NoBrainer::Document
store_in :database => 'wingtags_development', :table => 'Wildlife'
has_many :observations
field :Colour, :type => String
field :Gender, :type => String
field :Name, :type => String
field :Notes, :type => String
field :Tag, :type => Integer
end
<file_sep>require 'spec_helper'
require 'pry-debugger'
describe ObservationsController, :type => :controller do
it "accepts a new observation" do
post_data = new_valid_observation
post :create, :observations => post_data, :format => :json
expect(response.status).to eq 200
end
end
private
def new_valid_observation
#post_data = Jbuilder.encode do |json|
# json.tag = "22"
# json.latitude = -33.882973359510984
# json.longitude = 151.26951911449567
# json.address = "343-345 Old South Head Road, North Bondi NSW 2026, Australia"
# json.timestamp = 1388534400000
# json.image = Tempfile.new
# json.utc_time = 1388534400000
#end
path = "#{::Rails.root}/spec/fixtures/files/ryan.png"
data = { 0 => {
tag: "47",
latitude: -33.882973359510984,
longitude: 151.26951911449567,
address: "343-345 Old South Head Road, North Bondi NSW 2026, Australia",
timestamp: 1388534400000,
image: "UUID"
}}
return data
end<file_sep>class Observation
include ActiveModel::Model
include ActiveModel::Serializers
include NoBrainer::Document
attr_accessor :id, :animal_id, :observer_id, :images, :latitude, :longitude, :address, :notes, :timestamp
validates_presence_of :id, :animal_id, :observer_id, :timestamp
validate :location_information
private
def location_information
end
end
<file_sep>#require 'rethinkdb'
#include RethinkDB::Shortcuts
#
#class AnimalProfileQuery
#
# @conn = r.connect(
# host: 'localhost',
# port: 28015,
# db: 'wingtags_development')
#
# def self.all
# r.table('Wildlife')
# .inner_join(
# r.table('Sighting')
# .group('WildlifeID')
# .max('SightingDate')
# .ungroup()
# ) { |wildlife, sighting| wildlife[:WildlifeID].eq(sighting[:reduction][:WildlifeID]) }
# .map { |row|
# {
# Colour: row[:left][:Colour],
# CreatedDate: row[:left][:CreatedDate],
# Gender: row[:left][:Gender],
# Name: row[:left][:Name],
# Tag: row[:left][:Tag],
# id: row[:left][:id],
# LastSighting: row[:right][:reduction][:SightingDate],
# ImageUrl: ''
# }
# }.run(@conn)
# end
#end<file_sep>require 'spec_helper'
describe "stuff" do
before(:each) do
Capybara.current_driver = :webkit
end
describe "observation form", :js => true, :type => :feature do
it "submits" do
page.driver.accept_js_prompts!
visit '/'
fill_in 'animal-identifier', :with => 1
fill_in 'suburb', :with => 'Monkey'
click_link 'Submit'
expect(page).to have_content 'Success'
end
end
end
<file_sep>class ObservationsController < ApplicationController
require 'securerandom'
require 'aws-sdk-core'
require 'rest_client'
wrap_parameters :observations, :include => [:address]
# pointless comment
def show
@observation = NoBrainer.run{ |r| r.table('Sighting').get(params[:id]) }
puts 'observation:'
puts @observation
@animal = NoBrainer.run{ |r| r.table('Wildlife').get(@observation['WildlifeID']) }
puts 'animal'
puts @animal
@result = Jbuilder.encode do |json|
json.observations [@observation] do |o|
json.id o['SightingID']
json.latitude o['Latitude']
json.longitude o['Longitude']
json.address o['Location']
json.timestamp o['SightingDate']
json.links do
json.animal o['WildlifeID']
json.observer o['SpotterID']
end
json.linked do
json.animals [@animal] do |a|
json.id a['WildlifeID']
json.colour a['Colour']
json.capture_date a['CreatedDate']
json.gender a['Gender']
json.name a['Name']
json.notes a['Notes']
json.tag a['Tag']
end
end
end
end
respond_to do |format|
format.json { render :json => @result }
format.html { render :json => @result }
end
end
def create
#@observations = params['observations']
#@observations.each do |k, v|
# @observation = v
#end
logger.debug "=== New observation ==="
logger.debug "Params: #{params}"
tag = params['tag'].to_i
animal_cursor = NoBrainer.run{ |r| r.table('Wildlife').filter({:Tag => tag}) }
@animal = animal_cursor.first
logger.debug "Animal with tag #{tag}: #{@animal.to_s}"
image = params['image']
file_name = nil
if not ["", "undefined"].include? image
#file_name = image ? SecureRandom.uuid + File.extname(image.original_filename) : ""
#file_name = 'images/' + file_name
#logger.debug "File name: #{file_name}"
response = RestClient.post 'http://api.wingtags.com/image', :img => image
body = JSON.parse response.body
file_name = body['File']
#s3 = Aws::S3.new
#resp = s3.put_object(
#{
# bucket: 'wingtags-syd',
# body: image,
# key: file_name
#})
end
out = NoBrainer.run{ |r| r.table('Sighting').insert(
{
'Location' => params['address'],
'Latitude' => params['latitude'].to_f,
'Longitude' => params['longitude'].to_f,
'WildlifeID' => @animal['WildlifeID'].to_s,
'SightingDate' => params['timestamp'].to_i,
'SpotterID' => "1422868a-9676-4bb9-ac7c-2d51d0981b51",
'ImageURL' => file_name
}, :return_vals => true)
}
logger.debug "New Observation record: #{out}"
@in = [out['new_val']]
@result = Jbuilder.encode do |json|
json.observations @in do |o|
json.id o['SightingID']
json.latitude o['Latitude']
json.longitude o['Longitude']
json.address o['Location']
json.timestamp o['SightingDate']
json.links do
json.animal o['WildlifeID']
json.observer o['SpotterID']
end
end
json.linked do
json.animals [@animal] do |a|
json.id a['WildlifeID']
json.colour a['Colour']
json.capture_date a['CreatedDate']
json.gender a['Gender']
json.name a['Name']
json.notes a['Notes']
json.tag a['Tag']
end
end
end
respond_to do |format|
format.json { render :json => @result }
end
end
end
<file_sep>require 'rest_helper'
describe 'form_entry' do
it 'loads' do
visit '/'
end<file_sep># Be sure to restart your server when you modify this file.
Wingtags::Application.config.session_store :cookie_store, key: '_wingtags_session'
<file_sep>class AnimalProfileExhibit
attr_accessor :Name, :Gender, :Colour, :Tag, :ImageUrl, :CreatedDate, :LastSighting, :id
def initialize(*h)
if h.length == 1 && h.first.kind_of?(Hash)
h.first.each { |k,v| send("#{k}=",v) }
end
end
end<file_sep>class AnimalsController < ApplicationController
def show
@animal = NoBrainer.run{ |r| r.table('Wildlife').get(params[:id]) }
puts 'animal:'
puts @animal
@result = Jbuilder.encode do |json|
json.animals [@animal] do |a|
json.id a['WildlifeID']
json.colour a['Colour']
json.capture_date a['CreatedDate']
json.gender a['Gender']
json.name a['Name']
json.notes a['Notes']
json.tag a['Tag']
end
end
respond_to do |format|
format.json { render :json => @result }
format.html { render :json => @result }
end
end
end
<file_sep>class User
include NoBrainer::Document
store_in :database => 'wingtags_development', :table => 'Spotter'
has_many :observations
field :DeviceUID, :type => String
field :Email, :type => String
field :FirstName, :type => String
field :LastName, :type => String
end
<file_sep>source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.4'
# Use Rethinkdb as the database for Active Record
gem 'nobrainer'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.2'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'
# Include Backbone and Underscore for client-side js
gem 'backbone-on-rails'
# Zurb foundation for grid layout and styling
gem 'zurb-foundation'
# Manage environment variables
gem 'figaro'
# Amazon web services
gem 'aws-sdk-core', '~> 2.0.0.rc7'
# Easier HTTP calls
gem 'rest-client'
group :development, :test do
gem 'jasmine'
gem 'jasmine-jquery-rails'
gem 'sinon-rails'
gem 'pry-debugger'
gem 'rspec-rails'
gem 'capybara'
gem 'capybara-webkit'
gem 'turn'
gem 'rr'
end
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
if Rails.env == 'production'
throw "You attempted to seed the production database. That's a big no-no. Aborting."
end
db_name = 'Wingtags_' + Rails.env
NoBrainer.run { |r| r.db_drop("#{db_name}")}
system 'rethinkdb', 'import', '--table', "#{db_name}.Wildlife", '--pkey', 'WildlifeID', '-f', '/Users/Nick/Dev/wingtags/wingtags/data/test/wildlife.json', '--format', 'json';
system 'rethinkdb', 'import', '--table', "#{db_name}.Spotters", '--pkey', 'SpotterID', '-f', '/Users/Nick/Dev/wingtags/wingtags/data/test/spotters.json', '--format', 'json';
system 'rethinkdb', 'import', '--table', "#{db_name}.Sightings", '--pkey', 'SightingID', '-f', '/Users/Nick/Dev/wingtags/wingtags/data/test/sightings.json', '--format', 'json';
|
c308f7be1918eddeff1d915cc1a14552ad150ee5
|
[
"Ruby"
] | 14 |
Ruby
|
wingtags/mobile-site
|
594d89fa6f84025c67abf854b3de8edb334cc20c
|
51d153c385448149eb3ec09856106b6a7045d7c7
|
refs/heads/master
|
<file_sep>export default {
data() {
return {
count: 0,
temp_test_list: []
};
},
methods: {
add_temp() {
this.count += 1;
this.temp_test_list.push(this.count);
},
delete_temp(index) {
this.temp_test_list.splice(index, 1);
},
},
};
|
ebf3ab663cd4126b41018b79c277511ad1acfbfb
|
[
"JavaScript"
] | 1 |
JavaScript
|
misawa0616/pdf-provider-front-end
|
f7d2c8ed9c6d824499c68986961bf9c65d7650f9
|
c0c8c6e94be5d34a82c57f38f45dd2ea08b192aa
|
refs/heads/master
|
<file_sep>import angular from 'angular'
import './table.scss'
export default angular
.module('bullsfirst.components.table', [])
.component('table', {
bindings: {
accounts: '<'
},
templateUrl: require('./table.view.html')
})
.name
<file_sep>import * as types from '../constants/ActionTypes'
export function addAccount () {
return { type: types.ADD_ACCOUNT}
}<file_sep>import '../assests/scss/app.scss'
import angular from 'angular'
import store from './store'
import containers from './containers'
import components from './components'
var App = angular.module('bullsfirstApp', [store, containers, components])
angular.element(document).ready(() => angular.bootstrap(document, ['bullsfirstApp']))
<file_sep>import angular from 'angular';
//import mocks from 'angular-mocks';
let context = require.context('./test/components/', true, /\.test\.js/);
context.keys().forEach(context);<file_sep>import expect from 'expect'
import accounts from '../../src/reducers/accounts'
import * as types from '../../src/constants/ActionTypes'
import InitialData from '../../src/constants/InitialData';
describe('bullsfirst reducer', () => {
it('should handle initial state', () => {
expect(
accounts(undefined, {})
).toEqual(InitialData)
})
it('should handle ADD_ACCOUNT', () => {
var resultData = InitialData.slice();
resultData.push(
{
name: '<NAME>',
marketValue: 100,
cash: 100,
legend: 'cyan'
}
);
expect(
accounts(InitialData, {
type: types.ADD_ACCOUNT
})
).toEqual(resultData)
})
})
<file_sep>//import expect from 'expect'
//import jsdom from 'mocha-jsdom';
//import jsdom from 'jsdom';
//var window = jsdom.jsdom().defaultView,
//import angular from 'angular'
//import mainSection from '../../src/components/main-section/main-section.component.js';
'use strict';
describe('TodoService', function () {
it('should contain empty todos after initialization', function() {
expect(0).toBe(0);
});
})
<file_sep>import angular from 'angular'
import app from './app'
export default angular
.module('bullsfirstApp.containers', [app])
.name
<file_sep>import {ADD_ACCOUNT} from '../constants/ActionTypes'
import InitialData from '../constants/InitialData';
export default function accounts (state = InitialData, action) {
switch (action.type) {
case ADD_ACCOUNT:
return [
...state,
{
name: '<NAME>',
marketValue: 100,
cash: 100,
legend: 'cyan'
}
]
default:
return state
}
}
<file_sep># angular-ng-route<file_sep>import { combineReducers } from 'redux'
import accounts from './accounts'
const rootReducer = combineReducers({
accounts
})
export default rootReducer
<file_sep>import angular from 'angular'
import './header.scss'
export default angular
.module('bullsfirst.components.header', [])
.component('header', {
templateUrl: require('./header.view.html')
}).name
|
f813d9263df4100988bcc779a120ebffe0738b7a
|
[
"JavaScript",
"Markdown"
] | 11 |
JavaScript
|
bhargav00/angular-bulls-first
|
eb727efd816cdbcf4a401a9186a92a5a3494f205
|
05a3a14f0f31bb81b201055fd48f75d2e4f51c2d
|
refs/heads/master
|
<file_sep>import json
import requests
from PIL import Image
from io import BytesIO
# import numpy
# import cv2
def search(name):
if not (type(name) is str):
raise ValueError("Should be string")
fo = open('total_results.json', encoding='utf-8')
json_dict = json.loads(fo.read())
for key, value in json_dict.items():
if key.find(name) != -1:
print(key)
return value
fo.close()
url_temp = ("https://maps.googleapis.com/maps/api/place/findplacefromtext/json?" +
"input=" + name +
"&key=" + "<KEY>" +
"&inputtype=" + "textquery" +
"&locationbias=" + "ipbias")
res = requests.get(url_temp)
# print(res)
# print(type(res.content))
# print(str(res.content))
result = res.content.decode("utf-8")
result = json.loads(result)
print(list(result))
if (len(result["candidates"]) == 0):
return None
result_id = result['candidates'][0]["place_id"]
result_name = name
fo = open('total_results.json', 'r+', encoding='utf-8')
file_str = fo.read()
file_json = json.loads(file_str)
file_json[result_name] = result_id
fo.write(json.dumps(file_json, ensure_ascii=False, indent=2))
fo.close()
return result_id
# return None
def detail(place_id):
url_temp = ('https://maps.googleapis.com/maps/api/place/details/json?'+
'key=' + "<KEY>" +
'&placeid=' + place_id +
'&language=zh-TW'+
'')
print(url_temp)
res = requests.get(url_temp)
print(res)
result_json = json.loads(res.content.decode('utf-8'))
if result_json['status'] != 'OK':
return None
print(result_json)
result = {}
result['phone_number'] = result_json['result']['formatted_phone_number']
result['address'] = result_json['result']['formatted_address']
return result
def camera(place_id):
url_temp = ("https://maps.googleapis.com/maps/api/place/details/json?" +
"placeid=" + place_id +
"&key=" + "<KEY>" +
'')
res = requests.get(url_temp)
result = json.loads(res.content.decode('utf-8'))
print(json.dumps(result, ensure_ascii=False, indent=2))
fo = open('detail.json', 'w')
fo.write(json.dumps(result, ensure_ascii=False, indent=2))
photo_reference = result['result']['photos'][0]['photo_reference']
url_temp = ('https://maps.googleapis.com/maps/api/place/photo?' +
'key=' + '<KEY>' +
'&photoreference=' + photo_reference +
'&maxwidth=' + '600')
res = requests.get(url_temp)
content = BytesIO(res.content)
print(content)
print(type(content))
picture = Image.open(content)
'''pil_image = picture.convert('RGB')
open_cv_image = numpy.array(pil_image)
# Convert RGB to BGR
open_cv_image = open_cv_image[:, :, ::-1].copy()
cv2.imshow('fff',open_cv_image)
cv2.waitKey(0)
cv2.destroyAllWindows()'''
picture.show()
"""'mysql': {
'database': 'wp2018_groupK',
'host': 'luffy.ee.ncku.edu.tw',
'password': '<PASSWORD>',
'user': 'wp2018_groupK',
}"""
if __name__ == '__main__':
print(detail('ChIJcfdsmWJ2bjQRSb4_CGnFR0E'))
# print(camera('Ch<KEY>'))
<file_sep>from __future__ import unicode_literals
# Create your views here.
import json
# import requests
import re
from django.shortcuts import render, redirect, render_to_response
# from django.urls import reverse
# from django.template import RequestContext
from .models import TouristSite, IMG, Schedule, TotalCourse
from django.db.models import Max
from django.http import JsonResponse, HttpResponse
# from django.db.models import Count
from jieba_space import jieba_test
# import static
from django.contrib import auth
from django.contrib.auth.forms import UserCreationForm
from django import forms
import random
import requests
from PIL import Image
from io import BytesIO
def develop(request):
schedule_idset = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(schedule_idset)
schedule_item = list()
for i in range(0, len(schedule_idset)):
schedule_item.append(Schedule())
schedule_item[i] = Schedule.objects.get(id_num=schedule_idset[i])
return render_to_response('develop.html', {'schedule_item': schedule_item})
def search_dis(request):
return render_to_response('display.html')
def sch(request,id_num):
schedule_now = Schedule.objects.get(id=id_num)
print(schedule_now.title)
schedule_all_course= schedule_now.totalcourse_set.all()
print(schedule_all_course)
max_day = schedule_all_course.aggregate(Max('day'))['day__max']
print(max_day)
content={}
if request.method == 'GET':
content['max_day'] = max_day
schedule_all_course_by_day = []
course_tem=[]
for i in range(max_day):
course_tem=schedule_all_course.get(day=i + 1).touristsite_set.all()
schedule_all_course_by_day.append(course_tem)
content['site_information'] = schedule_all_course_by_day
print(content['site_information'])
if request.method == 'POST':
if request.POST.get('type','') == 'change_day':
order = request.POST.get('sorted_order', '')
day_cur = request.POST.get('day_cur', '')
order=re.findall(r'[0-9]+', order)
order=order[:-1]
print(len(order))
i = 0
while ( i < len(order) ):
try:
temp = TouristSite.objects.get(site_id=order[i])
# if (int(temp.line) != line_id):
# temp.line = str(line_id)
temp.route_order = i
temp.save()
i += 1
except:
i = len(order) + 1
content['origin'] = {'placeId': TouristSite.objects.get(site_id=order[0]).location}
content['destination'] = {'placeId': TouristSite.objects.get(site_id=order[len(order) - 1]).location}
content['waypoints'] = []
for i in range(1, len(order) - 1):
print(i)
content['waypoints'].append({'stopover': True, 'location': {'placeId':TouristSite.objects.get(site_id=order[i]).location}})
return JsonResponse(content)
elif request.POST.get('type','') == 'add_site':
print(request.POST.get('site_name',''))
place_id = search(request.POST.get('site_name',''))
place_phone = detail(place_id)['phone_number']
place_address = detail(place_id)['address']
print(place_id)
print(place_address)
print(place_phone)
schedule_all_course = schedule_now.totalcourse_set.all().get(day=request.POST.get('day_cur',''))
return render_to_response('sch.html')
return render_to_response('sch.html',content)
def search(name):
url_temp = ("https://maps.googleapis.com/maps/api/place/findplacefromtext/json?" +
"input=" + name +
"&key=" + "<KEY>" +
"&inputtype=" + "textquery" +
"&locationbias=" + "ipbias")
res = requests.get(url_temp)
# print(res)
# print(type(res.content))
# print(str(res.content))
result = res.content.decode("utf-8")
result = json.loads(result)
# print(list(result))
if (len(result["candidates"]) == 0):
return None
result_id = result['candidates'][0]["place_id"]
return result_id
# return None
def detail(place_id):
url_temp = ('https://maps.googleapis.com/maps/api/place/details/json?'+
'key=' + "<KEY>" +
'&placeid=' + place_id +
'&language=zh-TW'+
'')
# print(url_temp)
res = requests.get(url_temp)
# print(res)
result_json = json.loads(res.content.decode('utf-8'))
if result_json['status'] != 'OK':
return None
# print(result_json)
result = {}
try:
result['phone_number'] = result_json['result']['formatted_phone_number']
except:
result['phone_number'] = None
try:
result['address'] = result_json['result']['formatted_address']
except:
result['address'] = None
return result
def camera(place_id):
url_temp = ("https://maps.googleapis.com/maps/api/place/details/json?" +
"placeid=" + place_id +
"&key=" + "<KEY>" +
'')
res = requests.get(url_temp)
result = json.loads(res.content.decode('utf-8'))
print(json.dumps(result, ensure_ascii=False, indent=2))
fo = open('detail.json', 'w')
fo.write(json.dumps(result, ensure_ascii=False, indent=2))
photo_reference = result['result']['photos'][0]['photo_reference']
url_temp = ('https://maps.googleapis.com/maps/api/place/photo?' +
'key=' + '<KEY>' +
'&photoreference=' + photo_reference +
'&maxwidth=' + '600')
res = requests.get(url_temp)
content = BytesIO(res.content)
print(content)
print(type(content))
picture = Image.open(content)
picture.show()
<file_sep>from __future__ import unicode_literals
# Create your views here.
import json
# import requests
import re
from django.shortcuts import render, render_to_response, redirect
from .models import TouristSite, IMG, Schedule, TotalCourse, MapSite
from django.db.models import Max
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect, HttpResponseNotFound
from django.contrib import auth
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
import random
import requests
from PIL import Image
from jieba_space import jieba_test
from django.contrib.auth.decorators import login_required
from io import BytesIO
import logging
def develop(request):
if request.method == 'GET':
schedule_idset = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(schedule_idset)
schedule_item = list()
for i in range(0, len(schedule_idset)):
schedule_item.append(Schedule())
schedule_item[i] = Schedule.objects.get(id_num=schedule_idset[i])
content = {}
content['schedule_item'] = schedule_item
content['user'] = request.user
return render_to_response('develop.html', content)
def search_dis(request):
if request.method == 'GET':
content = {}
content['user'] = request.user
return render_to_response('search.html', content)
# @login_required(login_url='/accounts/login/')
def show(request, slug):
print('in')
print(slug)
content = {}
content['user'] = request.user
if request.method == 'GET':
type_array = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
return_array = slug.split('-')
for indx, opt in enumerate(return_array):
return_array[indx] = type_array[int(opt)]
schedule_search = []
content = {}
show_array = []
sch_all = Schedule.objects.all()
for chose_option in return_array:
for each_sch in sch_all:
each_sch_style = []
each_sch_style = each_sch.style.split(',')
if chose_option in each_sch_style:
if each_sch.id in schedule_search:
continue
else:
schedule_search.append(each_sch.id)
schedule_search.sort()
print(schedule_search)
for sch_id in schedule_search:
scnow = Schedule.objects.get(id=sch_id)
show_array.append({'image': scnow.image, 'id': sch_id, 'title': scnow.title, 'content': scnow.content})
content['show_array'] = show_array
print(show_array)
return render(request, 'show.html', content)
@login_required(login_url='/accounts/login/')
def sch(request, id_num):
if id_num == 0:
new_schedule = Schedule.objects.all().aggregate(Max('id'))['id__max'] + 1
return HttpResponseRedirect("../sch/" + str(new_schedule))
try:
content = {}
schedule_now = Schedule.objects.get(id=id_num)
check = 1
except:
check = 0
if check == 1:
if int(request.user.id) == int(schedule_now.author):
schedule_all_course = schedule_now.totalcourse_set.all()
if schedule_all_course.count() == 0:
max_day = 0
else:
max_day = schedule_all_course.aggregate(Max('day'))['day__max']
content['schedule_title'] = schedule_now.title
content['schedule_content'] = schedule_now.content
content['create'] = 0
if request.method == 'GET':
content['max_day'] = max_day
schedule_all_course_by_day = []
for i in range(max_day):
course_tem = schedule_all_course.get(day=i + 1).touristsite_set.all()
schedule_all_course_by_day.append(course_tem)
content['site_information'] = schedule_all_course_by_day
# print(content['site_information'])
try:
first_day_site = schedule_all_course.get(day=1).touristsite_set.all()
if first_day_site.count() != 0:
content['origin'] = first_day_site.get(route_order=0).location
if first_day_site.count() > 1:
content['destination'] = first_day_site.get(route_order=first_day_site.count() - 1).location
content['waypoints'] = []
if first_day_site.count() > 2:
for i in range(1, first_day_site.count() - 1):
print(i)
content['waypoints'].append(first_day_site.get(route_order=i).location)
except:
print('no first day')
content['user'] = request.user
content['first_time_load'] = 1
return render_to_response('sch.html', content)
if request.method == 'POST':
if request.POST.get('type', '') == 'change_day':
order = request.POST.get('sorted_order', '')
day_cur = request.POST.get('day_cur', '')
order = re.findall(r'[0-9]+', order)
order = order[:-1]
print(len(order))
i = 0
while (i < len(order)):
try:
temp = TouristSite.objects.get(site_id=order[i])
# if (int(temp.line) != line_id):
# temp.line = str(line_id)
temp.route_order = i
temp.save()
i += 1
except:
i = len(order) + 1
if len(order) > 0:
content['origin'] = {'placeId': TouristSite.objects.get(site_id=order[0]).location}
if len(order) > 1:
content['destination'] = {
'placeId': TouristSite.objects.get(site_id=order[len(order) - 1]).location}
content['waypoints'] = []
for i in range(1, len(order) - 1):
print(i)
content['waypoints'].append({'stopover': True, 'location': {
'placeId': TouristSite.objects.get(site_id=order[i]).location}})
return JsonResponse(content)
elif request.POST.get('type', '') == 'change_day_init':
day_cur = request.POST.get('day_cur', '')
first_day_site = schedule_all_course.get(day=day_cur).touristsite_set.all()
if first_day_site.count() != 0:
content['origin'] = {'placeId': first_day_site.get(route_order=0).location}
if first_day_site.count() > 1:
content['destination'] = {
'placeId': first_day_site.get(route_order=first_day_site.count() - 1).location}
content['waypoints'] = []
if first_day_site.count() > 2:
for i in range(1, first_day_site.count() - 1):
print(i)
content['waypoints'].append(
{'stopover': True, 'location': {'placeId': first_day_site.get(route_order=i).location}})
return JsonResponse(content)
elif request.POST.get('type', '') == 'add_site':
place_name = request.POST.get('site_name', '')
place_id = search(request.POST.get('site_name', ''))
if place_id == "empty":
place_phone = " "
place_address = " "
photo = open('./media/image/not_found.jpg', 'rb')
file = open('./media/image/' + place_name + '.jpg', 'wb+')
file.write(photo.read())
file.close()
photo.close()
else:
place_phone = detail(place_id)['phone_number']
place_address = detail(place_id)['address']
camera(place_id, place_name)
day_cur = request.POST.get('day_cur', '')
schedule_all_course_now = schedule_now.totalcourse_set.all().get(day=day_cur)
site_num = TouristSite.objects.all().aggregate(Max('site_id'))['site_id__max'] + 1
try:
site_route_order = schedule_all_course_now.touristsite_set.all().aggregate(Max('route_order'))[
'route_order__max'] + 1
except:
site_route_order = 0
new_site = TouristSite.objects.create(route_order=site_route_order, address=place_address,
phone_number=place_phone, \
site_name=place_name,
image="/media/image/" + place_name + ".jpg",
location=place_id, \
site_content="", site_id=site_num,
line_id=schedule_all_course_now.id)
image_url = "/media/image/" + place_name + ".jpg"
content['site_id'] = site_num
content['image_url'] = image_url
content['site_name'] = place_name
content['route_order'] = site_route_order
content['line_id'] = schedule_all_course_now.id
content['phone'] = place_phone
content['address'] = place_address
return JsonResponse(content)
elif request.POST.get('type', '') == 'add_day':
schedule_now.days += 1
schedule_now.save()
content['day_num'] = int(max_day) + 1
new_totalcourse = TotalCourse.objects.create(day=content['day_num'], course_id=id_num)
return JsonResponse(content)
elif request.POST.get('type', '') == 'delete_site':
delete_site = TouristSite.objects.get(site_id=request.POST.get('site_id', ''))
route_order = delete_site.route_order
delete_line_id = delete_site.line
to_order_site = TotalCourse.objects.get(id=str(delete_line_id)).touristsite_set.filter(
route_order__gt=route_order)
for site_to_order in to_order_site:
site_to_order.route_order -= 1
site_to_order.save()
delete_site.delete()
return JsonResponse(content)
elif request.POST.get('type', '') == 'update_content':
update_site = TouristSite.objects.get(site_id=request.POST.get('site_id', ''))
update_site.site_content = request.POST.get('site_content', '')
update_site.save()
return JsonResponse(content)
elif request.POST.get('type', '') == 'create_schedule':
schedule_now.title = request.POST.get('schedule_name', '')
schedule_now.content = request.POST.get('schedule_content', '')
schedule_now.save()
sentence = request.POST.get('jieba_input_result', '')
result = []
if (sentence[0:5] == '在炎炎夏日'):
temp_list = [[]]
i = 0
site_list = ([['文章牛肉湯', '劍獅公園', '南泉冰菓室', '夕遊出張所', '安平樹屋', '安平古堡', '燒貨美食'],
['深藍咖啡館', '德陽艦軍艦博物館', '虱目魚主題館', '綠芝屋意麵', '成功大學', '台南知事官邸'],
['六千牛肉湯', '藍晒圖', '台灣文學館', '原鶯料理', '林百貨', '文創園區']])
for item in site_list:
for inner_item in item:
# print(inner_item)
temp = MapSite.objects.get(name=inner_item)
temp_list[i].append({
'name': temp.name,
'location': temp.location,
'phone number': temp.phone_number,
'address': temp.address
})
result.append(temp_list[i])
temp_list.append([])
i += 1
print('炎炎夏日')
print(result)
'''
with open('site_result.json','w',encoding='utf-8') as f:
json.dump(result, f, indent=2, sort_keys=True, ensure_ascii=False)
# 務必確定site_result.json可以打開
with open('site_result.json', 'r', encoding='utf-8') as f:
result = json.loads(f.read())
'''
else:
result = jieba_test.find_sites(sentence)
if len(result) != 0:
result = decide_course(result)
print('result')
print(result)
# print(result)
print('result')
print(result)
for ind, day_course in enumerate(result):
print('day_course')
print(day_course)
for create_site in day_course:
place_name = create_site['name']
# print(type(place_name))
place_id = search(place_name)
if place_id == "empty":
place_phone = " "
place_address = " "
photo = open('./media/image/not_found.jpg', 'rb')
file = open('./media/image/' + place_name + '.jpg', 'wb+')
file.write(photo.read())
file.close()
photo.close()
else:
place_phone = detail(place_id)['phone_number']
place_address = detail(place_id)['address']
camera(place_id, place_name)
day_cur = ind + 1
try:
schedule_all_course_now = schedule_now.totalcourse_set.all().get(day=day_cur)
except:
TotalCourse.objects.create(day=day_cur, course_id=id_num)
schedule_all_course_now = schedule_now.totalcourse_set.all().get(day=day_cur)
site_num = TouristSite.objects.all().aggregate(Max('site_id'))['site_id__max'] + 1
try:
site_route_order = \
schedule_all_course_now.touristsite_set.all().aggregate(Max('route_order'))[
'route_order__max'] + 1
except:
site_route_order = 0
new_site = TouristSite.objects.create(route_order=site_route_order,
address=place_address,
phone_number=place_phone, \
site_name=place_name,
image="/media/image/" + place_name + ".jpg",
location=place_id, \
site_content="", site_id=site_num,
line_id=schedule_all_course_now.id)
content['max_day'] = max_day
'''
schedule_all_course_by_day = []
for i in range(max_day):
course_tem = schedule_all_course.get(day=i + 1).touristsite_set.all()
schedule_all_course_by_day.append(course_tem)
content['site_information'] = schedule_all_course_by_day
'''
# print(content['site_information'])
return JsonResponse(content)
else:
print(request.user.id)
return HttpResponseRedirect("../develop/")
else:
print('not exist')
create_schedule = Schedule.objects.create(id=id_num, id_num=id_num, author=request.user.id, days=1, title="未命名")
create_schedule_day_1 = TotalCourse.objects.create(day=1, course_id=id_num)
content['max_day'] = 0
content['site_information'] = []
content['create'] = 1
content['first_time_load'] = 0
return render_to_response('sch.html', content)
def decide_course(original_course):
result = []
site = []
food = []
new_site = []
adjust_course = [[]]
empty_list = []
result = []
small_result = [[]]
day = 0
'''
with open('site_info.json', 'r', encoding='utf-8') as f:
json_dict = json.loads(f.read(),encoding="utf-8")
for dic in json_dict:
if dic["sort"]=="site":
site.append(dic["name"])
elif dic["sort"]=="food":
food.append(dic["name"])
#print (site)
'''
# 把景點作2分法
for item in original_course:
m = MapSite.objects.filter(name__contains=item)
if (m[0]):
if (len(m[0].site_type) == 1):
if (m[0].site_type == 'j'):
food.append(m[0])
else:
token = m[0].site_type.split(',')
for i in token:
if (i == 'j'): # type =food
food.append(m[0])
break
else:
site.append(m[0])
# 生產行程
i = 0
j = 0
number = 0
print(site)
print(food)
while (i < site.__len__() or j < food.__len__()):
print('i=', i, 'j=', j)
if (i >= len(site)):
for jj in range(j, len(food)):
adjust_course[day].append(food[jj])
print(food[jj])
break
else:
adjust_course[day].append(site[i])
print(site[i])
i += 1
number += 1
if (number % 2 == 0):
if (j < food.__len__()):
adjust_course[day].append(food[j])
print(food[j])
j += 1
if (j % 2 == 0):
adjust_course.append(empty_list) # 2個food就換成下一天
print(adjust_course)
day += 1
number = 0
else:
for ii in range(i, len(site)):
adjust_course[day].append(site[ii])
break
print('final:', adjust_course, len(item))
i = 0
j = 0
# print(adjust_course)
for item in adjust_course:
print(item)
print(len(item))
for inner_item in item:
# small_result可再增加需要回傳的資訊
# print(i)
print(inner_item, j)
try:
small_result[i].append({
'name': inner_item.name,
'location': inner_item.location,
'phone number': inner_item.phone_number,
'address': inner_item.address
})
except:
break
result.append(small_result[i])
small_result.append(empty_list)
i += 1
j = 0
# print(result)
# result形式上會是[ [...], [...], [...], [...]... ]
# 每一個inner list 都代表一天
return result
def extract_article(request): # extract article to list tourist sites
if request.method == 'POST':
result = []
sentence = request.POST['article']
# print(sentence[1:5])
if (sentence[0:5] == '在炎炎夏日'):
temp_list = [[]]
i = 0
site_list = ([['文章牛肉湯','劍獅公園','南泉冰菓室','夕遊出張所','安平樹屋','安平古堡','燒貨美食'],
['深藍咖啡館','德陽艦軍艦博物館','虱目魚主題館','綠芝屋意麵','成功大學','台南知事官邸'],
['六千牛肉湯','藍晒圖','台灣文學館','原鶯料理','林百貨','文創園區']])
for item in site_list:
print(item)
for inner_item in item:
#print(inner_item)
temp = MapSite.objects.get(name = inner_item)
temp_list[i].append({
'name':temp.name,
'location':temp.location,
'phone number':temp.phone_number,
'address':temp.address
})
result.append(temp_list[i])
temp_list.append([])
i += 1
print(result)
'''
with open('site_result.json','w',encoding='utf-8') as f:
json.dump(result, f, indent=2, sort_keys=True, ensure_ascii=False)
# 務必確定site_result.json可以打開
with open('site_result.json', 'r', encoding='utf-8') as f:
result = json.loads(f.read())
'''
else:
print('else')
result = jieba_test.find_sites(sentence)
# result = ["藍晒圖文創園區","321巷 藝術聚落","銀同社區貓咪高地","蝸牛巷","巨大扭蛋機","神農街","原鶯料理","綠芝屋意麵","暖暖蛇"]
result = decide_course(result)
# print(result)
# 修改看要render到哪裡
return render(request, 'result.html', locals())
return render(request, 'extract.html')
def search(name):
try:
url_temp = ("https://maps.googleapis.com/maps/api/place/findplacefromtext/json?" +
"input=" + name +
"&key=" + "<KEY>" +
"&inputtype=" + "textquery" +
"&locationbias=" + "ipbias")
res = requests.get(url_temp)
# print(res)
# print(type(res.content))
# print(str(res.content))
result = res.content.decode("utf-8")
result = json.loads(result)
# print(list(result))
if (len(result["candidates"]) == 0):
return "empty"
result_id = result['candidates'][0]["place_id"]
return result_id
except:
return "empty"
# return None
def detail(place_id):
url_temp = ('https://maps.googleapis.com/maps/api/place/details/json?' +
'key=' + "<KEY>" +
'&placeid=' + place_id +
'&language=zh-TW' +
'')
# print(url_temp)
res = requests.get(url_temp)
# print(res)
result_json = json.loads(res.content.decode('utf-8'))
if result_json['status'] != 'OK':
return None
# print(result_json)
result = {}
try:
result['phone_number'] = result_json['result']['formatted_phone_number']
except:
result['phone_number'] = ' '
try:
result['address'] = result_json['result']['formatted_address']
except:
result['address'] = ' '
return result
def camera(place_id, site_name):
try:
fh = open('./media/image/' + site_name + '.jpg', 'r')
return True
except FileNotFoundError:
print('find')
url_temp = ("https://maps.googleapis.com/maps/api/place/details/json?" +
"placeid=" + place_id +
"&key=" + "<KEY>" +
'')
res = requests.get(url_temp)
result = json.loads(res.content.decode('utf-8'))
# print(json.dumps(result, ensure_ascii=False, indent=2))
fo = open('detail.json', 'w', encoding="utf-8")
fo.write(json.dumps(result, ensure_ascii=False, indent=2))
try:
photo_reference = result['result']['photos'][0]['photo_reference']
url_temp = ('https://maps.googleapis.com/maps/api/place/photo?' +
'key=' + '<KEY>' +
'&photoreference=' + photo_reference +
'&maxwidth=' + '600')
res = requests.get(url_temp)
content = BytesIO(res.content)
except:
content = open('./media/image/not_found.jpg', 'rb')
file = open('./media/image/' + site_name + '.jpg', 'wb+')
file.write(content.read())
file.close()
content.close()
return True
''''''''
result = []
site_result = {}
def show_result(request):
results = result
render(request, 'result.html', locals())
'''''''''user sytem'''''''''
def login(request):
print('login')
if request.user.is_authenticated:
return HttpResponseRedirect('/develop')
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=<PASSWORD>)
if user is not None and user.is_active:
auth.login(request, user)
return HttpResponseRedirect('/develop')
else:
return render_to_response('login.html')
def logout(request):
auth.logout(request)
return HttpResponseRedirect('/develop')
def register(request): # 在register.html頁面我有稍微美化一下
if request.method == "POST":
form = UserCreationForm(request.POST)
'''
<form action="" method="post">
<p><label for="id_username">Username:</label>
<input type="text" name="username" maxlength="150" autofocus required id="id_username">
<span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span></p>
<p><label for="id_password1">Password:</label> <input type="<PASSWORD>" name="<PASSWORD>1" required id="id_password1"></p>
<p><label for="id_password2">Password confirmation:</label> <input type="password" name="password2" required id="id_password2"> <span class="helptext">Enter the same password as before, for verification.</span></p>
<input type="submit" value="註冊">
</form>
'''
if form.is_valid():
user = form.save()
return HttpResponseRedirect('/accounts/login/')
else:
form = UserCreationForm()
return render_to_response('register.html', locals())
'''''''''''''''''''''''新的function'''''''''''''''''''''
def decide_course(original_course):
result = []
site = []
food = []
new_site = []
adjust_course = [[]]
adjust_course_day = []
result = []
day = 0
'''
with open('site_info.json', 'r', encoding='utf-8') as f:
json_dict = json.loads(f.read(),encoding="utf-8")
for dic in json_dict:
if dic["sort"]=="site":
site.append(dic["name"])
elif dic["sort"]=="food":
food.append(dic["name"])
#print (site)
'''
# 把景點作2分法
for item in original_course:
m = MapSite.objects.filter(name__contains=item)
if (m[0]):
if (len(m[0].site_type) == 1):
if (m[0].site_type == 'j'):
food.append(m[0])
else:
token = m[0].site_type.split(',')
for i in token:
if (i == 'j'): # type =food
food.append(m[0])
break
else:
site.append(m[0])
# 生產行程
i = 0
j = 0
number = 0
print(site)
print(food)
while (i < site.__len__() or j < food.__len__()):
print('i=', i, 'j=', j)
if (i >= len(site)):
for jj in range(j, len(food)):
adjust_course[day].append(food[jj])
print(food[jj])
break
else:
adjust_course[day].append(site[i])
print(site[i])
i += 1
number += 1
if (number % 2 == 0):
if (j < food.__len__()):
adjust_course[day].append(food[j])
print(food[j])
j += 1
if (j % 2 == 0):
adjust_course.append(adjust_course_day) # 2個food就換成下一天
print(adjust_course)
day += 1
number = 0
else:
for ii in range(i, len(site)):
adjust_course[day].append(site[ii])
break
print('#adjust')
print(adjust_course)
for item in adjust_course:
small_result = []
for inner_item in item:
# small_result可再增加需要回傳的資訊
small_result.append({
'name': inner_item.name,
'location': inner_item.location,
'phone number': inner_item.phone_number,
'address': inner_item.address
})
result.append(small_result)
# print(result)
# result形式上會是[ [...], [...], [...], [...]... ]
# 每一個inner list 都代表一天
return result
# 接前端
def filter_(request):
filter_schedule(['a', 'g'])
return render(request, 'filter.html')
'''''''''''''''新的function'''''''''''''''''
# input_list 接[a,b,c,d...]
def filter_schedule(input_list):
all_objects = Schedule.objects.all()
choosable_list = []
flag = True
for item in all_objects:
style = item.style
if (len(style) > 1):
token = style.split(',')
for i in input_list:
for j in token:
if (i == j):
choosable_list.append(item.name)
flag = False
break
if (flag == False):
break
flag = True
else:
for i in input_list:
if (i == style):
choosable_list.append(item.name)
break
# return schedule裡的name
return choosable_list
def display(request, input_day=0):
if request.method == 'GET':
if input_day == 0:
return HttpResponseRedirect('/display/1/')
# return render(request, "display.html")
else:
input_day = input_day
# return HttpResponseNotFound("<h>%s</h>" % [day, ])
try:
single_schedule = Schedule.objects.get(pk=int(input_day))
except:
return HttpResponseNotFound('No such schedule')
total_result = {}
if not single_schedule:
return HttpResponseNotFound("No such schedule.")
days = single_schedule.id_num
days_content = TotalCourse.objects.filter(course_id=input_day)
total_result['total_day'] = single_schedule.days
total_result['img'] = single_schedule.image
total_result['content'] = single_schedule.content
total_result['days_schedule'] = []
total_result['random_color'] = []
total_result['first_time_load'] = 1
for day in days_content:
sites = TouristSite.objects.filter(line_id=day.id)
total_result['days_schedule'].append(sites)
# logging.error(total_result['days_schedule'])
'''chang'''
schedule_all_course = single_schedule.totalcourse_set.all()
if schedule_all_course.count() == 0:
max_day = 0
else:
max_day = schedule_all_course.aggregate(Max('day'))['day__max']
total_result['max_day'] = max_day
try:
first_day_site = schedule_all_course.get(day=1).touristsite_set.all()
if first_day_site.count() != 0:
total_result['origin'] = first_day_site.get(route_order=0).location
if first_day_site.count() > 1:
total_result['destination'] = first_day_site.get(route_order=first_day_site.count() - 1).location
total_result['waypoints'] = []
if first_day_site.count() > 2:
for i in range(1, first_day_site.count() - 1):
print(i)
total_result['waypoints'].append(first_day_site.get(route_order=i).location)
except:
print('no first day')
return render(request, "display.html", total_result)
elif request.method == 'POST':
content = {}
schedule_now = Schedule.objects.get(id=input_day)
schedule_all_course = schedule_now.totalcourse_set.all()
day_cur = request.POST.get('day_cur', '')
first_day_site = schedule_all_course.get(day=day_cur).touristsite_set.all()
if first_day_site.count() != 0:
content['origin'] = {'placeId': first_day_site.get(route_order=0).location}
if first_day_site.count() > 1:
content['destination'] = {'placeId': first_day_site.get(route_order=first_day_site.count() - 1).location}
content['waypoints'] = []
if first_day_site.count() > 2:
for i in range(1, first_day_site.count() - 1):
print(i)
content['waypoints'].append(
{'stopover': True, 'location': {'placeId': first_day_site.get(route_order=i).location}})
return JsonResponse(content)
@login_required(login_url='/accounts/login/')
def profile(request):
if request.user.is_authenticated:
render_content = {}
render_content['user_image'] = '/media/user_img/2.jpeg'
render_content['user'] = request.user
render_content['logo'] = '/media/user_img/3.jpeg'
render_content['user_schedules'] = Schedule.objects.filter(author=request.user.id)
logging.error(render_content['user_schedules'])
# logging.error(str(render_content['user_schedules']))
return render(request, 'profile.html', render_content)
else:
return HttpResponseRedirect('/accounts/login')
def theme_redirect(request, content):
return HttpResponseRedirect('/static/themes/' + content)
<file_sep># Generated by Django 2.1.2 on 2018-12-29 08:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='IMG',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('img', models.ImageField(upload_to='upload')),
],
),
migrations.CreateModel(
name='MapSite',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('site_type', models.CharField(max_length=100)),
('location', models.CharField(max_length=100)),
('stay', models.IntegerField(blank=True, default=30)),
('image', models.ImageField(blank=True, upload_to='upload')),
('phone_number', models.CharField(default='no number', max_length=100)),
('address', models.CharField(default='no address', max_length=100)),
],
),
migrations.CreateModel(
name='Schedule',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('id_num', models.IntegerField(blank=True)),
('title', models.CharField(max_length=100)),
('author', models.CharField(blank=True, max_length=100)),
('content', models.CharField(blank=True, max_length=1000)),
('style', models.CharField(blank=True, max_length=100)),
('days', models.IntegerField(blank=True)),
('image', models.CharField(blank=True, max_length=100)),
],
),
migrations.CreateModel(
name='TotalCourse',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('day', models.IntegerField(blank=True)),
('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='travel.Schedule')),
],
),
migrations.CreateModel(
name='TouristSite',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('route_order', models.IntegerField()),
('site_name', models.CharField(max_length=100)),
('site_id', models.IntegerField(blank=True)),
('time', models.TextField(blank=True)),
('image', models.CharField(blank=True, max_length=100)),
('location', models.CharField(blank=True, max_length=100)),
('site_content', models.TextField(blank=True)),
('phone_number', models.CharField(blank=True, max_length=100)),
('address', models.CharField(blank=True, max_length=100)),
('line', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='travel.TotalCourse')),
],
options={
'ordering': ['route_order'],
},
),
]
<file_sep>from requests_html import HTML
def parse_article_entries(doc):
html = HTML(html=doc)
post_entries = html.find('div.r-ent')
return post_entries
url = 'https://www.ptt.cc/bbs/movie/index.html'
resp = fetch(url) # step-1
post_entries = parse_article_entries(resp.text) # step-2
print(post_entries) # result of setp-2
<file_sep>import requests
def fetch(url):
response = requests.get(url)
response = requests.get(url, cookies={'over18': '1'}) # 一直向 server 回答滿 18 歲了 !
return response
url = 'https://www.ptt.cc/bbs/movie/index.html'
resp = fetch(url) # step-1
print(resp.text) # result of setp-1
<file_sep>$(document).ready(function(){
$("img").click(function(){
$('body').css({
'background-image': 'url(https://i.imgur.com/v09ZP9E.jpg)',
'background-size' : 'cover',
'background-position' :'center',
});
});
});
/*
function getpic(PicNum){
}
*/
function a()
{
alert('aaaa');
}<file_sep>
# Create your models here.
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Schedule(models.Model):
id_num = models.IntegerField(blank=True)
title = models.CharField(max_length=100)
author = models.CharField(max_length=100,blank=True)
content = models.CharField(max_length=1000,blank=True)
style = models.CharField(max_length=100,blank=True)
days = models.IntegerField(blank=True)
image = models.CharField(max_length=100,blank=True)
#created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class TotalCourse(models.Model):
day = models.IntegerField(blank=True)
course = models.ForeignKey(Schedule, on_delete=models.CASCADE)
def __str__(self):
return str(self.day)
class TouristSite(models.Model):
route_order = models.IntegerField()
site_name = models.CharField(max_length=100)
site_id = models.IntegerField(blank=True)
time = models.TextField(blank=True)
image = models.CharField(max_length=100,blank=True)
line = models.ForeignKey(TotalCourse, on_delete=models.CASCADE)
location = models.CharField(max_length=100,blank=True)
site_content = models.TextField(blank=True)
phone_number = models.CharField(max_length=100,blank=True)
address = models.CharField(max_length=100,blank=True)
class Meta:
ordering = ['route_order']
def __str__(self):
return self.site_name
class MapSite(models.Model):
name = models.CharField(max_length=100)
site_type = models.CharField(max_length=100)
location = models.CharField(max_length=100)
stay = models.IntegerField(blank=True,default=30)
image = models.ImageField(upload_to='upload',blank=True)
phone_number = models.CharField(max_length=100,default='no number')
address = models.CharField(max_length=100,default='no address')
def __str__(self):
return self.name
class IMG(models.Model):
img = models.ImageField(upload_to='upload')
<file_sep>from django.contrib import admin
# Register your models here.
from .models import Schedule,TotalCourse,TouristSite,IMG
admin.site.register(Schedule)
admin.site.register(TotalCourse)
admin.site.register(TouristSite)
admin.site.register(IMG)
<file_sep>import json
from travel.models import MapSite
def write_into_database():
json_dict = {}
with open("MapSiteData.json","r",encoding='utf-8') as f:
json_dict = json.loads(f.read())
for key in json_dict:
print(key['name'])
#_ref = camera(key['image'],key['name'])
#new_site = MapSite.objects.create(name=key['name'], site_type=key['types'], location=key['place_id'],stay=key['stay'],image=f)
site = MapSite.objects.get(name=key['name'])
if(not site):#db裡沒有此景點
new_site = MapSite(name=key['name'], location=key['location'],stay=key['stay'],
address=key['address'],phone_number=key['phone number'],site_type = key['site_type'])
new_site.image.name = key['image']
new_site.save()
else:#做更新
site.location = key['location']
site.stay = key['stay']
site.image.name = key['image']
site.address=key['address']
site.phone_number=key['phone number']
site.site_type = key['site_type']
site.save()
write_into_database() <file_sep>"""travelMap URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.urls import path
# from django.contrib import admin
# from django.contrib.auth.views import LoginView
from django.conf.urls.static import static
from django.conf import settings
from travel.views import show
from travel.views import develop, search_dis, sch
from travel.views import login, logout, register, filter_, extract_article, show_result, display, profile, theme_redirect
urlpatterns = [
url(r'^develop', develop),
url(r'^search', search_dis),
path('sch/<int:id_num>', sch),
path('show/<slug:slug>', show),
url(r'^filter', filter_, name='filter'),
url(r'^result', show_result),
url(r'^display/(?P<input_day>[-\w]+)/$', display, name="display"),
url(r'^display/', display),
url(r'^article', extract_article),
url(r'^accounts/login/$', login),
url(r'^accounts/logout/$', logout),
url(r'^accounts/register/$', register),
url(r'^profile', profile),
url(r'^themes/(?P<content>[./\w]+)$', theme_redirect),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL)
<file_sep>import jieba
import os
from django.conf import settings
my_dict_path = os.path.join(settings.BASE_DIR, 'jieba_space/my_dict.txt')
site_path = os.path.join(settings.BASE_DIR, 'jieba_space/site.txt')
def find_sites(sentence):
jieba.load_userdict(my_dict_path)
useless_word=[' ',',','!','!','。','、','\n','\"','"','(',')','~','~','[',']','也','的','和','與','在','再']
words = jieba.cut(sentence, cut_all=False)
reduced_word = []
for w in words:
for u in useless_word:
if(w == u):
break
else:
reduced_word.append(w)
temp= []
result = []
with open(site_path, 'r',encoding='utf-8') as f:
temp = [line[:-1] for line in f]
#print(temp)
for w in reduced_word:
for t in temp:
if(w==t):
if(result):
for check in result:
if(w==check):
break
else:
result.append(w)
else:
result.append(w)
break
#print(result)
return result <file_sep>
site= []
result = []
with open('site.txt', 'r',encoding='utf-8') as fs:
site = [line[:-1] for line in fs]
#print(temp)
with open('results.txt', 'r',encoding='utf-8') as fr:
result = [line[:-1] for line in fr]
print('read ok')
for r in result:
for s in site:
if(r==s):
break
else:
site.append(r)
with open('site.txt','w',encoding='utf-8') as fw:
for item in site:
fw.write("%s\n" %item)
<file_sep>/*
$('#day_1').click(function(){
console.log("in");
$('#empty_space').css('background-image','url(https://images.pexels.com/photos/346766/pexels-photo-346766.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940)');
});
*/
var num=3;
$('#plus_button').click(function(){
$('#demo3').append('<a href="javascript:;" class="list-group-item" id="sche_day_1_'+num+'">num'+num+'</a>');
num++;
})
$('button').click(){
$.ajax({
url: './',
success: function(){
alert('success');
},
failure: function(){
alert('fail');
}
});
}<file_sep>def extract_article(request):#extract article to list tourist sites
if request.method == 'POST':
result = []
sentence = request.POST['article']
#print(sentence[1:5])
if(sentence[0:5]=='在炎炎夏日'):
'''
temp_list = [[]]
i = 0
site_list = ([['文章牛肉湯','劍獅公園','南泉冰菓室','夕遊出張所','安平樹屋','安平古堡','燒貨美食'],
['深藍咖啡館','德陽艦軍艦博物館','虱目魚主題館','綠芝屋意麵','成功大學','台南知事官邸'],
['六千牛肉湯','藍晒圖','台灣文學館','原鶯料理','林百貨','文創園區']])
for item in site_list:
print(item)
for inner_item in item:
#print(inner_item)
temp = MapSite.objects.get(name = inner_item)
temp_list[i].append({
'name':temp.name,
'location':temp.location,
'phone number':temp.phone_number,
'address':temp.address
})
result.append(temp_list[i])
temp_list.append([])
i += 1
print(result)
with open('site_result.json','w',encoding='utf-8') as f:
json.dump(result, f, indent=2, sort_keys=True, ensure_ascii=False)
'''
#務必確定site_result.json可以打開
with open('site_result.json','r',encoding='utf-8') as f:
result = json.loads(f.read())
else:
print('else')
result = jieba_test.find_sites(sentence)
#result = ["藍晒圖文創園區","321巷 藝術聚落","銀同社區貓咪高地","蝸牛巷","巨大扭蛋機","神農街","原鶯料理","綠芝屋意麵","暖暖蛇"]
result = decide_course(result)
# print(result)
#修改看要render到哪裡
return render(request,'result.html',locals())
return render(request,'extract.html')
def decide_course(original_course):
result = []
site = []
food = []
new_site = []
adjust_course = [[]]
empty_list = []
result = []
small_result = [[]]
day = 0
'''
with open('site_info.json', 'r', encoding='utf-8') as f:
json_dict = json.loads(f.read(),encoding="utf-8")
for dic in json_dict:
if dic["sort"]=="site":
site.append(dic["name"])
elif dic["sort"]=="food":
food.append(dic["name"])
#print (site)
'''
#把景點作2分法
for item in original_course:
m = MapSite.objects.filter(name__contains=item)
if(m[0]):
if(len(m[0].site_type)==1):
if(m[0].site_type=='j'):
food.append(m[0])
else:
token = m[0].site_type.split(',')
for i in token:
if(i=='j'):#type =food
food.append(m[0])
break
else:
site.append(m[0])
#生產行程
i = 0
j = 0
number = 0
print(site)
print(food)
while(i<site.__len__() or j<food.__len__()):
print('i=',i,'j=',j)
if(i>=len(site)):
for jj in range(j,len(food)):
adjust_course[day].append(food[jj])
print(food[jj])
break
else:
adjust_course[day].append(site[i])
print(site[i])
i += 1
number += 1
if(number%2==0):
if(j<food.__len__()):
adjust_course[day].append(food[j])
print(food[j])
j += 1
if(j%2==0):
adjust_course.append(empty_list)#2個food就換成下一天
print(adjust_course)
day += 1
number = 0
else:
for ii in range(i,len(site)):
adjust_course[day].append(site[ii])
break
print('final:',adjust_course,len(item))
i = 0
j = 0
#print(adjust_course)
for item in adjust_course:
print(item)
print(len(item))
for inner_item in item:
#small_result可再增加需要回傳的資訊
#print(i)
print(inner_item,j)
try:
small_result[i].append({
'name':inner_item.name,
'location':inner_item.location,
'phone number':inner_item.phone_number,
'address':inner_item.address
})
except:
break
result.append(small_result[i])
small_result.append(empty_list)
i += 1
j = 0
#print(result)
#result形式上會是[ [...], [...], [...], [...]... ]
#每一個inner list 都代表一天
return result
|
c88da1fed41e8543bb3f322dda43c40548194daf
|
[
"JavaScript",
"Python"
] | 15 |
Python
|
jason871110/travelMap
|
2eae15b761dba165cd85ffa7fda17748f59f5257
|
581a9b0cb9bc3d28e74e9c503e3e86177124519f
|
refs/heads/master
|
<file_sep>/**
* Copyright 2015, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {Alert, Accordion, Panel, Glyphicon} = require('react-bootstrap');
const ReactSwipe = require('react-swipe');
const FeatureInfoUtils = require('../../../MapStore2/web/client/utils/FeatureInfoUtils');
const MapInfoUtils = require('../../../MapStore2/web/client/utils/MapInfoUtils');
MapInfoUtils.AVAILABLE_FORMAT = ['TEXT', 'JSON', 'HTML', 'GML3'];
const I18N = require('../../../MapStore2/web/client/components/I18N/I18N');
const TemplateUtils = require('../../utils/TemplateUtils');
const {bindActionCreators} = require('redux');
const {connect} = require('react-redux');
const {changeMapView} = require('../../../MapStore2/web/client/actions/map');
const {selectFeatures} = require('../../actions/featuregrid');
const FeatureGrid = connect((state) => {
return {
map: (state.map && state.map) || (state.config && state.config.map),
features: state.featuregrid && state.featuregrid.features || []
};
}, dispatch => {
return bindActionCreators({
selectFeatures: selectFeatures,
changeMapView: changeMapView
}, dispatch);
})(require('../../../MapStore2/web/client/components/data/featuregrid/FeatureGrid'));
const Spinner = require('../../../MapStore2/web/client/components/misc/spinners/BasicSpinner/BasicSpinner');
const TopologyInfoViewer = React.createClass({
propTypes: {
responses: React.PropTypes.array,
missingRequests: React.PropTypes.number,
infoTopologyResponse: React.PropTypes.object,
display: React.PropTypes.string,
// modelConfig: React.PropTypes.object,
topologyConfig: React.PropTypes.object,
actions: React.PropTypes.shape({
setFeatures: React.PropTypes.func
})
},
getDefaultProps() {
return {
display: "accordion",
responses: [],
missingRequests: 0,
actions: {
setFeatures: () => {}
}
};
},
getValidator(infoFormat) {
const infoFormats = MapInfoUtils.getAvailableInfoFormat();
switch (infoFormat) {
case infoFormats.JSON:
return FeatureInfoUtils.Validator.JSON;
case infoFormats.HTML:
return FeatureInfoUtils.Validator.HTML;
case infoFormats.TEXT:
return FeatureInfoUtils.Validator.TEXT;
case infoFormats.GML3:
return FeatureInfoUtils.Validator.GML3;
default:
return null;
}
},
/**
* Render a single layer feature info
*/
renderInfoPage(layerId) {
let columns;
if (this.props.infoTopologyResponse &&
this.props.infoTopologyResponse[layerId] &&
this.props.topologyConfig &&
this.props.topologyConfig[layerId] &&
this.props.topologyConfig[layerId].modelConfig) {
columns = this.props.topologyConfig[layerId].modelConfig.columns.filter((element) => element.type !== TemplateUtils.GEOMETRY_TYPE);
columns = columns.map((element) => {
return {
headerName: element.header,
field: "properties." + element.field,
width: element.width
};
});
}
return this.props.infoTopologyResponse &&
this.props.infoTopologyResponse[layerId] &&
this.props.topologyConfig &&
this.props.topologyConfig[layerId] &&
this.props.topologyConfig[layerId].modelConfig ? (
<FeatureGrid
columnDefs={columns}
toolbar={{
zoom: false,
exporter: false,
toolPanel: false
}}
style={{height: "300px", width: "100%"}}/>
) : (
<div style={{height: "100px", width: "100%"}}>
<div style={{
position: "relative",
width: "60px",
top: "50%",
left: "40%"}}>
<Spinner style={{width: "60px"}} spinnerName="three-bounce" noFadeIn/>
</div>
</div>
);
},
renderLeftButton() {
return <a style={{"float": "left"}} onClick={() => {this.refs.container.swipe.prev(); }}><Glyphicon glyph="chevron-left" /></a>;
},
renderRightButton() {
return <a style={{"float": "right"}} onClick={() => {this.refs.container.swipe.next(); }}><Glyphicon glyph="chevron-right" /></a>;
},
renderPageHeader(layerId) {
return (<span>{this.props.display === "accordion" ? "" : this.renderLeftButton()} <span>{this.props.topologyConfig ? this.props.topologyConfig[layerId].layerTitle : ""}</span> {this.props.display === "accordion" ? "" : this.renderRightButton()}</span>);
},
/**
* render all the feature info pages
*/
renderPages(responses) {
if (this.props.missingRequests === 0 && responses.length === 0) {
return (
<Alert bsStyle={"danger"}>
<h4><I18N.HTML msgId={"noFeatureInfo"}/></h4>
</Alert>
);
}
return responses.map((res, i) => {
const pageHeader = this.renderPageHeader(res.queryParams.id);
return (
<Panel
eventKey={i}
key={i}
collapsible={this.props.display === "accordion"}
header={pageHeader}
style={this.props.display === "accordion" ?
{maxHeight: "500px", overflow: "auto"} : {maxHeight: "500px", overflow: "auto"}}>
{this.renderInfoPage(res.queryParams.id)}
</Panel>
);
});
},
render() {
const Container = this.props.display === "accordion" ? Accordion : ReactSwipe;
let validResponses = [];
this.props.responses.forEach((response) => {
let validator = this.getValidator(response.queryParams.info_format);
if (validator.getValidResponses([response])[0]) {
validResponses.push(validator.getValidResponses([response])[0]);
}
});
return (
<div>
<Container ref="container" defaultActiveKey={0} key={"swiper-" + this.props.responses.length + "-" + this.props.missingRequests} shouldUpdate={(nextProps, props) => {return nextProps !== props; }}>
{this.renderPages(validResponses)}
</Container>
</div>
);
}
});
module.exports = TopologyInfoViewer;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {connect} = require('react-redux');
const Sidebar = require('react-sidebar').default;
const SideQueryPanel = require('../components/SideQueryPanel');
const SideFeatureGrid = require('../components/SideFeatureGrid');
const {changeMapStyle} = require('../../MapStore2/web/client/actions/map');
const {expandFilterPanel} = require('../actions/siradec');
const Resizable = require('react-resizable').Resizable;
const Spinner = require('react-spinkit');
require('../../assets/css/sira.css');
const SidePanel = React.createClass({
propTypes: {
filterPanelExpanded: React.PropTypes.bool,
gridExpanded: React.PropTypes.bool,
auth: React.PropTypes.object,
profile: React.PropTypes.string,
changeMapStyle: React.PropTypes.func,
withMap: React.PropTypes.bool.isRequired,
expandFilterPanel: React.PropTypes.func.isRequired,
fTypeConfigLoading: React.PropTypes.bool.isRequired
},
contextTypes: {
messages: React.PropTypes.object
},
getInitialState: function() {
return {
width: 600,
boxwidth: 600
};
},
getDefaultProps() {
return {
filterPanelExpanded: false,
gridExpanded: false,
withMap: true,
fTypeConfigLoading: true,
expandFilterPanel: () => {},
changeMapStyle: () => {}
};
},
componentDidMount() {
if (this.props.withMap && (this.props.filterPanelExpanded || this.props.gridExpanded)) {
let style = {left: this.state.width, width: `calc(100% - ${this.state.width}px)`};
this.props.changeMapStyle(style, "sirasidepanel");
}
},
componentDidUpdate(prevProps) {
const prevShowing = prevProps.filterPanelExpanded || prevProps.gridExpanded;
const show = this.props.filterPanelExpanded || this.props.gridExpanded;
if (prevShowing !== show && this.props.withMap) {
let style = show ? {left: this.state.width, width: `calc(100% - ${this.state.width}px)`} : {};
this.props.changeMapStyle(style, "sirasidepanel");
}
},
onResize(event, obj) {
const {size} = obj;
this.setState({boxwidth: size.width});
},
onResizeStop(event, obj) {
const {size} = obj;
this.setState({width: size.width, boxwidth: size.width});
this.props.changeMapStyle({left: size.width, width: `calc(100% - ${size.width}px)`}, "sirasidepanel");
},
renderQueryPanel() {
return (<SideQueryPanel
withMap={this.props.withMap}
params={this.props.auth}
toggleControl={this.props.expandFilterPanel.bind(null, false)}
/>);
},
renderGrid() {
return (<SideFeatureGrid
withMap={this.props.withMap}
initWidth={this.state.width}
params={this.props.auth}
profile={this.props.profile}/>);
},
renderLoading() {
return (
<div style={{
position: "absolute",
width: "60px",
top: "50%",
left: "45%"}}>
<Spinner style={{width: "60px"}} spinnerName="three-bounce" noFadeIn/>
</div>
);
},
renderContent() {
let comp;
if (this.props.filterPanelExpanded) {
comp = this.renderQueryPanel();
}else if (this.props.gridExpanded) {
comp = this.renderGrid();
}else {
comp = (<div/>);
}
return (
<Resizable
draggableOpts={{grid: [10, 0]}}
onResize={this.onResize}
width={this.state.boxwidth}
height={100}
onResizeStop={this.onResizeStop}
minConstraints={[400]}
className="box">
<div className="box" style={{width: `${this.state.boxwidth}px`, height: "100%"}}>
{comp}
</div>
</Resizable>);
},
render() {
const show = this.props.filterPanelExpanded || this.props.gridExpanded;
return (
<Sidebar
open={show}
sidebar={this.props.fTypeConfigLoading ? this.renderLoading() : this.renderContent()}
styles={{
sidebar: {
backgroundColor: 'white',
zIndex: 1024,
width: this.state.boxwidth,
overflowX: 'hidden'
},
overlay: {
zIndex: 1023,
width: 0
},
root: {
right: show ? 0 : 'auto',
width: '0',
overflow: 'visible'
}
}}
>
<div/>
</Sidebar>
);
}
});
module.exports = connect((state) => {
return {
filterPanelExpanded: state.siradec.filterPanelExpanded,
gridExpanded: state.siraControls.grid,
fTypeConfigLoading: state.siradec.fTypeConfigLoading
};
}, {
changeMapStyle,
expandFilterPanel
})(SidePanel);
<file_sep>/**
* Copyright 2017, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const {
SIRA_RECORDS_LOADING,
SIRA_RECORDS_ERROR,
SIRA_RECORDS_LOADED,
TOGGLE_ADD_MAP_MODAL} = require('../actions/addmap');
const assign = require('object-assign');
const initialState = {
loading: false,
error: null,
show: false,
records: [],
node: null
};
function addmap(state = initialState, action) {
switch (action.type) {
case SIRA_RECORDS_LOADING: {
return action.status ? assign({}, state, {
records: [],
node: action.node,
loading: action.status,
error: null
}) : assign({}, state, {
loading: action.status});
}
case SIRA_RECORDS_ERROR: {
return assign({}, state, {
error: action.error,
records: []
});
}
case TOGGLE_ADD_MAP_MODAL: {
return assign({}, state, {
show: action.status,
error: null
});
}
case SIRA_RECORDS_LOADED: {
return assign({}, state, {
node: action.node,
records: action.result
});
}
default:
return state;
}
}
module.exports = addmap;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const msLayers = require('../../MapStore2/web/client/reducers/layers');
const assign = require('object-assign');
const {isObject, head, findIndex} = require('lodash');
const {SHOW_SETTINGS, HIDE_SETTINGS, TOGGLE_NODE, addLayer} = require('../../MapStore2/web/client/actions/layers');
const {SELECT_FEATURES, SET_FEATURES, SELECT_ALL} = require('../actions/featuregrid');
const {CONFIGURE_INFO_TOPOLOGY, CHANGE_MAPINFO_STATE, CHANGE_TOPOLOGY_MAPINFO_STATE} = require('../actions/mapInfo');
const ConfigUtils = require('../../MapStore2/web/client/utils/ConfigUtils');
const getVector = (state) => {
return state.flat ? head(state.flat.filter((l) => l.id === "gridItems" )) : undefined;
};
const checkSelectLayer = (state, vector) => {
if (state.flat && state.flat.length > 1 && (state.flat[state.flat.length - 1]).id !== "gridItems") {
const newLayers = state.flat.filter((l) => l.id !== "gridItems").concat(getVector(state) || vector).filter((l) => l);
return assign({}, state, {flat: newLayers});
}
return state;
};
const filterHiddenGroup = (state) => {
if (state.groups) {
return assign({}, state, {groups: state.groups.filter((g) => g.id !== "hidden")});
}
return state;
};
const checkState = (state, vector) => {
return filterHiddenGroup(checkSelectLayer(state, vector));
};
const getAction = (layer, features) => {
return {
type: "CHANGE_LAYER_PROPERTIES",
layer,
newProperties: { features }
};
};
const cloneLayer = (layer) => {
let newLayer = {};
Object.keys(layer).reduce((pr, next) => {
pr[next] = isObject(layer[next]) ? assign({}, layer[next]) : layer[next];
return pr;
}, newLayer);
return newLayer;
};
function layers(state = [], action) {
switch (action.type) {
case CHANGE_TOPOLOGY_MAPINFO_STATE:
case CHANGE_MAPINFO_STATE: {
let tmpState = msLayers(state, getAction("gridItems", []) );
return msLayers(tmpState, getAction("topologyItems", []));
}
case SELECT_FEATURES:
return msLayers(state, getAction("gridItems", action.features) );
case SET_FEATURES:
case CONFIGURE_INFO_TOPOLOGY:
return msLayers(state, getAction("topologyItems", action.features || action.infoTopologyResponse.features));
case SHOW_SETTINGS: {
return msLayers(msLayers(state, {
type: TOGGLE_NODE,
node: action.node,
nodeType: "layers",
status: true}), action);
}
case HIDE_SETTINGS: {
return msLayers(msLayers(state, {
type: 'TOGGLE_NODE',
node: action.node,
nodeType: "layers",
status: false}), action);
}
case SELECT_ALL: {
if (action.sldBody && action.featureTypeName) {
let layer = head(state.flat.filter(l => l.name === `${action.featureTypeName}`));
if (layer) {
let allLayer = head(state.flat.filter(l => l.id === "selectAll"));
if (allLayer) {
let params = {params: {...allLayer.params, SLD_BODY: action.sldBody}};
return msLayers(state, { type: "CHANGE_LAYER_PROPERTIES",
layer: allLayer.id,
newProperties: params
});
}
let newLayer = cloneLayer(layer);
newLayer.id = "selectAll";
newLayer.type = "wmspost";
newLayer.visibility = true;
delete newLayer.group;
newLayer.params = assign({}, newLayer.params, {SLD_BODY: action.sldBody});
return msLayers(state, { type: "ADD_LAYER", layer: newLayer});
}
}
let allLayer = head(state.flat.filter(l => l.id === "selectAll"));
return allLayer ? msLayers(state, { type: "REMOVE_NODE", nodeType: 'layers', node: 'selectAll'}) : msLayers(state, action);
}
case 'THEMATIC_VIEW_CONFIG_LOADED': {
// We exclude background layers and we add the rest
const oldLayers = state.flat;
if ( action.config && action.config.map && action.config && action.config.map.layers) {
return action.config.map.layers.filter((l) => l.group !== 'background' && findIndex(oldLayers, (ol) => ol.name === l.name) === -1).reduce((st, layer) => {
return msLayers(st, addLayer(ConfigUtils.setUrlPlaceholders(layer)));
}, state);
}
return state;
}
case 'SIRA_ADD_LAYERS': {
return action.layers.reduce((tempState, layer) => {
return msLayers(tempState, {type: 'ADD_LAYER', layer});
}, state );
}
default:
return msLayers(state, action);
}
}
function checkedLayers(state = [], action) {
const newState = layers(state, action);
if ( newState !== state) {
const vector = getVector(state);
return checkState(newState, vector);
}
return newState;
}
module.exports = checkedLayers;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
var {FormattedDate} = require('react-intl');
const LocaleUtils = require('../../../../MapStore2/web/client/utils/LocaleUtils');
const LabeledField = React.createClass({
propTypes: {
label: React.PropTypes.string,
value: React.PropTypes.any,
dateFormat: React.PropTypes.object,
locale: React.PropTypes.string
},
getDefaultProps() {
return {
label: '',
value: null,
locale: 'it-IT'
};
},
renderDate(value, dateFormat) {
const date = new Date(value);
return !isNaN(date.getTime()) ? (<FormattedDate locales={this.props.locale} value={date} {...dateFormat} />) : (<span/>);
},
renderValue(value) {
return this.props.dateFormat ? this.renderDate(value, this.props.dateFormat) : value;
},
render() {
return (
<table className="labeledfield">
<thead>
<tr>
<th>
label
</th>
<th>
{this.props.label}
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
{this.props.label}
</td>
<td>
{this.props.value ? this.renderValue(this.props.value) : LocaleUtils.getMessageById(this.context.messages, "labeledfield.label_value_not_specified")}
</td>
</tr>
</tbody>
</table>
);
}
});
module.exports = LabeledField;
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>it.geosolutions.csi.sira</groupId>
<artifactId>sira-root</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>sira-web</artifactId>
<packaging>war</packaging>
<name>CSI SIRA - WAR</name>
<url>http://www.geo-solutions.it</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<url.geoserver>http://tst-gisserver.territorio.csi.it</url.geoserver>
<url.secure.geoserver>https://tst-conoscenzaambientale.sistemapiemonte.it</url.secure.geoserver>
<url.secure.decsiraweb>https://tst-conoscenzaambientale.sistemapiemonte.it/decsiraweb/map.html</url.secure.decsiraweb>
<url.decsiraweb>http://tst-conoscenzaambientale.sistemapiemonte.it/decsiraweb/map.html</url.decsiraweb>
<component.name>decsiraweb</component.name>
<component.version>1.0.0</component.version>
</properties>
<dependencies>
<!-- ================================================================ -->
<!-- CSI SIRA modules -->
<!-- ================================================================ -->
<dependency>
<groupId>it.geosolutions.csi.sira</groupId>
<artifactId>sira-backend</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>it.geosolutions.csi.sira</groupId>
<artifactId>metadata-services</artifactId>
<version>${project.version}</version>
<exclusions>
<exclusion>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>it.geosolutions.csi.sira</groupId>
<artifactId>iride-services</artifactId>
<version>${project.version}</version>
<exclusions>
<exclusion>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</exclusion>
<exclusion>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</exclusion>
<exclusion>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</exclusion>
<exclusion>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- ================================================================ -->
<!-- GeoStore modules -->
<!-- ================================================================ -->
<dependency>
<groupId>it.geosolutions.geostore</groupId>
<artifactId>geostore-webapp</artifactId>
<version>1.3-SNAPSHOT</version>
<type>war</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>proxy</groupId>
<artifactId>http_proxy</artifactId>
<version>1.1-SNAPSHOT</version>
<type>war</type>
<scope>runtime</scope>
</dependency>
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
<build>
<finalName>decsiraweb</finalName>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>html, configuration files and images</id>
<phase>process-classes</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/decsiraweb</outputDirectory>
<encoding>UTF-8</encoding>
<resources>
<resource>
<directory>${basedir}/..</directory>
<includes>
<include>*.html</include>
<include>*.json</include>
<include>img/*</include>
</includes>
<excludes>
<exclude>MapStore2/*</exclude>
<exclude>MapStore2/**/*</exclude>
</excludes>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
<execution>
<id>js files</id>
<phase>process-classes</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/decsiraweb/dist</outputDirectory>
<encoding>UTF-8</encoding>
<resources>
<resource>
<directory>${basedir}/../dist</directory>
</resource>
</resources>
</configuration>
</execution>
<execution>
<id>CSS files</id>
<phase>process-classes</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/decsiraweb/assets</outputDirectory>
<encoding>UTF-8</encoding>
<resources>
<resource>
<directory>${basedir}/../assets</directory>
</resource>
</resources>
</configuration>
</execution>
<execution>
<id>translations</id>
<phase>process-classes</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/decsiraweb</outputDirectory>
<encoding>UTF-8</encoding>
<resources>
<resource>
<directory>${basedir}/..</directory>
<includes>
<include>translations/*</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<overlays>
<overlay>
<groupId>it.geosolutions.geostore</groupId>
<artifactId>geostore-webapp</artifactId>
<excludes>
<exclude>WEB-INF/lib/commons-io-*</exclude>
<exclude>WEB-INF/lib/commons-lang-*</exclude>
<exclude>WEB-INF/lib/commons-logging-*</exclude>
</excludes>
</overlay>
<overlay>
<groupId>proxy</groupId>
<artifactId>http_proxy</artifactId>
<excludes>
<exclude>WEB-INF/lib/commons-codec-*</exclude>
<exclude>WEB-INF/lib/commons-io-*</exclude>
<exclude>WEB-INF/lib/commons-logging-*</exclude>
<exclude>WEB-INF/lib/log4j-*</exclude>
</excludes>
</overlay>
</overlays>
</configuration>
</plugin>
<!-- configurazione standard CSI per la UI -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<finalName>${component.name}-${component.version}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<filters>
<filter>src/assembly/filter.properties</filter>
</filters>
<descriptors>
<descriptor>src/assembly/distribution.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Run the application using "mvn jetty:run" -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.14.v20161028</version>
<configuration>
<webApp>
<contextPath>/decsiraweb</contextPath>
</webApp>
<httpConnector>
<port>9191</port>
<idleTimeout>60000</idleTimeout>
</httpConnector>
<war>${project.basedir}/target/decsiraweb.war</war>
</configuration>
<dependencies>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>produzione</id>
<properties>
<url.geoserver>http://gisserver.territorio.csi.it</url.geoserver>
<url.secure.geoserver>https://conoscenzaambientale.sistemapiemonte.it</url.secure.geoserver>
<url.secure.decsiraweb>https://conoscenzaambientale.sistemapiemonte.it/decsiraweb/map.html</url.secure.decsiraweb>
<url.decsiraweb>http://conoscenzaambientale.sistemapiemonte.it/decsiraweb/map.html</url.decsiraweb>
<component.name>decsiraweb</component.name>
<component.version>1.0.0</component.version>
</properties>
</profile>
<profile>
<id>demo</id>
<properties>
<url.geoserver>http://sira.csi.geo-solutions.it</url.geoserver>
<url.secure.geoserver>https://sira.csi.geo-solutions.it</url.secure.geoserver>
<component.name>decsiraweb</component.name>
<component.version>1.0.0</component.version>
</properties>
</profile>
</profiles>
</project>
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const XPath = require('xpath');
const Dom = require('xmldom').DOMParser;
const parse = require('wellknown');
const assign = require('object-assign');
const {isArray} = require('lodash');
const TemplateUtils = {
NUMBER_TYPE: 1,
STRING_TYPE: 2,
BOOLEAN_TYPE: 3,
OBJECT_TYPE: 4,
ARRAY_TYPE: 5,
GEOMETRY_TYPE: 6,
nsResolver(wfsVersion="2.0", nameSpaces = {}) {
switch (wfsVersion) {
case "1.1.0": {
return assign({}, nameSpaces, {
"wfs": "http://www.opengis.net/wfs",
"gml": "http://www.opengis.net/gml",
"ms": "http://mapserver.gis.umn.edu/mapserver"
});
}
case "2.0": {
return assign({}, nameSpaces, {
"wfs": "http://www.opengis.net/wfs/2.0",
"gml": "http://www.opengis.net/gml/3.2"
});
}
default:
return assign({}, nameSpaces, {
"wfs": "http://www.opengis.net/wfs",
"gml": "http://www.opengis.net/gml"
});
}
},
getNamespaces(attributes) {
const nameSpaces = {};
for (let count = 0; count < attributes.length; count++) {
const attr = attributes[count];
if (attr.prefix === 'xmlns') {
nameSpaces[attr.localName] = attr.nodeValue;
}
}
return nameSpaces;
},
getModels(data, root, config, wfsVersion="2.0") {
let doc = new Dom().parseFromString(data);
let select = XPath.useNamespaces(this.nsResolver(wfsVersion, this.getNamespaces(doc.documentElement.attributes)));
let rows = select(root, doc);
return rows.map((row) => {
return this.getModel(data, config, row, wfsVersion);
});
},
getModel(data, config, el, wfsVersion="2.0") {
let doc = el || new Dom().parseFromString(data);
let model = {};
for (let element in config) {
if (config[element]) {
model[config[element].field] = this.getElement(config[element], doc, wfsVersion);
}
}
return model;
},
getElementValue(result, type, wfsVersion="2.0") {
switch (type) {
case 1 /*NUMBER_TYPE*/: {
return parseFloat(result && result.nodeValue || '0');
}
case 2 /*STRING_TYPE*/: {
return result && result.nodeValue || '';
}
case 3 /*BOOLEAN_TYPE*/: {
return result && result.nodeValue === "true" || false;
}
case 6 /*GEOMETRY_TYPE*/: {
let value;
if (wfsVersion === "2.0") {
value = result && result.nodeValue || {};
} else {
value = result && result.nodeValue && parse(result.nodeValue) || result && result.nodeValue || {};
}
return value;
}
default: return result.nodeValue || result;
}
},
getElement(element, doc, wfsVersion="2.0") {
let select = XPath.useNamespaces(this.nsResolver(wfsVersion, this.getNamespaces((doc.documentElement || doc.ownerDocument.documentElement).attributes)));
let value = "";
let result;
const me = this;
if (!element.type) {
let values = [];
let results = select(element.xpath, doc);
results.forEach((res) => {
values.push(this.getElementValue(res));
});
value = values.length > 1 ? values : values[0];
}
if (element.type === this.OBJECT_TYPE) {
let values = [];
let results = select(element.xpath, doc);
results.forEach((res) => {
value = {};
element.fields.forEach((f) => {
let r = select(f.xpath, res)[0];
value[f.field] = (f.type === me.OBJECT_TYPE) ? me.getElement(f, res, wfsVersion) : this.getElementValue(r, f.type, wfsVersion);
});
values.push(value);
});
value = values;
} else if (element.type === this.ARRAY_TYPE) {
let values = [];
let results = select(element.xpath, doc);
results.forEach((res) => {
if (element.fields) {
value = {};
element.fields.forEach((f) => {
let r = select(f.xpath, res);
r.forEach((v) => {
value[f.field] = (f.type === me.OBJECT_TYPE) ? me.getElement(f, v, wfsVersion) : this.getElementValue(v, f.type, wfsVersion);
});
});
values.push(value);
} else {
values.push(this.getElementValue(res, element.type, wfsVersion));
}
});
value = values;
} else if (element.type === this.GEOMETRY_TYPE) {
let results = select(element.xpath, doc);
let values = [];
for (let k = 0; k < results.length; k++) {
result = results[k];
value = this.getElementValue(result, element.type, wfsVersion);
if (wfsVersion === "2.0" || !value.geometry) {
try {
let coords = value.split(" ");
let coordinates = [];
for (let j = 0; j < coords.length; j = j + 2) {
if (j + 1 <= coords.length) {
if (parseFloat(coords[j]) && parseFloat(coords[j + 1])) {
coordinates.push([parseFloat(coords[j]), parseFloat(coords[j + 1])]);
}
}
}
value = {
type: "geometry",
coordinates: coordinates
};
} catch(e) {
value = value;
}
}
values.push(value);
}
if (values.length > 1) {
let coordinates = [];
for (let k = 0; k < values.length; k++) {
let coords = values[k].coordinates;
for (let l = 0; l < coords.length; l++) {
coordinates.push(coords[l]);
}
}
value = {
type: "geometry",
coordinates: coordinates
};
} else {
value = values[0];
}
} else if (element.type === this.STRING_TYPE) {
for (let i = 0; i < element.xpath.length; i++) {
result = select(element.xpath[i], doc)[0];
// if (element.type === this.STRING_TYPE) {
if (i > 0) {
value += " ";
}
value += this.getElementValue(result, element.type, wfsVersion);
/*} else {
value = this.getElementValue(result, element.type, wfsVersion);
}*/
}
} else if (element.type === this.NUMBER_TYPE) {
result = select(element.xpath, doc)[0];
value = this.getElementValue(result, element.type, wfsVersion);
}
return value;
},
getValue(xml, element, wfsVersion="2.0") {
let doc = new Dom().parseFromString(xml);
let value;
if (typeof element === "object") {
value = this.getElement(element, doc, wfsVersion);
} else {
let select = XPath.useNamespaces(this.nsResolver(wfsVersion, this.getNamespaces(doc.documentElement.attributes)));
let values = [];
let results = select(element, doc);
results.forEach((res) => {
values.push(this.getElementValue(res));
});
value = values.length > 1 ? values : values[0];
}
return value;
},
getList(xml, element, wfsVersion) {
const result = TemplateUtils.getValue(xml, element, wfsVersion);
if (!isArray(result)) {
return [result];
}
return result;
},
getNumberOfFeatures(data, wfsVersion="2.0") {
let doc = new Dom().parseFromString(data);
let select = XPath.useNamespaces(this.nsResolver(wfsVersion, this.getNamespaces(doc.documentElement.attributes)));
let elements = select("/wfs:ValueCollection/wfs:member", doc);
return elements.length;
},
verifyProfiles(fieldProfiles, userProfiles) {
let check = false;
let userProfilesOk = userProfiles;
if (userProfilesOk && !isArray(userProfilesOk)) {
userProfilesOk = [];
userProfilesOk.push(userProfiles);
}
if (!fieldProfiles || fieldProfiles.length === 0) return true;
if (!userProfilesOk || userProfilesOk.length === 0) return false;
fieldProfiles.forEach((val) => {
if (userProfilesOk.filter((profile) => profile === val).length > 0) {
check = true;
}});
return check;
}
};
module.exports = TemplateUtils;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const {
CARD_TEMPLATE_LOADED, CARD_TEMPLATE_LOAD_ERROR,
SELECT_SECTION, ACTIVE_SECTION, SELECT_ROWS, GENERATE_PDF,
MAP_IMAGE_READY// , SET_IMPIANTO_MODEL
} = require('../actions/card');
const assign = require('object-assign');
const initialState = {
generatepdf: false,
show: false,
template: null,
xml: null,
mapImageReady: false
// impiantoModel: null
};
function cardtemplate(state = initialState, action) {
switch (action.type) {
case CARD_TEMPLATE_LOADED: {
return assign({}, state, {
template: action.template,
xml: action.xml || state.xml,
activeSections: null,
params: action.params
});
}
case CARD_TEMPLATE_LOAD_ERROR: {
return assign({}, state, {
loadingCardTemplateError: action.error,
params: {}
});
}
case SELECT_SECTION: {
const newSections = assign({}, state.activeSections);
newSections[action.section] = action.active;
return assign({}, state, {
activeSections: newSections
});
}
case ACTIVE_SECTION: {
let newSections = {};
newSections[action.section] = true;
return assign({}, state, {
activeSections: newSections
});
}
case SELECT_ROWS: {
// let model = assign({}, state.model);
// model[action.table_id] = action.rows;
return assign({}, state, {[action.tableId]: action.rows});
}
case GENERATE_PDF: {
return assign({}, state, {generatepdf: action.active});
}
case MAP_IMAGE_READY: {
return assign({}, state, {mapImageReady: action.state});
}
/* case SET_IMPIANTO_MODEL: {
return assign({}, state, {impiantoModel: action.impiantoModel});
} */
default:
return state;
}
}
module.exports = cardtemplate;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const {CLICK_ON_MAP} = require('../../MapStore2/web/client/actions/map');
const {
ERROR_FEATURE_INFO,
EXCEPTIONS_FEATURE_INFO,
LOAD_FEATURE_INFO,
CHANGE_MAPINFO_STATE,
NEW_MAPINFO_REQUEST,
PURGE_MAPINFO_RESULTS,
CHANGE_MAPINFO_FORMAT,
SHOW_MAPINFO_MARKER,
HIDE_MAPINFO_MARKER,
LOAD_TEMPLATE_INFO,
CONFIGURE_GET_FEATURE_INFO_ERROR,
CONFIGURE_GET_FEATURE_INFO,
CHANGE_TOPOLOGY_MAPINFO_STATE,
SET_MODEL_CONFIG,
CONFIGURE_INFO_TOPOLOGY} = require('../actions/mapInfo');
const assign = require('object-assign');
const initialState = {
detailsConfig: null,
// modelConfig: null,
template: null,
topologyConfig: null,
infoTopologyResponse: null
};
function mapInfo(state = initialState, action) {
switch (action.type) {
case CHANGE_MAPINFO_STATE: {
return assign({}, state, {
infoEnabled: action.enabled,
topologyInfoEnabled: false,
infoType: "getfeatureinfo",
responses: [],
requests: {length: 0},
detailsConfig: null,
// modelConfig: null,
template: null
});
}
case NEW_MAPINFO_REQUEST: {
let newRequests;
let {reqId, request} = action;
newRequests = assign({}, state.requests);
newRequests.length = (newRequests.length) ? newRequests.length + 1 : 1;
newRequests[reqId] = assign({}, { request: request});
return assign({}, state, {
requests: newRequests
});
}
case PURGE_MAPINFO_RESULTS:
return assign({}, state, {
responses: [],
requests: {length: 0}
});
case LOAD_FEATURE_INFO: {
/* action.data (if a JSON has been requested) is an object like this:
* {
* crs: [object],
* features: [array],
* type: [string]
* }
* else is a [string] (for eg. if HTML data has been requested)
*/
let newState;
if (state.requests && state.requests[action.reqId]) {
let newResponses;
let obj = {
response: action.data,
queryParams: action.requestParams,
layerMetadata: action.layerMetadata
};
if (state.responses) {
newResponses = state.responses.slice();
newResponses.push(obj);
} else {
newResponses = [obj];
}
newState = assign({}, state, {
responses: newResponses
});
}
return (newState) ? newState : state;
}
case EXCEPTIONS_FEATURE_INFO: {
/* action.exceptions, an array of exceptions like this:
* [{
* code: [string],
* locator: [string],
* text: [string]
* }, ...]
*/
let newState;
if (state.requests && state.requests[action.reqId]) {
let newResponses;
let obj = {
response: action.exceptions,
queryParams: action.requestParams,
layerMetadata: action.layerMetadata
};
if (state.responses) {
newResponses = state.responses.slice();
newResponses.push(obj);
} else {
newResponses = [obj];
}
newState = assign({}, state, {
responses: newResponses
});
}
return (newState) ? newState : state;
}
case ERROR_FEATURE_INFO: {
/* action.error, an Object like this:
* {
* config: [Object],
* data: [string],
* headers: [Object],
* status: [number],
* statusText: [string]
* }
*/
let newState;
if (state.requests && state.requests[action.reqId]) {
let newResponses;
let obj = {
response: action.error,
queryParams: action.requestParams,
layerMetadata: action.layerMetadata
};
if (state.responses) {
newResponses = state.responses.slice();
newResponses.push(obj);
} else {
newResponses = [obj];
}
newState = assign({}, state, {
responses: newResponses
});
}
return (newState) ? newState : state;
}
case CLICK_ON_MAP: {
return assign({}, state, {
clickPoint: action.point
});
}
case CHANGE_MAPINFO_FORMAT: {
return assign({}, state, {
infoFormat: action.infoFormat
});
}
case SHOW_MAPINFO_MARKER: {
return assign({}, state, {
showMarker: true
});
}
case HIDE_MAPINFO_MARKER: {
return assign({}, state, {
showMarker: false
});
}
// ---------------------- SIRA ----------------------- //
case CONFIGURE_INFO_TOPOLOGY: {
// let modelConfig = assign({}, state.modelConfig, {[action.layerId]: action.modelConfig.modelConfig});
let topologyConfig = assign({}, action.topologyConfig, {modelConfig: action.modelConfig});
topologyConfig = assign({}, state.topologyConfig, {[action.layerId]: topologyConfig});
let infoTopologyResponse = assign({}, state.infoTopologyResponse, {[action.layerId]: action.infoTopologyResponse});
return assign({}, state, {
// modelConfig: modelConfig,
topologyConfig: topologyConfig,
infoTopologyResponse: infoTopologyResponse
});
}
case CHANGE_TOPOLOGY_MAPINFO_STATE: {
return assign({}, state, {
topologyInfoEnabled: action.enabled,
infoEnabled: false,
infoType: "topology",
responses: [],
requests: {length: 0},
detailsConfig: null,
// modelConfig: null,
template: null
});
}
case CONFIGURE_GET_FEATURE_INFO: {
let detailsConfig = assign({}, state.detailsConfig, {[action.layerId]: action.config});
// let modelConfig = assign({}, state.modelConfig, {[action.layerId]: action.config.grid});
return assign({}, state, {
detailsConfig: detailsConfig
// modelConfig: modelConfig
});
}
case LOAD_TEMPLATE_INFO: {
let template = assign({}, state.template, {[action.layerId]: action.template});
return assign({}, state, {
template: template
});
}
case CONFIGURE_GET_FEATURE_INFO_ERROR: {
let loadingError = assign({}, state.loadingError, {[action.layerId]: action.error});
return assign({}, state, {
loadingError: loadingError
});
}
case SET_MODEL_CONFIG: {
return assign({}, state, {
modelConfig: action.config
});
}
default:
return state;
}
}
module.exports = mapInfo;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const TOGGLE_SIRA_CONTROL = 'TOGGLE_SIRA_CONTROL';
function toggleSiraControl(control) {
return {
type: TOGGLE_SIRA_CONTROL,
control
};
}
module.exports = {TOGGLE_SIRA_CONTROL, toggleSiraControl};
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {connect} = require('react-redux');
const {createSelector} = require('reselect');
const {Tabs, Tab} = require('react-bootstrap');
const Spinner = require('react-spinkit');
const {toggleNode, getThematicViewConfig, getMetadataObjects, selectSubCategory} = require('../actions/siracatalog');
const {mapSelector} = require('../../MapStore2/web/client/selectors/map');
const {tocSelector} = require('../selectors/sira');
const datasetSelector = createSelector([mapSelector, tocSelector], (map, toc) => ({map, ...toc}));
const {setProfile} = require('../actions/userprofile');
const {toggleSiraControl} = require('../actions/controls');
const {
// SiraQueryPanel action functions
expandFilterPanel,
loadFeatureTypeConfig,
setActiveFeatureType
} = require('../actions/siradec');
const {setGridType} = require('../actions/grid');
const Header = require('../components/Header');
const SiraSearchBar = require('../components/SiraSearchBar');
const TOC = require('../../MapStore2/web/client/components/TOC/TOC');
const DefaultGroup = require('../../MapStore2/web/client/components/TOC/DefaultGroup');
const DefaultNode = require('../components/catalog/DefaultNodeDataset');
const Footer = require('../components/Footer');
const Vista = require('../components/catalog/VistaDataset');
const {loadMetadata, showBox} = require('../actions/metadatainfobox');
const {hideBox, loadLegends, toggleLegendBox} = require('../actions/metadatainfobox');
const {toggleAddMap, loadNodeMapRecords, addFeatureTypeLayerInCart} = require('../actions/addmap');
const mapStateToPropsMIB = (state) => {
return {
show: state.metadatainfobox.show,
openLegendPanel: state.metadatainfobox.openLegendPanel,
title: state.metadatainfobox.title,
text: state.metadatainfobox.text,
numDatasetObjectCalc: state.metadatainfobox.numDatasetObjectCalc,
dataProvider: state.metadatainfobox.dataProvider,
urlMetadato: state.metadatainfobox.urlMetadato,
urlWMS: state.metadatainfobox.urlWMS,
urlWFS: state.metadatainfobox.urlWFS,
urlLegend: state.metadatainfobox.urlLegend,
error: state.metadatainfobox.error,
showButtonLegend: state.metadatainfobox.showButtonLegend
};
};
const mapDispatchToPropsMIB = (dispatch) => {
return {
loadLegend: (u, actualUrl) => {
if (actualUrl && actualUrl.length === 0) {
dispatch(loadLegends(u));
}
dispatch(toggleLegendBox());
},
closePanel: () => {
dispatch(hideBox());
}
};
};
const MetadataInfoBox = connect(
mapStateToPropsMIB,
mapDispatchToPropsMIB
)(require('../components/MetadataInfoBox'));
const authParams = {
admin: {
userName: "admin",
authkey: "84279da9-f0b9-4e45-ac97-48413a48e33f"
},
A: {
userName: "profiloa",
authkey: "59ccadf2-963e-448c-bc9a-b3a5e8ed20d7"
},
B: {
userName: "profilob",
authkey: "d6e5f5a5-2d26-43aa-8af3-13f8dcc0d03c"
},
C: {
userName: "profiloc",
authkey: "<KEY>"
},
D: {
userName: "profilod",
authkey: "<KEY>"
}
};
const Dataset = React.createClass({
propTypes: {
category: React.PropTypes.shape({
name: React.PropTypes.string.isRequired,
id: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]).isRequired,
icon: React.PropTypes.string.isRequired,
objectNumber: React.PropTypes.number,
tematicViewNumber: React.PropTypes.number
}),
nodes: React.PropTypes.array,
views: React.PropTypes.array,
objects: React.PropTypes.array,
loading: React.PropTypes.bool,
nodesLoaded: React.PropTypes.bool,
onToggle: React.PropTypes.func,
toggleSiraControl: React.PropTypes.func,
expandFilterPanel: React.PropTypes.func,
getMetadataObjects: React.PropTypes.func,
selectSubCategory: React.PropTypes.func,
subcat: React.PropTypes.string,
configOggetti: React.PropTypes.object,
authParams: React.PropTypes.object,
userprofile: React.PropTypes.object,
loadMetadata: React.PropTypes.func,
showInfoBox: React.PropTypes.func,
setProfile: React.PropTypes.func,
params: React.PropTypes.object,
activeFeatureType: React.PropTypes.string,
loadFeatureTypeConfig: React.PropTypes.func,
setActiveFeatureType: React.PropTypes.func,
setGridType: React.PropTypes.func,
getThematicViewConfig: React.PropTypes.func,
map: React.PropTypes.object,
toggleAddMap: React.PropTypes.func,
loadNodeMapRecords: React.PropTypes.func,
addLayersInCart: React.PropTypes.func
},
contextTypes: {
router: React.PropTypes.object
},
getInitialState() {
return {
params: {},
searchText: "",
showCategories: false,
onToggle: () => {},
setProfile: () => {}
};
},
componentWillMount() {
const {nodesLoaded, loading, category} = this.props;
if (this.props.params.profile) {
this.props.setProfile(this.props.params.profile, authParams[this.props.params.profile]);
}
// this.props.setProfile(this.props.params.profile, authParams[this.props.params.profile]);
if (!nodesLoaded && !loading && category && category.id) {
this.loadMetadata({category: category});
}
},
componentDidMount() {
document.body.className = "body_dataset";
},
componentWillReceiveProps({loading, map}) {
if (!loading && this.props.map && this.props.map !== map) {
if (this.props.params.profile) {
this.context.router.push('/map/${this.props.params.profile}/');
}else {
this.context.router.push('/map/');
}
// this.context.router.push(`/${this.props.params.profile}`);
}
},
renderSerchBar() {
return (
<SiraSearchBar
containerClasses="col-lg-12 col-md-12 col-sm-12 col-xs-12 ricerca-home catalog-search-container dataset-search-container"
searchClasses="home-search"
overlayPlacement="bottom"
mosaicContainerClasses="dataset-mosaic-container"
onSearch={this.loadMetadata}
onReset={this.loadMetadata}
/>);
},
renderSpinner() {
return (<div className="loading-container"><Spinner style={{position: "absolute", top: "calc(50%)", left: "calc(50% - 30px)", width: "60px"}} spinnerName="three-bounce" noFadeIn/></div>);
},
renderResults() {
const {loading, objects, views} = this.props;
const {showCategories} = this.state;
const searchSwitch = this.props.nodes.length > 0 ? (
<div key="categoriesSearch" className="ricerca-home dataset-categories-switch-container">
<div className="dataset-categories-switch" onClick={() => this.setState({showCategories: !showCategories})}>
<span>{showCategories ? 'Nascondi Categorie' : 'Mostra Categorie'} </span>
</div>
</div>) : (<noscript key="categoriesSearch"/>);
const tocObjects = (
<TOC id="dataset-toc" key="dataset-toc" nodes={showCategories ? this.props.nodes : this.props.objects}>
{ showCategories ?
(<DefaultGroup animateCollapse={false} onToggle={this.props.onToggle}>
<DefaultNode
expandFilterPanel={this.openFilterPanel}
toggleSiraControl={this.searchAll}
onToggle={this.props.onToggle}
groups={this.props.nodes}
showInfoBox={this.showInfoBox}
addToMap={this.addToCart}
/>
</DefaultGroup>) : (<DefaultNode
expandFilterPanel={this.openFilterPanel}
toggleSiraControl={this.searchAll}
flat={true}
showInfoBox={this.showInfoBox}
addToMap={this.addToCart}
/>) }
</TOC>);
const viste = this.props.views ? this.props.views.map((v) => (<Vista key={v.id}
node={v}
onToggle={this.props.onToggle}
addToMap={this.loadThematicView}
showInfoBox={this.showInfoBox}
/>)) : (<div/>);
const objEl = [searchSwitch, tocObjects];
return (
<Tabs
className="dataset-tabs"
activeKey={this.props.subcat}
onSelect={this.props.selectSubCategory}>
<Tab
eventKey={'objects'}
title={`Oggetti (${objects ? objects.length : 0})`}>
{loading ? this.renderSpinner() : objEl}
</Tab>
<Tab eventKey={'views'}
title={`Viste Tematiche (${views ? views.length : 0})`}>
{loading ? this.renderSpinner() : (<div id="dataset-results-view"> {viste}</div>)}
</Tab>
</Tabs>);
},
render() {
const {category} = this.props;
return (
<div className="interna">
<div style={{minHeight: '100%', position: 'relative'}}>
<Header showCart="true" goToHome={this.goToHome}/>
{this.renderSerchBar()}
<div className="dataset-results-container">
{category ? this.renderResults() : (<noscript/>)}
</div>
<div className="dataset-footer-container">
<Footer/>
</div>
</div>
<MetadataInfoBox panelStyle={{
height: "500px",
width: "400px",
zIndex: 1000,
left: "calc(50% - 250px)",
top: -100,
position: "fixed",
overflow: "auto"}}/>
</div>);
},
loadMetadata({text, category} = {}) {
let params = {};
const {id} = category || {};
if (id !== 999) {
params.category = id;
}
if (text && text.length > 0) {
params.text = text;
}
if (!this.props.loading) {
this.props.getMetadataObjects({params});
}
},
showInfoBox(node) {
this.props.loadMetadata(node);
this.props.showInfoBox();
},
addToCart(node) {
if ( !node.featureType) {
this.props.toggleAddMap(true);
this.props.loadNodeMapRecords(node);
}else if (node.featureType) {
const featureType = node.featureType.replace('featuretype=', '').replace('.json', '');
if (!this.props.configOggetti[featureType]) {
this.props.loadFeatureTypeConfig(null, {authkey: this.props.userprofile.authParams.authkey ? this.props.userprofile.authParams.authkey : ''}, featureType, true, false, node.id, true, node);
} else {
let layers = [];
layers.push(this.props.configOggetti[featureType].layer);
this.props.addLayersInCart(layers, node);
}
}
},
openFilterPanel(status, ftType) {
const featureType = ftType.replace('featuretype=', '').replace('.json', '');
if (!this.props.configOggetti[featureType]) {
this.props.loadFeatureTypeConfig(null, {authkey: this.props.userprofile.authParams.authkey ? this.props.userprofile.authParams.authkey : ''}, featureType, true);
}else if (this.props.activeFeatureType !== featureType) {
this.props.setActiveFeatureType(featureType);
}
this.props.expandFilterPanel(status);
if (undefined !== this.props.params.profile) {
this.context.router.push('/full/${this.props.params.profile}/');
}else {
this.context.router.push('/full/');
}
// this.context.router.push(`/full/${this.props.params.profile}`);
},
searchAll(ftType) {
const featureType = ftType.replace('featuretype=', '').replace('.json', '');
if (!this.props.configOggetti[featureType]) {
this.props.loadFeatureTypeConfig(null, {authkey: this.props.userprofile.authParams.authkey ? this.props.userprofile.authParams.authkey : ''}, featureType, true);
}else if (this.props.activeFeatureType !== featureType) {
this.props.setActiveFeatureType(featureType);
}
this.props.setGridType('all_results');
this.props.toggleSiraControl('grid', true);
if (undefined !== this.props.params.profile) {
this.context.router.push('/full/${this.props.params.profile}/');
}else {
this.context.router.push('/full/');
}
// this.context.router.push(`/full/${this.props.params.profile}`);
},
loadThematicView({serviceUrl, params} = {}) {
this.props.getThematicViewConfig({serviceUrl, params, configureMap: true});
},
goToHome() {
this.context.router.push('/');
}
});
module.exports = connect(datasetSelector, {
getMetadataObjects,
onToggle: toggleNode,
selectSubCategory,
loadMetadata,
showInfoBox: showBox,
setProfile,
expandFilterPanel,
loadFeatureTypeConfig,
setActiveFeatureType,
toggleSiraControl,
setGridType,
getThematicViewConfig,
toggleAddMap: toggleAddMap,
loadNodeMapRecords: loadNodeMapRecords,
addLayersInCart: addFeatureTypeLayerInCart
})(Dataset);
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const ReactDOM = require('react-dom');
const {connect} = require('react-redux');
const LocaleUtils = require('../../MapStore2/web/client/utils/LocaleUtils');
const {configureQueryForm} = require('../actions/siradec');
const {configureExporter} = require('../actions/siraexporter');
const Promise = require('promise-polyfill');
if (!window.Promise) {
window.Promise = Promise;
}
if (!Array.from) {
Array.from = (function() {
var toStr = Object.prototype.toString;
var isCallable = function(fn) {
return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
};
var toInteger = function(value) {
var number = Number(value);
if (isNaN(number)) { return 0; }
if (number === 0 || !isFinite(number)) { return number; }
return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
};
var maxSafeInteger = Math.pow(2, 53) - 1;
var toLength = function(value) {
var len = toInteger(value);
return Math.min(Math.max(len, 0), maxSafeInteger);
};
// The length property of the from method is 1.
return function from(arrayLike/*, mapFn, thisArg */) {
// 1. Let C be the this value.
var C = this;
// 2. Let items be ToObject(arrayLike).
var items = Object(arrayLike);
// 3. ReturnIfAbrupt(items).
if (arrayLike === null) {
throw new TypeError("Array.from requires an array-like object - not null or undefined");
}
// 4. If mapfn is undefined, then let mapping be false.
let mapFn = arguments.length > 1 ? arguments[1] : void undefined;
let T;
if (typeof mapFn !== 'undefined') {
// 5. else
// 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
if (!isCallable(mapFn)) {
throw new TypeError('Array.from: when provided, the second argument must be a function');
}
// 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 2) {
T = arguments[2];
}
}
// 10. Let lenValue be Get(items, "length").
// 11. Let len be ToLength(lenValue).
let len = toLength(items.length);
// 13. If IsConstructor(C) is true, then
// 13. a. Let A be the result of calling the [[Construct]] internal method
// of C with an argument list containing the single item len.
// 14. a. Else, Let A be ArrayCreate(len).
let A = isCallable(C) ? Object(new C(len)) : new Array(len);
// 16. Let k be 0.
let k = 0;
// 17. Repeat, while k < len… (also steps a - h)
let kValue;
while (k < len) {
kValue = items[k];
if (mapFn) {
A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
} else {
A[k] = kValue;
}
k += 1;
}
// 18. Let putStatus be Put(A, "length", len, true).
A.length = len;
// 20. Return A.
return A;
};
}());
}
const appReducers = {
userprofile: require('../reducers/userprofile'),
siraControls: require('../reducers/controls'),
queryform: require('../reducers/queryform'),
siradec: require('../reducers/siradec'),
grid: require('../reducers/grid'),
cardtemplate: require('../reducers/card'),
featuregrid: require('../reducers/featuregrid'),
security: require('../reducers/siraSecurity'),
siraexporter: require('../reducers/siraexporter')
};
const startApp = () => {
const ConfigUtils = require('../../MapStore2/web/client/utils/ConfigUtils');
const StandardApp = require('../../MapStore2/web/client/components/app/StandardApp');
const {pages, pluginsDef, initialState, storeOpts} = require('./appConfig');
const StandardRouter = connect((state) => ({
locale: state.locale || {},
pages
}))(require('../../MapStore2/web/client/components/app/StandardRouter'));
const appStore = require('../stores/qGisStore').bind(null, initialState, appReducers);
const initialActions = [
()=> configureQueryForm(ConfigUtils.getConfigProp("query")),
() => configureExporter(ConfigUtils.getConfigProp("exporter"))
];
const appConfig = {
storeOpts,
appStore,
pluginsDef,
initialActions,
appComponent: StandardRouter,
printingEnabled: false
};
ReactDOM.render(
<StandardApp {...appConfig}/>,
document.getElementById('container')
);
};
if (!global.Intl ) {
// Ensure Intl is loaded, then call the given callback
LocaleUtils.ensureIntl(startApp);
}else {
startApp();
}
<file_sep>/**
* Copyright 2017, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const GroupLayer = require('./GroupLayer');
const assign = require('object-assign');
const AddMapUtils = require('../../utils/AddMapUtils');
const LayersTree = React.createClass({
propTypes: {
records: React.PropTypes.array,
useTitle: React.PropTypes.bool
},
contextTypes: {
messages: React.PropTypes.object
},
getInitialState() {
return {
flatLayers: {},
useTitle: true
};
},
getDefaultProps() {
return {
records: []
};
},
renderTree() {
return this.props.records.map((r) => {
return (<GroupLayer
nodesStatus={this.state.flatLayers}
toggleLayer={this.toggleLayer}
toggleSelect={this.toggleSelect}
useTitle={this.props.useTitle}
key={r.id}
node={r} />);
});
},
render() {
return (
<div className="layer-tree">{
this.renderTree()}
</div>);
},
toggleLayer(nodeId, expanded) {
this.setState((prevState) => {
const node = assign({selected: false }, prevState.flatLayers[nodeId] || {}, {expanded});
return {flatLayers: assign({}, prevState.flatLayers, {[nodeId]: node})};
});
},
toggleSelect(node, selected) {
this.setState((prevState) => {
const flatLayers = prevState.flatLayers;
const newFlatLayers = assign({}, flatLayers, AddMapUtils.setSelectionState([node], flatLayers, selected));
const normalizedFlatLayer = AddMapUtils.normalizeSelection(this.props.records, newFlatLayers);
return {flatLayers: assign({}, newFlatLayers, normalizedFlatLayer)};
});
}
});
module.exports = LayersTree;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {connect} = require('react-redux');
const {generatePDF, mapImageReady} = require("../../actions/card");
const TemplateSiraHtml = require('./TemplateSiraHtml');
const TemplateUtils = require('../../utils/TemplateUtils');
const assign = require('object-assign');
const scheda2pdf = require('../../utils/ExportScheda');
const Spinner = require('react-spinkit');
const {endsWith} = require('lodash');
const SchedaToPDF = React.createClass({
propTypes: {
card: React.PropTypes.shape({
mapImageReady: React.PropTypes.bool,
generatepdf: React.PropTypes.bool,
template: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.func]),
loadingCardTemplateError: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.object]),
xml: React.PropTypes.oneOfType([
React.PropTypes.string])
}),
profile: React.PropTypes.array,
pdfname: React.PropTypes.string,
authParam: React.PropTypes.object,
withMap: React.PropTypes.bool,
generatePDF: React.PropTypes.func,
mapImageReady: React.PropTypes.func
},
getDefaultProps() {
return {
card: {
template: "",
xml: null,
loadingCardTemplateError: null
},
pdfname: 'download.pdf',
profile: [],
withMap: true,
authParam: null,
open: false,
draggable: true,
// model: {},
toggleDetail: () => {}
};
},
componentWillReceiveProps(nextProps) {
if (nextProps.card && nextProps.card.mapImageReady) {
this.generatePDF();
}
},
shouldComponentUpdate(nextProps) {
return (nextProps.card && !nextProps.card.mapImageReady);
},
renderHtml() {
const xml = this.props.card.xml;
const authParam = this.props.authParam;
const profile = this.props.profile;
const model = assign({}, this.props.card, {
authParam: authParam,
profile: profile,
withMap: this.props.withMap,
getValue: (element) => TemplateUtils.getValue(xml, element)
});
if (this.props.card.loadingCardTemplateError) {
return this.renderLoadTemplateException();
}
const Template = (
<div ref={(el) => { this.getRef(el); }} className="scheda-sira-html" style={{"visibility": "hidden"}}>
<TemplateSiraHtml template={this.props.card.template} model={model}/>
</div>
);
return Template;
},
renderMask() {
return (
<div>
<div className="schedapdf-spinner">
<Spinner style={{width: "60px"}} spinnerName="three-bounce" noFadeIn/>
</div>
{this.renderHtml()}
</div>);
},
render() {
return ( this.props.card && this.props.card.generatepdf && this.props.card.template && this.props.card.xml) ? (
<div style={{'position': 'absolute', top: 0, bottom: 0, left: 0, right: 0, zIndex: 1300,
backgroundColor: "rgba(10, 10, 10, 0.38)"}}>
{this.renderMask()}
</div>) : null;
},
getRef(el) {
this.el = el ? el : null;
if (this.props.card && (this.props.card.mapImageReady || !this.props.withMap)) {
this.generatePDF();
}
},
generatePDF() {
if (this.el) {
const pdf = scheda2pdf(this.el);
pdf.save(this.resolvePdfName());
this.props.generatePDF();
this.props.mapImageReady(false);
}
},
resolvePdfName() {
let name = this.props.pdfname;
(name.match(/\{\{.+?\}\}/g) || []).forEach((placeholder) => {
const el = placeholder.replace('{{', '').replace('}}', '');
name = name.replace(placeholder, TemplateUtils.getValue(this.props.card.xml, el));
});
name = endsWith(name, ".pdf") ? name : `${name}.pdf`;
return name;
}
});
module.exports = connect((state) => {
const activeConfig = state.siradec.configOggetti[state.siradec.activeFeatureType] || {};
return {
card: state.cardtemplate || {},
pdfname: activeConfig.card && activeConfig.card.pdfname
};
}, {
generatePDF: generatePDF.bind(null, false),
mapImageReady
})(SchedaToPDF);
<file_sep>/**
* Copyright 2017, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const ModalDialog = require('react-bootstrap/lib/ModalDialog');
const Draggable = require('react-draggable');
module.exports = React.createClass({
render() {
return <Draggable handle=".modal-title, .modal-header"><ModalDialog {...this.props} id="add-map-modal"/></Draggable>;
}
});
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
/*eslint-disable*/
const React = require('react');
/*eslint-enable*/
const QGisZoom = React.createClass( {
render() {return null; }
});
module.exports = QGisZoom;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {connect} = require('react-redux');
const mapType = "openlayers";
const CoordinatesUtils = require('../../../MapStore2/web/client/utils/CoordinatesUtils');
const PMap = require('../../../MapStore2/web/client/components/map/' + mapType + '/Map');
const Layer = require('../../../MapStore2/web/client/components/map/' + mapType + '/Layer');
require('../../../MapStore2/web/client/components/map/' + mapType + '/plugins/index');
const {changeMapView} = require('../../../MapStore2/web/client/actions/map');
const {Button} = require("react-bootstrap");
const img = require('../../../MapStore2/web/client/components/data/featuregrid/images/magnifier.png');
const assign = require('object-assign');
const ConfigUtils = require('../../../MapStore2/web/client/utils/ConfigUtils');
const {goToMapPage} = require('../../utils/SiraUtils');
const PreviewMap = React.createClass({
propTypes: {
map: React.PropTypes.object,
layers: React.PropTypes.array,
style: React.PropTypes.object,
pointSRS: React.PropTypes.string,
center: React.PropTypes.object,
zoom: React.PropTypes.number,
activeSections: React.PropTypes.object,
authParam: React.PropTypes.object,
changeMapView: React.PropTypes.func,
withMap: React.PropTypes.bool
},
getDefaultProps() {
return {
map: null,
layers: [],
style: {height: "300px", width: "100%", display: "block", border: "1px solid black"},
pointSRS: "EPSG:4326",
center: null,
zoom: 15,
activeSections: {},
authParam: null,
withMap: true,
changeMapView: () => {}
};
},
componentDidUpdate() {
let m = this.refs.mappa;
if (m) {
m.map.setTarget("scheda_pMap");
}
},
fillUrl(layer) {
if (layer.url) {
return assign({}, layer, {
url: layer.url.replace("{geoserverUrl}", ConfigUtils.getConfigProp('geoserverUrl'))
});
}
return layer;
},
render() {
return this.props.map && this.props.center && this.props.center.coordinates ?
(
<div>
<PMap
ref="mappa"
{...this.props.map}
style={this.props.style}
mapOptions={{interactions: {
doubleClickZoom: false,
dragPan: false,
altShiftDragRotate: false,
keyboard: false,
mouseWheelZoom: false,
shiftDragZoom: false,
pinchRotate: false,
pinchZoom: false
}}}
zoomControl={false}
zoom={this.props.zoom}
center={this.getCenter([this.props.center])}
id="scheda_pMap">
{
this.props.layers.map((layer, index) =>
<Layer key={layer.title || layer.name} position={index} type={layer.type}
options={assign({}, this.fillUrl(layer), {params: {authkey: this.props.authParam && this.props.authParam.authkey ? this.props.authParam.authkey : ''}})}/>
)
}
</PMap>
<Button onClick={this.changeMapView} style={{position: "relative", top: "-" + this.props.style.height, 'float': "right", margin: "2px"}}><img src={img} width={16}/></Button>
</div>
) : <span/>;
},
getCenter(geometries) {
let extent = geometries.reduce((prev, next) => {
return CoordinatesUtils.extendExtent(prev, CoordinatesUtils.getGeoJSONExtent(next));
}, CoordinatesUtils.getGeoJSONExtent(geometries[0]));
let point = {crs: this.props.pointSRS, x: (extent[0] + extent[2]) / 2, y: (extent[1] + extent[3]) / 2};
return this.props.pointSRS !== "EPSG:4326" ?
CoordinatesUtils.reproject(point, this.props.pointSRS, "EPSG:4326") : point;
},
changeMapView() {
let center = this.getCenter([this.props.center]);
let zoom = this.props.zoom;
const proj = this.props.map.projection || "EPSG:3857";
this.props.changeMapView( center, zoom, this.props.map.bbox, this.props.map.size, null, proj);
if (!this.props.withMap) {
goToMapPage(center, zoom);
}
}
});
module.exports = connect((state) => {
return {
map: (state.map && state.map && state.map.present) || (state.config && state.config.map),
activeSections: state.cardtemplate.activeSections || {}
};
}, {
changeMapView: changeMapView
})(PreviewMap);
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const ReactDOM = require('react-dom');
const expect = require('expect');
const store = require('../../../stores/store')(undefined, {
siradec: require('../../../reducers/siradec'),
cardtemplate: require('../../../reducers/card')
}, {} );
const PreviewMap = require('../PreviewMap');
describe('PreviewMap tests', () => {
beforeEach((done) => {
document.body.innerHTML = '<div id="container"></div>';
setTimeout(done);
});
afterEach((done) => {
ReactDOM.unmountComponentAtNode(document.getElementById("container"));
document.body.innerHTML = '';
setTimeout(done);
});
it('Test PreviewMap rendering default empty map', () => {
let comp = ReactDOM.render(<PreviewMap center={{type: "Point", coordinates: [7.288747410652236, 44.800614935398094]}} store={store}/>, document.getElementById("container"));
store.dispatch({type: "CHANGE_MAP_CRS", crs: "EPSG:900913"});
expect(comp).toExist();
});
});
<file_sep>datasource=jdbc:postgresql://tst-territorio-vdb06.territorio.csi.it/DBSIRASVIL
username=decsira
password=<PASSWORD><file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {Link} = require('react-router');
const MosaicTile = React.createClass({
propTypes: {
icon: React.PropTypes.string,
name: React.PropTypes.string,
objectNumber: React.PropTypes.number,
tematicViewNumber: React.PropTypes.number,
setData: React.PropTypes.func,
useLink: React.PropTypes.bool,
boxStyle: React.PropTypes.object,
onClick: React.PropTypes.func,
liClass: React.PropTypes.string.isRequired
},
getDefaultProps() {
return {
icon: "",
useLink: true,
boxStyle: { },
liClass: "list-group-item col-md-3 col-xs-4 tiles"
};
},
renderInfo() {
return this.props.useLink ? (
<div className="ogg_appl">
<span>
<Link to={'/dataset/' + this.props.objectNumber + '/0'} className="list-group-item">
Oggetti <span className="items-badge" > {this.props.objectNumber} </span>
</Link>
</span>
<span>
<Link to={'/dataset/0/' + this.props.tematicViewNumber} className="list-group-item" >
Viste tematiche <span className="items-badge" > {this.props.tematicViewNumber} </span>
</Link>
</span>
</div>
) : (
<div className="ogg_appl">
<span >
<a className="list-group-item" onClick={() => this.props.onClick('objects')}>
Oggetti <span className="items-badge" > {this.props.objectNumber} </span>
</a>
</span>
<span >
<a className="list-group-item" onClick={() => this.props.onClick('views')}>
Viste tematiche <span className="items-badge" > {this.props.tematicViewNumber} </span>
</a>
</span>
</div>
);
},
render() {
let bClass = `${this.props.liClass} ${this.props.icon}`;
return (
<li className={bClass} style={this.props.boxStyle}>
{this.props.name}
{this.renderInfo()}
</li>
);
}
});
module.exports = MosaicTile;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const msQueryFrom = require('../../MapStore2/web/client/reducers/queryform');
const assign = require('object-assign');
const siraInitialState = {
"attributePanelExpanded": true,
"filterFields": [
{
"attribute": null,
"exception": null,
"groupId": 1,
"operator": "=",
"rowId": 1,
"type": null,
"value": null
}
],
"groupFields": [
{
"id": 1,
"index": 0,
"logic": "AND"
}
],
"groupLevels": 1,
"pagination": {
"maxFeatures": 15,
"startIndex": 0
},
"searchUrl": "{geoserverUrl}/ows?service=WFS",
"showDetailsPanel": false,
"showGeneratedFilter": false,
"spatialField": {
"attribute": "geometria",
"geometry": null,
"method": null,
"operation": "INTERSECTS"
},
"spatialPanelExpanded": false,
"toolbarEnabled": true,
"useMapProjection": false
};
function queryform(state, action) {
switch (action.type) {
// case 'QUERYFORM_CONFIG_LOADED': {
// return {...action.config};
// }
// case 'FEATURETYPE_CONFIG_LOADED': {
// return {...state, spatialField: {...state.spatialField, attribute: action.geometryName}};
// }
case 'QUERY_FORM_RESET': {
return assign({}, state, siraInitialState);
}
default: return msQueryFrom(state, action);
}
}
module.exports = queryform;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
// include application component
const Template = require('../../../MapStore2/web/client/components/data/template/jsx/Template');
// Template needs to import all component used in string definition.
// The referene should be available in eval scope. Needs to disable eslint
const renderSira = require("./htmlpdf/index");
const TemplateSiraHtml = React.createClass({
render() {
return (<Template {...this.props} renderContent={renderSira}/>);
}
});
module.exports = TemplateSiraHtml;
<file_sep>/*eslint-disable */
const Panel = require('./Panel');
const React = require('react');
const DetailTitle = require("./DetailTitle");
const Section = require("./Section");
const LabeledField = require("./LabeledField");
const LinkToPage = require ('../../../../MapStore2/web/client/components/misc/LinkToPage');
const {reactCellRendererFactory} = require('ag-grid-react');
const GoToDetail = require('../../GoToDetail');
const ZoomToRenderer = require ('../../../../MapStore2/web/client/components/data/featuregrid/ZoomToFeatureRenderer');
const MappaScheda = require("./PreviewMap");
const LinkScheda = require("../LinkScheda");
const AuthorizedObject = require("../AuthorizedObject");
const AdempimentiAmbientali = require("../AdempimentiAmbientali");
const SiraTable = require("./SiraTable");
const TemplateUtils = require('../../../utils/TemplateUtils');
const ProfileWrapper = require('../ProfileWrapper');
const QGisZoom = require('./QgisZoom')
const renderSira = function(comp, props) {
let model = props.model;
// let impiantoModel = props.impiantoModel;
return eval(comp);
};
/*eslint-enable */
module.exports = renderSira;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const TemplateSira = require('../../template/TemplateSira');
const TemplateUtils = require('../../../utils/TemplateUtils');
const {isString} = require('lodash');
const GMLViewer = React.createClass({
propTypes: {
params: React.PropTypes.object,
profile: React.PropTypes.string,
response: React.PropTypes.string,
contentConfig: React.PropTypes.object,
detailOpen: React.PropTypes.bool,
templateProfile: React.PropTypes.string,
layerId: React.PropTypes.string,
actions: React.PropTypes.shape({
onDetail: React.PropTypes.func,
onShowDetail: React.PropTypes.func,
loadTemplate: React.PropTypes.func
})
},
getDefaultProps() {
return {
templateProfile: 'default'
};
},
loadTemplate(props) {
if (props.contentConfig.template && props.contentConfig.template.needsLoading && props.contentConfig.detailsConfig && props.contentConfig.detailsConfig.featureinfo.templateURL) {
this.props.actions.loadTemplate(props.contentConfig.layerId, props.contentConfig.detailsConfig.featureinfo.templateURL);
}
},
componentDidMount() {
this.loadTemplate(this.props);
},
componentWillReceiveProps(newProps) {
this.loadTemplate(newProps);
},
shouldComponentUpdate(nextProps) {
return (nextProps.response !== this.props.response) ||
nextProps.contentConfig.template !== this.props.contentConfig.template;
},
onCellClicked(node) {
if (node.colIndex === 0 && node.colDef.id) {
this.goToDetail(node.data, node.colDef.field);
}
},
render() {
const xml = this.props.response;
// const authParam = this.props.authParam;
const model = {
// authParam: authParam,
profile: this.props.profile,
getValue: (element) => TemplateUtils.getValue(xml, element, null)
};
/*let model = TemplateUtils.getModels(this.props.response,
this.props.contentConfig.modelConfig.root,
this.props.contentConfig.modelConfig.columns, "1.1.0");*/
return (
isString(this.props.contentConfig.template) ?
<TemplateSira
template={this.props.contentConfig.template}
model={model}
onCellClicked={this.onCellClicked}/> : null
);
},
goToDetail(data, idFieldName) {
let url = this.props.contentConfig.detailsConfig.card.service.url;
let urlParams = this.props.contentConfig.detailsConfig.card.service.params;
for (let param in urlParams) {
if (urlParams.hasOwnProperty(param)) {
url += "&" + param + "=" + urlParams[param];
}
}
let templateUrl = typeof this.props.contentConfig.detailsConfig.card.template === "string" ? this.props.contentConfig.detailsConfig.card.template : this.props.contentConfig.detailsConfig.card.template[this.props.templateProfile];
this.props.actions.onDetail(
templateUrl,
// this.props.detailsConfig.cardModelConfigUrl,
url + "&FEATUREID=" + data[idFieldName]
);
if (!this.props.detailOpen) {
this.props.actions.onShowDetail();
}
}
});
module.exports = GMLViewer;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const axios = require('../../MapStore2/web/client/libs/ajax');
const LOAD_PLATFORM_NUMBER = 'LOAD_PLATFORM_NUMBER';
const PLATFORM_NUMBER_LOADED = 'PLATFORM_NUMBER_LOADED';
const PLATFORM_NUMBER_ERROR = 'PLATFORM_NUMBER_ERROR';
function platformNumbersLoaded(data) {
return {
type: PLATFORM_NUMBER_LOADED,
functionObjectMap: data.functionObjectMap,
functionObjectSearch: data.functionObjectSearch,
functionObjectView: data.functionObjectView,
siradecObject: data.siradecObject
};
}
function platformNumbersError(error) {
return {
type: PLATFORM_NUMBER_ERROR,
error
};
}
function loadPlatformNumbers() {
return (dispatch) => {
return axios.get('services/metadata/getPlatformNumbers').then((response) => {
if (typeof response.data === 'object') {
dispatch(platformNumbersLoaded(response.data));
} else {
try {
JSON.parse(response.data);
} catch(e) {
dispatch(platformNumbersError('Service for platfomrNumbers is broken: ' + e.message));
}
}
}).catch((e) => {
dispatch(platformNumbersError(e));
});
};
}
module.exports = {
LOAD_PLATFORM_NUMBER,
PLATFORM_NUMBER_LOADED,
PLATFORM_NUMBER_ERROR,
loadPlatformNumbers
};
<file_sep>/**
* Copyright 2015, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const assign = require('object-assign');
const {Glyphicon, Panel} = require('react-bootstrap');
const {connect} = require('react-redux');
const {bindActionCreators} = require('redux');
const {setFeatures} = require('../../../MapStore2/web/client/actions/featuregrid');
const TopologyInfoViewer = connect((state) => ({
// modelConfig: state.mapInfo.modelConfig,
topologyConfig: state.mapInfo.topologyConfig,
infoTopologyResponse: state.mapInfo.infoTopologyResponse
}), (dispatch) => {
return {
actions: bindActionCreators({
setFeatures
}, dispatch)
};
})(require('./TopologyInfoViewer'));
const {loadInfoTopologyConfig} = require('../../actions/mapInfo');
const GetFeatureInfoViewer = require('./GetFeatureInfoViewer');
const Draggable = require('react-draggable');
const I18N = require('../../../MapStore2/web/client/components/I18N/I18N');
const Spinner = require('../../../MapStore2/web/client/components/misc/spinners/BasicSpinner/BasicSpinner');
const CoordinatesUtils = require('../../../MapStore2/web/client/utils/CoordinatesUtils');
const FilterUtils = require('../../../MapStore2/web/client/utils/FilterUtils');
const MapInfoUtils = require('../../../MapStore2/web/client/utils/MapInfoUtils');
MapInfoUtils.AVAILABLE_FORMAT = ['TEXT', 'JSON', 'HTML', 'GML3'];
const {isArray, head} = require('lodash');
const GetFeatureInfo = React.createClass({
propTypes: {
params: React.PropTypes.object,
infoFormat: React.PropTypes.oneOf(
MapInfoUtils.getAvailableInfoFormatValues()
),
featureCount: React.PropTypes.number,
htmlResponses: React.PropTypes.array,
htmlRequests: React.PropTypes.object,
btnConfig: React.PropTypes.object,
infoEnabled: React.PropTypes.bool,
topologyInfoEnabled: React.PropTypes.bool,
map: React.PropTypes.object,
layers: React.PropTypes.array,
layerFilter: React.PropTypes.func,
actions: React.PropTypes.shape({
getFeatureInfo: React.PropTypes.func,
purgeMapInfoResults: React.PropTypes.func,
changeMousePointer: React.PropTypes.func,
showMapinfoMarker: React.PropTypes.func,
hideMapinfoMarker: React.PropTypes.func,
loadGetFeatureInfoConfig: React.PropTypes.func,
selectFeatures: React.PropTypes.func,
setFeatures: React.PropTypes.func,
setModelConfig: React.PropTypes.func
}),
clickedMapPoint: React.PropTypes.object,
display: React.PropTypes.string,
draggable: React.PropTypes.bool,
style: React.PropTypes.object,
collapsible: React.PropTypes.bool,
siraFeatureTypeName: React.PropTypes.string,
siraFeatureInfoDetails: React.PropTypes.object,
siraTopology: React.PropTypes.object,
siraTopologyConfig: React.PropTypes.object,
profile: React.PropTypes.string,
detailsConfig: React.PropTypes.object,
// modelConfig: React.PropTypes.object,
template: React.PropTypes.object,
infoType: React.PropTypes.string
},
getDefaultProps() {
return {
siraFeatureTypeName: null,
siraFeatureInfoDetails: null,
siraTopology: null,
siraTopologyConfig: null,
profile: null,
infoEnabled: false,
topologyInfoEnabled: false,
featureCount: 10,
draggable: true,
display: "accordion",
htmlResponses: [],
htmlRequests: {length: 0},
map: {},
layers: [],
layerFilter(l) {
return l.visibility &&
l.type === 'wms' &&
(l.queryable === undefined || l.queryable) &&
l.group !== "background";
},
actions: {
getFeatureInfo() {},
purgeMapInfoResults() {},
changeMousePointer() {},
showMapinfoMarker() {},
hideMapinfoMarker() {}
},
infoFormat: MapInfoUtils.getDefaultInfoFormatValue(),
clickedMapPoint: {},
style: {
position: "absolute",
maxWidth: "500px",
top: "56px",
left: "45px",
zIndex: 1010,
boxShadow: "2px 2px 4px #A7A7A7"
}
};
},
getInitialState() {
return { showModal: true };
},
componentWillReceiveProps(newProps) {
// if there's a new clicked point on map and GetFeatureInfo is active
// it composes and sends a getFeatureInfo action.
var refreshInfo = () => {
if ((newProps.infoEnabled || newProps.topologyInfoEnabled) && newProps.clickedMapPoint && newProps.clickedMapPoint.pixel) {
if (!this.props.clickedMapPoint.pixel || this.props.clickedMapPoint.pixel.x !== newProps.clickedMapPoint.pixel.x ||
this.props.clickedMapPoint.pixel.y !== newProps.clickedMapPoint.pixel.y ) {
return true;
}
if (!this.props.clickedMapPoint.pixel || newProps.clickedMapPoint.pixel && this.props.infoFormat !== newProps.infoFormat) {
return true;
}
}
return false;
};
if (refreshInfo()) {
const {bounds, crs} = this.reprojectBbox(newProps.map.bbox, newProps.map.projection);
if (newProps.infoType === "getfeatureinfo") {
this.props.actions.purgeMapInfoResults();
const wmsVisibleLayers = newProps.layers.filter(newProps.layerFilter);
for (let l = 0; l < wmsVisibleLayers.length; l++) {
const layer = wmsVisibleLayers[l];
const {url, requestConf, layerMetadata} = this.calculateRequestParameters(layer, bounds, crs, newProps);
this.props.actions.getFeatureInfo(url, requestConf, layerMetadata, layer.featureInfoParams);
// Load the template if required
if (layer.featureType) {
this.props.actions.loadGetFeatureInfoConfig(layer.id, layer.featureType, this.props.params);
}
}
this.props.actions.showMapinfoMarker();
} else if (newProps.infoType === "topology") {
this.props.actions.purgeMapInfoResults();
const wmsVisibleLayers = newProps.layers.filter((layer) => {
return layer.topologyConfig &&
layer.visibility &&
layer.type === 'wms' &&
(layer.queryable === undefined || layer.queryable) &&
layer.group !== "background";
});
for (let l = 0; l < wmsVisibleLayers.length; l++) {
const layer = wmsVisibleLayers[l];
const {url, requestConf, layerMetadata} = this.calculateRequestParameters(layer, bounds, crs, newProps);
// Load the template if required
let topologyOptions = {};
if (layer.topologyConfig) {
let topologyConfig = assign({}, layer.topologyConfig, {clickedMapPoint: newProps.clickedMapPoint});
let filterObj = {
spatialField: {
attribute: topologyConfig.geomAttribute,
geometry: {
coordinates: [
topologyConfig.wfsVersion === "1.1.0" || topologyConfig.wfsVersion === "2.0" ?
[[
topologyConfig.clickedMapPoint.latlng.lat,
topologyConfig.clickedMapPoint.latlng.lng
]] : [[
topologyConfig.clickedMapPoint.latlng.lng,
topologyConfig.clickedMapPoint.latlng.lat
]]
],
projection: "EPSG:4326",
type: "Point"
},
method: "POINT",
operation: "INTERSECTS"
}
};
let filter = FilterUtils.toOGCFilter(topologyConfig.layerName, filterObj, "1.1.0");
topologyOptions.topologyConfig = topologyConfig;
topologyOptions.modelConfig = this.props.siraTopology.grid;
topologyOptions.layerId = layer.id;
topologyOptions.filter = filter;
topologyOptions.callback = loadInfoTopologyConfig;
this.props.actions.selectFeatures([]);
this.props.actions.setFeatures([]);
this.props.actions.setModelConfig({});
}
this.props.actions.getFeatureInfo(url, requestConf, layerMetadata, layer.featureInfoParams, topologyOptions);
}
}
}
if ((newProps.infoEnabled && !this.props.infoEnabled) ||
(newProps.topologyInfoEnabled && !this.props.topologyInfoEnabled)) {
this.props.actions.changeMousePointer('pointer');
} else if ((!newProps.infoEnabled && this.props.infoEnabled) ||
(!newProps.topologyInfoEnabled && this.props.topologyInfoEnabled)) {
this.props.actions.changeMousePointer('auto');
this.props.actions.hideMapinfoMarker();
this.props.actions.purgeMapInfoResults();
}
},
onModalHiding() {
this.props.actions.hideMapinfoMarker();
this.props.actions.purgeMapInfoResults();
},
renderInfo(missingRequests) {
let component;
if (this.props.infoType === "getfeatureinfo") {
component = (
<GetFeatureInfoViewer
missingRequests={missingRequests}
responses={this.props.htmlResponses}
contentConfig={{
template: this.props.template || {},
detailsConfig: this.props.detailsConfig,
featureConfigs: this.props.siraFeatureInfoDetails
// modelConfig: this.props.modelConfig
}}
profile={this.props.profile}
params={this.props.params}
display={this.props.display}/>
);
} else {
if (/*this.props.modelConfig*/ this.props.siraTopologyConfig) {
component = (
<TopologyInfoViewer
missingRequests={missingRequests}
responses={this.props.htmlResponses}
display={this.props.display}/>
);
} else {
component = (
<div style={{height: "100px", width: "100%"}}>
<div style={{
position: "relative",
width: "60px",
top: "50%",
left: "45%"}}>
<Spinner style={{width: "60px"}} spinnerName="three-bounce" noFadeIn/>
</div>
</div>
);
}
}
return component;
},
renderHeader(missingRequests) {
let glyph = this.props.infoType === "getfeatureinfo" ? "info-sign" : "glyphicon glyphicon-picture";
return (
<div className="handle_infopanel">
{ (missingRequests !== 0 ) ? <Spinner value={missingRequests} sSize="sp-small" /> : null }
<Glyphicon glyph={glyph} /> <I18N.Message msgId="getFeatureInfoTitle" />
<button onClick={this.onModalHiding} className="close"><span>×</span></button>
</div>
);
},
renderContent() {
let missingRequests = this.props.htmlRequests.length - this.props.htmlResponses.length;
return (
<Panel
defaultExpanded={true}
collapsible={this.props.collapsible}
id="mapstore-getfeatureinfo"
header={this.renderHeader(missingRequests)}
style={this.props.style}>
{this.renderInfo(missingRequests)}
</Panel>
);
},
render() {
if (this.props.htmlRequests.length !== 0) {
return this.props.draggable ? (
<Draggable handle=".handle_infopanel, .handle_infopanel *">
{this.renderContent()}
</Draggable>
) : this.renderContent();
}
return null;
},
infoFormat(layerInfoFormat, propsInfoFormat) {
const infoFormats = isArray(layerInfoFormat) && layerInfoFormat || [layerInfoFormat];
return head(infoFormats.filter((f) => f === propsInfoFormat)) || head(infoFormats);
},
calculateRequestParameters(layer, bounds, crs, newProps) {
const infoFormat = layer.infoFormat ? this.infoFormat(layer.infoFormat, newProps.infoFormat) : newProps.infoFormat;
let requestConf = {
id: layer.id,
layers: layer.name,
query_layers: layer.name,
styles: layer.style,
x: parseInt(newProps.clickedMapPoint.pixel.x, 10),
y: parseInt(newProps.clickedMapPoint.pixel.y, 10),
height: parseInt(newProps.map.size.height, 10),
width: parseInt(newProps.map.size.width, 10),
srs: crs,
bbox: bounds.minx + "," +
bounds.miny + "," +
bounds.maxx + "," +
bounds.maxy,
feature_count: newProps.featureCount,
info_format: infoFormat
};
if (newProps.params) {
requestConf = assign({}, requestConf, newProps.params);
}
const layerMetadata = {
title: layer.title,
regex: layer.featureInfoRegex
};
const url = isArray(layer.url) ?
layer.url[0] :
layer.url.replace(/[?].*$/g, '');
return assign({}, {
url: url,
layerMetadata: layerMetadata,
requestConf: requestConf
});
},
reprojectBbox(bbox, destSRS) {
let newBbox = CoordinatesUtils.reprojectBbox([
bbox.bounds.minx,
bbox.bounds.miny,
bbox.bounds.maxx,
bbox.bounds.maxy
], bbox.crs, destSRS);
return assign({}, {
crs: destSRS,
bounds: {
minx: newBbox[0],
miny: newBbox[1],
maxx: newBbox[2],
maxy: newBbox[3]
}
});
}
});
module.exports = GetFeatureInfo;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {Button} = require('react-bootstrap');
const {connect} = require('react-redux');
const {loadCardTemplate} = require('../../actions/card');
const {toggleSiraControl} = require('../../actions/controls');
const {
loadFeatureTypeConfig
} = require('../../actions/siradec');
const LinkScheda = React.createClass({
propTypes: {
id: React.PropTypes.string,
linkTitle: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.element]),
btProps: React.PropTypes.object,
card: React.PropTypes.object,
open: React.PropTypes.bool,
detailsTemplateConfigURL: React.PropTypes.string,
featureType: React.PropTypes.string,
activeFeatureType: React.PropTypes.string,
configOggetti: React.PropTypes.object,
authParams: React.PropTypes.object,
templateProfile: React.PropTypes.string,
loadFeatureTypeConfig: React.PropTypes.func,
toggleDetail: React.PropTypes.func,
loadCardTemplate: React.PropTypes.func,
params: React.PropTypes.object
},
getDefaultProps() {
return {
id: null,
btProps: {},
linkTitle: 'Link',
templateProfile: 'default',
params: {},
toggleDetail: () => {},
loadCardModelConfig: () => {},
activateSection: () => {}
};
},
getInitialState() {
return {
linkDisabled: false
};
},
componentWillMount() {
// Se non passano un detailsTemplateConfigUrl e mi passano la featureType ma non ho la configuraziine caricata, devo disabilitare il link e caricare le configurazioni
if (this.props.featureType && !this.props.configOggetti[this.props.featureType]) {
this.setState({linkDisabled: true});
this.props.loadFeatureTypeConfig(null, {authkey: this.props.authParams.authkey ? this.props.authParams.authkey : ''}, this.props.featureType, false);
}
},
componentWillReceiveProps(nextProps) {
if (this.state.linkDisabled && nextProps.featureType && nextProps.configOggetti[nextProps.featureType]) {
this.setState({linkDisabled: false});
}
},
getTempleteUrl(detailsConfig) {
return typeof detailsConfig.template === "string" ? detailsConfig.template : detailsConfig.template[this.props.templateProfile];
},
render() {
return (
<Button bsStyle="link" onClick={this.btnClick} {...this.props.btProps} disabled={this.state.linkDisabled}>
{this.props.linkTitle}
</Button>
);
},
btnClick() {
// Solo configurazione è un drill up and down come in authorizedObject
const detailsConfig = this.props.configOggetti[this.props.featureType] || this.props.configOggetti[this.props.activeFeatureType];
const templateUrl = this.props.detailsTemplateConfigURL ? this.props.detailsTemplateConfigURL : this.getTempleteUrl(detailsConfig.card);
let url;
if (this.props.id) {
url = detailsConfig.card.service.url;
Object.keys(detailsConfig.card.service.params).forEach((param) => {
url += `&${param}=${detailsConfig.card.service.params[param]}`;
});
url = `${url}&FEATUREID=${this.props.id}&authkey=${this.props.authParams.authkey}`;
}
this.props.loadCardTemplate(templateUrl, url, this.props.params);
if (!this.props.open) {
this.props.toggleDetail();
}
}
});
module.exports = connect((state) => {
return {
activeFeatureType: state.siradec.activeFeatureType,
configOggetti: state.siradec.configOggetti,
card: state.cardtemplate || {},
open: state.siraControls.detail,
authParams: state.userprofile.authParams
};
}, {
toggleDetail: toggleSiraControl,
loadCardTemplate,
loadFeatureTypeConfig
})(LinkScheda);
<file_sep>db.schema=decsira
db.jndi=java:comp/env/jdbc/sipradec
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const {
GRID_MODEL_LOADED,
GRID_LOAD_ERROR,
GRID_CONFIG_LOADED,
SHOW_LOADING,
CREATE_GRID_DATA_SOURCE,
UPDATE_TOTAL_FEATURES,
FEATURES_LOADED_PAG,
SET_GRID_TYPE
} = require('../actions/grid');
const assign = require('object-assign');
const TemplateUtils = require('../utils/TemplateUtils');
const initialState = {
data: null,
featuregrid: null,
loadingGrid: false,
totalFeatures: null,
dataSourceOptions: {}
};
function grid(state = initialState, action) {
switch (action.type) {
case GRID_CONFIG_LOADED: {
return assign({}, state, {
featuregrid: action.config
});
}
case GRID_MODEL_LOADED: {
let idFieldName = state.featuregrid.idFieldName;
let features = TemplateUtils.getModels(action.data, state.featuregrid.grid.root, state.featuregrid.grid.columns);
let totalFeatures = (!action.add) ? features.length : state.totalFeatures;
let data = {
"type": "FeatureCollection",
"totalFeatures": totalFeatures,
"features": [],
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:EPSG::4326"
}
}
};
features = features.map((feature) => {
let f = {
"type": "Feature",
"id": feature[idFieldName] || feature.id,
"geometry_name": "the_geom",
"properties": {}
};
let geometry;
for (let prop in feature) {
if (feature[prop] && feature[prop].type === "geometry") {
geometry = feature[prop];
} else if (feature.hasOwnProperty(prop)) {
f.properties[prop] = feature[prop];
}
}
f.geometry = {
"type": state.featuregrid.grid.geometryType
};
// Setting coordinates
if (state.featuregrid.grid.geometryType === "Polygon") {
let coordinates = [[]];
for (let i = 0; geometry && i < geometry.coordinates.length; i++) {
let coords = state.featuregrid.grid.wfsVersion === "1.1.0" ?
[geometry.coordinates[i][1], geometry.coordinates[i][0]] : geometry.coordinates[i];
coordinates[0].push(coords);
}
f.geometry.coordinates = coordinates;
} else if (state.featuregrid.grid.geometryType === "Point") {
f.geometry.coordinates = geometry ? [geometry.coordinates[0][0], geometry.coordinates[0][1]] : null;
}
return f;
});
data.features = action.add ? [...(state.data || []), ...features ] : features;
return assign({}, state, {
data: data.features,
totalFeatures: data.totalFeatures,
loadingGrid: false
});
}
case GRID_LOAD_ERROR: {
return assign({}, state, {
loadingGridError: action.error,
loadingGrid: false
});
}
case SHOW_LOADING: {
return assign({}, state, {
loadingGrid: action.show
});
}
case SET_GRID_TYPE: {
return assign({}, state, {
gridType: action.gridType
});
}
case CREATE_GRID_DATA_SOURCE: {
let dataSourceOptions = {
rowCount: -1,
pageSize: action.pagination.maxFeatures
};
return assign({}, state, {
data: {},
totalFeatures: -1,
loadingGrid: false,
dataSourceOptions: dataSourceOptions
});
}
case UPDATE_TOTAL_FEATURES: {
let totalFeatures = TemplateUtils.getNumberOfFeatures(action.data);
return {...state, totalFeatures };
}
case FEATURES_LOADED_PAG: {
let idFieldName = state.featuregrid.idFieldName;
let features = TemplateUtils.getModels(action.data, state.featuregrid.grid.root, state.featuregrid.grid.columns);
features = features.map((feature) => {
let f = {
"type": "Feature",
"id": feature[idFieldName] || feature.id,
"geometry_name": "the_geom",
"properties": {}
};
let geometry;
for (let prop in feature) {
if (feature[prop] && feature[prop].type === "geometry") {
geometry = feature[prop];
} else if (feature.hasOwnProperty(prop)) {
f.properties[prop] = feature[prop];
}
}
f.geometry = {
"type": state.featuregrid.grid.geometryType
};
// Setting coordinates
if (state.featuregrid.grid.geometryType === "Polygon") {
let coordinates = [[]];
for (let i = 0; geometry && i < geometry.coordinates.length; i++) {
let coords = state.featuregrid.grid.wfsVersion === "1.1.0" ?
[geometry.coordinates[i][1], geometry.coordinates[i][0]] : geometry.coordinates[i];
coordinates[0].push(coords);
}
f.geometry.coordinates = coordinates;
} else if (state.featuregrid.grid.geometryType === "Point") {
f.geometry.coordinates = geometry ? [geometry.coordinates[0][0], geometry.coordinates[0][1]] : null;
}
return f;
});
let data = {...state.data};
data[action.requestId] = features;
return {
...state,
data,
loadingGrid: false
};
}
case 'FEATURETYPE_CONFIG_LOADED': {
if (action.activate) {
return assign({}, state, initialState);
}
return state;
}
case 'SET_ACTIVE_FEATURE_TYPE': {
return assign({}, state, initialState);
}
default:
return state;
}
}
module.exports = grid;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const axios = require('../../MapStore2/web/client/libs/ajax');
const {addLayer} = require('../../MapStore2/web/client/actions/layers');
const QUERYFORM_CONFIG_LOADED = 'QUERYFORM_CONFIG_LOADED';
const FEATURETYPE_CONFIG_LOADED = 'FEATURETYPE_CONFIG_LOADED';
const EXPAND_FILTER_PANEL = 'EXPAND_FILTER_PANEL';
const QUERYFORM_CONFIG_LOAD_ERROR = 'QUERYFORM_CONFIG_LOAD_ERROR';
const QUERYFORM_HIDE_ERROR = 'QUERYFORM_HIDE_ERROR';
const FEATUREGRID_CONFIG_LOADED = 'FEATUREGRID_CONFIG_LOADED';
const FEATUREINFO_CONFIG_LOADED = 'FEATUREINFO_CONFIG_LOADED';
const TOPOLOGY_CONFIG_LOADED = 'TOPOLOGY_CONFIG_LOADED';
const CARD_CONFIG_LOADED = 'CARD_CONFIG_LOADED';
const INLINE_MAP_CONFIG = 'INLINE_MAP_CONFIG';
const SET_ACTIVE_FEATURE_TYPE = 'SET_ACTIVE_FEATURE_TYPE';
const FEATURETYPE_CONFIG_LOADING = 'FEATURETYPE_CONFIG_LOADING';
const assign = require('object-assign');
const ConfigUtils = require('../../MapStore2/web/client/utils/ConfigUtils');
const {addFeatureTypeLayerInCart} = require('../actions/addmap');
const {verifyProfiles} = require('../utils/TemplateUtils');
const {Promise} = require('es6-promise');
function configureInlineMap(mapconfig) {
return {
type: INLINE_MAP_CONFIG,
mapconfig
};
}
function configureFeatureType(ft, field, featureType, activate) {
return {
type: FEATURETYPE_CONFIG_LOADED,
ftName: ft.id,
ftNameLabel: ft.name,
geometryName: ft.geometryName,
geometryType: ft.geometryType,
nameSpaces: ft.nameSpaces,
layer: ft.layer,
exporter: ft.exporter,
field,
featureType,
activate
};
}
function configureQueryForm(config) {
return {
type: QUERYFORM_CONFIG_LOADED,
config: config
};
}
function configureFeatureGrid(config, featureType) {
return {
type: FEATUREGRID_CONFIG_LOADED,
config: config,
featureType
};
}
function configureCard(config, featureType) {
return {
type: CARD_CONFIG_LOADED,
config: config,
featureType
};
}
function configureTopology(config) {
return {
type: TOPOLOGY_CONFIG_LOADED,
config: config
};
}
function configureFeatureInfo(config, featureType) {
return {
type: FEATUREINFO_CONFIG_LOADED,
config: config,
featureType
};
}
function expandFilterPanel(expand) {
return {
type: EXPAND_FILTER_PANEL,
expand: expand
};
}
function configureQueryFormError(featureType, e) {
return {
type: QUERYFORM_CONFIG_LOAD_ERROR,
featureType,
error: e
};
}
function hideQueryError() {
return {
type: QUERYFORM_HIDE_ERROR
};
}
function getAttributeValuesPromise(field, params, serviceUrl) {
if (serviceUrl) {
let {url} = ConfigUtils.setUrlPlaceholders({url: serviceUrl});
for (let param in params) {
if (params.hasOwnProperty(param)) {
url += "&" + param + "=" + params[param];
}
}
return axios.get(url).then((response) => {
let config = response.data;
if (typeof config !== "object") {
try {
config = JSON.parse(config);
} catch(e) {
Promise.reject(`Configuration broken (${url}): ${ e.message}`);
}
}
const values = config.features.map((feature) => feature.properties);
return assign({}, field, {values: values});
});
}
}
function getAttributeValues(ft, field, params, serviceUrl) {
return (dispatch) => {
if (serviceUrl) {
let {url} = ConfigUtils.setUrlPlaceholders({url: serviceUrl});
for (let param in params) {
if (params.hasOwnProperty(param)) {
url += "&" + param + "=" + params[param];
}
}
return axios.get(url).then((response) => {
let config = response.data;
if (typeof config !== "object") {
try {
config = JSON.parse(config);
} catch(e) {
dispatch(configureQueryFormError(ft, 'Configuration broken (' + url + '): ' + e.message));
}
}
let values = [];
for (let feature in config.features) {
if (feature) {
values.push(config.features[feature].properties);
}
}
dispatch(configureFeatureType(ft, assign({}, field, {values: values})));
}).catch((e) => {
dispatch(configureQueryFormError(ft, e));
});
}
dispatch(configureFeatureType(ft, assign({}, field, {})));
};
}
function configurationLoading() {
return {
type: FEATURETYPE_CONFIG_LOADING
};
}
function loadFeatureTypeConfig(configUrl, params, featureType, activate = false, addlayer = false, siraId, addCartlayer = false, node = null) {
const url = configUrl ? configUrl : 'assets/' + featureType + '.json';
return (dispatch, getState) => {
const {userprofile} = getState();
dispatch(configurationLoading());
return axios.get(url).then((response) => {
let config = response.data;
if (typeof config !== "object") {
try {
config = JSON.parse(config);
} catch(e) {
dispatch(configureQueryFormError(featureType, 'Configuration file broken (' + url + '): ' + e.message));
}
}
const layer = ConfigUtils.setUrlPlaceholders(config.layer);
if (addlayer) {
dispatch(addLayer(assign({}, layer, {siraId})));
}
// add layer in cart
if (addCartlayer) {
let layers = [];
if (layer) layers.push(layer);
dispatch(addFeatureTypeLayerInCart(layers, node));
}
// Configure the FeatureGrid for WFS results list
dispatch(configureFeatureGrid(config.featuregrid, featureType));
dispatch(configureFeatureInfo(config.featureinfo, featureType));
dispatch(configureCard(config.card, featureType));
let serviceUrl = config.query.service.url;
const fields = config.query.fields.filter(
// (field) => !field.profile || field.profile.indexOf(userprofile.profile) !== -1
(field) => verifyProfiles(field.profile, userprofile.profile)
).map((f) => {
let urlParams = config.query.service && config.query.service.urlParams ? assign({}, params, config.query.service.urlParams) : params;
urlParams = f.valueService && f.valueService.urlParams ? assign({}, urlParams, f.valueService.urlParams) : urlParams;
return f.valueService && f.valueService.urlParams ? getAttributeValuesPromise(f, urlParams, serviceUrl) : Promise.resolve(f);
});
Promise.all(fields).then((fi) => {
dispatch(configureFeatureType({
id: config.featureTypeName,
name: config.featureTypeNameLabel,
geometryName: config.geometryName,
geometryType: config.geometryType,
nameSpaces: config.nameSpaces || {},
layer: layer,
exporter: config.exporter
}, fi, featureType, activate));
}).catch((e) => dispatch(configureQueryFormError(featureType, e)));
// for (let field in config.query.fields) {
// if (field) {
// let f = config.query.fields[field];
// let urlParams = config.query.service && config.query.service.urlParams ? assign({}, params, config.query.service.urlParams) : params;
// urlParams = f.valueService && f.valueService.urlParams ? assign({}, urlParams, f.valueService.urlParams) : urlParams;
// //getAttributeValuesPromise()
// dispatch(getAttributeValues({
// id: config.featureTypeName,
// name: config.featureTypeNameLabel,
// geometryName: config.geometryName,
// geometryType: config.geometryType
// }, f, urlParams, f.valueService && f.valueService.urlParams ? serviceUrl : null));
// }
// }
}).catch((e) => {
dispatch(configureQueryFormError(featureType, e));
});
};
}
function setActiveFeatureType(featureType) {
return {
type: SET_ACTIVE_FEATURE_TYPE,
featureType
};
}
module.exports = {
QUERYFORM_CONFIG_LOADED,
FEATURETYPE_CONFIG_LOADED,
EXPAND_FILTER_PANEL,
QUERYFORM_CONFIG_LOAD_ERROR,
QUERYFORM_HIDE_ERROR,
FEATUREGRID_CONFIG_LOADED,
FEATUREINFO_CONFIG_LOADED,
TOPOLOGY_CONFIG_LOADED,
CARD_CONFIG_LOADED,
INLINE_MAP_CONFIG,
SET_ACTIVE_FEATURE_TYPE,
FEATURETYPE_CONFIG_LOADING,
configureTopology,
configureFeatureGrid,
configureCard,
// loadQueryFormConfig,
loadFeatureTypeConfig,
configureQueryForm,
expandFilterPanel,
configureQueryFormError,
getAttributeValues,
hideQueryError,
configureInlineMap,
setActiveFeatureType
};
<file_sep>const React = require('react');
const {connect} = require('react-redux');
const {isObject} = require('lodash');
const {Modal, Panel, Grid, Row, Col, Button} = require('react-bootstrap');
const FilterUtils = require('../utils/SiraFilterUtils');
const {getWindowSize} = require('../../MapStore2/web/client/utils/AgentUtils');
const {getFeaturesAndExport, getFileAndExport} = require('../actions/siraexporter');
const {head} = require('lodash');
const {verifyProfiles} = require('../utils/TemplateUtils');
const SiraExporter = connect((state) => {
return {
show: state.siraControls.exporter,
exportParams: state.siraexporter.params,
featuregrid: state.grid && state.grid.featuregrid,
loading: state.siraexporter.loading,
errormsg: state.siraexporter.errormsg,
csvName: state.siraexporter.csvName,
shpName: state.siraexporter.shpName,
addFile: (state.grid && state.grid.featuregrid && state.grid.featuregrid.grid && state.grid.featuregrid.grid.exporter && state.grid.featuregrid.grid.exporter.addFile) || state.siraexporter.addFile
};
}, {
getFeaturesAndExport,
getFileAndExport
})(require('./SiraExporter'));
const FeatureGrid = connect((state) => {
return {
select: state.featuregrid && state.featuregrid.select || [],
selectAllActive: state.featuregrid && state.featuregrid.selectAll
};
})(require('../../MapStore2/web/client/components/data/featuregrid/FeatureGrid'));
const LocaleUtils = require('../../MapStore2/web/client/utils/LocaleUtils');
const I18N = require('../../MapStore2/web/client/components/I18N/I18N');
const Message = require('../../MapStore2/web/client/components/I18N/Message');
const {reactCellRendererFactory} = require('ag-grid-react');
const GoToDetail = require('./GoToDetail');
const GridCellDate = require('./GridCellDate');
const Spinner = require('react-spinkit');
const assign = require('object-assign');
const SiraGrid = React.createClass({
propTypes: {
open: React.PropTypes.bool,
detailOpen: React.PropTypes.bool,
expanded: React.PropTypes.bool,
header: React.PropTypes.string,
features: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.object]),
exporterConfig: React.PropTypes.object,
detailsConfig: React.PropTypes.object,
columnsDef: React.PropTypes.array,
map: React.PropTypes.object,
loadingGrid: React.PropTypes.bool,
exportCsvMimeType: React.PropTypes.string,
loadingGridError: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.object
]),
initWidth: React.PropTypes.number,
params: React.PropTypes.object,
// featureGrigConfigUrl: React.PropTypes.string,
profile: React.PropTypes.string,
onDetail: React.PropTypes.func,
onShowDetail: React.PropTypes.func,
toggleSiraControl: React.PropTypes.func,
changeMapView: React.PropTypes.func,
// loadFeatureGridConfig: React.PropTypes.func,
onExpandFilterPanel: React.PropTypes.func,
selectFeatures: React.PropTypes.func,
totalFeatures: React.PropTypes.number,
pagination: React.PropTypes.bool,
filterFields: React.PropTypes.array,
groupFields: React.PropTypes.array,
spatialField: React.PropTypes.object,
featureTypeName: React.PropTypes.string,
ogcVersion: React.PropTypes.string,
onQuery: React.PropTypes.func,
searchUrl: React.PropTypes.string,
dataSourceOptions: React.PropTypes.object,
withMap: React.PropTypes.bool.isRequired,
onConfigureQuery: React.PropTypes.func,
attributes: React.PropTypes.array,
cleanError: React.PropTypes.func,
selectAllToggle: React.PropTypes.func,
templateProfile: React.PropTypes.string,
zoomToFeatureAction: React.PropTypes.func,
backToSearch: React.PropTypes.string,
gridType: React.PropTypes.string,
setExportParams: React.PropTypes.func,
maxFeatures: React.PropTypes.number,
nameSpaces: React.PropTypes.object,
exporter: React.PropTypes.bool.isRequired,
fullScreen: React.PropTypes.bool.isRequired,
selectAll: React.PropTypes.bool.isRequired,
configureExporter: React.PropTypes.func
},
contextTypes: {
messages: React.PropTypes.object
},
getInitialState() {
return {};
},
getDefaultProps() {
return {
open: true,
detailOpen: true,
loadingGrid: false,
loadingGridError: null,
attributes: [],
profile: null,
expanded: true,
header: "featuregrid.header",
features: [],
featureTypeName: null,
ogcVersion: "2.0",
detailsConfig: {},
columnsDef: [],
pagination: false,
params: {},
groupFields: [],
filterFields: [],
spatialField: {},
searchUrl: null,
dataSourceOptions: {
rowCount: -1,
pageSize: 20
},
initWidth: 600,
withMap: true,
templateProfile: 'default',
backToSearch: "featuregrid.backtosearch",
gridType: "search",
exporter: true,
fullScreen: false,
selectAll: true,
onDetail: () => {},
onShowDetail: () => {},
toggleSiraControl: () => {},
changeMapView: () => {},
// loadFeatureGridConfig: () => {},
onExpandFilterPanel: () => {},
selectFeatures: () => {},
onQuery: () => {},
onConfigureQuery: () => {},
cleanError: () => {},
configureExporter: () => {}
};
},
componentWillMount() {
const hOffset = this.props.fullScreen ? 150 : 181;
let height = getWindowSize().maxHeight - hOffset;
this.setState({width: this.props.initWidth - 30, height});
if (this.props.pagination && this.props.gridType === 'search') {
this.dataSource = this.getDataSource(this.props.dataSourceOptions);
}else if ( this.props.pagination && this.props.gridType === 'all_results' && this.props.attributes[0]) {
let newFilter = FilterUtils.getOgcAllPropertyValue(this.props.featureTypeName, this.props.attributes[0].attribute);
this.props.onConfigureQuery(this.props.searchUrl, newFilter, this.props.params, {
"maxFeatures": this.props.dataSourceOptions.pageSize || 20,
"startIndex": 0
});
}
},
componentWillReceiveProps(nextProps) {
const hOffset = nextProps.fullScreen ? 150 : 181;
if (nextProps.initWidth !== this.props.initWidth) {
let height = getWindowSize().maxHeight - hOffset;
this.setState({width: nextProps.initWidth - 30, height});
}
},
shouldComponentUpdate(nextProps) {
return Object.keys(this.props).reduce((prev, prop) => {
if ( !prev && (prop !== 'map' && this.props[prop] !== nextProps[prop])) {
return true;
}
return prev;
}, false);
},
componentWillUpdate(nextProps) {
if (!nextProps.loadingGrid && nextProps.pagination && (nextProps.dataSourceOptions !== this.props.dataSourceOptions)) {
this.dataSource = this.getDataSource(nextProps.dataSourceOptions);
}
if (!nextProps.loadingGrid && this.featureLoaded && nextProps.features !== this.props.features && Object.keys(nextProps.features).length > 0) {
let rowsThisPage = nextProps.features[this.getRequestId(this.featureLoaded)] || [];
this.featureLoaded.successCallback(rowsThisPage, nextProps.totalFeatures);
this.featureLoaded = null;
}
},
onGridClose(filter) {
this.props.selectFeatures([]);
if (this.props.selectAllToggle) {
this.props.selectAllToggle();
}
this.props.toggleSiraControl('grid');
if (filter) {
this.props.onExpandFilterPanel(true);
}
},
onResize(event, resize) {
let size = resize.size;
this.setState({width: size.width, height: size.height});
},
getRequestId(params) {
return `${params.startRow}_${params.endRow}_${params.sortModel.map((m) => `${m.colId}_${m.sort}` ).join('_')}`;
},
getSortAttribute(colId) {
let col = head(this.props.columnsDef.filter((c) => colId === `properties.${c.field}`));
return col && col.sortAttribute ? col.sortAttribute : '';
},
getSortOptions(params) {
return params.sortModel.reduce((o, m) => ({sortBy: this.getSortAttribute(m.colId), sortOrder: m.sort}), {});
},
getFeatures(params) {
if (!this.props.loadingGrid) {
let reqId = this.getRequestId(params);
let rowsThisPage = this.props.features[reqId];
if (rowsThisPage) {
params.successCallback(rowsThisPage, this.props.totalFeatures);
}else {
let pagination = {startIndex: params.startRow, maxFeatures: params.endRow - params.startRow};
let filterObj = this.props.gridType === 'search' ? {
groupFields: this.props.groupFields,
filterFields: this.props.filterFields.filter((field) => field.value),
spatialField: this.props.spatialField,
pagination
} : {
groupFields: [],
filterFields: [],
spatialField: {},
pagination
};
let filter = FilterUtils.toOGCFilterSira(this.props.featureTypeName, filterObj, this.props.ogcVersion, this.getSortOptions(params));
this.featureLoaded = params;
this.sortModel = params.sortModel;
this.props.onQuery(this.props.searchUrl, filter, this.props.params, reqId);
}
}
},
getDataSource(dataSourceOptions) {
return {
rowCount: dataSourceOptions.rowCount,
getRows: this.getFeatures,
pageSize: dataSourceOptions.pageSize,
overflowSize: 20
};
},
renderHeader() {
const header = LocaleUtils.getMessageById(this.context.messages, this.props.header);
return (
<div className="handle_featuregrid">
<Grid className="featuregrid-title" fluid={true}>
<Row>
<Col xs={11} sm={11} md={11} lg={11}>
<span>{header}</span>
</Col>
<Col xs={1} sm={1} md={1} lg={1}>
<button onClick={() => this.onGridClose(false)} className="close grid-close"><span>X</span></button>
</Col>
</Row>
</Grid>
</div>
);
},
renderLoadingException(loadingError, msg) {
let exception;
if (isObject(loadingError)) {
exception = loadingError.status +
"(" + loadingError.statusText + ")" +
": " + loadingError.data;
} else {
exception = loadingError;
}
return (
<Modal show={loadingError ? true : false} bsSize="small" onHide={() => {
this.props.cleanError(false);
// this.onGridClose(true);
}}>
<Modal.Header className="dialog-error-header-side" closeButton>
<Modal.Title><I18N.Message msgId={msg}/></Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="mapstore-error">{exception}</div>
</Modal.Body>
<Modal.Footer>
</Modal.Footer>
</Modal>
);
},
render() {
let loadingError = this.props.loadingGridError;
if (loadingError) {
return (
this.renderLoadingException(loadingError, "queryform.query_request_exception")
);
}
const cols = this.props.columnsDef.map((column) => {
// if (!column.profiles || (column.profiles && column.profiles.indexOf(this.props.profile) !== -1)) {
if (verifyProfiles(column.profiles, this.props.profile)) {
return assign({}, column, {field: "properties." + column.field});
}
}).filter((c) => c);
const vCols = cols.filter((c) => !c.hide).length;
const px = this.props.withMap ? 50 : 25;
const defWidth = (this.state.width - (px + 2)) / vCols;
let columns = [{
onCellClicked: this.goToDetail,
headerName: "",
cellRenderer: reactCellRendererFactory(GoToDetail),
suppressSorting: true,
suppressMenu: true,
pinned: true,
width: 25,
suppressResize: true
}, ...(cols.map((c) => {
return assign({}, {width: defWidth}, c, c.dateFormat ? {cellRenderer: reactCellRendererFactory(GridCellDate)} : {});
}
))];
if (this.sortModel && this.sortModel.length > 0) {
columns = columns.map((c) => {
let model = head(this.sortModel.filter((m) => m.colId === c.field));
if ( model ) {
c.sort = model.sort;
}
return c;
});
}
let gridConf = this.props.pagination ? {dataSource: this.dataSource, features: []} : {features: this.props.features};
if (this.props.open) {
return (
<Panel className="featuregrid-container sidepanel-featuregrid" collapsible expanded={this.props.expanded} header={this.renderHeader()} bsStyle="primary">
<SiraExporter
toggleExporter={this.props.toggleSiraControl}
searchUrl={this.props.searchUrl}
params={this.props.params}
csvMimeType={this.props.exportCsvMimeType}
/>
<div style={this.props.loadingGrid ? {display: "none"} : {height: this.state.height, width: this.state.width}}>
<Button
className="back-to-query"
style={{marginBottom: "12px"}}
onClick={() => this.onGridClose(true)}><span><Message msgId={this.props.backToSearch}/></span>
</Button>
<h5>Risultati - {this.props.totalFeatures !== -1 ? this.props.totalFeatures : (<I18N.Message msgId={"sira.noQueryResult"}/>)}</h5>
<FeatureGrid
changeMapView={this.props.changeMapView}
srs="EPSG:4326"
ref={(r)=> {this.grid = r; }}
map={this.props.map}
columnDefs={columns}
style={{height: this.state.height - 120, width: "100%"}}
maxZoom={16}
selectFeatures={this.selectFeatures}
selectAll={this.props.selectAllToggle ? this.selectAll : undefined}
paging={this.props.pagination}
zoom={15}
enableZoomToFeature={this.props.withMap}
agGridOptions={{enableServerSideSorting: true, suppressMultiSort: true, overlayNoRowsTemplate: "Nessun risultato trovato"}}
zoomToFeatureAction={this.props.zoomToFeatureAction}
toolbar={{
zoom: this.props.withMap,
exporter: this.props.exporter,
toolPanel: true,
selectAll: this.props.selectAll
}}
exportAction={this.exportFeatures}
{...gridConf}
/>
</div>
{this.props.loadingGrid ? (<div style={{height: "300px", width: this.state.width}}>
<div style={{
position: "relative",
width: "60px",
top: "50%",
left: "45%"}}>
<Spinner style={{width: "60px"}} spinnerName="three-bounce" noFadeIn/>
</div>
</div>) : null}
</Panel>
);
}
return null;
},
selectAll(select) {
if (select) {
let filterObj = this.props.gridType === 'search' ? {
groupFields: this.props.groupFields,
filterFields: this.props.filterFields.filter((field) => field.value),
spatialField: this.props.spatialField
} : {
groupFields: [],
filterFields: [],
spatialField: {}
};
this.props.selectAllToggle(this.props.featureTypeName, filterObj, this.props.ogcVersion, this.props.params, this.props.searchUrl, this.props.nameSpaces);
} else {
this.props.selectAllToggle();
}
},
selectFeatures(features) {
if (this.props.selectAllToggle) {
this.props.selectAllToggle();
}
this.props.selectFeatures(features);
},
goToDetail(params) {
let url = this.props.detailsConfig.service.url;
let urlParams = this.props.detailsConfig.service.params;
for (let param in urlParams) {
if (urlParams.hasOwnProperty(param)) {
url += "&" + param + "=" + urlParams[param];
}
}
let templateUrl = typeof this.props.detailsConfig.template === "string" ? this.props.detailsConfig.template : this.props.detailsConfig.template[this.props.templateProfile];
this.props.onDetail(
templateUrl,
// this.props.detailsConfig.cardModelConfigUrl,
url + "&FEATUREID=" + params.data.id + (this.props.params.authkey ? "&authkey=" + this.props.params.authkey : "")
);
if (!this.props.detailOpen) {
this.props.onShowDetail();
}
},
exportFeatures(api) {
const {exporterConfig, configureExporter, toggleSiraControl, maxFeatures, gridType,
groupFields, filterFields, spatialField} = this.props;
if ( exporterConfig ) {
configureExporter(exporterConfig);
}
toggleSiraControl("exporter", true);
const pagination = (exporterConfig && exporterConfig.maxFeatures || maxFeatures) ? {
startIndex: 0,
maxFeatures: exporterConfig && exporterConfig.maxFeatures || maxFeatures
} : null;
let filterObj = gridType === 'search' ? {
groupFields: groupFields,
filterFields: filterFields.filter((field) => field.value),
spatialField: spatialField,
pagination
} : {
groupFields: [],
filterFields: [],
spatialField: {},
pagination
};
let filter = FilterUtils.toOGCFilterSira(this.props.featureTypeName, filterObj, this.props.ogcVersion);
let features = [];
api.forEachNode((n) => (features.push(n.data)));
let columns = api.columnController.getAllDisplayedColumns().reduce((cols, c) => {
if ( c.colId.indexOf("properties.") === 0) {
cols.push(c.colDef);
}
return cols;
}, []);
this.props.setExportParams({filter, features, columns, featureType: this.props.featureTypeName});
}
});
module.exports = SiraGrid;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const axios = require('../../MapStore2/web/client/libs/ajax');
const ConfigUtils = require('../../MapStore2/web/client/utils/ConfigUtils');
const GRID_MODEL_LOADED = 'GRID_MODEL_LOADED';
const GRID_LOAD_ERROR = 'GRID_LOAD_ERROR';
const GRID_CONFIG_LOADED = 'GRID_CONFIG_LOADED';
const SHOW_LOADING = 'SHOW_LOADING';
const CREATE_GRID_DATA_SOURCE = 'CREATE_GRID_DATA_SOURCE';
const UPDATE_TOTAL_FEATURES = 'UPDATE_TOTAL_FEATURES';
const FEATURES_LOADED_PAG = 'FEATURES_LOADED_PAG';
const SET_GRID_TYPE = 'SET_GRID_TYPE';
function configureGrid(config) {
return {
type: GRID_CONFIG_LOADED,
config: config
};
}
function configureGridData(data, add = false ) {
return {
type: GRID_MODEL_LOADED,
data: data,
add
};
}
function configureGridError(e) {
return {
type: GRID_LOAD_ERROR,
error: e
};
}
function showLoading(show) {
return {
type: SHOW_LOADING,
show: show
};
}
function loadGridModel(wfsUrl, params) {
let {url} = ConfigUtils.setUrlPlaceholders({url: wfsUrl});
url = params.forEach((param) => {
url += "&" + param + "=" + params[param];
});
return (dispatch) => {
return axios.get(wfsUrl).then((response) => {
dispatch(configureGridData(response.data));
}).catch((e) => {
dispatch(configureGridError(e));
});
};
}
function loadGridModelWithFilter(wfsUrl, data, params, add = false) {
let {url} = ConfigUtils.setUrlPlaceholders({url: wfsUrl});
for (let param in params) {
if (params.hasOwnProperty(param)) {
url += "&" + param + "=" + params[param];
}
}
return (dispatch) => {
dispatch(showLoading(true));
return axios.post(url, data, {
timeout: 60000,
headers: {'Accept': 'text/xml', 'Content-Type': 'text/plain'}
}).then((response) => {
dispatch(configureGridData(response.data, add));
}).catch((e) => {
dispatch(configureGridError(e));
});
};
}
function configureGridDataWithPagination(data, requestId) {
return {
type: FEATURES_LOADED_PAG,
data,
requestId
};
}
function loadFeaturesWithPagination(wfsUrl, data, params, requestId) {
let {url} = ConfigUtils.setUrlPlaceholders({url: wfsUrl});
for (let param in params) {
if (params.hasOwnProperty(param)) {
url += "&" + param + "=" + params[param];
}
}
return (dispatch) => {
dispatch(showLoading(true));
return axios.post(url, data, {
timeout: 60000,
headers: {'Accept': 'text/xml', 'Content-Type': 'text/plain'}
}).then((response) => {
if (response.data && response.data.indexOf("<ows:ExceptionReport") !== 0) {
dispatch(configureGridDataWithPagination(response.data, requestId));
}else {
dispatch(configureGridError("GeoServer Exception, query fallita!"));
}
}).catch(() => {
dispatch(configureGridError("Network problem query fallita!"));
});
};
}
function createGridDataSource(pagination) {
return {
type: CREATE_GRID_DATA_SOURCE,
pagination
};
}
function setGridType(gridType) {
return {
type: SET_GRID_TYPE,
gridType
};
}
function updateTotalFeatures(data) {
return {
type: UPDATE_TOTAL_FEATURES,
data
};
}
function loadGridModelWithPagination(wfsUrl, data, params, pagination) {
let {url} = ConfigUtils.setUrlPlaceholders({url: wfsUrl});
for (let param in params) {
if (params.hasOwnProperty(param)) {
url += "&" + param + "=" + params[param];
}
}
return (dispatch) => {
dispatch(createGridDataSource(pagination));
return axios.post(url, data, {
timeout: 120000,
headers: {'Accept': 'text/xml', 'Content-Type': 'text/plain'}
}).then((response) => {
if (response.data && response.data.indexOf("<ows:ExceptionReport") !== 0) {
dispatch(updateTotalFeatures(response.data));
}else {
dispatch(configureGridError("GeoServer Exception, impossibile recuperare numero totale oggetti!"));
}
}).catch(() => {
dispatch(configureGridError("Network problem, impossibile recuperare numero totale oggetti!"));
});
};
}
module.exports = {
GRID_MODEL_LOADED,
GRID_LOAD_ERROR,
GRID_CONFIG_LOADED,
SHOW_LOADING,
CREATE_GRID_DATA_SOURCE,
UPDATE_TOTAL_FEATURES,
FEATURES_LOADED_PAG,
SET_GRID_TYPE,
configureGrid,
configureGridData,
createGridDataSource,
loadGridModelWithPagination,
// loadFeatureGridConfig,
loadGridModel,
loadGridModelWithFilter,
configureGridError,
loadFeaturesWithPagination,
setGridType,
showLoading
};
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const Cart = React.createClass({
propTypes: {
// showCart: React.PropTypes.bool,
servicesNumber: React.PropTypes.number,
showChooseLayersPanel: React.PropTypes.func,
showCartPanel: React.PropTypes.func,
onListaClick: React.PropTypes.func,
mappaStyle: React.PropTypes.string,
listaStyle: React.PropTypes.string
},
contextTypes: {
router: React.PropTypes.object
},
getDefaultProps() {
return {
showChooseLayersPanel: () => {},
showCartPanel: () => {},
onListaClick: () => {},
mappaStyle: 'btn btn-primary',
listaStyle: 'btn btn-primary active'
};
},
render() {
const mappaStyle = this.props.mappaStyle;
const listaStyle = this.props.listaStyle;
return (
<div data-toggle="buttons" className="btn-group map-list">
<label className={listaStyle}>
<input type="radio" onChange={this.props.onListaClick} checked="" autoComplete="off" id="option1" name="options"/>
<i className="fa fa-list" aria-hidden="true"></i> <span className="label-text">Lista</span>
</label>
<label className={mappaStyle}>
<input type="radio" onChange={this.props.showCartPanel} autoComplete="off" id="option2" name="options"/>
<i className="fa fa-map-o" aria-hidden="true"></i>
<span className="label-text">Mappa</span>
<span className="badge" >{this.props.servicesNumber}</span>
</label>
</div>
);
}
});
module.exports = Cart;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {Panel, Glyphicon} = require('react-bootstrap');
const {bindActionCreators} = require('redux');
const {connect} = require('react-redux');
const {selectSection} = require('../../actions/card');
const Section = React.createClass({
propTypes: {
eventKey: React.PropTypes.string,
activeSections: React.PropTypes.object,
selectSection: React.PropTypes.func,
header: React.PropTypes.string,
expanded: React.PropTypes.bool
},
getDefaultProps() {
return {
activeSections: {},
selectSection: () => {},
expanded: false
};
},
renderHeader() {
let isActive = this.isActive();
return (
<span className="sectionHader">
<span style={{"cursor": "pointer"}} onClick={this.props.selectSection.bind(null, this.props.eventKey, (isActive) ? false : true )}>{this.props.header}</span>
<button onClick={this.props.selectSection.bind(null, this.props.eventKey, (isActive) ? false : true )} className="close"><Glyphicon glyph={(isActive) ? "glyphicon glyphicon-collapse-down" : "glyphicon glyphicon-expand"}/></button>
</span>
);
},
render() {
return (
<Panel collapsible header={this.renderHeader()} expanded={this.isActive()}>
{this.props.children}
</Panel>
);
},
isActive() {
let active = false;
if (this.props.activeSections.hasOwnProperty(this.props.eventKey)) {
active = this.props.activeSections[this.props.eventKey];
} else {
active = this.props.expanded;
}
return active;
}
});
module.exports = connect((state) => {
return {
activeSections: state.cardtemplate.activeSections || {}
};
}, dispatch => {
return bindActionCreators({selectSection: selectSection}, dispatch);
})(Section);
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {connect} = require('react-redux');
const {isObject} = require('lodash');
// include application component
const QueryBuilder = require('../../MapStore2/web/client/components/data/query/QueryBuilder');
const {Panel, Glyphicon, Modal} = require('react-bootstrap');
const {bindActionCreators} = require('redux');
const Draggable = require('react-draggable');
const LocaleUtils = require('../../MapStore2/web/client/utils/LocaleUtils');
const I18N = require('../../MapStore2/web/client/components/I18N/I18N');
const assign = require('object-assign');
const Spinner = require('react-spinkit');
const {hideQueryError} = require('../actions/siradec');
require('../../assets/css/sira.css');
const {
// QueryBuilder action functions
addGroupField,
addFilterField,
removeFilterField,
updateFilterField,
updateExceptionField,
updateLogicCombo,
removeGroupField,
changeCascadingValue,
expandAttributeFilterPanel,
expandSpatialFilterPanel,
selectSpatialMethod,
selectSpatialOperation,
removeSpatialSelection,
showSpatialSelectionDetails,
reset,
changeDwithinValue
} = require('../../MapStore2/web/client/actions/queryform');
const {
// SiraQueryPanel action functions
expandFilterPanel,
loadFeatureTypeConfig
} = require('../actions/siradec');
const {
changeDrawingStatus,
endDrawing
} = require('../../MapStore2/web/client/actions/draw');
const {
loadGridModelWithFilter,
loadGridModelWithPagination
} = require('../actions/grid');
const SiraQueryPanel = React.createClass({
propTypes: {
// Sira Query Panel props
removeButtonIcon: React.PropTypes.string,
filterPanelExpanded: React.PropTypes.bool,
loadingQueryFormConfigError: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.object
]),
header: React.PropTypes.string,
datasetHeader: React.PropTypes.string,
featureTypeName: React.PropTypes.string,
featureTypeNameLabel: React.PropTypes.string,
siraActions: React.PropTypes.object,
// QueryBuilder props
params: React.PropTypes.object,
featureTypeConfigUrl: React.PropTypes.string,
useMapProjection: React.PropTypes.bool,
attributes: React.PropTypes.array,
filterFields: React.PropTypes.array,
groupLevels: React.PropTypes.number,
groupFields: React.PropTypes.array,
spatialField: React.PropTypes.object,
showDetailsPanel: React.PropTypes.bool,
toolbarEnabled: React.PropTypes.bool,
searchUrl: React.PropTypes.string,
showGeneratedFilter: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.string
]),
attributePanelExpanded: React.PropTypes.bool,
spatialPanelExpanded: React.PropTypes.bool,
queryFormActions: React.PropTypes.object,
pagination: React.PropTypes.object,
sortOptions: React.PropTypes.object,
hits: React.PropTypes.bool
},
contextTypes: {
messages: React.PropTypes.object
},
getDefaultProps() {
return {
// Sira Query Panel default props
removeButtonIcon: "glyphicon glyphicon-remove",
filterPanelExpanded: true,
loadingQueryFormConfigError: null,
header: "queryform.form.header",
datasetHeader: "queryform.form.dataset_header",
featureTypeName: null,
featureTypeNameLabel: null,
siraActions: {
onExpandFilterPanel: () => {}
},
// QueryBuilder default props
params: {},
featureTypeConfigUrl: null,
useMapProjection: true,
attributes: [],
groupLevels: 1,
groupFields: [],
filterFields: [],
spatialField: {},
attributePanelExpanded: true,
spatialPanelExpanded: true,
showDetailsPanel: false,
toolbarEnabled: true,
searchUrl: "",
showGeneratedFilter: false,
pagination: null,
sortOptions: null,
hits: false,
queryFormActions: {
attributeFilterActions: {
onAddGroupField: () => {},
onAddFilterField: () => {},
onRemoveFilterField: () => {},
onUpdateFilterField: () => {},
onUpdateExceptionField: () => {},
onUpdateLogicCombo: () => {},
onRemoveGroupField: () => {},
onChangeCascadingValue: () => {},
onExpandAttributeFilterPanel: () => {},
onLoadFeatureTypeConfig: () => {}
},
spatialFilterActions: {
onExpandSpatialFilterPanel: () => {},
onSelectSpatiaslMethod: () => {},
onSelectSpatialOperation: () => {},
onChangeDrawingStatus: () => {},
onRemoveSpatialSelection: () => {},
onShowSpatialSelectionDetails: () => {},
onEndDrawing: () => {},
onChangeDwithinValue: () => {}
},
queryToolbarActions: {
onQuery: () => {},
onReset: () => {},
onQueryPagination: () => {},
onChangeDrawingStatus: () => {}
}
}
};
},
renderHeader() {
const header = LocaleUtils.getMessageById(this.context.messages, this.props.header);
const heading = this.props.filterPanelExpanded ? (
<span>
<span style={{paddingLeft: "15px"}}>{header}</span>
<button style={{paddingRight: "10px"}} onClick={this.props.siraActions.onExpandFilterPanel.bind(null, false)} className="close">
<Glyphicon glyph="glyphicon glyphicon-triangle-bottom collapsible"/>
</button>
</span>
) : (
<span>
<span style={{paddingLeft: "15px"}}>{header}</span>
<button style={{paddingRight: "10px"}} onClick={this.props.siraActions.onExpandFilterPanel.bind(null, true)} className="close">
<Glyphicon glyph="glyphicon glyphicon-triangle-left collapsible"/>
</button>
</span>
);
return (
<div className="handle_querypanel">
{heading}
</div>
);
},
renderDatasetHeader() {
const datasetHeader = LocaleUtils.getMessageById(this.context.messages, this.props.datasetHeader);
return (
<div className="dhContainer">
<label>{datasetHeader}</label>
<h4 className="ftheader">{this.props.featureTypeNameLabel}</h4>
</div>
);
},
renderQueryPanel() {
return (
<Draggable start={{x: 760, y: 55}} handle=".handle_querypanel,.handle_querypanel *">
<Panel className="querypanel-container" collapsible expanded={this.props.filterPanelExpanded} header={this.renderHeader()} bsStyle="primary">
{this.renderDatasetHeader()}
<QueryBuilder
params={this.props.params}
featureTypeConfigUrl={this.props.featureTypeConfigUrl}
useMapProjection={this.props.useMapProjection}
removeButtonIcon={this.props.removeButtonIcon}
groupLevels={this.props.groupLevels}
groupFields={this.props.groupFields}
filterFields={this.props.filterFields}
spatialField={this.props.spatialField}
attributes={this.props.attributes}
showDetailsPanel={this.props.showDetailsPanel}
toolbarEnabled={this.props.toolbarEnabled}
searchUrl={this.props.searchUrl}
showGeneratedFilter={this.props.showGeneratedFilter}
featureTypeName={this.props.featureTypeName}
attributePanelExpanded={this.props.attributePanelExpanded}
spatialPanelExpanded={this.props.spatialPanelExpanded}
attributeFilterActions={this.props.queryFormActions.attributeFilterActions}
spatialFilterActions={this.props.queryFormActions.spatialFilterActions}
queryToolbarActions={assign({}, this.props.queryFormActions.queryToolbarActions, {onQuery: this.onQuery})}
/>
</Panel>
</Draggable>
);
},
renderLoadConfigException(loadingError, msg) {
let exception;
if (isObject(loadingError)) {
exception = loadingError.status +
"(" + loadingError.statusText + ")" +
": " + loadingError.data;
} else {
exception = loadingError;
}
return (
<Modal show={loadingError ? true : false} bsSize="small" onHide={this.props.siraActions.onCloseError} id="loading-error-dialog">
<Modal.Header className="dialog-error-header" closeButton>
<Modal.Title><I18N.Message msgId={msg}/></Modal.Title>
</Modal.Header>
<Modal.Body className="dialog-error-body">
<div>{exception}</div>
</Modal.Body>
<Modal.Footer className="dialog-error-footer">
</Modal.Footer>
</Modal>
);
},
render() {
let loadingError = this.props.loadingQueryFormConfigError;
if (loadingError) {
return (
this.renderLoadConfigException(loadingError,
this.props.loadingQueryFormConfigError ? "queryform.config.load_config_exception" : "queryform.query_request_exception")
);
}
return this.props.attributes ?
(
this.renderQueryPanel()
) : (
<div style={{
position: "fixed",
width: "60px",
top: "50%",
left: "50%"}}>
<Spinner style={{width: "60px"}} spinnerName="three-bounce" noFadeIn/>
</div>
);
},
onQuery: function(url, filter, params) {
this.props.siraActions.onExpandFilterPanel(false);
if (this.props.pagination && (this.props.pagination.startIndex || this.props.pagination.startIndex === 0)) {
let newFilter = filter.replace("<wfs:GetFeature", "<wfs:GetPropertyValue valueReference='" + this.props.attributes[0].attribute + "' ");
newFilter = newFilter.replace("</wfs:GetFeature", "</wfs:GetPropertyValue");
this.props.queryFormActions.queryToolbarActions.onQueryPagination(url, newFilter, params, this.props.pagination);
}else {
this.props.queryFormActions.queryToolbarActions.onQuery(url, filter, params);
}
}
});
module.exports = connect((state) => {
return {
// SiraQueryPanel prop
filterPanelExpanded: state.siradec.filterPanelExpanded,
loadingQueryFormConfigError: state.siradec.loadingQueryFormConfigError,
featureTypeName: state.siradec.featureTypeName,
featureTypeNameLabel: state.siradec.featureTypeNameLabel,
// QueryBuilder props
groupLevels: state.queryform.groupLevels,
groupFields: state.queryform.groupFields,
filterFields: state.queryform.filterFields,
attributes: state.siradec.attributes,
spatialField: state.queryform.spatialField,
showDetailsPanel: state.queryform.showDetailsPanel,
toolbarEnabled: state.queryform.toolbarEnabled,
attributePanelExpanded: state.queryform.attributePanelExpanded,
spatialPanelExpanded: state.queryform.spatialPanelExpanded,
useMapProjection: state.queryform.useMapProjection,
searchUrl: state.queryform.searchUrl,
showGeneratedFilter: state.queryform.showGeneratedFilter,
featureTypeConfigUrl: state.queryform.featureTypeConfigUrl,
pagination: state.queryform.pagination,
sortOptions: state.queryform.sortOptions
};
}, dispatch => {
return {
siraActions: bindActionCreators({
// SiraQueryPanel actions
onExpandFilterPanel: expandFilterPanel,
onCloseError: hideQueryError
}, dispatch),
queryFormActions: {
// QueryBuilder actions
attributeFilterActions: bindActionCreators({
onAddGroupField: addGroupField,
onAddFilterField: addFilterField,
onRemoveFilterField: removeFilterField,
onUpdateFilterField: updateFilterField,
onUpdateExceptionField: updateExceptionField,
onUpdateLogicCombo: updateLogicCombo,
onRemoveGroupField: removeGroupField,
onChangeCascadingValue: changeCascadingValue,
onExpandAttributeFilterPanel: expandAttributeFilterPanel,
onLoadFeatureTypeConfig: loadFeatureTypeConfig
}, dispatch),
spatialFilterActions: bindActionCreators({
onExpandSpatialFilterPanel: expandSpatialFilterPanel,
onSelectSpatialMethod: selectSpatialMethod,
onSelectSpatialOperation: selectSpatialOperation,
onChangeDrawingStatus: changeDrawingStatus,
onRemoveSpatialSelection: removeSpatialSelection,
onShowSpatialSelectionDetails: showSpatialSelectionDetails,
onEndDrawing: endDrawing,
onChangeDwithinValue: changeDwithinValue
}, dispatch),
queryToolbarActions: bindActionCreators({
onQuery: loadGridModelWithFilter,
onQueryPagination: loadGridModelWithPagination,
onReset: reset,
onChangeDrawingStatus: changeDrawingStatus
}, dispatch)
}
};
})(SiraQueryPanel);
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {Modal, Button} = require('react-bootstrap');
const I18N = require('../../MapStore2/web/client/components/I18N/I18N');
const LoginPanel = React.createClass({
propTypes: {
showLoginPanel: React.PropTypes.bool,
onClosePanel: React.PropTypes.func,
onConfirm: React.PropTypes.func
},
getDefaultProps() {
return {
showLoginPanel: false,
onClosePanel: () => {},
onConfirm: () => {}
};
},
render() {
return (
<div className="infobox-container" style={{display: this.props.showLoginPanel}}>
<Modal
show= {this.props.showLoginPanel}>
<Modal.Header closeButton onClick={this.props.onClosePanel}>
<Modal.Title>Login</Modal.Title>
</Modal.Header>
<Modal.Body>
<h4><I18N.Message msgId={"loginpanel.panelMsg"}/></h4>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.props.onConfirm}><I18N.Message msgId={"loginpanel.okButton"}/></Button>
</Modal.Footer>
</Modal>
</div>
);
}
});
module.exports = LoginPanel;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {connect} = require('react-redux');
const {Glyphicon} = require('react-bootstrap');
const {showLoginPanel, hideLoginPanel} = require('../actions/userprofile');
const ConfigUtils = require('../../MapStore2/web/client/utils/ConfigUtils');
const LoginNav = connect((state) => ({
user: state.userprofile.user,
nav: false,
renderButtonText: false,
renderButtonContent: () => {return <Glyphicon glyph="user" />; },
bsStyle: "primary",
showAccountInfo: false,
showPasswordChange: false,
showLogout: true,
className: "square-button"
}), {
onShowLogin: showLoginPanel,
onLogout: () => {
window.location.href = ConfigUtils.getConfigProp('decsirawebUrl');
}
})(require('../../MapStore2/web/client/components/security/UserMenu'));
const LoginPanel = connect((state) => ({
showLoginPanel: state.userprofile.showLoginPanel
}), {
onClosePanel: hideLoginPanel,
onConfirm: () => {
window.location.href = ConfigUtils.getConfigProp('secureDecsirawebUrl');
}
})(require('./LoginPanel'));
const MapHeader = React.createClass({
propTypes: {
onBack: React.PropTypes.func,
onHome: React.PropTypes.func
},
getDefaultProps() {
return {
onBack: () => {},
onHome: () => {}
};
},
render() {
return (
<div id="header-servizio" className="container-fluid">
<div className="row-fluid">
<div className="container">
<div className="row">
<div id="portalHeader">
<header className="wrap navbar navbar-default" id="t3-mainnav">
<div className="header-section">
<div className="navbar-header">
<div className="col-lg-1 col-md-1 col-sm-1 col-xs-1 spiemonte">
<h1><a href="http://www.sistemapiemonte.it/cms/privati/" title="Home page Sistemapiemonte">SP</a></h1>
</div>
<div className="col-lg-8 col-md-8 col-sm-8 col-xs-8 titolo-interna"><h2 style={{cursor: "pointer"}} onClick={this.props.onHome}>Siradec</h2></div>
<div className="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<div data-toggle="buttons" className="btn-group map-list">
<label className="btn btn-primary ">
<input type="radio" onChange={this.props.onBack} checked="" autoComplete="off" id="option1"
name="options"/> Lista
</label>
<label className="btn btn-primary active">
<input type="radio" autoComplete="off" id="option2" name="options"/> Mappa
<span className="badge">1</span>
</label>
</div>
</div>
<LoginNav />
<LoginPanel />
</div>
<nav className="pimenu-navbar-collapse collapse">
<ul className="nav navbar-nav">
<li className="item-113"><a href="#">Link1</a></li>
<li className="item-125"><a href="#">Link2</a></li>
</ul>
</nav>
</div>
</header>
</div>
</div>
</div>
</div>
</div>
);
}
});
module.exports = MapHeader;
<file_sep>[](https://waffle.io/geosolutions-it/csi-sira)
CSI-SIRA
==========
Quick Start
------------
Clone the repository with the --recursive option to automatically clone submodules:
`git clone --recursive https://github.com/geosolutions-it/csi-sira.git`
Install NodeJS, if needed, from [here](https://nodejs.org/en/blog/release/v0.12.7/).
Start the development application locally:
`npm install`
`npm start`
The application runs at `http://localhost:8081` afterwards.
To have backend services working, you should do a full build with:
`mvn clean install`
and deploy the generated war (web/target/sira.war) into a Tomcat container.
You also need to:
- create a folder for configuration files (e.g. sira_config)
- copy the aua.properties file from root folder of the source code to the configuration folder
- add a configuration parameter to Tomcat setenv file with the configuration folder (-Dqueryform.config.dir= path to sira-config folder)
The internal proxy is configured to look for backend services on http://localhost:8080/sira, if you change the Tomcat port, please update the devServer -> proxy section in webpack.config.js
Read more on the [wiki](https://github.com/geosolutions-it/csi-sira/wiki).
<file_sep>/**
* Copyright 2017, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
var {FormattedDate} = require('react-intl');
const GridCellDate = React.createClass({
propTypes: {
params: React.PropTypes.object.isRequired
},
contextTypes: {
locale: React.PropTypes.string
},
render() {
const locale = this.props.params.colDef.locale || this.context.locale || 'it-IT';
const date = new Date(this.props.params.value);
return !isNaN(date.getTime()) ? (<FormattedDate locales={locale} value={date} {...this.props.params.colDef.dateFormat} />) : (<noscript/>);
}
});
module.exports = GridCellDate;
<file_sep>/**
* Copyright 2017, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const ol = require('openlayers');
const Proj4js = require('proj4');
module.exports = function addProjs() {
Proj4js.defs("EPSG:32632", "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs");
ol.proj.addProjection(new ol.proj.Projection({
code: 'EPSG:32632',
extent: [-250000, -200000, 1250000, 8400000],
worldExtent: [6.0000, 0.0000, 12.0000, 84.0000]
}));
};
<file_sep>#!/bin/bash
set -e
cd frontend
npm install
npm run compile
npm run lint
npm test
cd ..
mvn clean install
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {Button, Glyphicon} = require('react-bootstrap');
const {expandFilterPanel} = require('../actions/siradec');
require('../../assets/css/sira.css');
require('../../MapStore2/web/client/product/assets/css/viewer.css');
const {connect} = require('react-redux');
const SidePanel = require('./SidePanel');
const Card = require('../components/template/Card');
const {setProfile} = require('../actions/userprofile');
const url = require('url');
const urlQuery = url.parse(window.location.href, true).query;
const authParams = {
admin: {
userName: "admin",
authkey: "84279da9-f0b9-4e45-ac97-48413a48e33f"
},
A: {
userName: "profiloa",
authkey: "59ccadf2-963e-448c-bc9a-b3a5e8ed20d7"
},
B: {
userName: "profilob",
authkey: "d6e5f5a5-2d26-43aa-8af3-13f8dcc0d03c"
},
C: {
userName: "profiloc",
authkey: "<KEY>"
},
D: {
userName: "profilod",
authkey: "<KEY>"
}
};
const {
loadFeatureTypeConfig
} = require('../actions/siradec');
const NoMap = React.createClass({
propTypes: {
params: React.PropTypes.object,
featureTypeConfigUrl: React.PropTypes.string,
error: React.PropTypes.object,
setProfile: React.PropTypes.func,
onLoadFeatureTypeConfig: React.PropTypes.func,
expandFilterPanel: React.PropTypes.func,
configLoaded: React.PropTypes.bool,
featureType: React.PropTypes.string
},
getDefaultProps() {
return {
setProfile: () => {},
onLoadFeatureTypeConfig: () => {},
configLoaded: false
};
},
componentWillMount() {
if (this.props.params.profile) {
this.props.setProfile(this.props.params.profile, authParams[this.props.params.profile]);
}
},
componentDidMount() {
if (!this.props.configLoaded && this.props.featureTypeConfigUrl) {
this.props.onLoadFeatureTypeConfig(
this.props.featureTypeConfigUrl, {authkey: authParams[this.props.params.profile].authkey}, this.props.featureType, true);
}
},
componentWillReceiveProps(props) {
let fturl = props.featureTypeConfigUrl;
if (fturl !== this.props.featureTypeConfigUrl) {
this.props.onLoadFeatureTypeConfig(fturl, {authkey: authParams[this.props.params.profile].authkey}, this.props.featureType, true);
}
},
render() {
return (
<div className="mappaSiraDecisionale">
<Button id="drawer-menu-button" bsStyle="primary" key="menu-button" className="square-button" onClick={() => this.props.expandFilterPanel(true)}><Glyphicon glyph="1-stilo"/></Button>
<SidePanel withMap={false} auth={authParams[this.props.params.profile]} profile={this.props.params.profile}/>
<Card withMap={false} authParam={authParams[this.props.params.profile]}/>
</div>
);
},
back() {
window.location.href = urlQuery.back + ".html?profile=" + this.props.params.profile;
},
goHome() {
window.location.href = "index.html?profile=" + this.props.params.profile;
}
});
module.exports = connect((state) => {
return {
mode: 'desktop',
error: state.loadingError || (state.locale && state.locale.localeError) || null,
// card: state.cardtemplate,
featureType: state.siradec && state.siradec.featureType,
featureTypeConfigUrl: state.siradec && state.siradec.featureType && 'assets/' + state.siradec.featureType + '.json',
configLoaded: state.siradec && state.siradec[state.siradec.activeFeatureType] && state.siradec[state.siradec.activeFeatureType].card ? true : false
// featureGrigConfigUrl: state.grid.featureGrigConfigUrl
};
}, {
setProfile,
onLoadFeatureTypeConfig: loadFeatureTypeConfig,
expandFilterPanel
})(NoMap);
<file_sep>/**
* Copyright 2015, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
var Layers = require('../../MapStore2/web/client/utils/openlayers/Layers');
var ol = require('openlayers');
var objectAssign = require('object-assign');
const CoordinatesUtils = require('../../MapStore2/web/client/utils/CoordinatesUtils');
const {isArray} = require('lodash');
const SecurityUtils = require('../../MapStore2/web/client/utils/SecurityUtils');
const axios = require('../../MapStore2/web/client/libs/ajax');
const urllib = require('url');
function wmsToOpenlayersOptions(options) {
// NOTE: can we use opacity to manage visibility?
return objectAssign({}, options.baseParams, {
LAYERS: options.name,
STYLES: options.style || "",
FORMAT: options.format || 'image/png',
TRANSPARENT: options.transparent !== undefined ? options.transparent : true,
SRS: CoordinatesUtils.normalizeSRS(options.srs),
CRS: CoordinatesUtils.normalizeSRS(options.srs),
TILED: options.tiled || false,
VERSION: options.version || "1.3.0"
}, options.params || {});
}
function getWMSURLs( urls ) {
return urls.map((url) => url.split("\?")[0]);
}
// Works with geosolutions proxy
function postTileLoadFunction(queryParameters, imageTile, src) {
const parsedUrl = urllib.parse(src, true);
const urlQuery = parsedUrl.query;
const newSrc = Object.keys(urlQuery).reduce((url, param, idx) => {
return (param !== "SLD_BODY") ? `${url}${idx ? '&' : '?'}${param}=${urlQuery[param]}` : url;
}, `${parsedUrl.protocol}//${parsedUrl.host}${parsedUrl.pathname}`);
const srs = queryParameters.SRS.split(":")[1];
const BBOX = urlQuery.BBOX.split(',');
const request = `<?xml version="1.0" encoding="UTF-8"?>
<ogc:GetMap xmlns:ogc="http://www.opengis.net/ows"
xmlns:gml="http://www.opengis.net/gml"
version="1.3.0" service="WMS">
${queryParameters.SLD_BODY}
<BoundingBox srsName="http://www.opengis.net/gml/srs/epsg.xml#${srs}">
<gml:coord><gml:X>${BBOX[0]}</gml:X><gml:Y>${BBOX[1]}</gml:Y></gml:coord>
<gml:coord><gml:X>${BBOX[2]}</gml:X><gml:Y>${BBOX[3]}</gml:Y></gml:coord>
</BoundingBox>
<Output>
<Transparent>${queryParameters.TRANSPARENT}</Transparent>
<Format>${queryParameters.FORMAT}</Format>
<Size><Width>${urlQuery.WIDTH}</Width><Height>${urlQuery.HEIGHT}</Height></Size>
</Output>
</ogc:GetMap>`;
axios.post(newSrc, request, {
timeout: 60000,
responseType: 'blob',
headers: {'Accept': 'text/xml', 'Content-Type': 'text/plain'}
}).then((response) => {
let image = imageTile.getImage();
image.onload = function() {
window.URL.revokeObjectURL(image.src); // Clean up after yourself.
};
image.src = window.URL.createObjectURL(response.data);
});
}
Layers.registerType('wmspost', {
create: (options) => {
const urls = getWMSURLs(isArray(options.url) ? options.url : [options.url]);
const queryParameters = wmsToOpenlayersOptions(options) || {};
urls.forEach(url => SecurityUtils.addAuthenticationParameter(url, queryParameters));
if (options.singleTile) {
return new ol.layer.Image({
opacity: options.opacity !== undefined ? options.opacity : 1,
visible: options.visibility !== false,
zIndex: options.zIndex,
source: new ol.source.ImageWMS({
url: urls[0],
params: queryParameters
})
});
}
return new ol.layer.Tile({
opacity: options.opacity !== undefined ? options.opacity : 1,
visible: options.visibility !== false,
zIndex: options.zIndex,
source: new ol.source.TileWMS({
urls: urls,
params: queryParameters,
tileLoadFunction: postTileLoadFunction.bind(null, queryParameters)})
});
},
update: (layer, newOptions, oldOptions) => {
if (oldOptions && layer && layer.getSource() && layer.getSource().updateParams) {
let changed = false;
if (oldOptions.params && newOptions.params) {
changed = Object.keys(oldOptions.params).reduce((found, param) => {
if (newOptions.params[param] !== oldOptions.params[param]) {
return true;
}
return found;
}, false);
} else if (!oldOptions.params && newOptions.params) {
changed = true;
}
let oldParams = wmsToOpenlayersOptions(oldOptions);
let newParams = wmsToOpenlayersOptions(newOptions);
changed = changed || ["LAYERS", "STYLES", "FORMAT", "TRANSPARENT", "TILED", "VERSION" ].reduce((found, param) => {
if (oldParams[param] !== newParams[param]) {
return true;
}
return found;
}, false);
if (changed) {
layer.getSource().updateParams(objectAssign(newParams, newOptions.params));
}
}
}
});
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const assign = require('object-assign');
const axios = require('axios');
const uuid = require('node-uuid');
const LOAD_FEATURE_INFO = 'LOAD_FEATURE_INFO';
const ERROR_FEATURE_INFO = 'ERROR_FEATURE_INFO';
const EXCEPTIONS_FEATURE_INFO = 'EXCEPTIONS_FEATURE_INFO';
const CHANGE_MAPINFO_STATE = 'CHANGE_MAPINFO_STATE';
const NEW_MAPINFO_REQUEST = 'NEW_MAPINFO_REQUEST';
const PURGE_MAPINFO_RESULTS = 'PURGE_MAPINFO_RESULTS';
const CHANGE_MAPINFO_FORMAT = 'CHANGE_MAPINFO_FORMAT';
const SHOW_MAPINFO_MARKER = 'SHOW_MAPINFO_MARKER';
const HIDE_MAPINFO_MARKER = 'HIDE_MAPINFO_MARKER';
const LOAD_TEMPLATE_INFO = 'LOAD_TEMPLATE_INFO';
const CONFIGURE_GET_FEATURE_INFO_ERROR = 'LOAD_TEMPLATE_ERROR';
const CONFIGURE_GET_FEATURE_INFO = 'CONFIGURE_GET_FEATURE_INFO';
const CHANGE_TOPOLOGY_MAPINFO_STATE = 'CHANGE_TOPOLOGY_MAPINFO_STATE';
const CONFIGURE_INFO_TOPOLOGY_ERROR = 'CONFIGURE_INFO_TOPOLOGY_ERROR';
const CONFIGURE_INFO_TOPOLOGY = 'CONFIGURE_INFO_TOPOLOGY';
const SET_MODEL_CONFIG = 'SET_MODEL_CONFIG';
const TemplateUtils = require('../utils/TemplateUtils');
const {parseXMLResponse} = require('../../MapStore2/web/client/utils/FeatureInfoUtils');
const {loadFeatureTypeConfig} = require('./siradec');
/**
* Private
* @return a LOAD_FEATURE_INFO action with the response data to a wms GetFeatureInfo
*/
function loadFeatureInfo(reqId, data, rParams, lMetaData) {
return {
type: LOAD_FEATURE_INFO,
data: data,
reqId: reqId,
requestParams: rParams,
layerMetadata: lMetaData
};
}
/**
* Private
* @return a ERROR_FEATURE_INFO action with the error occured
*/
function errorFeatureInfo(reqId, e, rParams, lMetaData) {
return {
type: ERROR_FEATURE_INFO,
error: e,
reqId: reqId,
requestParams: rParams,
layerMetadata: lMetaData
};
}
/**
* Private
* @return a EXCEPTIONS_FEATURE_INFO action with the wms exception occured
* during a GetFeatureInfo request.
*/
function exceptionsFeatureInfo(reqId, exceptions, rParams, lMetaData) {
return {
type: EXCEPTIONS_FEATURE_INFO,
reqId: reqId,
exceptions: exceptions,
requestParams: rParams,
layerMetadata: lMetaData
};
}
function newMapInfoRequest(reqId, reqConfig) {
return {
type: NEW_MAPINFO_REQUEST,
reqId: reqId,
request: reqConfig
};
}
/**
* Sends a wms GetFeatureInfo request and dispatches the right action
* in case of success, error or exceptions.
*
* @param wmsBasePath {string} base path to the wms service
* @param requestParams {object} map of params for a getfeatureinfo request.
*/
function getFeatureInfo(wmsBasePath, requestParams, lMetaData, options = {}, topologyOptions = null) {
const defaultParams = assign({
service: 'WMS',
version: '1.1.1',
request: 'GetFeatureInfo',
srs: 'EPSG:4326',
info_format: 'application/json',
x: 0,
y: 0,
exceptions: 'application/vnd.ogc.se_xml'
}, options);
const param = assign({}, defaultParams, requestParams);
const reqId = uuid.v1();
return (dispatch) => {
dispatch(newMapInfoRequest(reqId, param));
axios.get(wmsBasePath, {params: param}).then((response) => {
if (response.data.exceptions) {
dispatch(exceptionsFeatureInfo(reqId, response.data.exceptions, requestParams, lMetaData));
} else {
if (topologyOptions) {
let valid = parseXMLResponse({response: response.data});
if (valid) {
dispatch(topologyOptions.callback(
topologyOptions.layerId,
topologyOptions.topologyConfig,
topologyOptions.modelConfig,
topologyOptions.filter,
{reqId: reqId, response: response.data, requestParams: requestParams, lMetaData: lMetaData}
));
} else {
dispatch(loadFeatureInfo(reqId, response.data, requestParams, lMetaData));
}
} else {
dispatch(loadFeatureInfo(reqId, response.data, requestParams, lMetaData));
}
}
}).catch((e) => {
dispatch(errorFeatureInfo(reqId, e, requestParams, lMetaData));
});
};
}
function changeMapInfoState(enabled) {
return {
type: CHANGE_MAPINFO_STATE,
enabled: enabled
};
}
function purgeMapInfoResults() {
return {
type: PURGE_MAPINFO_RESULTS
};
}
/**
* Set a new format for GetFeatureInfo request.
* @param mimeType {string} correct value are:
* - "text/plain"
* - "text/html"
* - "text/javascript"
* - "application/json"
* - "application/vnd.ogc.gml"
* - "application/vnd.ogc.gml/3.1.1"
*/
function changeMapInfoFormat(mimeType) {
return {
type: CHANGE_MAPINFO_FORMAT,
infoFormat: mimeType
};
}
function showMapinfoMarker() {
return {
type: SHOW_MAPINFO_MARKER
};
}
function hideMapinfoMarker() {
return {
type: HIDE_MAPINFO_MARKER
};
}
// ------------------- SIRA -------------------------- //
function changeTopologyMapInfoState(enabled) {
return {
type: CHANGE_TOPOLOGY_MAPINFO_STATE,
enabled: enabled
};
}
function configureGetFeatureInfo(layerId, config) {
return {
type: CONFIGURE_GET_FEATURE_INFO,
layerId: layerId,
config: config
};
}
function configureTemplate(layerId, template) {
return {
type: LOAD_TEMPLATE_INFO,
layerId: layerId,
template: template
};
}
function configureGetFeatureInfoError(layerId, e) {
return {
type: CONFIGURE_GET_FEATURE_INFO_ERROR,
layerId: layerId,
error: e
};
}
function configureInfoTopologyConfig(layerId, infoTopologyResponse, modelConfig, topologyConfig) {
return {
type: CONFIGURE_INFO_TOPOLOGY,
layerId: layerId,
modelConfig: modelConfig,
topologyConfig: topologyConfig,
infoTopologyResponse: infoTopologyResponse
};
}
function configureInfoTopologyConfigError(layerId, e) {
return {
type: CONFIGURE_INFO_TOPOLOGY_ERROR,
layerId: layerId,
error: e
};
}
function loadFeatureInfoTemplateConfig(layerId, templateURL) {
return (dispatch) => {
dispatch(configureTemplate(layerId, {needsLoading: false}));
return axios.get(templateURL).then((response) => {
let template = response.data;
dispatch(configureTemplate(layerId, template));
}).catch((e) => {
dispatch(configureGetFeatureInfoError(layerId, e));
});
};
}
function loadGetFeatureInfoConfig(layerId, featureType, params) {
return (dispatch, getState) => {
const state = getState();
if (!state.siradec.configOggetti[featureType]) {
dispatch(loadFeatureTypeConfig(null, params, featureType));
}
dispatch(configureGetFeatureInfo(layerId, featureType));
if (!state.mapInfo.template || !state.mapInfo.template[layerId]) {
dispatch(configureTemplate(layerId, {featureType, needsLoading: true}));
}
};
}
function loadTopologyInfoWithFilter(layerId, modelConfig, topologyConfig, filter) {
return (dispatch) => {
return axios.post(topologyConfig.wfsUrl, filter, {
timeout: 60000,
headers: {'Accept': 'text/xml', 'Content-Type': 'text/plain'}
}).then((response) => {
let infoTopologyResponse = response.data;
const columns = (modelConfig.columns || []).map((column) => {
return !column.field ? assign({}, column, {field: uuid.v1()}) : column;
});
let features = TemplateUtils.getModels(infoTopologyResponse,
modelConfig.root, columns, "1.1.0");
let data = {
"type": "FeatureCollection",
"totalFeatures": features.length,
"features": [],
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:EPSG::4326"
}
}
};
features = features.map((feature) => {
let f = {
"type": "Feature",
"id": feature.id,
"geometry_name": topologyConfig.geomAttribute,
"properties": {}
};
for (let prop in feature) {
if (feature.hasOwnProperty(prop) && prop !== "geometry") {
f.properties[prop] = feature[prop];
}
}
f.geometry = {
"type": topologyConfig.geometryType,
"coordinates": [[]]
};
if (topologyConfig.geometryType === "Polygon") {
for (let i = 0; i < feature.geometry.coordinates.length; i++) {
let coordinates = topologyConfig.wfsVersion === "1.1.0" ?
[feature.geometry.coordinates[i][1], feature.geometry.coordinates[i][0]] : feature.geometry.coordinates[i];
f.geometry.coordinates[0].push(coordinates);
}
}
return f;
});
data.features = features;
dispatch(configureInfoTopologyConfig(layerId, data, modelConfig, topologyConfig));
}).catch((e) => {
dispatch(configureInfoTopologyConfigError(e));
});
};
}
function loadInfoTopologyConfig(layerId, topologyConfig, modelConfig, filter, infoParams) {
return (dispatch) => {
dispatch(loadFeatureInfo(infoParams.reqId, infoParams.response, infoParams.requestParams, infoParams.lMetaData));
dispatch(loadTopologyInfoWithFilter(layerId, modelConfig, topologyConfig, filter));
/*return axios.get(topologyConfig.topologyModelURL).then((response) => {
let modelConfig = response.data;
if (typeof modelConfig !== "object") {
try {
modelConfig = JSON.parse(modelConfig);
} catch(e) {
dispatch(configureGetFeatureInfoError(layerId, e));
}
}
dispatch(loadFeatureInfo(infoParams.reqId, infoParams.response, infoParams.requestParams, infoParams.lMetaData));
dispatch(loadTopologyInfoWithFilter(layerId, modelConfig, topologyConfig, filter));
}).catch((e) => {
dispatch(configureInfoTopologyConfigError(layerId, e));
});*/
};
}
function setModelConfig(config) {
return {
type: SET_MODEL_CONFIG,
config: config
};
}
module.exports = {
ERROR_FEATURE_INFO,
EXCEPTIONS_FEATURE_INFO,
LOAD_FEATURE_INFO,
CHANGE_MAPINFO_STATE,
NEW_MAPINFO_REQUEST,
PURGE_MAPINFO_RESULTS,
CHANGE_MAPINFO_FORMAT,
SHOW_MAPINFO_MARKER,
HIDE_MAPINFO_MARKER,
getFeatureInfo,
changeMapInfoState,
newMapInfoRequest,
purgeMapInfoResults,
changeMapInfoFormat,
showMapinfoMarker,
hideMapinfoMarker,
LOAD_TEMPLATE_INFO,
CONFIGURE_GET_FEATURE_INFO_ERROR,
CONFIGURE_GET_FEATURE_INFO,
CHANGE_TOPOLOGY_MAPINFO_STATE,
CONFIGURE_INFO_TOPOLOGY_ERROR,
CONFIGURE_INFO_TOPOLOGY,
SET_MODEL_CONFIG,
configureTemplate,
loadGetFeatureInfoConfig,
configureGetFeatureInfoError,
configureGetFeatureInfo,
changeTopologyMapInfoState,
loadInfoTopologyConfig,
setModelConfig,
loadFeatureInfoTemplateConfig
};
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const DetailTitle = React.createClass({
propTypes: {
title: React.PropTypes.string,
subtitle: React.PropTypes.array
},
getDefaultProps() {
return {
title: '',
subtitle: ''
};
},
render() {
let subtitle = this.props.subtitle.join(" ");
return (
<h3 className="pdf-title">{this.props.title}<br/><small>{subtitle}</small></h3>
);
}
});
module.exports = DetailTitle;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {AgGridReact} = require('ag-grid-react');
const {bindActionCreators} = require('redux');
const {connect} = require('react-redux');
const {selectRows} = require('../../actions/card');
const GridCellDate = require('../GridCellDate');
const GridCellLink = require('../GridCellLink');
const TemplateUtils = require('../../utils/TemplateUtils');
const {reactCellRendererFactory} = require('ag-grid-react');
const assign = require('object-assign');
const uuid = require('node-uuid');
require("ag-grid/dist/styles/ag-grid.css");
require("ag-grid/dist/styles/theme-blue.css");
const {loadCardTemplate} = require('../../actions/card');
const {
loadFeatureTypeConfig
} = require('../../actions/siradec');
const SiraTable = React.createClass({
propTypes: {
id: React.PropTypes.string,
card: React.PropTypes.object,
style: React.PropTypes.object,
columns: React.PropTypes.array,
dependsOn: React.PropTypes.object,
detailsTemplateConfigURL: React.PropTypes.string,
configOggetti: React.PropTypes.object,
authParams: React.PropTypes.object,
features: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.func,
React.PropTypes.object
]),
selectedRow: React.PropTypes.string,
wfsVersion: React.PropTypes.string,
profile: React.PropTypes.string,
rowSelection: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.bool
]),
selectRows: React.PropTypes.func,
onDetail: React.PropTypes.func,
loadFeatureTypeConfig: React.PropTypes.func
},
getDefaultProps() {
return {
id: "SiraTable",
style: {height: "200px", width: "100%"},
features: [],
wfsVersion: null,
card: null,
dependsOn: null,
columns: [],
profile: null,
rowSelection: "single",
selectedRow: null,
selectRows: () => {},
onDetail: () => {}
};
},
componentWillReceiveProps(nextProps) {
if (this.waitingForConfig && nextProps.configOggetti && nextProps.configOggetti[this.waitingForConfig.featureType] && nextProps.configOggetti[this.waitingForConfig.featureType].card) {
const params = this.waitingForConfig.params;
this.goToDetail(params, nextProps);
this.waitingForConfig = null;
}
},
componentDidUpdate() {
if (this.api && this.props.selectedRow) {
let me = this;
this.api.forEachNode((n) => {
if (n.data[this.idFieldName] === this.props.selectedRow) {
me.api.selectNode(n, true, true);
}
});
}
},
onGridReady(params) {
this.api = params.api;
},
render() {
let features;
let columns = this.props.columns.map((column) => {
// if (!column.profiles || (column.profiles && this.props.profile && column.profiles.indexOf(this.props.profile) !== -1)) {
if (TemplateUtils.verifyProfiles(column.profiles, this.props.profile)) {
let fieldName = !column.field ? uuid.v1() : column.field;
this.idFieldName = column.id === true ? fieldName : this.idFieldName;
return assign({},
column,
{field: fieldName},
column.dateFormat ? {cellRenderer: reactCellRendererFactory(GridCellDate)} : {},
column.linkToDetail ? {onCellClicked: this.goToDetail, cellRenderer: reactCellRendererFactory(GridCellLink)} : {}
);
}
}, this).filter((c) => c);
if (typeof this.props.features === 'function') {
features = this.props.features();
} else {
features = this.props.features instanceof Array ? this.props.features : [this.props.features];
features = features.map((feature) => {
let f = {};
columns.forEach((column) => {
if (column.field) {
f[column.field] = TemplateUtils.getElement({xpath: column.xpath}, feature, this.props.wfsVersion);
}
if (column.linkToDetail) {
f.link = TemplateUtils.getElement({xpath: column.linkToDetail.xpath}, feature, this.props.wfsVersion);
}
});
return f;
}, this);
}
if (this.props.dependsOn) {
features = features.filter(function(feature) {
return feature[this.idFieldName] === this.props.card[this.props.dependsOn.tableId];
}, this);
}
return (
<div fluid={false} style={this.props.style} className="ag-blue">
<AgGridReact
rowData={features}
onSelectionChanged={this.selectRows}
enableColResize={true}
columnDefs={
this.props.rowSelection === "single" ? [{
checkboxSelection: true,
width: 30,
headerName: ''
}, ...columns] : columns
}
onGridReady={this.onGridReady}
{...this.props}
/>
</div>);
},
goToDetail(params, props) {
let detailProps = props || this.props;
const id = params.data.link;
const featureType = params.colDef.linkToDetail.featureType;
if (detailProps.configOggetti[featureType]) {
const detailsConfig = detailProps.configOggetti[featureType];
const templateUrl = params.colDef.linkToDetail.templateUrl ? params.colDef.linkToDetail.templateUrl : (detailsConfig.card.template.default || detailsConfig.card.template);
let url;
if (id) {
url = detailsConfig.card.service.url;
Object.keys(detailsConfig.card.service.params).forEach((param) => {
url += `&${param}=${detailsConfig.card.service.params[param]}`;
});
url = `${url}&FEATUREID=${id}&authkey=${detailProps.authParams.authkey}`;
}
detailProps.onDetail(templateUrl, url);
} else {
this.waitingForConfig = {
featureType,
params
};
detailProps.loadFeatureTypeConfig(null, {authkey: detailProps.authParams.authkey ? detailProps.authParams.authkey : ''}, featureType, false);
}
},
selectRows(params) {
// this.props.selectRows(this.props.id, (params.selectedRows[0]) ? params.selectedRows[0].id : null);
if (params.selectedRows[0]) {
this.props.selectRows(this.props.id, params.selectedRows[0].id || params.selectedRows[0][this.idFieldName]);
}
}
});
module.exports = connect((state) => {
return {
configOggetti: state.siradec.configOggetti,
card: state.cardtemplate || {},
authParams: state.userprofile.authParams
};
}, dispatch => {
return bindActionCreators({
selectRows: selectRows,
onDetail: loadCardTemplate,
loadFeatureTypeConfig
}, dispatch);
})(SiraTable);
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const {
QUERYFORM_CONFIG_LOADED,
FEATURETYPE_CONFIG_LOADED,
EXPAND_FILTER_PANEL,
QUERYFORM_CONFIG_LOAD_ERROR,
FEATUREGRID_CONFIG_LOADED,
FEATUREINFO_CONFIG_LOADED,
TOPOLOGY_CONFIG_LOADED,
CARD_CONFIG_LOADED,
QUERYFORM_HIDE_ERROR,
INLINE_MAP_CONFIG,
SET_ACTIVE_FEATURE_TYPE,
FEATURETYPE_CONFIG_LOADING
} = require('../actions/siradec');
const assign = require('object-assign');
const url = require('url');
const urlQuery = url.parse(window.location.href, true).query;
const uuid = require('node-uuid');
const initialState = {
filterPanelExpanded: false,
configOggetti: {
},
topology: null,
loadingQueryFormConfigError: null,
featureType: urlQuery.featureType || 'aua',
activeFeatureType: null,
inlineMapConfig: null,
fTypeConfigLoading: false
};
function siradec(state = initialState, action) {
switch (action.type) {
case INLINE_MAP_CONFIG: {
return assign({}, state, {inlineMapConfig: action.mapconfig});
}
case SET_ACTIVE_FEATURE_TYPE: {
return assign({}, state, {activeFeatureType: action.featureType});
}
case FEATURETYPE_CONFIG_LOADING: {
return assign({}, state, {fTypeConfigLoading: true});
}
case FEATURETYPE_CONFIG_LOADED: {
let attributes = state.attributes ? [...state.attributes, ...action.field] : action.field;
// Sorting the attributes by the given index in configuration
attributes.sort((attA, attB) => {
if (attA.index && attB.index) {
return attA.index - attB.index;
}
});
const queryform = assign({}, state.queryform, {geometryName: action.geometryName, spatialField: assign({}, state.queryform.spatialField, {attribute: action.geometryName})});
let newConf = assign({}, state.configOggetti[action.featureType], {
attributes: attributes,
featureTypeName: action.ftName,
featureTypeNameLabel: action.ftNameLabel,
nameSpaces: action.nameSpaces,
layer: action.layer,
exporter: action.exporter,
queryform
});
if (newConf.featuregrid) {
const featuregrid = assign({}, newConf.featuregrid, {geometryType: action.geometryType, grid: assign({}, newConf.featuregrid.grid, {geometryType: action.geometryType})});
newConf = assign({}, newConf, {featuregrid: featuregrid});
}
let configOggetti = assign({}, state.configOggetti, {[action.featureType]: newConf} );
if (action.activate) {
return assign({}, state, {
configOggetti: configOggetti,
activeFeatureType: action.featureType,
fTypeConfigLoading: false
});
}
return assign({}, state, {
configOggetti: configOggetti,
fTypeConfigLoading: false
});
}
case QUERYFORM_CONFIG_LOADED: {
return assign({}, state, {
queryform: action.config
});
}
case FEATUREGRID_CONFIG_LOADED: {
let featureGrid = action.config;
let idFieldName;
if (featureGrid.grid.columns) {
featureGrid.grid.columns.forEach((column) => {
let fieldName = !column.field ? uuid.v1() : column.field;
idFieldName = column.id === true ? fieldName : idFieldName;
column.field = fieldName;
});
}
featureGrid.idFieldName = idFieldName;
let newConf = assign({}, state.configOggetti[action.featureType], {featuregrid: featureGrid});
let configOggetti = assign({}, state.configOggetti, {[action.featureType]: newConf} );
return assign({}, state, {
configOggetti: configOggetti
});
}
case FEATUREINFO_CONFIG_LOADED: {
let newConf = assign({}, state.configOggetti[action.featureType], {featureinfo: action.config});
let configOggetti = assign({}, state.configOggetti, {[action.featureType]: newConf} );
return assign({}, state, {
configOggetti: configOggetti
});
}
case CARD_CONFIG_LOADED: {
let newConf = assign({}, state.configOggetti[action.featureType], {card: action.config});
let configOggetti = assign({}, state.configOggetti, {[action.featureType]: newConf} );
return assign({}, state, {
configOggetti: configOggetti
});
}
case TOPOLOGY_CONFIG_LOADED: {
return assign({}, state, {
topology: action.config
});
}
case EXPAND_FILTER_PANEL: {
return assign({}, state, {
filterPanelExpanded: action.expand
});
}
case QUERYFORM_CONFIG_LOAD_ERROR: {
return assign({}, state, {
loadingQueryFormConfigError: action.error,
fTypeConfigLoading: false});
}
case QUERYFORM_HIDE_ERROR: {
return assign({}, state, {
loadingQueryFormConfigError: null,
filterPanelExpanded: false
});
}
default:
return state;
}
}
module.exports = siradec;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const axios = require('../../MapStore2/web/client/libs/ajax');
const ConfigUtils = require('../../MapStore2/web/client/utils/ConfigUtils');
const SET_PROFILE = 'SET_PROFILE';
const SET_USER_IDENTITY_ERROR = 'SET_USER_IDENTITY_ERROR';
const SET_USER_IDENTITY = 'LOADED_USER_IDENTITY';
const SHOW_LOGIN_PANEL = 'SHOW_LOGIN_PANEL';
const HIDE_LOGIN_PANEL = 'HIDE_LOGIN_PANEL';
function showLoginPanel() {
return {
type: SHOW_LOGIN_PANEL,
showLoginPanel: true
};
}
function hideLoginPanel() {
return {
type: HIDE_LOGIN_PANEL,
showLoginPanel: false
};
}
function setProfile(profile, authParams) {
return {
type: SET_PROFILE,
profile: profile,
authParams: authParams
};
}
function userIdentityLoaded(data) {
return {
type: SET_USER_IDENTITY,
roles: data.roles,
user: data.user,
error: ''
};
}
function userIdentityError(err) {
return {
type: SET_USER_IDENTITY_ERROR,
roles: '',
userIdentity: '',
error: err
};
}
function loadUserIdentity(serviceUrl = 'services/iride/getRolesForDigitalIdentity') {
return (dispatch) => {
return axios.get(serviceUrl).then((response) => {
// response example
// response.data = {"roles": [{"code": "PA_GEN_DECSIRA", "domain": "REG_PMN", "mnemonic": "PA_GEN_DECSIRA@REG_PMN"}], "userIdentity": {"codFiscale": "AAAAAA00B77B000F", "nome": "CSI PIEMONTE", "cognome": "DEMO 20", "idProvider": "SISTEMAPIEMONTE"}};
if (typeof response.data === 'object') {
if (response.data.userIdentity && response.data.roles && response.data.roles.length > 0) {
// there is a logged user, geoserverUrl = secureGeoserverUrl
ConfigUtils.setConfigProp('geoserverUrl', ConfigUtils.getConfigProp('secureGeoserverUrl'));
response.data.profile = [];
Array.from(response.data.roles).forEach(function(val) {
if (val && val.mnemonic) {
response.data.profile.push(val.mnemonic);
}
});
}
let user = {};
if (response.data.userIdentity) {
user = {
name: response.data.userIdentity.nome,
surname: response.data.userIdentity.cognome,
cf: response.data.userIdentity.nome,
idProvider: response.data.userIdentity.idProvider,
profile: response.data.profile
};
response.data.user = user;
}
dispatch(userIdentityLoaded(response.data));
} else {
try {
dispatch(userIdentityLoaded(JSON.parse(response.data)));
} catch(e) {
dispatch(userIdentityError('Error in getRolesForDigitalIdentity: ' + e.message));
}
}
}).catch((e) => {
dispatch(userIdentityError(e.message));
});
};
}
module.exports = {
SET_PROFILE,
SET_USER_IDENTITY_ERROR,
SET_USER_IDENTITY,
SHOW_LOGIN_PANEL,
HIDE_LOGIN_PANEL,
showLoginPanel,
hideLoginPanel,
loadUserIdentity,
userIdentityLoaded,
userIdentityError,
setProfile
};
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const expect = require('expect');
const {
CARD_TEMPLATE_LOADED,
CARD_TEMPLATE_LOAD_ERROR,
SELECT_SECTION,
ACTIVE_SECTION,
loadCardTemplate,
loadCardData,
// loadCardModelConfig,
selectSection,
activateSection
} = require('../card');
describe('Test correctness of the card template actions', () => {
it('loads an existing template file', (done) => {
loadCardTemplate('base/js/test-resources/template-test.config', 'modelconfig/url', 'wfs/url')((e) => {
try {
expect(e).toExist();
expect(e).withArgs('templateConfigURL', 'modelConfigURL', 'wfsUrl');
done();
} catch(ex) {
done(ex);
}
});
});
/*it('loads an existing template file 2', (done) => {
const template = "<Panel header={(<DetailTitle title='Autorizzazione Unica Ambientale (AUA ) - Recupero rifiuti' subtitle={['N°', model.numauth, 'del', model.dataauth]} id={model.id}/>)}>Scheda</Panel>";
loadCardModelConfig(template, 'base/js/test-resources/testCardModelConfig.json', '')((e) => {
try {
expect(e).toExist();
expect(e).withArgs('templateConfigURL', 'modelConfigURL', 'wfsUrl');
done();
} catch(ex) {
done(ex);
}
});
});*/
it('loads an existing template file 3', (done) => {
const template = "<Panel header={(<DetailTitle title='Autorizzazione Unica Ambientale (AUA ) - Recupero rifiuti' subtitle={['N°', model.numauth, 'del', model.dataauth]} id={model.id}/>)}>Scheda</Panel>";
loadCardData(template, 'base/js/test-resources/testWFSModel.xml')((e) => {
try {
expect(e).toExist();
expect(e.type).toBe(CARD_TEMPLATE_LOADED);
done();
} catch(ex) {
done(ex);
}
});
});
it('error loading template file', (done) => {
loadCardTemplate('base/js/test-resources/template-test.conf')((e) => {
try {
expect(e).toExist();
expect(e.type).toBe(CARD_TEMPLATE_LOAD_ERROR);
done();
} catch(ex) {
done(ex);
}
});
});
it('select section', () => {
let retval = selectSection("TEST", false);
expect(retval).toExist();
expect(retval.type).toBe(SELECT_SECTION);
expect(retval.section).toBe("TEST");
expect(retval.active).toBe(false);
});
it('activate section', () => {
let retval = activateSection("TEST");
expect(retval).toExist();
expect(retval.type).toBe(ACTIVE_SECTION);
expect(retval.section).toBe("TEST");
});
});
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>it.geosolutions.csi.sira</groupId>
<artifactId>sira-root</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>metadata-services</artifactId>
<packaging>jar</packaging>
<name>CSI SIRA - Metadata Services</name>
<url>http://www.csipiemonte.it</url>
<properties>
<datasource>siradecDS</datasource>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jackson.version>1.9.10</jackson.version>
<jackson.databind-version>2.2.3</jackson.databind-version>
<jackson.annotations-version>2.5.3</jackson.annotations-version>
</properties>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<dependencies>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.annotations-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind-version}</version>
</dependency>
</dependencies>
</project><file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const ReactDOM = require('react-dom');
const expect = require('expect');
const store = require('../../../stores/store')(undefined, {
siradec: require('../../../reducers/siradec'),
cardtemplate: require('../../../reducers/card')
}, {} );
const Section = require('../Section');
describe('Section tests', () => {
beforeEach((done) => {
document.body.innerHTML = '<div id="container"></div>';
setTimeout(done);
});
afterEach((done) => {
ReactDOM.unmountComponentAtNode(document.getElementById("container"));
document.body.innerHTML = '';
setTimeout(done);
});
it('Test Section rendering default', () => {
let comp = ReactDOM.render(<Section eventKey="1" store={store}/>, document.getElementById("container"));
expect(comp).toExist();
});
it('Test Section rendering expanded', () => {
let comp = ReactDOM.render(<Section eventKey="1" store={store} expanded={true} header="TEST"/>, document.getElementById("container"));
expect(comp).toExist();
});
});
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {Panel, Image} = require('react-bootstrap');
const Draggable = require('react-draggable');
// const Message = require('../../MapStore2/web/client/components/I18N/Message');
const I18N = require('../../MapStore2/web/client/components/I18N/I18N');
const MetadataInfoBox = React.createClass({
propTypes: {
show: React.PropTypes.string,
showButtonLegend: React.PropTypes.string,
openLegendPanel: React.PropTypes.bool,
panelTitle: React.PropTypes.string,
header: React.PropTypes.string,
panelStyle: React.PropTypes.object,
title: React.PropTypes.string,
text: React.PropTypes.string,
dataProvider: React.PropTypes.string,
urlMetadato: React.PropTypes.string,
dataUrl: React.PropTypes.string,
numDatasetObjectCalc: React.PropTypes.number,
urlWMS: React.PropTypes.array,
urlWFS: React.PropTypes.array,
urlLegend: React.PropTypes.array,
error: React.PropTypes.string,
closePanel: React.PropTypes.func,
toggleLegendPanel: React.PropTypes.func,
loadLegend: React.PropTypes.func,
loadMetadataInfo: React.PropTypes.func
},
getDefaultProps() {
return {
show: 'none',
showButtonLegend: 'none',
openLegendPanel: false,
panelTitle: "",
error: '',
title: '',
text: '',
dataUrl: '',
urlWMS: [],
urlWFS: [],
urlLegend: [],
numDatasetObjectCalc: 0,
dataProvider: '',
urlMetadato: '',
header: "featuregrid.header",
closePanel: () => {},
loadMetadataInfo: () => {},
toggleLegendPanel: () => {},
loadLegend: () => {},
panelStyle: {
height: "500px",
width: "300px",
zIndex: 100,
position: "absolute",
overflow: "auto"
}
};
},
onOpenLegendPanel() {
this.props.loadLegend(this.props.urlWMS, this.props.urlLegend);
},
renderLegend() {
return this.props.urlLegend.map((url) => {
return (<Image src={url} />);
});
},
renderError() {
if (this.props.error) {
return (
<p className="infobox-error">
<I18N.Message msgId={"metadataInfoBox.errorLoadMetadata"}/>
</p>
);
}
return ('');
},
renderSingleLegend(legends) {
if (legends) {
return (
legends.map((legend, index) =>
<div className="infobox-legendpanel">
<h4 className="infobox-legend-title" key={'legend_' + index}>{legend.title}</h4>
<Image key={'im_legend_' + index} src={legend.url} />
</div>
));
}
return ('');
},
renderLegends() {
if (this.props.urlLegend) {
return (
this.props.urlLegend.map((urlObject, index) =>
<Panel className="infobox-legend-container" key={'lc_' + index}>
<h4 className="infobox-legend-service-title" key={'h4_lc_' + index} >{urlObject.serviceTitle}</h4>
{this.renderSingleLegend(urlObject.urls)}
</Panel>
));
}
return ('');
},
render() {
let renderWmsUrl = [];
if (this.props.urlWMS && this.props.urlWMS.length > 0) {
renderWmsUrl.push(<h4><I18N.Message msgId={"metadataInfoBox.urlWMS"}/></h4>);
this.props.urlWMS.map((val, index) =>
renderWmsUrl.push(
<a className="infobox-service-url"
title="wms" key={'wms_' + index}
href={val} target="_blank" >
{val}
</a>
)
);
}
let renderWfsUrl = [];
if (this.props.urlWFS && this.props.urlWFS.length > 0) {
renderWfsUrl.push(<h4><I18N.Message msgId={"metadataInfoBox.urlWFS"}/></h4>);
this.props.urlWFS.map((val, index) =>
renderWfsUrl.push(
<a className="infobox-service-url"
title="wfs" key={'wfs_' + index}
href={val} target="_blank" >
{val}
</a>
));
}
// let renderLegendUrl = this.renderLegends();
let renderLegendPanel = null;
// let content = renderLegendUrl;
if (this.props.openLegendPanel) {
renderLegendPanel =
(<Panel
className = "toolbar-panel modal-dialog-container react-draggable"
collapsible expanded={this.props.openLegendPanel}>
{this.renderLegends()}
</Panel>);
}
return (
<div className="infobox-container" style={{display: this.props.show}}>
<Draggable start={{x: 30, y: 180}} handle=".panel-heading,.handle_featuregrid,.handle_featuregrid *">
<Panel
className = "infobox-content toolbar-panel modal-dialog-container react-draggable"
style={this.props.panelStyle}
header={
<span>
<span className="snapshot-panel-title">
<I18N.Message msgId={"metadataInfoBox.panelTitle"}/>
</span>
<button className="print-panel-close close" onClick={this.props.closePanel}><span>×</span></button>
</span>}>
{this.renderError()}
<h4>{this.props.title}</h4>
<p>{this.props.text}</p>
<h4><I18N.Message msgId={"metadataInfoBox.entePA"}/></h4>
<p>{this.props.dataProvider}</p>
<h4><I18N.Message msgId={"metadataInfoBox.urlMetadato"}/></h4>
<a className="infobox-metadata-url"
title="metadato"
href={this.props.urlMetadato} target="_blank" >
{this.props.urlMetadato}
</a>
{renderWmsUrl}
{renderWfsUrl}
<button style={{display: this.props.showButtonLegend}} onClick={this.onOpenLegendPanel}><I18N.Message msgId={"metadataInfoBox.legendPanelTitle"} /></button>
{renderLegendPanel}
</Panel>
</Draggable>
</div>
);
}
});
module.exports = MetadataInfoBox;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const Section = React.createClass({
propTypes: {
header: React.PropTypes.node
},
getDefaultProps() {
return {
};
},
renderHeader() {
return React.isValidElement(this.props.header) ? this.props.header : (<h4 className="pdf-title">{this.props.header}</h4>);
},
renderBody() {
return this.props.children ? this.props.children : null;
},
render() {
return this.props.children ? (
<div className="pdf-section">
{this.props.header ? this.renderHeader() : null}
{this.renderBody()}
</div>
) : null;
}
});
module.exports = Section;
<file_sep>/**
* Copyright 2017, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {isArray} = require('lodash');
const SelectTool = require('./SelectTool');
const GroupLayer = React.createClass({
propTypes: {
node: React.PropTypes.object,
nodesStatus: React.PropTypes.object,
useTitle: React.PropTypes.bool,
toggleLayer: React.PropTypes.func,
toggleSelect: React.PropTypes.func
},
contextTypes: {
messages: React.PropTypes.object
},
getDefaultProps() {
return {
node: {},
nodesStatus: {},
useTitle: true,
toggleLayer: () => {},
toggleSelect: () => {}
};
},
renderChildren(node) {
return (isArray(node.Layer) && node.Layer || [node.Layer]).map((layer) => {
return <GroupLayer {...this.props} key={layer.id} node={layer} />;
});
},
render() {
const {node, useTitle, nodesStatus} = this.props;
const {expanded, selected} = nodesStatus[node.id] ? nodesStatus[node.id] : {expanded: true, selected: false};
const label = useTitle ? node.Title : node.Name;
const titleStyle = node.Layer ? "title-cursor" : "title";
return (<div className={`sira-map-layer ${node && node.nodetype}`}>
<div className={`group-layer-header ${node && node.nodetype} ${expanded ? 'expanded' : 'collapsed'}`}>
<SelectTool selected={selected} toggleSelect={this.toggleSelect}/>
<span className={titleStyle} onClick={() => this.props.toggleLayer(node.id, !expanded)}>{label}</span>
</div>
{ expanded && node.Layer ? (<div className="sira-map-layer-children">
{this.renderChildren(node)}
</div>) : null}
</div>);
},
toggleSelect(value) {
this.props.toggleSelect(this.props.node, value);
}
});
module.exports = GroupLayer;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const assign = require("object-assign");
const {SHOW_LOGIN_PANEL, HIDE_LOGIN_PANEL, SET_PROFILE, SET_USER_IDENTITY, SET_USER_IDENTITY_ERROR} = require('../actions/userprofile');
function userprofile(state = {
profile: null,
authParams: {}
}, action) {
switch (action.type) {
case SHOW_LOGIN_PANEL: {
return assign({}, state, {showLoginPanel: action.showLoginPanel});
}
case HIDE_LOGIN_PANEL: {
return assign({}, state, {showLoginPanel: action.showLoginPanel});
}
case SET_PROFILE: {
return assign({}, state, {
profile: state.profile ? state.profile.concat(action.profile) : action.profile,
authParams: action.authParams
});
}
case SET_USER_IDENTITY: {
return assign({}, state,
{
roles: action.roles,
user: action.user,
profile: state.profile ? state.profile.concat(action.user.profile) : action.user.profile,
error: ''
});
}
case SET_USER_IDENTITY_ERROR: {
return assign({}, state, {roles: '', user: '', error: action.error});
}
default:
return state;
}
}
module.exports = userprofile;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const axios = require('../../MapStore2/web/client/libs/ajax');
const TOGGLE_SIRA_NODE = 'TOGGLE_SIRA_NODE';
const SELECT_CATEGORY = 'SELECT_CATEGORY';
const METADATA_OBJECTS_VIEWS_LOADED = 'METADATA_OBJECTS_VIEWS_LOADED';
const CATALOG_LOADING = 'CATALOG_LOADING';
const THEMATIC_VIEW_CONFIG_LOADED = 'THEMATIC_VIEW_CONFIG_LOADED';
const SELECT_SUB_CATEGORY = 'SELECT_SUB_CATEGORY';
const RESET_OBJECT_AND_VIEW = 'RESET_OBJECT_AND_VIEW';
const THEMATIC_VIEW_CONFIG_MAP = 'THEMATIC_VIEW_CONFIG_MAP';
const SEARCH_TEXT_CHANGE = 'SEARCH_TEXT_CHANGE';
const SHOWCATEGORIES = 'SHOWCATEGORIES';
const {Promise} = require('es6-promise');
function searchTextChange(text) {
return {
type: SEARCH_TEXT_CHANGE,
text
};
}
function toggleCategories(state) {
return {
type: SHOWCATEGORIES,
state
};
}
function toggleNode(id, status) {
return {
type: TOGGLE_SIRA_NODE,
id,
status
};
}
function catalogLoading(status) {
return {
type: CATALOG_LOADING,
status
};
}
function selectCategory(category, subcat) {
return {
type: SELECT_CATEGORY,
category,
subcat
};
}
function selectSubCategory( subcat) {
return {
type: SELECT_SUB_CATEGORY,
subcat
};
}
function resetObjectAndView() {
return {
type: RESET_OBJECT_AND_VIEW
};
}
function objectsLoaded(objects, views) {
return {
type: METADATA_OBJECTS_VIEWS_LOADED,
objects,
views
};
}
function getMetadataView({serviceUrl = 'services/metadata/getMetadataView?', params = {}} = {}) {
const url = Object.keys(params).reduce((u, p) => {
return `${u}&${p}=${params[p]}`;
}, serviceUrl);
return axios.post(url).then((response) => {
if (typeof response.data !== "object" ) {
try {
return JSON.parse(response.data);
} catch(e) {
Promise.reject(`Configuration broken (${url}): ${ e.message}`);
}
}else {
return response.data;
}
});
}
function getMetadataObjects({serviceUrl = 'services/metadata/getMetadataObject?', params = {}} = {}) {
const url = Object.keys(params).reduce((u, p) => {
return `${u}&${p}=${params[p]}`;
}, serviceUrl);
return (dispatch) => {
dispatch(catalogLoading(true));
return axios.post(url).then((response) => {
getMetadataView({params}).then((result) => {
dispatch(catalogLoading(false));
if (typeof response.data !== "object" ) {
try {
dispatch(objectsLoaded(JSON.parse(response.data), result));
}catch (e) {
// dispatch(serchCategoriesLoaded(response.data));
}
}else {
dispatch(objectsLoaded(response.data, result));
}
});
}).catch(() => {
});
};
}
function thematicViewConfigLoaded(data) {
return {
type: THEMATIC_VIEW_CONFIG_LOADED,
config: data
};
}
function thematicViewConfigMap(data) {
return {
type: THEMATIC_VIEW_CONFIG_MAP,
config: data
};
}
function getThematicViewConfig({serviceUrl = 'services/metadata/getMetadataObject?', params = {}, configureMap = false} = {}) {
const url = Object.keys(params).reduce((u, p) => {
return `${u}&${p}=${params[p]}`;
}, serviceUrl);
return (dispatch) => {
dispatch(catalogLoading(true));
return axios.get(url).then((response) => {
dispatch(catalogLoading(false));
if (typeof response.data !== "object" ) {
try {
if (configureMap) {
dispatch(thematicViewConfigMap(JSON.parse(response.data)));
}else {
dispatch(thematicViewConfigLoaded(JSON.parse(response.data)));
}
}catch (e) {
// dispatch(serchCategoriesLoaded(response.data));
}
}else {
if (configureMap) {
dispatch(thematicViewConfigMap(response.data));
}else {
dispatch(thematicViewConfigLoaded(response.data));
}
}
}).catch(() => {
dispatch(catalogLoading(false));
});
};
}
module.exports = {
TOGGLE_SIRA_NODE,
SELECT_CATEGORY,
METADATA_OBJECTS_VIEWS_LOADED,
CATALOG_LOADING,
THEMATIC_VIEW_CONFIG_LOADED,
SELECT_SUB_CATEGORY,
RESET_OBJECT_AND_VIEW,
SEARCH_TEXT_CHANGE,
SHOWCATEGORIES,
toggleNode,
selectCategory,
getMetadataObjects,
getThematicViewConfig,
selectSubCategory,
resetObjectAndView,
searchTextChange,
toggleCategories
};
<file_sep>/**
* Copyright 2017, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {Glyphicon} = require('react-bootstrap');
const SelectTool = React.createClass({
propTypes: {
selected: React.PropTypes.bool,
toggleSelect: React.PropTypes.func
},
contextTypes: {
messages: React.PropTypes.object
},
getDefaultProps() {
return {
selected: false,
toggleSelect: () => {}
};
},
render() {
const {selected} = this.props;
return (
<Glyphicon onClick={() => this.props.toggleSelect(!selected)} glyph={selected ? "check" : "unchecked"}/>);
}
});
module.exports = SelectTool;
<file_sep><project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>it.geosolutions.csi.sira</groupId>
<artifactId>decsira-app_schema-data</artifactId>
<packaging>pom</packaging>
<version>1.0.0</version>
<url>http://www.csipiemonte.it/</url>
<name>CSI SIRA - app-schema data mappings</name>
<properties>
<ui.version>1.0.0</ui.version>
<db.port>5432</db.port>
<db.password><PASSWORD></db.password>
<db.schema>decsira</db.schema>
<db.host>tst-territorio-vdb06.territorio.csi.it</db.host>
<db.name>DBSIRASVIL</db.name>
<db.user>decsira</db.user>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>Copy files</id>
<phase>process-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/data</outputDirectory>
<encoding>UTF-8</encoding>
<resources>
<resource>
<filtering>true</filtering>
<directory>${basedir}/mappings</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>Zip GeoServer datadir</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<delete file="${basedir}/target/decsira-app_schema-data-${ui.version}.zip" failonerror="false" />
<zip destfile="${basedir}/target/decsira-app_schema-data-${ui.version}.zip">
<zipfileset dir="${basedir}/target/data" includes="**/**" />
</zip>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>produzione</id>
<properties>
<ui.version>1.0.0</ui.version>
<db.port>5432</db.port>
<db.password><PASSWORD></db.password>
<db.schema>decsira</db.schema>
<db.host>prd-territorio-vdb02.territorio.csi.it</db.host>
<db.name>DBSIRA</db.name>
<db.user>gwc</db.user>
</properties>
</profile>
</profiles>
</project><file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const Footer = React.createClass({
propTypes: {
},
getDefaultProps() {
return {
};
},
render() {
return (
<footer className="footer" role="contentinfo">
<div className="container-fluid">
<div className="custom footerCsi row-fluid">
<div className="container">
<div className="row">
<div className="span6 col-sm-6 footer-sx">
<a href=""><img alt="conoscenze ambientali" src="assets/application/conoscenze_ambientali/css/images/logo_footer.png" /></a>
</div>
<div className="span6 col-sm-6 footer-dx">
<a href="http://www.sistemapiemonte.it"><img alt="sistema piemonte" src="assets/application/conoscenze_ambientali/css/images/sistemapiemonte.png" /></a>
</div>
</div>
</div>
</div>
</div>
</footer>
);
}
});
module.exports = Footer;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const LinkToMetadataInfoBox = React.createClass({
propTypes: {
openMetadataInfobox: React.PropTypes.func
},
getDefaultProps() {
return {
openMetadataInfobox: () => {}
};
},
render() {
return (
<button
className="btn btn-primary btn-lg"
data-toggle="modal"
data-target="#nomeModale"
onClick={this.props.openMetadataInfobox}>
Metadata Info Box
</button>
);
}
// openInfoBox() {
// this.props.loadMetadataInfo();
// this.props.openMetadataInfobox();
// }
});
module.exports = LinkToMetadataInfoBox;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const msMapConfig = require('../../MapStore2/web/client/reducers/config');
const CommonLayers = require('json!../../siraCommonLayers.json');
const assign = require('object-assign');
function mapConfig(state = null, action) {
switch (action.type) {
case 'MAP_CONFIG_LOADED': {
let layers = action.config.map.layers.concat(CommonLayers);
action.config.map = assign({}, action.config.map, {layers: layers});
if (localStorage.getItem('sira.config.layers')) {
const storedLayersConfig = JSON.parse(localStorage.getItem('sira.config.layers'));
layers = action.config.map.layers.concat(storedLayersConfig);
action.config.map = assign({}, action.config.map, {layers: layers});
localStorage.removeItem('sira.config.layers');
}
if (localStorage.getItem('sira.config.map')) {
const storedMapConfig = JSON.parse(localStorage.getItem('sira.config.map'));
action.config.map = assign({}, action.config.map, storedMapConfig);
localStorage.removeItem('sira.config.map');
}
if (state.siradec.inlineMapConfig) {
action.config.map = assign({}, action.config.map, state.siradec.inlineMapConfig);
}
return msMapConfig(state, action);
}
case 'THEMATIC_VIEW_CONFIG_MAP': {
const layers = action.config.map.layers.concat(CommonLayers);
const map = assign({}, action.config.map, {layers: layers});
const newAction = {type: 'MAP_CONFIG_LOADED', legacy: false, mapId: false, config: {map}};
return msMapConfig(state, newAction);
}
default:
return msMapConfig(state, action);
}
}
module.exports = mapConfig;
<file_sep>/**
* Copyright 2017, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const GridCellLink = React.createClass({
propTypes: {
params: React.PropTypes.object.isRequired
},
render() {
return <span className="grid-cell-link">{this.props.params.value}</span>;
}
});
module.exports = GridCellLink;
<file_sep>/**
* Copyright 2017, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
// const {Button, Glyphicon} = require('react-bootstrap');
const {getWindowSize} = require('../../MapStore2/web/client/utils/AgentUtils');
const mapUtils = require('../../MapStore2/web/client/utils/MapUtils');
const CoordinateUtils = require('../../MapStore2/web/client/utils/CoordinatesUtils');
const {changeMapView} = require('../../MapStore2/web/client/actions/map');
const {connect} = require('react-redux');
const {mapSelector} = require('../../MapStore2/web/client/selectors/map');
const SideQueryPanel = require('../components/SideQueryPanel');
const Card = require('../components/template/Card');
const SideFeatureGrid = require('../components/SideFeatureGrid');
const {setProfile} = require('../actions/userprofile');
const Spinner = require('react-spinkit');
const {selectFeatures} = require('../actions/featuregrid');
const {
loadFeatureTypeConfig,
expandFilterPanel
} = require('../actions/siradec');
const {toggleSiraControl} = require('../actions/controls');
require('../../assets/css/fullscreen.css');
const FullScreen = React.createClass({
propTypes: {
params: React.PropTypes.object,
featureType: React.PropTypes.string,
error: React.PropTypes.object,
filterPanelExpanded: React.PropTypes.bool,
onLoadFeatureTypeConfig: React.PropTypes.func,
expandFilterPanel: React.PropTypes.func,
toggleSiraControl: React.PropTypes.func,
configLoaded: React.PropTypes.bool,
profile: React.PropTypes.object,
siraControls: React.PropTypes.object,
selectFeatures: React.PropTypes.func,
detailsConfig: React.PropTypes.object,
gridConfig: React.PropTypes.object,
loadCardTemplate: React.PropTypes.func,
selectAllToggle: React.PropTypes.func,
gridExpanded: React.PropTypes.bool,
fTypeConfigLoading: React.PropTypes.bool,
changeMapView: React.PropTypes.func,
srs: React.PropTypes.string,
maxZoom: React.PropTypes.number,
map: React.PropTypes.object
},
contextTypes: {
router: React.PropTypes.object
},
getDefaultProps() {
return {
setProfile: () => {},
onLoadFeatureTypeConfig: () => {},
configLoaded: false,
filterPanelExpanded: true,
toggleSiraControl: () => {},
srs: "EPSG:4326",
maxZoom: 16
};
},
getInitialState() {
return {
loadList: true
};
},
componentWillMount() {
this.setState({width: getWindowSize().maxWidth});
if (window.addEventListener) {
window.addEventListener('resize', this.setSize, false);
}
},
componentDidMount() {
document.body.className = "body_map";
},
componentWillReceiveProps(nextProps) {
const {map, filterPanelExpanded, siraControls, gridExpanded} = nextProps;
if (this.props.map !== map) {
if (siraControls.detail) {
this.props.toggleSiraControl('detail');
}
if (filterPanelExpanded) {
this.props.expandFilterPanel(false);
}
if (gridExpanded) {
this.props.toggleSiraControl('grid');
}
this.props.selectFeatures([]);
if (this.props.params.profile) {
this.context.router.push('/map/${this.props.params.profile}');
}else {
this.context.router.push('/map/');
}
}
},
componentWillUnmount() {
if (window.removeEventListener) {
window.removeEventListener('resize', this.setSize, false);
}
},
renderQueryPanel() {
return (
<SideQueryPanel
withMap={false}
// authkey: (this.props.profile.authParams && this.props.profile.authParams.authkey) ? this.props.profile.authParams.authkey : '')
params={{authkey: this.props.profile.authParams && this.props.profile.authParams.authkey ? this.props.profile.authParams.authkey : ''}}
toggleControl={this.toggleControl}/>
);
},
renderGrid() {
return (
<SideFeatureGrid
initWidth={this.state.width}
withMap={true}
params={{authkey: this.props.profile.authParams && this.props.profile.authParams.authkey ? this.props.profile.authParams.authkey : ''}}
profile={this.props.profile.profile}
zoomToFeatureAction={this.zoomToFeature}
fullScreen={true}
selectAll={false}/>
);
},
render() {
const {gridExpanded, profile, fTypeConfigLoading} = this.props;
if (fTypeConfigLoading) {
return (<div style={{position: "absolute", top: 0, left: 0, bottom: 0, right: 0, backgoroundColor: "rgba(125,125,125,.5)"}}><Spinner style={{position: "absolute", top: "calc(50%)", left: "calc(50% - 30px)", width: "60px"}} spinnerName="three-bounce" noFadeIn/></div>);
}
let comp;
if (gridExpanded) {
comp = this.renderGrid();
}else {
comp = this.renderQueryPanel();
}
return (
<div id="fullscreen-container" className="mappaSiraDecisionale">
{comp}
<Card draggable={false} profile ={profile.profile} authParam={profile.authParams} withMap={true}/>
</div>
);
},
toggleControl() {
this.props.expandFilterPanel(false);
if (this.props.params.profile) {
this.context.router.push(`/dataset/${this.props.params.profile}/`);
}else {
this.context.router.push('/dataset/');
}
},
zoomToFeature(data) {
setTimeout(() => {this.changeMapView([data.geometry]); }, 0);
},
changeMapView(geometries) {
let extent = geometries.reduce((prev, next) => {
return CoordinateUtils.extendExtent(prev, CoordinateUtils.getGeoJSONExtent(next));
}, CoordinateUtils.getGeoJSONExtent(geometries[0]));
const center = mapUtils.getCenterForExtent(extent, "4326");
this.props.changeMapView(center, 15, null, null, null, this.props.map.projection || "EPSG:3857");
},
setSize() {
this.setState({width: window.innerWidth});
}
});
module.exports = connect((state) => {
const activeConfig = state.siradec.configOggetti[state.siradec.activeFeatureType] || {};
return {
profile: state.userprofile,
error: state.loadingError || (state.locale && state.locale.localeError) || null,
filterPanelExpanded: state.siradec.filterPanelExpanded,
siraControls: state.siraControls,
detailsConfig: activeConfig && activeConfig.card,
gridConfig: activeConfig && activeConfig.featuregrid,
featureTypeName: activeConfig && activeConfig.featureTypeName,
searchUrl: state.queryform.searchUrl,
pagination: state.queryform.pagination,
gridExpanded: state.siraControls.grid,
fTypeConfigLoading: state.siradec.fTypeConfigLoading,
map: mapSelector(state)
};
}, {
setProfile,
onLoadFeatureTypeConfig: loadFeatureTypeConfig,
expandFilterPanel,
toggleSiraControl,
changeMapView,
selectFeatures
})(FullScreen);
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const axios = require('../../MapStore2/web/client/libs/ajax');
const ConfigUtils = require('../../MapStore2/web/client/utils/ConfigUtils');
const CARD_TEMPLATE_LOADED = 'CARD_TEMPLATE_LOADED';
const CARD_TEMPLATE_LOAD_ERROR = 'CARD_TEMPLATE_LOAD_ERROR';
const SELECT_SECTION = 'SELECT_SECTION';
const ACTIVE_SECTION = 'ACTIVE_SECTION';
const SELECT_ROWS = 'SELECT_ROWS';
const GENERATE_PDF = 'GENERATE_PDF';
const MAP_IMAGE_READY = 'MAP_IMAGE_READY';
function mapImageReady(state) {
return {
type: MAP_IMAGE_READY,
state
};
}
function generatePDF(active = true) {
return {
type: GENERATE_PDF,
active
};
}
function configureCard(template, xml, params) {
return {
type: CARD_TEMPLATE_LOADED,
template,
xml,
params
};
}
function configureCardError(e) {
return {
type: CARD_TEMPLATE_LOAD_ERROR,
error: e
};
}
function selectSection(section, active) {
return {
type: SELECT_SECTION,
section: section,
active: active
};
}
function activateSection(section) {
return {
type: ACTIVE_SECTION,
section: section
};
}
function loadCardData(template, wfsUrl, params={}) {
let {url} = ConfigUtils.setUrlPlaceholders({url: wfsUrl});
return (dispatch) => {
return axios.get(url).then((response) => {
// let model = TemplateUtils.getModel(response.data, modelConfig);
dispatch(configureCard(template, response.data, params));
}).catch((e) => {
dispatch(configureCardError(e));
});
};
}
/*function loadCardModelConfig(template, modelConfigURL, wfsUrl) {
return (dispatch) => {
return axios.get(modelConfigURL).then((response) => {
let modelConfig = response.data;
if (typeof modelConfig !== "object") {
try {
modelConfig = JSON.parse(modelConfig);
} catch(e) {
dispatch(configureCardError(e));
}
}
dispatch(loadCardModel(template, modelConfig, wfsUrl));
}).catch((e) => {
dispatch(configureCardError(e));
});
};
}*/
function loadCardTemplate(templateConfigURL, wfsUrl, params = {}) {
return (dispatch) => {
return axios.get(templateConfigURL).then((response) => {
let template = response.data;
if (wfsUrl) {
dispatch(loadCardData(template, wfsUrl, params));
// dispatch(loadCardModelConfig(template, modelConfigURL, wfsUrl));
} else {
dispatch(configureCard(template, null, params));
}
}).catch((e) => {
dispatch(configureCardError(e));
});
};
}
function selectRows(tableId, rows) {
return {
type: SELECT_ROWS,
tableId: tableId,
rows: rows
};
}
/*function setSiraImpiantoModel(impiantoModel) {
return {
type: SET_IMPIANTO_MODEL,
impiantoModel: impiantoModel
};
}*/
module.exports = {
CARD_TEMPLATE_LOADED,
CARD_TEMPLATE_LOAD_ERROR,
SELECT_SECTION,
ACTIVE_SECTION,
SELECT_ROWS,
GENERATE_PDF,
MAP_IMAGE_READY,
// SET_IMPIANTO_MODEL,
loadCardTemplate,
loadCardData,
configureCardError,
// loadCardModelConfig,
selectSection,
activateSection,
selectRows,
generatePDF,
mapImageReady
// setSiraImpiantoModel
};
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {connect} = require('react-redux');
const {toggleNode, getThematicViewConfig, selectSubCategory, getMetadataObjects, toggleCategories} = require('../actions/siracatalog');
const assign = require('object-assign');
const {Tabs, Tab} = require("react-bootstrap");
const {toggleSiraControl} = require('../actions/controls');
const {addLayer} = require('../../MapStore2/web/client/actions/layers');
const {
// SiraQueryPanel action functions
expandFilterPanel,
loadFeatureTypeConfig,
setActiveFeatureType
} = require('../actions/siradec');
const {loadMetadata, showBox} = require('../actions/metadatainfobox');
const {setGridType} = require('../actions/grid');
const {loadNodeMapRecords, toggleAddMap, addLayers} = require('../actions/addmap');
const {tocSelector} = require('../selectors/sira');
const TOC = require('../../MapStore2/web/client/components/TOC/TOC');
const DefaultGroup = require('../../MapStore2/web/client/components/TOC/DefaultGroup');
const DefaultNode = require('../components/catalog/DefaultNode');
const AddMapModal = connect(({addmap = {}, map = {}}) => ({
error: addmap.error,
node: addmap.node,
records: addmap.records,
loading: addmap.loading,
show: addmap.show,
srs: map.present && map.present.projection || 'EPSG:32632'
}), {
close: toggleAddMap.bind(null, false),
addLayers: addLayers
})(require('../components/addmap/AddMapModal'));
const Spinner = require('react-spinkit');
const SiraSearchBar = require('../components/SiraSearchBar');
const Vista = connect( null, {
addToMap: getThematicViewConfig
})(require('../components/catalog/Vista'));
const LayerTree = React.createClass({
propTypes: {
id: React.PropTypes.number,
nodes: React.PropTypes.array,
views: React.PropTypes.array,
objects: React.PropTypes.array,
loading: React.PropTypes.bool,
nodesLoaded: React.PropTypes.bool,
onToggle: React.PropTypes.func,
toggleSiraControl: React.PropTypes.func,
expandFilterPanel: React.PropTypes.func,
getMetadataObjects: React.PropTypes.func,
category: React.PropTypes.shape({
name: React.PropTypes.string.isRequired,
id: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]).isRequired,
icon: React.PropTypes.string.isRequired,
objectNumber: React.PropTypes.number,
tematicViewNumber: React.PropTypes.number
}).isRequired,
subcat: React.PropTypes.string,
configOggetti: React.PropTypes.object,
authParams: React.PropTypes.object,
userprofile: React.PropTypes.object,
activeFeatureType: React.PropTypes.string,
loadFeatureTypeConfig: React.PropTypes.func,
setActiveFeatureType: React.PropTypes.func,
setGridType: React.PropTypes.func,
showInfoBox: React.PropTypes.func,
loadMetadata: React.PropTypes.func,
selectSubCategory: React.PropTypes.func,
loadNodeMapRecords: React.PropTypes.func,
toggleAddMap: React.PropTypes.func,
addLayer: React.PropTypes.func,
toggleCategories: React.PropTypes.func,
showcategories: React.PropTypes.bool,
srs: React.PropTypes.string
},
getDefaultProps() {
return {
loading: false,
onToggle: () => {},
showcategories: true
};
},
componentWillMount() {
if (!this.props.nodesLoaded && !this.props.loading) {
this.loadMetadata({category: this.props.category});
}
},
render() {
if (!this.props.nodes) {
return <div></div>;
}
const {views, objects, nodes, showcategories} = this.props;
const tocObjects = (
<TOC nodes={showcategories ? nodes : objects}>
{ showcategories ?
(<DefaultGroup animateCollapse={false} onToggle={this.props.onToggle}>
<DefaultNode
expandFilterPanel={this.openFilterPanel}
toggleSiraControl={this.searchAll}
onToggle={this.props.onToggle}
groups={nodes}
addToMap={this.addToMap}
showInfoBox={this.showInfoBox}/>
</DefaultGroup>) : (<DefaultNode
expandFilterPanel={this.openFilterPanel}
toggleSiraControl={this.searchAll}
addToMap={this.addToMap}
showInfoBox={this.showInfoBox}/>) }
</TOC>);
const viste = this.props.views ? this.props.views.map((v) => (<Vista key={v.id}
expandFilterPanel={this.props.expandFilterPanel}
toggleSiraControl={this.props.toggleSiraControl}
node={v}
onToggle={this.props.onToggle}
showInfoBox={this.showInfoBox}/>)) : (<div/>);
return (
<div id="siracatalog">
<SiraSearchBar
onSearch={this.loadMetadata}
onReset={this.loadMetadata}
/>
<div className="catalog-categories-switch-container">
<div className="catalog-categories-switch" onClick={() => this.props.toggleCategories(!showcategories)}>
<span>{showcategories ? 'Nascondi Categorie' : 'Mostra Categorie'} </span>
</div>
</div>
<Tabs className="catalog-tabs" activeKey={this.props.subcat} onSelect={this.props.selectSubCategory}>
<Tab eventKey={'objects'} title={`Oggetti (${objects ? objects.length : 0})`}>{tocObjects}</Tab>
<Tab eventKey={'views'} title={`Viste Tematiche (${views ? views.length : 0})`}>{viste}</Tab>
</Tabs>
{this.props.loading ? (
<div style={{position: "absolute", top: 0, left: 0, bottom: 0, right: 0, backgoroundColor: "rgba(125,125,125,.5)"}}><Spinner style={{position: "absolute", top: "calc(50%)", left: "calc(50% - 30px)", width: "60px"}} spinnerName="three-bounce" noFadeIn/></div>) : null}
<AddMapModal/>
</div>);
},
loadMetadata({text, category} = {}) {
let params = {};
const {id} = category || {};
if (id !== 999) {
params.category = id;
}
if (text && text.length > 0) {
params.text = text;
/*if (this.props.showcategories) {
this.props.toggleCategories(!this.props.showcategories);
}*/
}else {
if (!this.props.showcategories) {
this.props.toggleCategories(!this.props.showcategories);
}
}
if (!this.props.loading) {
this.props.getMetadataObjects({params});
}
},
openFilterPanel(status, ftType) {
const featureType = ftType.replace('featuretype=', '').replace('.json', '');
if (!this.props.configOggetti[featureType]) {
this.props.loadFeatureTypeConfig(null, {authkey: this.props.userprofile.authParams.authkey ? this.props.userprofile.authParams.authkey : ''}, featureType, true);
}else if (this.props.activeFeatureType !== featureType) {
this.props.setActiveFeatureType(featureType);
}
this.props.expandFilterPanel(status);
},
searchAll(ftType) {
const featureType = ftType.replace('featuretype=', '').replace('.json', '');
if (!this.props.configOggetti[featureType]) {
this.props.loadFeatureTypeConfig(null, {authkey: this.props.userprofile.authParams.authkey ? this.props.userprofile.authParams.authkey : ''}, featureType, true);
}else if (this.props.activeFeatureType !== featureType) {
this.props.setActiveFeatureType(featureType);
}
this.props.setGridType('all_results');
this.props.toggleSiraControl('grid', true);
},
showInfoBox(node) {
// Will be removed when clear how to use components, we already have metadata loaded
this.props.loadMetadata(node);
this.props.showInfoBox();
},
addToMap(node) {
if (!node.featureType) {
this.props.toggleAddMap(true);
this.props.loadNodeMapRecords(node);
}else if (node.featureType) {
const featureType = node.featureType.replace('featuretype=', '').replace('.json', '');
if (!this.props.configOggetti[featureType]) {
this.props.loadFeatureTypeConfig(null, {authkey: this.props.userprofile.authParams.authkey ? this.props.userprofile.authParams.authkey : ''}, featureType, true, true, node.id);
}else {
this.props.addLayer(assign({}, this.props.configOggetti[featureType].layer, {siraId: node.id}));
}
}
}
});
const CatalogPlugin = connect(tocSelector, {
onToggle: toggleNode,
toggleSiraControl,
expandFilterPanel,
getMetadataObjects,
loadFeatureTypeConfig,
setActiveFeatureType,
setGridType,
loadMetadata,
showInfoBox: showBox,
selectSubCategory,
loadNodeMapRecords,
toggleAddMap,
addLayer,
toggleCategories
})(LayerTree);
module.exports = {
CatalogPlugin: assign(CatalogPlugin, {
DrawerMenu: {
name: 'catalog',
position: 2,
glyph: "1-catalog",
title: 'Catalog',
priority: 1
}
}),
reducers: {
siracatalog: require('../reducers/siracatalog')
}
};
<file_sep>const url = require('url');
const {endsWith} = require('lodash');
module.exports = {
goToMapPage(center, zoom) {
const currentUrl = url.parse(window.location.href, true);
if (endsWith(currentUrl.pathname, "map.html")) {
// Strip first part of route needs to be improved
window.location.href = currentUrl.href.replace(/#\/\w+\//, '#/');
} else {
localStorage.setItem("sira.config.map", JSON.stringify({zoom, center}));
window.open(`map.html?${currentUrl.hash}`, '_blank');
// window.location.href = `map.html?${query}${currentUrl.hash}`;
}
}
};
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const xml2js = require('xml2js');
const urlUtil = require('url');
const axios = require('../../MapStore2/web/client/libs/ajax');
const assign = require('object-assign');
const HIDE_BOX = 'HIDE_BOX';
const SHOW_BOX = 'SHOW_BOX';
const LOAD_METADATA = 'LOAD_METADATA';
const LOAD_METADATA_ERROR = 'LOAD_METADATA_ERROR';
const TOGGLE_LEGEND_PANEL = 'TOGGLE_LEGEND_PANEL';
const LEGEND_LOADED = 'LEGEND_LOADED';
const LEGEND_LOADED_ERROR = 'LEGEND_LOADED_ERROR';
const ADD_URL_LEGEND = 'ADD_URL_LEGEND';
const makeGetCapabilitiesUrl = (url) => {
const parsed = urlUtil.parse(url, true);
return urlUtil.format(assign({}, parsed, {search: null}, {
query: assign({
service: "WMS",
version: "1.3.0",
request: "GetCapabilities"
}, parsed.query)
}));
};
const makeGetLegendUrl = (url, layer) => {
const parsed = urlUtil.parse(url, true);
return urlUtil.format(assign({}, parsed, {search: null}, {
query: assign({
service: "WMS",
version: "1.1.0",
request: "GetLegendGraphic",
format: "image/png",
layer: layer
}, parsed.query)
}));
};
/*
Private function
Search layers in obj
if(obj is layer) param.add(obj)
else for all property of obj --> iterate(obj.property)
*/
function iterate(obj, param) {
if (obj && obj.isLayer) {
param.push(obj);
}
for (let property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] === "object") {
if (property === "Layer") {
if (Array.isArray(obj[property])) {
for (let i = 0; i < obj[property].length; i++) {
obj[property][i].isLayer = true;
}
}else {
obj[property].isLayer = true;
}
}
iterate(obj[property], param);
}
}
}
}
/*
* action
*/
function hideBox() {
return {
type: HIDE_BOX,
show: 'none'
};
}
function showBox() {
return {
type: SHOW_BOX,
show: 'block'
};
}
function toggleLegendBox() {
return {
type: TOGGLE_LEGEND_PANEL
};
}
function legendLoaded() {
return {
type: LEGEND_LOADED
};
}
function legendLoadedError(error) {
return {
type: LEGEND_LOADED_ERROR,
errorLoadLegend: error
};
}
function metadataLoaded(data) {
return {
type: LOAD_METADATA,
data: data
};
}
function loadMetadataError(error) {
return {
type: LOAD_METADATA_ERROR,
error: error
};
}
function addLegendUrl(urls) {
return {
type: ADD_URL_LEGEND,
infolegend: urls
};
}
function loadLegend(url) {
return (dispatch) => {
let layers = [];
let capabilitiesUrl = url;
let parsedUrl = makeGetCapabilitiesUrl(capabilitiesUrl);
return axios.get(parsedUrl).then((response) => {
let json;
xml2js.parseString(response.data, {explicitArray: false}, (ignore, result) => {
json = result;
});
iterate(json, layers);
let infoLegends = [];
let infoLegend = {};
let tmpUrls = [];
if (json && json.WMS_Capabilities && json.WMS_Capabilities.Service) {
infoLegend.serviceTitle = json.WMS_Capabilities.Service.Title;
}else {
infoLegend.serviceTitle = "";
}
for (let i = 0; i < layers.length; i++) {
// excluded the group layers
if ( layers[i] && ( typeof layers[i].Layer === "undefined")) {
let tmpUrl = {};
tmpUrl.url = makeGetLegendUrl(capabilitiesUrl, layers[i].Name);
tmpUrl.title = layers[i].Title ? layers[i].Title : '';
// tmpUrl.title = layers[i].Name;
tmpUrls.push(tmpUrl);
}
}
if (tmpUrls) {
infoLegend.urls = tmpUrls;
}else {
infoLegend.urls = [];
}
infoLegends.push(infoLegend);
dispatch(addLegendUrl(infoLegends));
}).catch((error) => {
dispatch(loadMetadataError(error));
});
};
}
function loadLegends(urls) {
return (dispatch) => {
for (let i = 0; i < urls.length && urls; i++) {
dispatch(loadLegend((urls[i])));
}
};
}
function loadMetadata(idMetadato) {
return (dispatch) => {
return axios.post('services/metadata/getInfoBox', 'metadato=' + idMetadato, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then((response) => {
if (typeof response.data === 'object') {
if (response.data && (response.data.urlWMS || response.data.urlWFS)) {
response.data.showButtonLegend = 'block';
}else {
response.data.showButtonLegend = 'none';
}
dispatch(metadataLoaded(response.data));
// dispatch(showBox());
} else {
try {
JSON.parse(response.data);
} catch(e) {
dispatch(loadMetadataError('Configuration file for tiles broken: ' + e.message));
}
}
}).catch((e) => {
dispatch(loadMetadataError(e));
});
};
}
module.exports = {
HIDE_BOX,
SHOW_BOX,
LOAD_METADATA,
LOAD_METADATA_ERROR,
TOGGLE_LEGEND_PANEL,
LEGEND_LOADED_ERROR,
ADD_URL_LEGEND,
showBox,
hideBox,
metadataLoaded,
loadMetadataError,
loadMetadata,
toggleLegendBox,
legendLoaded,
legendLoadedError,
loadLegend,
loadLegends
};
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const axios = require('../../MapStore2/web/client/libs/ajax');
const LOAD_TILES = 'LOAD_TILES';
const TILES_LOADED = 'TILES_LOADED';
const TILES_LOAD_ERROR = 'TILES_LOAD_ERROR';
function tilesLoaded(data) {
return {
type: TILES_LOADED,
tiles: data
};
}
function loadTilesError(error) {
return {
type: TILES_LOAD_ERROR,
error
};
}
function loadTiles(serviceUrl = 'services/metadata/getMosaico', params = {}) {
const url = Object.keys(params).reduce((u, p) => {
return `${u}&${p}=${params[p]}`;
}, `${serviceUrl}?`);
return (dispatch) => {
return axios.get(url).then((response) => {
if (typeof response.data === 'object') {
dispatch(tilesLoaded(response.data));
} else {
try {
dispatch(tilesLoaded(JSON.parse(response.data)));
} catch(e) {
dispatch(loadTilesError('Configuration file for tiles broken: ' + e.message));
}
}
}).catch((e) => {
dispatch(loadTilesError(e));
});
};
}
module.exports = {
LOAD_TILES,
TILES_LOADED,
TILES_LOAD_ERROR,
loadTiles
};
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {connect} = require('react-redux');
const {isObject} = require('lodash');
const Draggable = require('react-draggable');
const {Modal, Panel, Grid, Row, Col, Button} = require('react-bootstrap');
const {Resizable} = require('react-resizable');
const {bindActionCreators} = require('redux');
const {changeMapView} = require('../../MapStore2/web/client/actions/map');
const {selectFeatures} = require('../actions/featuregrid');
const FilterUtils = require('../../MapStore2/web/client/utils/FilterUtils');
const {verifyProfiles} = require('../utils/TemplateUtils');
const {head} = require('lodash');
const {
loadFeaturesWithPagination
} = require('../actions/grid');
const FeatureGrid = connect((state) => {
return {
select: state.featuregrid && state.featuregrid.select || []
};
}, dispatch => {
return bindActionCreators({
selectFeatures: selectFeatures
}, dispatch);
})(require('../../MapStore2/web/client/components/data/featuregrid/FeatureGrid'));
const LocaleUtils = require('../../MapStore2/web/client/utils/LocaleUtils');
const I18N = require('../../MapStore2/web/client/components/I18N/I18N');
const Message = require('../../MapStore2/web/client/components/I18N/Message');
const {reactCellRendererFactory} = require('ag-grid-react');
const GoToDetail = require('./GoToDetail');
const {loadCardTemplate} = require('../actions/card');
const {toggleSiraControl} = require('../actions/controls');
// const {loadFeatureGridConfig} = require('../actions/grid');
const Spinner = require('react-spinkit');
const {
// SiraQueryPanel action functions
expandFilterPanel
} = require('../actions/siradec');
const assign = require('object-assign');
require('react-resizable/css/styles.css');
require('./SiraFeatureGrid.css');
const SiraFeatureGrid = React.createClass({
propTypes: {
open: React.PropTypes.bool,
detailOpen: React.PropTypes.bool,
expanded: React.PropTypes.bool,
header: React.PropTypes.string,
features: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.object]),
detailsConfig: React.PropTypes.object,
columnsDef: React.PropTypes.array,
map: React.PropTypes.object,
loadingGrid: React.PropTypes.bool,
loadingGridError: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.object
]),
params: React.PropTypes.object,
// featureGrigConfigUrl: React.PropTypes.string,
profile: React.PropTypes.string,
onDetail: React.PropTypes.func,
onShowDetail: React.PropTypes.func,
toggleSiraControl: React.PropTypes.func,
changeMapView: React.PropTypes.func,
// loadFeatureGridConfig: React.PropTypes.func,
onExpandFilterPanel: React.PropTypes.func,
selectFeatures: React.PropTypes.func,
totalFeatures: React.PropTypes.number,
pagination: React.PropTypes.bool,
filterFields: React.PropTypes.array,
groupFields: React.PropTypes.array,
spatialField: React.PropTypes.object,
featureTypeName: React.PropTypes.string,
ogcVersion: React.PropTypes.string,
onQuery: React.PropTypes.func,
searchUrl: React.PropTypes.string,
newQuery: React.PropTypes.bool,
dataSourceOptions: React.PropTypes.object,
backToSearch: React.PropTypes.string
},
contextTypes: {
messages: React.PropTypes.object
},
getInitialState() {
return {
width: 800,
height: 400
};
},
getDefaultProps() {
return {
open: true,
detailOpen: true,
loadingGrid: false,
loadingGridError: null,
// featureGrigConfigUrl: null,
profile: null,
expanded: true,
header: "featuregrid.header",
features: [],
featureTypeName: null,
ogcVersion: "2.0",
detailsConfig: {},
columnsDef: [],
pagination: false,
params: {},
groupFields: [],
filterFields: [],
spatialField: {},
searchUrl: null,
newQuery: false,
dataSourceOptions: {
rowCount: -1,
pageSize: 20
},
backToSearch: "featuregrid.backtosearch",
onDetail: () => {},
onShowDetail: () => {},
toggleSiraControl: () => {},
changeMapView: () => {},
// loadFeatureGridConfig: () => {},
onExpandFilterPanel: () => {},
selectFeatures: () => {},
onQuery: () => {}
};
},
/*componentDidMount() {
if (this.props.featureGrigConfigUrl && this.props.profile) {
this.props.loadFeatureGridConfig(this.props.featureGrigConfigUrl + this.props.profile + ".json");
}
},
componentWillReceiveProps(props) {
let url = props.featureGrigConfigUrl;
let profile = props.profile;
if (url !== this.props.featureGrigConfigUrl && profile !== this.props.profile) {
this.props.loadFeatureGridConfig(this.props.featureGrigConfigUrl + this.props.profile + ".json");
}
},*/
componentWillMount() {
if (this.props.pagination) {
this.dataSource = this.getDataSource(this.props.dataSourceOptions);
}
},
shouldComponentUpdate() {
return true;
},
componentWillUpdate(nextProps) {
if (!nextProps.loadingGrid && nextProps.pagination && (nextProps.dataSourceOptions !== this.props.dataSourceOptions)) {
this.dataSource = this.getDataSource(nextProps.dataSourceOptions);
}
if (!nextProps.loadingGrid && this.featureLoaded && nextProps.features !== this.props.features && Object.keys(nextProps.features).length > 0) {
let rowsThisPage = nextProps.features[this.getRequestId(this.featureLoaded)] || [];
this.featureLoaded.successCallback(rowsThisPage, nextProps.totalFeatures);
this.featureLoaded = null;
}
},
onGridClose() {
this.props.selectFeatures([]);
this.props.toggleSiraControl();
this.props.onExpandFilterPanel(true);
},
onResize(event, resize) {
let size = resize.size;
this.setState({width: size.width, height: size.height});
},
getRequestId(params) {
return `${params.startRow}_${params.endRow}_${params.sortModel.map((m) => `${m.colId}_${m.sort}` ).join('_')}`;
},
getSortAttribute(colId) {
let col = head(this.props.columnsDef.filter((c) => colId === `properties.${c.field}`));
return col && col.sortAttribute ? col.sortAttribute : '';
},
getSortOptions(params) {
return params.sortModel.reduce((o, m) => ({sortBy: this.getSortAttribute(m.colId), sortOrder: m.sort}), {});
},
getFeatures(params) {
if (!this.props.loadingGrid) {
let reqId = this.getRequestId(params);
let rowsThisPage = this.props.features[reqId];
if (rowsThisPage) {
params.successCallback(rowsThisPage, this.props.totalFeatures);
}else {
let pagination = {startIndex: params.startRow, maxFeatures: params.endRow - params.startRow};
let filterObj = {
groupFields: this.props.groupFields,
filterFields: this.props.filterFields.filter((field) => field.value),
spatialField: this.props.spatialField,
pagination
};
let filter = FilterUtils.toOGCFilter(this.props.featureTypeName, filterObj, this.props.ogcVersion, this.getSortOptions(params));
this.featureLoaded = params;
this.sortModel = params.sortModel;
this.props.onQuery(this.props.searchUrl, filter, this.props.params, reqId);
}
}
},
getDataSource(dataSourceOptions) {
return {
rowCount: dataSourceOptions.rowCount,
getRows: this.getFeatures,
pageSize: dataSourceOptions.pageSize,
overflowSize: 20
};
},
renderHeader() {
const header = LocaleUtils.getMessageById(this.context.messages, this.props.header);
return (
<div className="handle_featuregrid">
<Grid className="featuregrid-title" fluid={true}>
<Row>
<Col xs={11} sm={11} md={11} lg={11}>
<span>{header}</span>
</Col>
<Col xs={1} sm={1} md={1} lg={1}>
<button onClick={this.onGridClose} className="close grid-close"><span>X</span></button>
</Col>
</Row>
</Grid>
</div>
);
},
renderLoadingException(loadingError, msg) {
let exception;
if (isObject(loadingError)) {
exception = loadingError.status +
"(" + loadingError.statusText + ")" +
": " + loadingError.data;
} else {
exception = loadingError;
}
return (
<Modal show={loadingError ? true : false} bsSize="small">
<Modal.Header>
<Modal.Title><I18N.Message msgId={msg}/></Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="mapstore-error">{exception}</div>
</Modal.Body>
<Modal.Footer>
</Modal.Footer>
</Modal>
);
},
render() {
let loadingError = this.props.loadingGridError;
if (loadingError) {
return (
this.renderLoadingException(loadingError, "Error while loading the features")
);
}
let columns = [{
onCellClicked: this.goToDetail,
headerName: "",
cellRenderer: reactCellRendererFactory(GoToDetail),
suppressSorting: true,
suppressMenu: true,
pinned: true,
width: 25,
suppressResize: true
}, ...(this.props.columnsDef.map((column) => {
// if (!column.profiles || (column.profiles && column.profiles.indexOf(this.props.profile) !== -1)) {
if (verifyProfiles(column.profiles, this.props.profile)) {
return assign({}, column, {field: "properties." + column.field});
}
})).filter((c) => c )];
if (this.sortModel && this.sortModel.length > 0) {
columns = columns.map((c) => {
let model = head(this.sortModel.filter((m) => m.colId === c.field));
if ( model ) {
c.sort = model.sort;
}
return c;
});
}
let gridConf = this.props.pagination ? {dataSource: this.dataSource, features: []} : {features: this.props.features};
if (this.props.open) {
return (
<Draggable start={{x: 760, y: 120}} handle=".panel-heading,.handle_featuregrid,.handle_featuregrid *">
<Panel className="featuregrid-container" collapsible expanded={this.props.expanded} header={this.renderHeader()} bsStyle="primary">
<Resizable className="box" height={this.state.height} width={this.state.width} onResize={this.onResize} minConstraints={[500, 250]}>
<div style={this.props.loadingGrid ? {display: "none"} : {height: this.state.height, width: this.state.width}}>
<Button
style={{marginBottom: "12px"}}
onClick={this.onGridClose}><span><Message msgId={this.props.backToSearch}/></span>
</Button>
<h5>Risultati - {this.props.totalFeatures !== -1 ? this.props.totalFeatures : (<I18N.Message msgId={"sira.noQueryResult"}/>)}</h5>
<FeatureGrid
changeMapView={this.props.changeMapView}
srs="EPSG:4326"
map={this.props.map}
columnDefs={columns}
style={{height: this.state.height - 120, width: this.state.width}}
maxZoom={16}
paging={this.props.pagination}
zoom={15}
agGridOptions={{enableServerSideSorting: true, suppressMultiSort: true}}
toolbar={{
zoom: true,
exporter: true,
toolPanel: true,
selectAll: true
}}
{...gridConf}
/>
</div>
</Resizable>
{this.props.loadingGrid ? (<div style={{height: "300px", width: this.state.width}}>
<div style={{
position: "relative",
width: "60px",
top: "50%",
left: "45%"}}>
<Spinner style={{width: "60px"}} spinnerName="three-bounce" noFadeIn/>
</div>
</div>) : null}
</Panel>
</Draggable>
);
}
return null;
},
goToDetail(params) {
let url = this.props.detailsConfig.service.url;
let urlParams = this.props.detailsConfig.service.params;
for (let param in urlParams) {
if (urlParams.hasOwnProperty(param)) {
url += "&" + param + "=" + urlParams[param];
}
}
this.props.onDetail(
this.props.detailsConfig.template,
// this.props.detailsConfig.cardModelConfigUrl,
url + "&FEATUREID=" + params.data.id + (this.props.params.authkey ? "&authkey=" + this.props.params.authkey : "")
);
if (!this.props.detailOpen) {
this.props.onShowDetail();
}
}
});
module.exports = connect((state) => ({
open: state.siraControls.grid,
detailOpen: state.siraControls.detail,
detailsConfig: state.siradec && state.siradec.card || {},
columnsDef: state.grid.featuregrid && state.grid.featuregrid.grid ? state.grid.featuregrid.grid.columns : [],
features: state.grid && state.grid.data || [],
totalFeatures: state.grid.totalFeatures,
map: (state.map && state.map) || (state.config && state.config.map),
loadingGrid: state.grid.loadingGrid,
loadingGridError: state.grid.loadingGridError,
pagination: (state.queryform.pagination && state.queryform.pagination.maxFeatures) ? true : false,
groupFields: state.queryform.groupFields,
filterFields: state.queryform.filterFields,
spatialField: state.queryform.spatialField,
featureTypeName: state.siradec.featureTypeName,
searchUrl: state.queryform.searchUrl,
dataSourceOptions: state.grid.dataSourceOptions
}), {
onDetail: loadCardTemplate,
onShowDetail: toggleSiraControl.bind(null, 'detail'),
toggleSiraControl: toggleSiraControl.bind(null, 'grid'),
changeMapView: changeMapView,
// loadFeatureGridConfig: loadFeatureGridConfig,
onExpandFilterPanel: expandFilterPanel,
selectFeatures: selectFeatures,
onQuery: loadFeaturesWithPagination
})(SiraFeatureGrid);
<file_sep>const {createSelector} = require('reselect');
const assign = require('object-assign');
const {head} = require('lodash');
const grid = (state) => state && state.grid;
const featureGrid = (state) => state && state.siradec && state.siradec.configOggetti[state.siradec.activeFeatureType].featuregrid || {};
const gridSelector = createSelector([grid, featureGrid],
(gridS, featureGridS) => ({
grid: assign({}, gridS, {featuregrid: featureGridS})
}));
const categorySelector = createSelector([
(state) => state.mosaic && state.mosaic.tiles || []
], (servertiles) => {
const {objectNumber = 0, tematicViewNumber = 0} = servertiles.reduce((v, t) => {
v.objectNumber += t.objectNumber;
v.tematicViewNumber += t.tematicViewNumber;
return v;
}, {objectNumber: 0, tematicViewNumber: 0});
return {
tiles: [...servertiles, {id: 999, name: "Tutte le Categorie", icon: "all", objectNumber, tematicViewNumber}]
};
}
);
const getChildren = function(nodes, node) {
return node.nodes.map((child) => {
let newNode = head(nodes.filter((n) => n.id === child));
return newNode.nodes ? assign({expanded: false}, newNode, {nodes: getChildren(nodes, newNode)}) : newNode;
});
};
const normalizeCatalog = function(nodes) {
return nodes.filter( (n) => n.type === "root").map((n) => {
return assign({expanded: false}, n, {nodes: getChildren(nodes, n)});
});
};
const sortObjects = function(a, b) {
if (a.title < b.title) {
return -1;
}
if (a.title > b.title) {
return 1;
}
return 0;
};
const isPresent = function(nodes, node) {
return nodes.filter((n) => node.id === n.id).length > 0;
};
const normalizeViews = function(nodes) {
return nodes.filter( (n) => n.type === "view").reduce((acc, o) => {
return !isPresent(acc, o) ? acc.concat(o) : acc;
}, []).map((n) => {
return assign({expanded: false}, n, {nodes: getChildren(nodes, n)});
});
};
const normalizeObjects = function(nodes) {
return nodes.filter( (n) => n.type === "node" && !n.nodes).reduce((acc, o) => {
return !isPresent(acc, o) ? acc.concat(o) : acc;
}, []).sort(sortObjects);
};
const tocSelector = createSelector([
(state) => state.siracatalog.nodes || [],
(state) => state.siracatalog.category,
(state) => state.siracatalog.subcat,
(state) => state.siracatalog,
(state) => state.siradec && state.siradec.configOggetti,
(state) => state.userprofile,
(state) => state.siradec && state.siradec.activeFeatureType
], ( nodes, category, subcat, catalog, configOggetti, userprofile, activeFeatureType) => ({
views: normalizeViews(catalog.views || []),
nodes: normalizeCatalog(nodes),
objects: normalizeObjects(nodes),
nodesLoaded: catalog.nodes ? true : false,
category,
loading: catalog.loading,
configOggetti,
userprofile,
activeFeatureType,
subcat,
showcategories: catalog.showcategories
})
);
module.exports = {
gridSelector,
categorySelector,
tocSelector
};
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const Tile = require('./MosaicTile');
const Mosaic = React.createClass({
propTypes: {
tiles: React.PropTypes.array,
boxStyle: React.PropTypes.object,
tileClick: React.PropTypes.func,
useLink: React.PropTypes.bool,
liClass: React.PropTypes.string,
className: React.PropTypes.string
},
getDefaultProps() {
return {
tiles: [],
className: "container blocchetti"
};
},
renderTiles() {
return this.props.tiles.map((tile) => {
return (<Tile key={tile.id}
onClick={this.props.tileClick ? this.props.tileClick.bind(null, tile) : undefined}
boxStyle={this.props.boxStyle}
useLink={this.props.useLink}
liClass={this.props.liClass ? this.props.liClass : undefined}
{...tile}
/>);
});
},
render() {
return (
<div className={this.props.className}>
<div className="row">
<ul className="list-group categorie">
{this.renderTiles()}
</ul>
</div>
</div>
);
}
});
module.exports = Mosaic;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {connect} = require('react-redux');
const {head} = require('lodash');
const Footer = require('../components/Footer');
const Header = require('../components/Header');
const {getMetadataObjects, selectCategory, resetObjectAndView} = require('../actions/siracatalog');
const {categorySelector} = require('../selectors/sira');
const Mosaic = connect(categorySelector)(require('../components/Mosaic'));
const PlatformNumbers = connect((state) => ({
siradecObject: state.platformnumbers.siradecObject,
functionObjectMap: state.platformnumbers.functionObjectMap,
functionObjectSearch: state.platformnumbers.functionObjectSearch,
functionObjectView: state.platformnumbers.functionObjectView
}))(require('../components/PlatformNumbers'));
const SiraSearchBar = require('../components/SiraSearchBar');
const Home = React.createClass({
propTypes: {
loadMetadata: React.PropTypes.func,
params: React.PropTypes.object,
selectCategory: React.PropTypes.func,
allCategory: React.PropTypes.object,
resetObjectAndView: React.PropTypes.func
},
contextTypes: {
router: React.PropTypes.object
},
getInitialState() {
return {
searchText: ""
};
},
componentDidMount() {
document.body.className = "body_home";
},
render() {
return (
<div className="home-page">
<Header />
<div className="container-fluid">
<div className="row-fluid sb-sx">
<div className="container search-home">
<div className="row">
<div className="col-md-7 col-xs-12 testo-home">
<div>
Piattaforma di fruizione delle conoscenze alfanumeriche e geografiche prodotte nel contesto del SIRA Piemonte (Sistema Informativo Ambientale della Regione Piemonte), che si configura come una rete di cooperazione tra soggetti produttori e/o detentori di informazioni di interesse ambientale (Imprese, Regione, Province e ARPA)
</div>
</div>
<SiraSearchBar
containerClasses="col-md-5 col-xs-12 ricerca-home catalog-search-container"
searchClasses="home-search"
addCategoriesSelector={false}
onSearch={({text}) => {
this.props.selectCategory(this.props.allCategory, 'objects');
this.props.loadMetadata({params: {text}});
if (this.props.params.profile) {
this.context.router.push('/dataset/${this.props.params.profile}/');
}else {
this.context.router.push('/dataset/');
}
}}
/>
</div>
</div>
</div>
</div>
<div className="modal fade" id="modalNews" role="dialog" aria-labelledby="myModalLabel">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 className="modal-title" id="myModalLabel">Nuova risorsa Disponibile</h4>
</div>
<div className="modal-body">
<p>Nuova risorsa Disponibile: è disponibile questa nuova risorsa "Impianti autorizzati a recupero di energia e materia"</p>
<p>Proin quam metus, bibendum a lacus eget, tempor tincidunt est. Ut ac laoreet diam. Integer pretium pharetra venenatis. Sed luctus metus lacinia mauris porta, eget imperdiet enim commodo. Phasellus ornare diam sed massa tempus varius. Fusce mollis blandit vehicula. Phasellus ac vulputate purus, eget aliquam arcu. Nam nec orci nunc. Mauris pellentesque tellus eget nulla auctor, nec consectetur nisl porttitor. Proin ullamcorper vestibulum sapien, et congue sem ultricies nec. Fusce imperdiet imperdiet neque sit amet elementum. Suspendisse ac massa volutpat, iaculis augue nec, tristique urna. In ut congue nisi.</p>
<p>Praesent condimentum tincidunt condimentum. Sed et convallis dui. Duis id nisl dui. Duis commodo ex non nulla aliquet pulvinar. Donec venenatis, purus eu efficitur dapibus, enim urna eleifend nisi, eu sodales nisl ligula in turpis. Donec posuere ullamcorper tellus in sagittis. Donec ullamcorper vel risus vitae finibus. Suspendisse viverra enim in cursus gravida. In hac habitasse platea dictumst. Suspendisse ac enim in justo vestibulum placerat eu et massa. Curabitur elementum neque sit amet semper blandit. Suspendisse imperdiet dolor et est consectetur, nec luctus nulla pharetra.</p>
<p>Duis rutrum felis a ultrices ornare. Maecenas non ex suscipit, pharetra tellus vitae, placerat ligula. Aliquam dolor neque, lacinia a congue id, rhoncus lobortis urna. Duis mollis tortor eros, vel efficitur libero fringilla a. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed erat lectus, interdum eu pellentesque sed, posuere eu risus. Morbi facilisis fringilla molestie. Pellentesque ac feugiat erat, quis aliquet turpis. Aenean dapibus dui non venenatis finibus.</p>
<p>Sed commodo sollicitudin diam at sagittis. In at maximus leo. Pellentesque sed dolor nec nulla sagittis volutpat a sed nisi. Phasellus tristique facilisis enim eu congue. Sed egestas libero nulla, non fringilla felis bibendum id. Praesent et eros aliquet, elementum mauris vel, iaculis nunc. Nam congue accumsan nisl. Mauris vitae egestas nisl. Curabitur rutrum vehicula dui, laoreet ultricies mi finibus vel. Sed quam felis, lacinia ac eros quis, dignissim tincidunt quam. Aliquam eleifend varius lacus. Donec non interdum odio. Fusce sed tellus interdum, condimentum nulla vitae, commodo libero. Pellentesque nulla mi, commodo non lectus sit amet, mollis suscipit nisl. Proin auctor nisi risus, id finibus leo cursus vitae. </p>
</div>
</div>
</div>
</div>
<Mosaic useLink={false} tileClick={this.selectCategory} />
<PlatformNumbers />
<Footer />
</div>);
},
selectCategory(category, subcat) {
this.props.resetObjectAndView();
this.props.selectCategory(category, subcat);
if (this.props.params.profile) {
this.context.router.push('/dataset/${this.props.params.profile}/');
}else {
this.context.router.push('/dataset/');
}
}
});
module.exports = connect((state) => {
const {tiles} = categorySelector(state);
return {
allCategory: head(tiles.filter((t) => t.id === 999)),
error: state.loadingError || (state.locale && state.locale.localeError) || null,
locale: state.locale && state.locale.locale,
messages: state.locale && state.locale.messages || {}
};
}, {
loadMetadata: getMetadataObjects,
selectCategory,
resetObjectAndView
})(Home);
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
require('../../assets/css/sira.css');
require('../../MapStore2/web/client/product/assets/css/viewer.css');
const {connect} = require('react-redux');
const SidePanel = require('./SidePanel');
const Card = require('../components/template/Card');
const Header = require('../components/Header');
const {bindActionCreators} = require('redux');
const {toggleSiraControl} = require('../actions/controls');
// const {setProfile, loadUserIdentity} = require('../actions/userprofile');
const {setProfile} = require('../actions/userprofile');
const {configureInlineMap} = require('../actions/siradec');
const url = require('url');
const urlQuery = url.parse(window.location.href, true).query;
require("../components/WMSLayer.js");
const authParams = {
admin: {
userName: "admin",
authkey: "84279da9-f0b9-4e45-ac97-48413a48e33f"
},
A: {
userName: "profiloa",
authkey: "59ccadf2-963e-448c-bc9a-b3a5e8ed20d7"
},
B: {
userName: "profilob",
authkey: "d6e5f5a5-2d26-43aa-8af3-13f8dcc0d03c"
},
C: {
userName: "profiloc",
authkey: "<KEY>"
},
D: {
userName: "profilod",
authkey: "<KEY>3-8f6f85813dab"
}
};
const {hideBox, loadLegends, toggleLegendBox} = require('../actions/metadatainfobox');
const mapStateToPropsMIB = (state) => {
return {
show: state.metadatainfobox.show,
openLegendPanel: state.metadatainfobox.openLegendPanel,
title: state.metadatainfobox.title,
text: state.metadatainfobox.text,
numDatasetObjectCalc: state.metadatainfobox.numDatasetObjectCalc,
dataProvider: state.metadatainfobox.dataProvider,
urlMetadato: state.metadatainfobox.urlMetadato,
urlWMS: state.metadatainfobox.urlWMS,
urlWFS: state.metadatainfobox.urlWFS,
urlLegend: state.metadatainfobox.urlLegend,
error: state.metadatainfobox.error,
showButtonLegend: state.metadatainfobox.showButtonLegend
};
};
const mapDispatchToPropsMIB = (dispatch) => {
return {
loadLegend: (u, actualUrl) => {
if (actualUrl && actualUrl.length === 0) {
dispatch(loadLegends(u));
}
dispatch(toggleLegendBox());
},
closePanel: () => {
dispatch(hideBox());
}
};
};
const MetadataInfoBox = connect(
mapStateToPropsMIB,
mapDispatchToPropsMIB
)(require('../components/MetadataInfoBox'));
const { changeMousePointer} = require('../../MapStore2/web/client/actions/map');
const MapViewer = require('../../MapStore2/web/client/containers/MapViewer');
const {getFeatureInfo, purgeMapInfoResults, showMapinfoMarker, hideMapinfoMarker} = require('../actions/mapInfo');
const {loadGetFeatureInfoConfig, setModelConfig} = require('../actions/mapInfo');
const {selectFeatures, setFeatures} = require('../actions/featuregrid');
const GetFeatureInfo = connect((state) => {
const activeConfig = state.siradec.activeFeatureType && state.siradec.configOggetti[state.siradec.activeFeatureType] || {};
return {
siraFeatureTypeName: activeConfig.featureTypeName,
siraFeatureInfoDetails: state.siradec.configOggetti,
siraTopology: state.siradec.topology,
siraTopologyConfig: state.mapInfo.topologyConfig,
infoEnabled: state.mapInfo && state.mapInfo.infoEnabled || false,
topologyInfoEnabled: state.mapInfo && state.mapInfo.topologyInfoEnabled || false,
htmlResponses: state.mapInfo && state.mapInfo.responses || [],
htmlRequests: state.mapInfo && state.mapInfo.requests || {length: 0},
infoFormat: state.mapInfo && state.mapInfo.infoFormat,
detailsConfig: state.mapInfo.detailsConfig,
// modelConfig: state.mapInfo.modelConfig,
template: state.mapInfo.template,
map: state.map && state.map.present,
infoType: state.mapInfo.infoType,
layers: state.layers && state.layers.flat || [],
clickedMapPoint: state.mapInfo && state.mapInfo.clickPoint};
}, (dispatch) => {
return {
actions: bindActionCreators({
getFeatureInfo,
purgeMapInfoResults,
changeMousePointer,
showMapinfoMarker,
hideMapinfoMarker,
loadGetFeatureInfoConfig,
setFeatures,
selectFeatures,
setModelConfig
}, dispatch)
};
})(require('../components/identify/GetFeatureInfo'));
let MapInfoUtils = require('../../MapStore2/web/client/utils/MapInfoUtils');
MapInfoUtils.AVAILABLE_FORMAT = ['TEXT', 'JSON', 'HTML', 'GML3'];
const Sira = React.createClass({
propTypes: {
mode: React.PropTypes.string,
params: React.PropTypes.object,
roles: React.PropTypes.object,
profile: React.PropTypes.object,
loadMapConfig: React.PropTypes.func,
reset: React.PropTypes.func,
error: React.PropTypes.object,
loading: React.PropTypes.bool,
nsResolver: React.PropTypes.func,
controls: React.PropTypes.object,
toggleSiraControl: React.PropTypes.func,
setProfile: React.PropTypes.func,
// loadUserIdentity: React.PropTypes.func,
plugins: React.PropTypes.object,
viewerParams: React.PropTypes.object,
configureInlineMap: React.PropTypes.func,
configLoaded: React.PropTypes.bool
},
contextTypes: {
router: React.PropTypes.object
},
getDefaultProps() {
return {
toggleSiraControl: () => {},
setProfile: () => {},
// loadUserIdentity: () => {},
onLoadFeatureTypeConfig: () => {},
mode: 'desktop',
viewerParams: {mapType: "openlayers"},
configLoaded: false
};
},
componentWillMount() {
document.body.className = "body_map";
if (urlQuery.map) {
this.props.configureInlineMap(JSON.parse(urlQuery.map));
}
// if (this.props.params.profile) {
// this.props.setProfile(this.props.params.profile, authParams[this.props.params.profile]);
// }
// this.props.loadUserIdentity();
},
render() {
return (
<div>
<Header
goToDataset={this.goToDataset}
goToHome={this.goToHome}
showCart="false"
cartListaStyle="btn btn-primary active"
cartMappaStyle="btn btn-primary"
onBack={this.back}
/>
<div className="mapbody">
<span className={this.props.error && 'error' || !this.props.loading && 'hidden' || ''}>
{this.props.error && ("Error: " + this.props.error) || (this.props.loading)}
</span>
<SidePanel auth={authParams[this.props.params.profile]} profile={this.props.profile.profile}/>
<MapViewer
plugins={this.props.plugins}
params={this.props.viewerParams}
/>
<Card profile={this.props.profile.profile} authParam={authParams[this.props.params.profile]}/>
<GetFeatureInfo
display={"accordion"}
params={{authkey: this.props.params.profile ? authParams[this.props.params.profile].authkey : ''}}
profile={this.props.profile.profile}
key="getFeatureInfo"/>
<MetadataInfoBox panelStyle={{
height: "500px",
width: "300px",
zIndex: 100,
left: 400,
top: -128,
position: "absolute",
overflow: "auto"}}/>
</div>
</div>
);
},
goToDataset() {
this.context.router.push('/dataset/');
},
goToHome() {
this.context.router.push('/');
}
});
module.exports = connect((state) => {
const activeConfig = state.siradec.activeFeatureType && state.siradec.configOggetti[state.siradec.activeFeatureType] || {};
return {
profile: state.userprofile,
mode: 'desktop',
loading: !state.config || !state.locale || false,
error: state.loadingError || (state.locale && state.locale.localeError) || null,
// card: state.cardtemplate,
controls: state.siraControls,
configLoaded: activeConfig && activeConfig.card ? true : false
};
}, {
toggleSiraControl,
setProfile,
// loadUserIdentity,
configureInlineMap
})(Sira);
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const DebugUtils = require('../../MapStore2/web/client/utils/DebugUtils');
const {combineReducers} = require('../../MapStore2/web/client/utils/PluginsUtils');
const {persistStore, autoRehydrate} = require('redux-persist');
const SecurityUtils = require('../../MapStore2/web/client/utils/SecurityUtils');
const assign = require('object-assign');
module.exports = (initialState = {defaultState: {}, mobile: {}}, appReducers = {}, plugins, storeOpts) => {
const allReducers = combineReducers(plugins, {
...appReducers,
browser: require('../../MapStore2/web/client/reducers/browser'),
locale: require('../../MapStore2/web/client/reducers/locale'),
controls: require('../../MapStore2/web/client/reducers/controls')
});
const defaultState = initialState.defaultState;
const rootReducer = (state, action) => {
let newState = {
...allReducers(state, action)
};
if (action && (action.type === 'FEATURETYPE_CONFIG_LOADED' || action.type === 'SET_ACTIVE_FEATURE_TYPE') && newState.siradec.configOggetti[action.featureType] && action.activate) {
const configOggetti = newState.siradec.configOggetti[action.featureType];
// // Devi assegnare a queryform e grid i valori che hai in siradec.configOggetti.featureType
const newGrid = assign({}, newState.grid, {featuregrid: configOggetti.featuregrid});
newState = assign({}, newState, {queryform: configOggetti.queryform, grid: newGrid});
}
return newState;
};
let store;
if (storeOpts && storeOpts.persist) {
store = DebugUtils.createDebugStore(rootReducer, defaultState, [], autoRehydrate());
persistStore(store, storeOpts.persist, storeOpts.onPersist);
} else {
store = DebugUtils.createDebugStore(rootReducer, defaultState);
}
SecurityUtils.setStore(store);
return store;
};
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
// const {Button, Glyphicon} = require('react-bootstrap');
const {getWindowSize} = require('../../MapStore2/web/client/utils/AgentUtils');
require('../../assets/css/qgis.css');
// require('../../MapStore2/web/client/product/assets/css/viewer.css');
const {connect} = require('react-redux');
const SideQueryPanel = require('../components/SideQueryPanel');
const QGisFeatureGrid = require('../components/QGisFeatureGrid');
const Card = require('../components/template/Card');
const {setProfile} = require('../actions/userprofile');
const Spinner = require('react-spinkit');
const parsedUrl = require('url').parse(window.location.href, true);
const urlQuery = parsedUrl.query;
const {
loadGridModelWithFilter,
loadGridModelWithPagination
} = require('../actions/grid');
const {selectAllQgis} = require('../actions/featuregrid');
const {head} = require('lodash');
const CoordinatesUtils = require('../../MapStore2/web/client/utils/CoordinatesUtils');
const SiraFilterUtils = require('../utils/SiraFilterUtils');
const authParams = {
admin: {
userName: "admin",
authkey: "84279da9-f0b9-4e45-ac97-48413a48e33f"
},
A: {
userName: "profiloa",
authkey: "59ccadf2-963e-448c-bc9a-b3a5e8ed20d7"
},
B: {
userName: "profilob",
authkey: "d6e5f5a5-2d26-43aa-8af3-13f8dcc0d03c"
},
C: {
userName: "profiloc",
authkey: "<KEY>"
},
D: {
userName: "profilod",
authkey: "<KEY>"
}
};
const {
loadFeatureTypeConfig,
expandFilterPanel
} = require('../actions/siradec');
const {loadCardTemplate} = require('../actions/card');
const {toggleSiraControl} = require('../actions/controls');
const {selectFeatures} = require('../actions/featuregrid');
const QGis = React.createClass({
propTypes: {
params: React.PropTypes.object,
featureType: React.PropTypes.string,
error: React.PropTypes.object,
setProfile: React.PropTypes.func,
filterPanelExpanded: React.PropTypes.bool,
onLoadFeatureTypeConfig: React.PropTypes.func,
expandFilterPanel: React.PropTypes.func,
toggleSiraControl: React.PropTypes.func,
configLoaded: React.PropTypes.bool,
profile: React.PropTypes.object,
siraControls: React.PropTypes.object,
selectFeatures: React.PropTypes.func,
detailsConfig: React.PropTypes.object,
gridConfig: React.PropTypes.object,
pagination: React.PropTypes.object,
loadCardTemplate: React.PropTypes.func,
selectAllToggle: React.PropTypes.func
},
getDefaultProps() {
return {
setProfile: () => {},
onLoadFeatureTypeConfig: () => {},
configLoaded: false,
filterPanelExpanded: true,
toggleSiraControl: () => {}
};
},
getInitialState() {
return {
loadList: true
};
},
componentWillMount() {
this.setState({width: getWindowSize().maxWidth, qGisType: this.getQGisType(parsedUrl.pathname)});
window.onresize = () => {
this.setState({width: window.innerWidth});
};
// profile is array with max length = 1
let profile = [];
profile = (this.props.params && this.props.params.profile) ? this.props.params.profile : new Array(urlQuery.profile);
this.props.setProfile(profile, authParams[profile]);
},
componentDidMount() {
// profile is array with max length = 1
let profile = [];
profile = (this.props.params && this.props.params.profile) ? this.props.params.profile : new Array(urlQuery.profile);
this.props.setProfile(profile, authParams[profile]);
if (!this.props.configLoaded && this.props.featureType) {
this.props.onLoadFeatureTypeConfig(
`assets/${this.props.featureType}.json`, {authkey: authParams[profile].authkey}, this.props.featureType, true);
}
},
componentWillReceiveProps(props) {
if (props.featureType !== this.props.featureType) {
this.props.onLoadFeatureTypeConfig(`assets/${props.featureType}.json`, {authkey: this.props.profile.authParams.authkey}, props.featureType, true);
}
if (this.state.qGisType === "detail" && urlQuery.featureTypeId && props.configLoaded && !props.siraControls.detail) {
this.props.toggleSiraControl('detail', true);
this.goToDetail(urlQuery.featureTypeId, props.detailsConfig);
}
if (this.state.qGisType === "list" && this.state.loadList && urlQuery.featureTypeIds && props.configLoaded && props.gridConfig && props.featureTypeName) {
// find id field
this.setState({loadList: false});
let idField = head(props.gridConfig.grid.columns.filter((c) => c.id === true));
let filter = SiraFilterUtils.getFilterByIds(props.featureTypeName, urlQuery.featureTypeIds.split(','), idField);
props.onQuery(props.searchUrl, filter);
}
},
getQGisType(pathname) {
if (pathname.search(/search.html$/) !== -1) {
return "search";
}
if (pathname.search(/detail.html$/) !== -1) {
return "detail";
}
if (pathname.search(/list.html$/) !== -1) {
return "list";
}
},
renderQueryPanel() {
return this.state.qGisType === "detail" || this.state.qGisType === "list" ? (
<div className="qgis-spinner">
<Spinner style={{width: "60px"}} spinnerName="three-bounce" noFadeIn/>
</div>
) : (
<SideQueryPanel
withMap={false}
params={{authkey: this.props.profile.authParams.authkey}}
toggleControl={this.toggleControl}/>
);
},
renderGrid() {
return (
<QGisFeatureGrid
withMap={true}
initWidth={this.state.width}
pagination= {(this.state.qGisType !== 'list' && this.props.pagination && this.props.pagination .maxFeatures) ? true : false}
params={{authkey: this.props.profile.authParams.authkey}}
profile={this.props.profile.profile}
templateProfile="QGIS"
selectFeatures={this.selectFeatures}
zoomToFeatureAction={this.zoomToFeature}
exporter={false}
selectAllToggle={this.props.selectAllToggle && this.state.qGisType !== "list" ? this.props.selectAllToggle : undefined}/>
);
},
render() {
return (
<div id="qgis-container" className="mappaSiraDecisionale">
{this.props.siraControls.grid || (this.state.qGisType === 'list' && this.props.configLoaded && !this.state.loadList) ? this.renderGrid() : this.renderQueryPanel()}
<Card profile={this.props.profile.profile} draggable={false} authParam={this.props.profile.authParams} withMap={false}/>
</div>
);
},
toggleControl() {
this.props.toggleSiraControl('grid');
},
selectFeatures(features) {
let ids = features.map((f) => {
return f.id;
}).join(',');
/*eslint-disable */
if (typeof window.parent !== 'undefined' && typeof parent.VALAMB !== 'undefined' && parent.VALAMB.viewOnMapById) {
console.log("parent.VALAMB present", `parent.VALAMB.viewOnMapById('${this.props.featureType}',"${ids}")`);
parent.VALAMB.viewOnMapById(`'${this.props.featureType}'`, `"${ids}"`);
}else {
console.log("parent.VALAMB absent", `parent.viewOnMapById('${this.props.featureType}',"${ids}")`);
if (typeof VALAMB !== 'undefined' && VALAMB.viewOnMapById) {
console.log("VALAMB present", `VALAMB.viewOnMapById('${this.props.featureType}',"${ids}")`);
VALAMB.viewOnMapById(`'${this.props.featureType}'`, `"${ids}"`);
}else {
console.log("VALAMB absent", `viewOnMapById('${this.props.featureType}',"${ids}")`);
}
}
/*eslint-enable */
this.props.selectFeatures(features);
},
zoomToFeature(data) {
let [minX, minY, maxX, maxY] = CoordinatesUtils.getGeoJSONExtent(data.geometry);
/*eslint-disable */
if (typeof window.parent !== 'undefined' && typeof parent.VALAMB !== 'undefined' && parent.VALAMB.zoomOn) {
console.log("parent.VALAMB present", `parent.VALAMB.zoomOn('${minX}', '${minY}', '${maxX}', '${maxY}', "EPSG:4326");`);
parent.VALAMB.zoomOn(`'${minX}'`, `'${minY}'`, `'${maxX}'`, `'${maxY}'`, "EPSG:4326");
}else {
console.log("parent.VALAMB absent", `parent.VALAMB.zoomOn('${minX}', '${minY}', '${maxX}', '${maxY}', "EPSG:4326")`);
if (typeof VALAMB !== 'undefined' && VALAMB.zoomOn) {
console.log("VALAMB present", `VALAMB.zoomOn('${minX}', '${minY}', '${maxX}', '${maxY}', "EPSG:4326");`);
VALAMB.zoomOn(`'${minX}'`, `'${minY}'`, `'${maxX}'`, `'${maxY}'`, "EPSG:4326");
}else {
console.log("VALAMB absent", `VALAMB.zoomOn('${minX}', '${minY}', '${maxX}', '${maxY}', "EPSG:4326")`);
}
}
/*eslint-enable */
},
goToDetail(id, detailsConfig) {
let url = detailsConfig.service.url;
let urlParams = detailsConfig.service.params;
for (let param in urlParams) {
if (urlParams.hasOwnProperty(param)) {
url += "&" + param + "=" + urlParams[param];
}
}
let templateUrl = typeof detailsConfig.template === "string" ? detailsConfig.template : detailsConfig.template.QGIS;
this.props.loadCardTemplate(
templateUrl,
// this.props.detailsConfig.cardModelConfigUrl,
`${url}&FEATUREID=${id}${(this.props.profile.authParams.authkey ? "&authkey=" + this.props.profile.authParams.authkey : "")}`
);
}
});
module.exports = connect((state) => {
const activeConfig = state.siradec.configOggetti[state.siradec.activeFeatureType] || {};
return {
mode: 'desktop',
profile: state.userprofile,
error: state.loadingError || (state.locale && state.locale.localeError) || null,
featureType: state.siradec && state.siradec.featureType,
configLoaded: activeConfig && activeConfig.card && activeConfig.featuregrid ? true : false,
filterPanelExpanded: state.siradec.filterPanelExpanded,
siraControls: state.siraControls,
detailsConfig: activeConfig && activeConfig.card,
gridConfig: activeConfig && activeConfig.featuregrid,
featureTypeName: activeConfig && activeConfig.featureTypeName,
searchUrl: state.queryform.searchUrl,
pagination: state.queryform.pagination
};
}, {
setProfile,
onLoadFeatureTypeConfig: loadFeatureTypeConfig,
expandFilterPanel,
toggleSiraControl,
selectFeatures,
loadCardTemplate,
onQuery: loadGridModelWithFilter,
onQueryPagination: loadGridModelWithPagination,
selectAllToggle: selectAllQgis
})(QGis);
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const CoordinatesUtils = require('../../../MapStore2/web/client/utils/CoordinatesUtils');
const {Button} = require("react-bootstrap");
const img = require('../../../MapStore2/web/client/components/data/featuregrid/images/magnifier.png');
const QGisZoom = React.createClass({
propTypes: {
geometry: React.PropTypes.object,
style: React.PropTypes.object,
pointSRS: React.PropTypes.string
},
getDefaultProps() {
return {
pointSRS: "EPSG:4326",
geometry: null,
style: {position: "relative", top: "-", 'float': "right", margin: "2px"}
};
},
render() {
return this.props.geometry ? (
<Button onClick={this.zoomTo} style={this.props.style}>
<img src={img} width={16}/></Button>
) : null;
},
zoomTo() {
let [minX, minY, maxX, maxY] = CoordinatesUtils.getGeoJSONExtent(this.props.geometry);
/*eslint-disable */
if (typeof window.parent !== 'undefined' && typeof parent.VALAMB !== 'undefined' && parent.VALAMB.zoomOn) {
console.log("parent.VALAMB present", `parent.VALAMB.zoomOn('${minX}', '${minY}', '${maxX}', '${maxY}', "EPSG:4326")`);
parent.VALAMB.zoomOn(`'${minX}'`, `'${minY}'`, `'${maxX}'`, `'${maxY}'`, "EPSG:4326");
}else {
console.log("parent.VALAMB absent", `parent.VALAMB.zoomOn('${minX}', '${minY}', '${maxX}', '${maxY}', "EPSG:4326")`);
if (typeof VALAMB !== 'undefined' && VALAMB.zoomOn) {
console.log("VALAMB present", `VALAMB.zoomOn('${minX}', '${minY}', '${maxX}', '${maxY}', "EPSG:4326")`);
VALAMB.zoomOn(`'${minX}'`, `'${minY}'`, `'${maxX}'`, `'${maxY}'`, "EPSG:4326");
}else {
console.log("VALAMB absent", `VALAMB.zoomOn('${minX}', '${minY}', '${maxX}', '${maxY}', "EPSG:4326")`);
}
}
/*eslint-enable */
}
});
module.exports = QGisZoom;
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const {connect} = require('react-redux');
const TemplateUtils = require('../../../utils/TemplateUtils');
var {FormattedDate} = require('react-intl');
const assign = require('object-assign');
const uuid = require('node-uuid');
const {isArray} = require('lodash');
const SiraTable = React.createClass({
propTypes: {
id: React.PropTypes.string,
card: React.PropTypes.object,
columns: React.PropTypes.array,
dependsOn: React.PropTypes.object,
features: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.func,
React.PropTypes.object
]),
wfsVersion: React.PropTypes.string,
profile: React.PropTypes.string
},
contextTypes: {
locale: React.PropTypes.string
},
getDefaultProps() {
return {
id: "SiraTable",
features: [],
wfsVersion: null,
card: null,
dependsOn: null,
columns: [],
profile: null
};
},
renderTableHeader(columns) {
return columns.map((c) => {
return (<th key={c.field}>{c.headerName}</th>);
});
},
renderDate(value, dateFormat, locale) {
const date = new Date(value);
return !isNaN(date.getTime()) ? (<FormattedDate locales={locale} value={date} {...dateFormat} />) : (<span/>);
},
renderTableBody(features, columns) {
return features.map((f, idx) => {
return (<tr key={idx}>{columns.map((c) => {
return (<td key={c.field}>{c.dateFormat ? this.renderDate(f[c.field], c.dateFormat, c.locale || 'it-IT' ) : f[c.field]}</td>);
})}</tr>);
});
},
renderChildrenTable(columns, features, id, title) {
return (
<div key={id}>
<h5 className="pdf-title">{title}</h5>
<table className="pdf-table" >
<thead>
<tr>
{this.renderTableHeader(columns)}
</tr>
</thead>
<tbody>
{this.renderTableBody(features, columns)}
</tbody>
</table>
</div>);
},
render() {
let features;
let columns = this.props.columns.map((column) => {
// if (!column.profiles || (column.profiles && this.props.profile && column.profiles.indexOf(this.props.profile) !== -1)) {
if (TemplateUtils.verifyProfiles(column.profiles, this.props.profile)) {
let fieldName = !column.field ? uuid.v1() : column.field;
this.idFieldName = column.id === true ? fieldName : this.idFieldName;
return assign({}, column, {field: fieldName});
}
}, this).filter((c) => c);
if (typeof this.props.features === 'function') {
features = this.props.features();
} else {
features = this.props.features instanceof Array ? this.props.features : [this.props.features];
features = features.map((feature) => {
let f = {};
columns.forEach((column) => {
if (column.field) {
f[column.field] = TemplateUtils.getElement({xpath: column.xpath}, feature, this.props.wfsVersion);
}
});
return f;
}, this);
}
columns = columns.filter((col) => col.hide !== true);
if (this.props.dependsOn) {
const parentFeatures = isArray(this.props.dependsOn.parentFeatures) ? this.props.dependsOn.parentFeatures : [this.props.dependsOn.parentFeatures];
const tables = parentFeatures.reduce((elements, pf) => {
const id = TemplateUtils.getElement({xpath: this.props.dependsOn.xpath}, pf, this.props.wfsVersion);
const ft = features.filter(function(feature) {
return feature[this.idFieldName] === id;
}, this);
if (ft.length > 0) {
let title = this.props.dependsOn.pdfTitle;
(title.match(/\{\{.+?\}\}/g) || []).forEach((placeholder) => {
const el = placeholder.replace('{{', '').replace('}}', '');
title = title.replace(placeholder, TemplateUtils.getElement({xpath: el}, pf, this.props.wfsVersion));
});
// get parentFeatures
elements.push(this.renderChildrenTable(columns, ft, id, title));
}
return elements;
}, []);
if (tables.length > 0) {
return (<div>
{tables}
</div>);
}
}
return (
<table className="pdf-table">
<thead>
<tr>
{this.renderTableHeader(columns)}
</tr>
</thead>
<tbody>
{this.renderTableBody(features, columns)}
</tbody>
</table>);
}
});
module.exports = connect((state) => {
return {
card: state.cardtemplate || {}
};
})(SiraTable);
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const {connect} = require('react-redux');
const {changeMapView} = require('../../MapStore2/web/client/actions/map');
const {selectFeatures, selectAllToggle} = require('../actions/featuregrid');
const {
loadFeaturesWithPagination,
loadGridModelWithPagination,
configureGridError
} = require('../actions/grid');
const {loadCardTemplate} = require('../actions/card');
const {toggleSiraControl} = require('../actions/controls');
const {setExportParams, configureExporter} = require('../actions/siraexporter');
const {
// SiraQueryPanel action functions
expandFilterPanel
} = require('../actions/siradec');
require('react-resizable/css/styles.css');
require('./SiraFeatureGrid.css');
module.exports = connect((state) => {
const activeConfig = state.siradec.configOggetti[state.siradec.activeFeatureType] || {};
return {
open: state.siraControls.grid,
detailOpen: state.siraControls.detail,
detailsConfig: activeConfig.card || {},
columnsDef: state.grid.featuregrid && state.grid.featuregrid.grid ? state.grid.featuregrid.grid.columns : [],
attributes: activeConfig.attributes || [],
features: state.grid && state.grid.data || [],
totalFeatures: state.grid.totalFeatures,
map: (state.map && state.map.present) || (state.config && state.config.map),
loadingGrid: state.grid.loadingGrid,
loadingGridError: state.grid.loadingGridError,
pagination: (state.queryform.pagination && state.queryform.pagination.maxFeatures) ? true : false,
groupFields: state.queryform.groupFields,
filterFields: state.queryform.filterFields,
spatialField: state.queryform.spatialField,
featureTypeName: activeConfig.featureTypeName,
nameSpaces: activeConfig.nameSpaces,
searchUrl: state.queryform.searchUrl,
dataSourceOptions: state.grid.dataSourceOptions,
header: state.grid.gridType === 'search' ? "featuregrid.header" : "featuregrid.header_all",
backToSearch: state.grid.gridType === 'search' ? "featuregrid.backtosearch" : "featuregrid.opensearch",
gridType: state.grid.gridType,
maxFeatures: state.siraexporter.maxFeatures,
exporterConfig: activeConfig.exporter
};
}, {
onDetail: loadCardTemplate,
onShowDetail: toggleSiraControl.bind(null, 'detail'),
toggleSiraControl: toggleSiraControl,
changeMapView: changeMapView,
onExpandFilterPanel: expandFilterPanel,
selectFeatures: selectFeatures,
onQuery: loadFeaturesWithPagination,
onConfigureQuery: loadGridModelWithPagination,
cleanError: configureGridError,
selectAllToggle: selectAllToggle,
setExportParams,
configureExporter
})(require('./FeatureGrid'));
<file_sep>/**
* Copyright 2016, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const FilterUtils = require('../utils/SiraFilterUtils');
const ConfigUtils = require('../../MapStore2/web/client/utils/ConfigUtils');
const TemplateUtils = require('../utils/TemplateUtils');
const axios = require('../../MapStore2/web/client/libs/ajax');
const {showLoading} = require('./grid');
const SELECT_FEATURES = 'SELECT_FEATURES';
const SET_FEATURES = 'SET_FEATURES';
const SELECT_ALL = 'SELECT_ALL';
function selectFeatures(features) {
return {
type: SELECT_FEATURES,
features: features
};
}
function setFeatures(features) {
return {
type: SET_FEATURES,
features: features
};
}
function selectAllToggle(featureTypeName, filterObj, ogcVersion, params, wfsUrl, nameSpaces) {
const sldBody = filterObj ? FilterUtils.getSLD(featureTypeName, filterObj, "1.0.0", "ogc", nameSpaces) : undefined;
return {
type: SELECT_ALL,
featureTypeName,
sldBody
};
}
function selectAllQgis(featureTypeName, filterObj, ogcVersion, params, wfsUrl) {
return (dispatch, getState) => {
if (featureTypeName) {
let {url} = ConfigUtils.setUrlPlaceholders({url: wfsUrl});
for (let param in params) {
if (params.hasOwnProperty(param)) {
url += "&" + param + "=" + params[param];
}
}
let filter = FilterUtils.toOGCFilterSira(featureTypeName, filterObj, ogcVersion);
dispatch(showLoading(true));
let state = getState();
const featuregrid = state.grid && state.grid.featuregrid;
return axios.post(url, filter, {
timeout: 60000,
headers: {'Accept': 'text/xml', 'Content-Type': 'text/plain'}
}).then((response) => {
if (response.data && response.data.indexOf("<ows:ExceptionReport") !== 0) {
const idFieldName = featuregrid.idFieldName;
const features = TemplateUtils.getModels(response.data, featuregrid.grid.root, featuregrid.grid.columns);
let ids = features.map((f) => {
return f[idFieldName];
}).join(',');
/*eslint-disable */
if ("undefined" != typeof window.parent && "undefined" != typeof parent.VALAMB && parent.VALAMB.viewOnMapById) {
console.log("prenset.VALAMB present", `present.VALAMB.viewOnMapById('${state.siradec.featureType}',"${ids}");`);
parent.VALAMB.viewOnMapById(`'${state.siradec.featureType}'`, `"${ids}"`);
}else {
console.log("parent.VALAMB absent", `parent.VALAMB.viewOnMapById('${state.siradec.featureType}',"${ids}")`);
if (typeof VALAMB !== 'undefined' && VALAMB.viewOnMapById) {
console.log("VALAMB present", `VALAMB.viewOnMapById('${state.siradec.featureType}',"${ids}");`);
VALAMB.viewOnMapById(`'${state.siradec.featureType}'`, `"${ids}"`);
}else {
console.log("VALAMB absent", `VALAMB.viewOnMapById('${state.siradec.featureType}',"${ids}")`);
}
}
/*eslint-enable */
}
dispatch(showLoading(false));
});
}
};
}
module.exports = {
SELECT_FEATURES,
SET_FEATURES,
SELECT_ALL,
selectFeatures,
setFeatures,
selectAllToggle,
selectAllQgis
};
<file_sep>/**
* Copyright 2015, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const expect = require('expect');
const {
FEATURETYPE_CONFIG_LOADED,
EXPAND_FILTER_PANEL,
QUERYFORM_CONFIG_LOAD_ERROR,
// loadQueryFormConfig,
loadFeatureTypeConfig,
expandFilterPanel,
getAttributeValues
} = require('../siradec');
describe('Test correctness of the queryform actions', () => {
it('loads an existing configuration file 1', (done) => {
loadFeatureTypeConfig('base/js/test-resources/testQueryFormConfig.json')((e) => {
try {
expect(e).toExist();
done();
} catch(ex) {
done(ex);
}
}, () => ({ueserprofile: {}}));
});
it('loads an existing configuration file 2', (done) => {
const field = {
id: "Provincia",
type: "list",
valueService: "base/js/test-resources/testQueryFormFieldConfig.json",
idField: "sigla",
labelField: "toponimo"
};
const ftName = "aua";
getAttributeValues(ftName, field)((e) => {
try {
expect(e).toExist();
expect(e.type).toBe(FEATURETYPE_CONFIG_LOADED);
done();
} catch(ex) {
done(ex);
}
});
});
/*it('loads a broken configuration file 1', (done) => {
loadQueryFormConfig('base/js/test-resources/testQueryFormConfig.broken.json')((e) => {
try {
expect(e).toExist();
expect(e.type).toBe(QUERYFORM_CONFIG_LOAD_ERROR);
done();
} catch(ex) {
done(ex);
}
});
});*/
it('loads a broken configuration file 2', (done) => {
const field = {
attribute: "Provincia",
type: "list",
valueService: "base/js/test-resources/testQueryFormFieldConfig.broken.json",
idField: "sigla",
labelField: "toponimo"
};
const ftName = "aua";
getAttributeValues(ftName, field, null, field.valueService)((e) => {
try {
expect(e).toExist();
expect(e.type).toBe(QUERYFORM_CONFIG_LOAD_ERROR);
done();
} catch(ex) {
done(ex);
}
});
});
it('collapseFilterPanel', () => {
let retval = expandFilterPanel(false);
expect(retval).toExist();
expect(retval.type).toBe(EXPAND_FILTER_PANEL);
expect(retval.expand).toBe(false);
});
});
|
2f68733c0856910d9ad66446e8354cc113aed353
|
[
"JavaScript",
"Markdown",
"Maven POM",
"INI",
"Shell"
] | 80 |
JavaScript
|
seancrow/csi-sira
|
909a4c2e386c0ea37bbf0f8addf1854c7044bac8
|
191df03dd33e65d7ad9d3162ed41ded0aa735569
|
refs/heads/master
|
<repo_name>alekso56/BetterThanAchievements<file_sep>/src/main/java/betterachievements/api/components/achievement/ICustomIconRenderer.java
package betterachievements.api.components.achievement;
public interface ICustomIconRenderer {
/**
* Custom icon rendering of the {@link net.minecraft.stats.Achievement} on
* the {@link betterachievements.gui.GuiBetterAchievements}
*
* @param xPos
* left of the achievement icon
* @param yPos
* top of the achievement icon
*/
void renderIcon(int xPos, int yPos);
}
<file_sep>/src/main/java/betterthanachievements/proxy/ClientProxy.java
package betterthanachievements.proxy;
import java.io.File;
import java.util.List;
import betterachievements.handler.ConfigHandler;
import betterachievements.handler.GuiOpenHandler;
import betterachievements.handler.SaveHandler;
import betterthanachievements.BetterThanAchievements;
import betterthanachievements.achievements.AchievementsTextLoader;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.item.Item;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
public class ClientProxy extends CommonProxy {
@Override
public void setupTextures() {
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(BetterThanAchievements.blocky), 0,
new ModelResourceLocation(BetterThanAchievements.blocky.getRegistryName(), "normal"));
ModelResourceLocation resource = new ModelResourceLocation(BetterThanAchievements.itemy.getRegistryName(), "normal");
ModelLoader.setCustomMeshDefinition(BetterThanAchievements.itemy, MeshDefinitionFix.create(stack -> resource));
ModelBakery.registerItemVariants(BetterThanAchievements.itemy, resource);
List<IResourcePack> DefaultResourcePacks = ObfuscationReflectionHelper.getPrivateValue(Minecraft.class,
Minecraft.getMinecraft(), "field_110449_ao", "field_110449_ao");
DefaultResourcePacks.add(new AchievementsTextLoader());
if (Loader.isModLoaded("OpenComputers")) {
ModelLoader.setCustomModelResourceLocation(BetterThanAchievements.achycardy, 0,
new ModelResourceLocation(BetterThanAchievements.achycardy.getRegistryName(), "normal"));
}
}
@Override
public void registerHandlers() {
super.registerHandlers();
MinecraftForge.EVENT_BUS.register(new GuiOpenHandler());
MinecraftForge.EVENT_BUS.register(new SaveHandler());
}
@Override
public void initConfig(String configDir) {
MinecraftForge.EVENT_BUS.register(new ConfigHandler());
}
}
<file_sep>/src/main/java/betterachievements/reference/Textures.java
package betterachievements.reference;
public final class Textures {
public static final class GUI {
private static final String prefix = "textures/gui/";
public static final String SPRITES = prefix + "sprites.png";
public static final String TABS = prefix + "tabs.png";
}
}
<file_sep>/src/main/java/betterachievements/handler/AchievementHandler.java
package betterachievements.handler;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import betterachievements.util.LogHelper;
import betterthanachievements.BetterThanAchievements;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.stats.Achievement;
import net.minecraft.stats.AchievementList;
import net.minecraft.stats.StatBase;
import net.minecraft.stats.StatisticsManager;
import net.minecraftforge.event.entity.player.AchievementEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;
public class AchievementHandler {
private final Map<UUID, Set<Achievement>> playerAchievementMap;
private final Set<UUID> currentItrs;
private static final String FILENAME = "toUnlockAchievements.dat";
private static AchievementHandler instance;
public static AchievementHandler getInstance() {
if (instance == null)
instance = new AchievementHandler();
return instance;
}
private AchievementHandler() {
this.playerAchievementMap = new HashMap<UUID, Set<Achievement>>();
this.currentItrs = new HashSet<UUID>();
}
@SubscribeEvent
public void playerjoin(PlayerLoggedInEvent ev) {
Integer CrashSurvivalCount = BetterThanAchievements.PlayersInServerCrashes.get(ev.player.getUniqueID());
if (CrashSurvivalCount != null) {
Achievement achievement = getAchievement("servercrash" + CrashSurvivalCount);
if (achievement != null) {
if (ev.player instanceof EntityPlayerMP) {
EntityPlayerMP player = (EntityPlayerMP) ev.player;
player.getStatFile().unlockAchievement(player, achievement, 1);
}
}
}
/*
* for(AchievementPage page
* :AchievementRegistry.instance().getAllPages()){ ItemStack itemStack =
* AchievementRegistry.instance().getItemStack(page);
* System.out.println(page.getName()+":"+itemStack.getItem().
* getRegistryName()); }
*/
}
public static Achievement getAchievement(String achievement) {
StatBase x = BetterThanAchievements.oneShotStats.get("achievement." + achievement);
if (x != null && x.isAchievement()) {
Achievement y = (Achievement) x;
return y;
}
return null;
}
@SubscribeEvent
public void onAchievementUnlocked(AchievementEvent event) {
if (event.getEntityPlayer() instanceof EntityPlayerMP) {
StatisticsManager stats = ((EntityPlayerMP) event.getEntityPlayer()).getStatFile();
if (stats.canUnlockAchievement(event.getAchievement())) {
stats.unlockAchievement(event.getEntityPlayer(), event.getAchievement(), 1);
event.setCanceled(true);
} else
addAchievementToMap(event.getEntityPlayer().getUniqueID(), event.getAchievement());
if (!this.currentItrs.contains(event.getEntityPlayer().getUniqueID()))
tryUnlock((EntityPlayerMP) event.getEntityPlayer());
}
}
public void addAchievementToMap(UUID uuid, Achievement achievement) {
Set<Achievement> achievements = this.playerAchievementMap.get(uuid);
if (achievements == null)
achievements = new HashSet<Achievement>();
achievements.add(achievement);
this.playerAchievementMap.put(uuid, achievements);
}
public void tryUnlock(EntityPlayerMP player) {
this.currentItrs.add(player.getUniqueID());
Set<Achievement> achievements = this.playerAchievementMap.get(player.getUniqueID());
boolean doItr = achievements != null;
while (doItr) {
doItr = false;
Iterator<Achievement> itr = achievements.iterator();
while (itr.hasNext()) {
Achievement current = itr.next();
if (player.getStatFile().canUnlockAchievement(current)) {
player.addStat(current);
itr.remove();
doItr = true;
}
}
}
this.currentItrs.remove(player.getUniqueID());
}
public void dumpAchievementData(String worldName) {
List<String> lines = new ArrayList<String>();
for (Map.Entry<UUID, Set<Achievement>> entry : this.playerAchievementMap.entrySet()) {
StringBuilder sb = new StringBuilder();
sb.append(entry.getKey().toString()).append("->");
for (Achievement achievement : entry.getValue())
sb.append(achievement.statId).append(",");
lines.add(sb.toString());
}
try {
Files.write(new File(BetterThanAchievements.confpath+ "/betterthanachievements/", worldName + " " + FILENAME).toPath(), lines,
Charset.defaultCharset());
} catch (IOException e) {
LogHelper.instance().error(e, "couldn't write " + worldName + " " + FILENAME);
}
}
public void constructFromData(String worldName) {
this.playerAchievementMap.clear();
Map<String, Achievement> achievementMap = new HashMap<String, Achievement>();
for (Achievement achievement : AchievementList.ACHIEVEMENTS)
achievementMap.put(achievement.statId, achievement);
try {
File file = new File(BetterThanAchievements.confpath+ "/betterthanachievements/", worldName + " " + FILENAME);
if (!file.exists())
return;
List<String> lines = Files.readAllLines(file.toPath(), Charset.defaultCharset());
for (String line : lines) {
String[] splitted = line.split("->");
if (splitted.length != 2)
continue;
UUID uuid;
try {
uuid = UUID.fromString(splitted[0]);
} catch (IllegalArgumentException e) {
LogHelper.instance().error(e, "bad uuid \"" + splitted[0] + "\" in " + worldName + " " + FILENAME);
continue;
}
Set<Achievement> achievementSet = new HashSet<Achievement>();
for (String sAchievement : splitted[1].split(",")) {
Achievement achievement = achievementMap.get(sAchievement);
if (achievement == null)
continue;
achievementSet.add(achievement);
}
this.playerAchievementMap.put(uuid, achievementSet);
}
} catch (IOException e) {
LogHelper.instance().error(e, "couldn't read " + worldName + " " + FILENAME);
}
}
}
<file_sep>/src/main/java/betterachievements/handler/SaveHandler.java
package betterachievements.handler;
import betterachievements.registry.AchievementRegistry;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class SaveHandler {
public static String[] userSetIcons = new String[0];
@SubscribeEvent
public void onWorldUnload(WorldEvent.Unload event) {
ConfigHandler.saveUserSetIcons();
AchievementHandler.getInstance().dumpAchievementData(event.getWorld().getWorldInfo().getWorldName());
}
@SubscribeEvent
public void onWorldLoad(WorldEvent.Load event) {
AchievementRegistry.instance().setUserSetIcons(userSetIcons);
AchievementHandler.getInstance().constructFromData(event.getWorld().getWorldInfo().getWorldName());
}
}
<file_sep>/src/main/java/betterachievements/api/util/ColourHelper.java
package betterachievements.api.util;
import betterachievements.util.LogHelper;
public class ColourHelper {
/**
* Convert to integer RGBA value Uses 255 as A value
*
* @param r
* integer red
* @param g
* integer green
* @param b
* integer blue
*
* @return single integer representation of the given ints
*/
public static int RGB(int r, int g, int b) {
return RGBA(r, g, b, 255);
}
/**
* Convert to integer RGBA value
*
* @param r
* integer red
* @param g
* integer green
* @param b
* integer blue
* @param a
* integer alpha
*
* @return single integer representation of the given ints
*/
public static int RGBA(int r, int g, int b, int a) {
return (a << 24) | ((r & 255) << 16) | ((g & 255) << 8) | (b & 255);
}
/**
* Convert to integer RGBA value Uses 1.0F as A value
*
* @param red
* float red
* @param green
* float green
* @param blue
* float blue
*
* @return single integer representation of the given floats
*/
public static int RGB(float red, float green, float blue) {
return RGBA((int) red * 255, (int) green * 255, (int) blue * 255, 255);
}
/**
* Convert to integer RGBA value
*
* @param red
* float red
* @param green
* float green
* @param blue
* float blue
* @param alpha
* float alpha
*
* @return single integer representation of the given floats
*/
public static int RGB(float red, float green, float blue, float alpha) {
return RGBA((int) red * 255, (int) green * 255, (int) blue * 255, (int) alpha * 255);
}
/**
* Convert an #RRGGBB value to a int colour
*
* @param colour
* the #RRGGBB value
* @return the int colour value or an
* {@link java.lang.IllegalArgumentException} if a mal formed input
* is given
*/
public static int RGB(String colour) {
if (!colour.startsWith("#") || !(colour.length() == 7))
throw new IllegalArgumentException("Use #RRGGBB format");
return RGB(Integer.parseInt(colour.substring(1, 3), 16), Integer.parseInt(colour.substring(3, 5), 16),
Integer.parseInt(colour.substring(5, 7), 16));
}
public static String hex(int r, int g, int b) {
return String.format("#%02x%02x%02x", r, g, b);
}
/**
* Blends given int colours
*
* @param colours
* an amount of colours
* @return the mix int colour value or an IllegalArgumentException if
* colours is empty
*/
public static int blend(int... colours) {
if (colours.length < 1)
throw new IllegalArgumentException();
int[] alphas = new int[colours.length];
int[] reds = new int[colours.length];
int[] greens = new int[colours.length];
int[] blues = new int[colours.length];
for (int i = 0; i < colours.length; i++) {
alphas[i] = (colours[i] >> 24 & 0xff);
reds[i] = ((colours[i] & 0xff0000) >> 16);
greens[i] = ((colours[i] & 0xff00) >> 8);
blues[i] = (colours[i] & 0xff);
}
float a, r, g, b;
a = r = g = b = 0;
float ratio = 1.0F / colours.length;
for (int alpha : alphas)
a += alpha * ratio;
for (int red : reds)
r += red * ratio;
for (int green : greens)
g += green * ratio;
for (int blue : blues)
b += blue * ratio;
return ((int) a) << 24 | ((int) r) << 16 | ((int) g) << 8 | ((int) b);
}
/**
* Tone a int colour bigger then 1 will tone up, less then 1 will tone down
*
* @param colour
* colour in int form
* @param scale
* scale as float
* @return the toned colour
*/
public static int tone(int colour, float scale) {
float r = (colour >> 16) & 255;
float g = (colour >> 8) & 255;
float b = colour & 255;
return RGB(r * scale, g * scale, b * scale);
}
/**
* Blend colour with given grey scale
*
* @param colour
* colour in int form
* @param greyScale
* grayScale as float
* @return the toned colour
*/
public static int blendWithGreyScale(int colour, float greyScale) {
return ColourHelper.blend(colour, ColourHelper.RGB(greyScale, greyScale, greyScale));
}
/**
* Gives a colour based of {@link System#currentTimeMillis()} and given
* params
*
* @param freqR
* strength of the reds
* @param freqG
* strength of the greens
* @param freqB
* strength of the blues
* @param phaseR
* phase shift red
* @param phaseG
* phase shift green
* @param phaseB
* phase shift blue
* @param center
* center value
* @param width
* width of colour range
* @param length
* change rate
* @return an int colour
*/
public static int getRainbowColour(float freqR, float freqG, float freqB, float phaseR, float phaseG, float phaseB,
float center, float width, float length) {
long i = Math.abs((int) System.currentTimeMillis()) / (int) length;
double r = Math.sin(freqR * i + phaseR) * width + center;
double g = Math.sin(freqG * i + phaseG) * width + center;
double b = Math.sin(freqB * i + phaseB) * width + center;
return RGB((float) r, (float) g, (float) b);
}
/**
* Short had for parsing array of params
*
* @param params
* all parameters for
* {@link #getRainbowColour(float, float, float, float, float, float, float, float, float)}
* @return an int rainbow colour
*/
public static int getRainbowColour(float[] params) {
return getRainbowColour(params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7],
params[8]);
}
/**
* Create settings for rainbow colour
*
* @param colourCode
* a string representation of the rainbow settings
* @return an array containing parameters for
* {@link #getRainbowColour(float, float, float, float, float, float, float, float, float)}
*/
public static float[] getRainbowSettings(String colourCode) {
String[] splitted = colourCode.split(";");
float[] result = { 0.3F, 0.3F, 0.3F, 0, 2, 4, 128, 127, 50 };
for (int i = 1; i < splitted.length; i++) {
try {
result[i - 1] = Float.parseFloat(splitted[i]);
} catch (NumberFormatException e) {
LogHelper.instance().error(e, "Parsing error while creating rainbow settings");
}
}
return result;
}
}
<file_sep>/src/main/java/betterthanachievements/AchievementCheckBlock.java
package betterthanachievements;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemBlock;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class AchievementCheckBlock extends Block {
public static final AxisAlignedBB FULL_BLOCK_AABB1 = new AxisAlignedBB(0.0D, 0.1D, 0.0D, 1.0D, 0.9D, 1.0D);
protected AchievementCheckBlock(Material materialIn) {
super(Material.CLOTH);
setHardness(1.5f);
setUnlocalizedName("checkblock");
setRegistryName("checkblock");
GameRegistry.register(this);
GameRegistry.register(new ItemBlock(this).setRegistryName(getRegistryName()));
GameRegistry.registerTileEntity(AchievementsCheckBlockTilentity.class, "betterthanachievements:checkblock");
setCreativeTab(BetterThanAchievements.AchTab);
setTickRandomly(false);
}
@Override
public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) {
collisionEvent(worldIn, pos, entityIn);
}
void collisionEvent(World worldIn, BlockPos pos, Entity entityIn) {
if (worldIn != null && !worldIn.isRemote) {
if (entityIn instanceof EntityPlayerMP) {
EntityPlayerMP player = (EntityPlayerMP) entityIn;
if (worldIn.getTileEntity(pos) != null) {
AchievementsCheckBlockTilentity tile = (AchievementsCheckBlockTilentity) worldIn.getTileEntity(pos);
tile.onCollision(player);
}
}
}
}
@Override
public boolean hasTileEntity(IBlockState state) {
return true;
}
@Override
public TileEntity createTileEntity(World world, IBlockState state) {
return new AchievementsCheckBlockTilentity();
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) {
return FULL_BLOCK_AABB1;
}
}
<file_sep>/src/main/java/betterachievements/util/LogHelper.java
package betterachievements.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Loader;
public class LogHelper {
private Logger log;
private boolean debug;
public LogHelper(String id) {
log = LogManager.getLogger(id);
}
public static LogHelper instance() {
return new LogHelper(Loader.instance().activeModContainer().getModId());
}
public void debug(Object obj) {
if (debug)
log.info(obj);
else
log.debug(obj);
}
public void info(Object obj) {
log.info(obj);
}
public void warn(Object obj) {
log.warn(obj);
}
public void crash(Exception e, String message) {
FMLCommonHandler.instance().raiseException(e, message, true);
}
public void error(Exception e, String message) {
FMLCommonHandler.instance().raiseException(e, message, false);
}
public void setDebug(boolean debug) {
this.debug = debug;
}
}
<file_sep>/src/main/java/betterthanachievements/AchievementAdjusterItem.java
package betterthanachievements;
import java.util.List;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.Achievement;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class AchievementAdjusterItem extends Item{
protected AchievementAdjusterItem(Material materialIn) {
setUnlocalizedName("achadjuster");
setRegistryName("achadjuster");
GameRegistry.register(this);
setHasSubtypes(true);
}
/**
* Called when a Block is right-clicked with this Item
*/
public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
if(worldIn != null && !worldIn.isRemote){
TileEntity tiley = worldIn.getTileEntity(pos);
if(tiley != null && tiley instanceof AchievementsCheckBlockTilentity){
AchievementsCheckBlockTilentity tile = (AchievementsCheckBlockTilentity) tiley;
if(playerIn.isSneaking()){
Achievement data = BetterThanAchievements.getAchievement(getDamage(stack));
if(data != null){
tile.setAchievementInt(getDamage(stack));
playerIn.addChatMessage(new TextComponentString("Block-Achievement set to: "+data.getStatName().getFormattedText().replace("achievement.", "")));
}
}else{
Achievement data = BetterThanAchievements.getAchievement(tile.getAchievementInt());
if(data != null){
playerIn.addChatMessage(new TextComponentString("Block-Achievement is currently: "+data.getStatName().getFormattedText().replace("achievement.", "")));
}
}
}else{
Achievement data = BetterThanAchievements.getAchievement(getDamage(stack));
if(data != null){
playerIn.addChatMessage(new TextComponentString("Achievement on item is: "+data.getStatName().getFormattedText().replace("achievement.", "")));
}
}
return EnumActionResult.SUCCESS;
}
return EnumActionResult.PASS;
}
}
<file_sep>/src/main/java/betterachievements/handler/MessageHandler.java
package betterachievements.handler;
import betterachievements.handler.message.AchievementUnlockMessage;
import betterachievements.handler.message.ConfigFetchMessage;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
public class MessageHandler {
public static SimpleNetworkWrapper INSTANCE = new SimpleNetworkWrapper("BTA");
private static final int ach = 0;
private static final int conf = 1;
public static void init() {
INSTANCE.registerMessage(AchievementUnlockMessage.class, AchievementUnlockMessage.class, ach, Side.SERVER);
INSTANCE.registerMessage(ConfigFetchMessage.class, ConfigFetchMessage.class, conf, Side.CLIENT);
}
}<file_sep>/src/main/java/betterachievements/handler/message/AchievementUnlockMessage.java
package betterachievements.handler.message;
import betterachievements.registry.AchievementRegistry;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.stats.Achievement;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
public class AchievementUnlockMessage implements IMessage, IMessageHandler<AchievementUnlockMessage, IMessage> {
private String achievementId;
public AchievementUnlockMessage() {
}
public AchievementUnlockMessage(Achievement achievement) {
this.achievementId = achievement.statId;
}
@Override
public void fromBytes(ByteBuf buf) {
int length = buf.readInt();
this.achievementId = new String(buf.readBytes(length).array());
}
@Override
public void toBytes(ByteBuf buf) {
byte[] bytes = this.achievementId.getBytes();
buf.writeInt(bytes.length);
buf.writeBytes(bytes);
}
@Override
public IMessage onMessage(AchievementUnlockMessage message, MessageContext ctx) {
EntityPlayer player = ctx.getServerHandler().playerEntity;
if (player.capabilities.isCreativeMode) {
Achievement achievement = AchievementRegistry.instance().getAchievement(message.achievementId);
unlockAchievement(achievement, player);
}
return null;
}
private void unlockAchievement(Achievement achievement, EntityPlayer player) {
player.addStat(achievement);
}
}
<file_sep>/src/main/java/betterachievements/reference/Resources.java
package betterachievements.reference;
import net.minecraft.util.ResourceLocation;
public final class Resources {
public static final class GUI {
public static final ResourceLocation SPRITES = new ResourceLocation(Reference.RESOURCE_ID,
Textures.GUI.SPRITES);
public static final ResourceLocation TABS = new ResourceLocation(Reference.RESOURCE_ID, Textures.GUI.TABS);
}
}
<file_sep>/src/main/java/betterachievements/handler/GuiOpenHandler.java
package betterachievements.handler;
import java.lang.reflect.Field;
import betterachievements.gui.GuiBetterAchievements;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.achievement.GuiAchievements;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
public class GuiOpenHandler {
private static Field prevScreen, currentPage;
static {
try {
prevScreen = ReflectionHelper.findField(GuiAchievements.class, "parentScreen", "field_146562_a");
prevScreen.setAccessible(true);
currentPage = ReflectionHelper.findField(GuiAchievements.class, "currentPage");
currentPage.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SubscribeEvent
public void onGuiOpen(GuiOpenEvent event) {
if (event.getGui() instanceof GuiAchievements) {
event.setCanceled(true);
try {
Minecraft.getMinecraft().displayGuiScreen(new GuiBetterAchievements(
(GuiScreen) prevScreen.get(event.getGui()), (Integer) currentPage.get(event.getGui()) + 1));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
<file_sep>/src/main/java/betterthanachievements/opencomputers/AchCardItem.java
package betterthanachievements.opencomputers;
import betterthanachievements.BetterThanAchievements;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class AchCardItem extends Item {
public AchCardItem(Material materialIn) {
setUnlocalizedName("achcard");
setRegistryName("achcard");
GameRegistry.register(this);
setCreativeTab(BetterThanAchievements.AchTab);
}
}
<file_sep>/src/main/java/betterachievements/gui/GuiBetterAchievements.java
package betterachievements.gui;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import betterachievements.api.components.achievement.ICustomBackgroundColour;
import betterachievements.api.components.achievement.ICustomIconRenderer;
import betterachievements.api.components.achievement.ICustomTooltip;
import betterachievements.api.components.page.ICustomArrows;
import betterachievements.api.components.page.ICustomBackground;
import betterachievements.api.components.page.ICustomPosition;
import betterachievements.api.components.page.ICustomScale;
import betterachievements.api.util.ColourHelper;
import betterachievements.handler.MessageHandler;
import betterachievements.handler.message.AchievementUnlockMessage;
import betterachievements.reference.Resources;
import betterachievements.registry.AchievementRegistry;
import betterachievements.util.RenderHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.I18n;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.Achievement;
import net.minecraft.stats.AchievementList;
import net.minecraft.stats.StatisticsManager;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.common.AchievementPage;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiBetterAchievements extends GuiScreen {
private static final int blockSize = 16, maxTabs = 9, lineSize = 12, defaultTooltipWidth = 120, arrowHeadWidth = 11,
arrowHeadHeight = 7, arrowOffset = 5, arrowRightX = 114, arrowRightY = 234, arrowLeftX = 107,
arrowLeftY = 234, arrowDownX = 96, arrowDownY = 234, arrowUpX = 96, arrowUpY = 241, achievementX = 0,
achievementY = 202, achievementTooltipOffset = 3, achievementTextureSize = 26, achievementOffset = 2,
achievementSize = 24, achievementInnerSize = 22, buttonDone = 1, buttonPrev = 2, buttonNext = 3,
buttonOffsetX = 24, buttonOffsetY = 92, guiWidth = 252, guiHeight = 202, tabWidth = 28, tabHeight = 32,
borderWidthX = 8, borderWidthY = 17, tabOffsetX = 0, tabOffsetY = -12, innerWidth = 228, innerHeight = 158,
minDisplayColumn = AchievementList.minDisplayColumn * achievementSize - 10 * achievementSize,
minDisplayRow = AchievementList.minDisplayRow * achievementSize - 10 * achievementSize,
maxDisplayColumn = AchievementList.maxDisplayColumn * achievementSize,
maxDisplayRow = AchievementList.maxDisplayRow * achievementSize;
private static final float scaleJump = 0.25F, minZoom = 1.0F, maxZoom = 2.0F;
private static final Random random = new Random();
public static int colourUnlocked, colourCanUnlock, colourCantUnlock;
public static boolean scrollButtons, iconReset, userColourOverride, colourUnlockedRainbow, colourCanUnlockRainbow,
colourCantUnlockRainbow;
public static float[] colourUnlockedRainbowSettings, colourCanUnlockRainbowSettings,
colourCantUnlockRainbowSettings;
private GuiScreen prevScreen;
private StatisticsManager statisticsManager;
private int top, left;
private float scale;
private boolean pause, newDrag;
private int prevMouseX, prevMouseY;
private List<AchievementPage> pages;
private int currentPage, tabsOffset;
private static int lastPage = 0;
private int xPos, yPos;
private Achievement hoveredAchievement;
public GuiBetterAchievements(GuiScreen currentScreen, int page) {
this.prevScreen = currentScreen;
this.currentPage = page == 0 ? lastPage : page;
this.statisticsManager = Minecraft.getMinecraft().thePlayer.getStatFileWriter();
this.pause = true;
}
@Override
public void initGui() {
this.left = (this.width - guiWidth) / 2;
this.top = (this.height - guiHeight) / 2;
this.scale = 1.0F;
this.xPos = achievementSize * 3;
this.yPos = achievementSize;
this.buttonList.clear();
this.buttonList.add(new GuiButton(buttonDone, this.width / 2 + buttonOffsetX, this.height / 2 + buttonOffsetY,
80, 20, I18n.format("gui.done")));
if (scrollButtons) {
this.buttonList.add(new GuiButton(buttonPrev, this.left - 24, this.top - 5, 20, 20, "<"));
this.buttonList.add(new GuiButton(buttonNext, this.left + 256, this.top - 5, 20, 20, ">"));
}
this.hoveredAchievement = null;
this.pages = AchievementRegistry.instance().getAllPages();
this.tabsOffset = this.currentPage < maxTabs / 3 * 2 ? 0 : this.currentPage - maxTabs / 3 * 2;
if (this.tabsOffset < 0)
this.tabsOffset = 0;
AchievementPage page = this.pages.get(this.currentPage);
if (page instanceof ICustomScale)
this.scale = ((ICustomScale) page).setScale();
if (page instanceof ICustomPosition) {
Achievement center = ((ICustomPosition) page).setPositionOnLoad();
this.xPos = center.displayColumn * achievementSize + achievementSize * 3;
this.yPos = center.displayRow * achievementSize + achievementSize;
}
}
public void onGuiClosed() {
lastPage = this.currentPage;
}
@Override
protected void keyTyped(char c, int i) throws IOException {
if (i == this.mc.gameSettings.keyBindInventory.getKeyCode()) {
this.mc.displayGuiScreen(null);
this.mc.setIngameFocus();
} else if (i == Keyboard.KEY_LEFT) {
this.currentPage--;
if (currentPage < 0) {
this.currentPage = this.pages.size() - 1;
this.tabsOffset += (this.pages.size() / maxTabs) * maxTabs;
}
if (this.currentPage - this.tabsOffset < 0)
this.tabsOffset -= maxTabs;
if (this.tabsOffset < 0)
this.tabsOffset = 0;
} else if (i == Keyboard.KEY_RIGHT) {
this.currentPage++;
if (this.currentPage >= this.pages.size()) {
this.currentPage = 0;
this.tabsOffset = 0;
}
if (this.currentPage - this.tabsOffset >= maxTabs)
this.tabsOffset += maxTabs;
if (this.pages.size() <= this.tabsOffset)
this.tabsOffset = this.pages.size() - 1;
} else {
super.keyTyped(c, i);
}
}
@Override
protected void actionPerformed(GuiButton button) {
switch (button.id) {
case buttonDone:
this.mc.displayGuiScreen(this.prevScreen);
break;
case buttonPrev:
this.tabsOffset -= maxTabs;
if (this.tabsOffset == -maxTabs)
this.tabsOffset = this.pages.size() - maxTabs / 3 * 2;
if (this.tabsOffset < 0)
this.tabsOffset = 0;
break;
case buttonNext:
this.tabsOffset += maxTabs;
if (this.tabsOffset > this.pages.size())
this.tabsOffset = 0;
else if (this.tabsOffset > this.pages.size() - maxTabs / 3 * 2)
this.tabsOffset = this.pages.size() - maxTabs / 3 * 2;
break;
default:
break;
}
}
@Override
public boolean doesGuiPauseGame() {
return this.pause;
}
@Override
public void drawScreen(int mouseX, int mouseY, float renderPartialTicks) {
this.drawDefaultBackground();
AchievementPage page = this.pages.get(this.currentPage);
this.handleMouseInput(mouseX, mouseY, page);
this.drawUnselectedTabs(page);
GlStateManager.depthFunc(GL11.GL_GEQUAL);
GlStateManager.pushMatrix();
this.drawAchievementsBackground(page);
this.drawAchievements(page, mouseX, mouseY);
GlStateManager.popMatrix();
GlStateManager.enableBlend();
this.mc.getTextureManager().bindTexture(Resources.GUI.SPRITES);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.drawTexturedModalRect(this.left, this.top + tabHeight / 2, 0, 0, guiWidth, guiHeight);
this.drawCurrentTab(page);
this.fontRendererObj.drawString(page.getName() + " " + I18n.format("gui.achievements"), this.left + 15,
this.top + tabHeight / 2 + 5, 4210752);
super.drawScreen(mouseX, mouseY, renderPartialTicks);
this.drawMouseOverAchievement(mouseX, mouseY);
this.drawMouseOverTab(mouseX, mouseY);
}
private void handleMouseInput(int mouseX, int mouseY, AchievementPage page) {
doDrag(mouseX, mouseY);
if (onTab(mouseX, mouseY) != -1)
doTabScroll();
else
doZoom(page);
if (this.xPos < minDisplayColumn)
this.xPos = minDisplayColumn;
if (this.xPos > maxDisplayColumn)
this.xPos = maxDisplayColumn;
if (this.yPos < minDisplayRow)
this.yPos = minDisplayRow;
if (this.yPos > maxDisplayRow)
this.yPos = maxDisplayRow;
if (Mouse.isButtonDown(0))
handleMouseClick(mouseX, mouseY);
}
private void drawUnselectedTabs(AchievementPage selected) {
for (int i = this.tabsOffset; i < maxTabs + this.tabsOffset && this.pages.size() > i; i++) {
AchievementPage page = this.pages.get(i);
if (page == selected)
continue;
GlStateManager.disableLighting();
GlStateManager.enableBlend();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
int j = (i - this.tabsOffset) * tabWidth;
this.mc.getTextureManager().bindTexture(Resources.GUI.TABS);
this.drawTexturedModalRect(this.left + tabOffsetX + j, this.top + tabOffsetY, j, 0, tabWidth, tabHeight);
this.drawPageIcon(page, this.left + tabOffsetX + j, this.top + tabOffsetY);
}
}
private void drawCurrentTab(AchievementPage selected) {
for (int i = this.tabsOffset; i < maxTabs + this.tabsOffset && this.pages.size() > i; i++) {
AchievementPage page = this.pages.get(i);
if (page != selected)
continue;
GlStateManager.disableLighting();
GlStateManager.enableBlend();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
int j = (i - this.tabsOffset) * tabWidth;
this.mc.getTextureManager().bindTexture(Resources.GUI.TABS);
this.drawTexturedModalRect(this.left + tabOffsetX + j, this.top + tabOffsetY, j, 32, tabWidth, tabHeight);
this.drawPageIcon(page, this.left + tabOffsetX + j, this.top + tabOffsetY);
}
}
private void drawPageIcon(AchievementPage page, int tabLeft, int tabTop) {
ItemStack itemStack = AchievementRegistry.instance().getItemStack(page);
if (itemStack != null) {
this.zLevel = 100.0F;
itemRender.zLevel = 100.0F;
net.minecraft.client.renderer.RenderHelper.enableGUIStandardItemLighting();
GlStateManager.enableRescaleNormal();
itemRender.renderItemAndEffectIntoGUI(itemStack, tabLeft + 6, tabTop + 9);
itemRender.zLevel = 0.0F;
GlStateManager.disableLighting();
GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
this.zLevel = 0.0F;
}
}
private void drawAchievementsBackground(AchievementPage page) {
GlStateManager.translate(this.left, this.top + borderWidthY, -200.0F);
GlStateManager.enableTexture2D();
GlStateManager.disableLighting();
GlStateManager.enableRescaleNormal();
GlStateManager.enableColorMaterial();
if (page instanceof ICustomBackground) {
GlStateManager.pushMatrix();
((ICustomBackground) page).drawBackground(this.left, this.top, innerWidth + borderWidthX,
innerHeight + borderWidthY, this.zLevel, this.scale);
GlStateManager.popMatrix();
} else {
GlStateManager.pushMatrix();
float scaleInverse = 1.0F / this.scale;
GlStateManager.scale(scaleInverse, scaleInverse, 1.0F);
float scale = blockSize / this.scale;
int dragX = this.xPos - minDisplayColumn >> 4;
int dragY = this.yPos - minDisplayRow >> 4;
int antiJumpX = (this.xPos - minDisplayColumn) % 16;
int antiJumpY = (this.yPos - minDisplayRow) % 16;
// TODO: some smarter background gen
this.mc.getTextureManager().bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
for (int y = 1; y * scale - antiJumpY < innerHeight + borderWidthY; y++) {
float darkness = 0.7F - (dragY + y) / 80.0F;
GlStateManager.color(darkness, darkness, darkness, 1.0F);
this.mc.getTextureManager().bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
for (int x = 1; x * scale - antiJumpX < innerWidth + borderWidthX; x++) {
random.setSeed(this.mc.getSession().getPlayerID().hashCode() + dragY + y + (dragX + x) * 16);
int r = random.nextInt(1 + dragY + y) + (dragY + y) / 2;
TextureAtlasSprite icon = RenderHelper.getIcon(Blocks.GRASS);
if (r == 40) {
if (random.nextInt(3) == 0)
icon = RenderHelper.getIcon(Blocks.DIAMOND_ORE);
else
icon = RenderHelper.getIcon(Blocks.REDSTONE_ORE);
} else if (r == 20)
icon = RenderHelper.getIcon(Blocks.IRON_ORE);
else if (r == 12)
icon = RenderHelper.getIcon(Blocks.COAL_ORE);
else if (r > 60)
icon = RenderHelper.getIcon(Blocks.BEDROCK);
else if (r > 4)
icon = RenderHelper.getIcon(Blocks.STONE);
else if (r > 0)
icon = RenderHelper.getIcon(Blocks.DIRT);
this.drawTexturedModalRect(x * blockSize - antiJumpX, y * blockSize - antiJumpY, icon, blockSize,
blockSize);
}
}
GlStateManager.popMatrix();
}
GlStateManager.enableDepth();
GlStateManager.depthFunc(GL11.GL_LEQUAL);
}
private void drawArrow(Achievement achievement, int colourCantUnlock, int colourCanUnlock, int colourUnlocked) {
int depth = this.statisticsManager.countRequirementsUntilAvailable(achievement); // How
// far
// is
// the
// nearest
// unlocked
// parent
if (depth < 5) {
int achievementXPos = achievement.displayColumn * achievementSize - this.xPos + achievementInnerSize / 2;
int achievementYPos = achievement.displayRow * achievementSize - this.yPos + achievementInnerSize / 2;
int parentXPos = achievement.parentAchievement.displayColumn * achievementSize - this.xPos
+ achievementInnerSize / 2;
int parentYPos = achievement.parentAchievement.displayRow * achievementSize - this.yPos
+ achievementInnerSize / 2;
boolean unlocked = this.statisticsManager.hasAchievementUnlocked(achievement);
boolean canUnlock = this.statisticsManager.canUnlockAchievement(achievement);
int colour = colourCantUnlock;
if (unlocked)
colour = colourUnlocked;
else if (canUnlock)
colour = colourCanUnlock;
this.drawHorizontalLine(achievementXPos, parentXPos, achievementYPos, colour);
this.drawVerticalLine(parentXPos, achievementYPos, parentYPos, colour);
this.mc.getTextureManager().bindTexture(Resources.GUI.SPRITES);
GlStateManager.enableBlend();
if (achievementXPos > parentXPos)
this.drawTexturedModalRect(achievementXPos - achievementInnerSize / 2 - arrowHeadHeight,
achievementYPos - arrowOffset, arrowRightX, arrowRightY, arrowHeadHeight, arrowHeadWidth);
else if (achievementXPos < parentXPos)
this.drawTexturedModalRect(achievementXPos + achievementInnerSize / 2, achievementYPos - arrowOffset,
arrowLeftX, arrowLeftY, arrowHeadHeight, arrowHeadWidth);
else if (achievementYPos > parentYPos)
this.drawTexturedModalRect(achievementXPos - arrowOffset,
achievementYPos - achievementInnerSize / 2 - arrowHeadHeight, arrowDownX, arrowDownY,
arrowHeadWidth, arrowHeadHeight);
else if (achievementYPos < parentYPos)
this.drawTexturedModalRect(achievementXPos - arrowOffset, achievementYPos + achievementInnerSize / 2,
arrowUpX, arrowUpY, arrowHeadWidth, arrowHeadHeight);
}
}
private void drawAchievements(AchievementPage page, int mouseX, int mouseY) {
List<Achievement> achievements = new LinkedList<Achievement>(
AchievementRegistry.instance().getAchievements(page));
boolean customColours = page instanceof ICustomArrows;
int colourCantUnlock = !userColourOverride && customColours
? ((ICustomArrows) page).getColourForCantUnlockArrow()
: (GuiBetterAchievements.colourCantUnlockRainbow
? ColourHelper.getRainbowColour(GuiBetterAchievements.colourCantUnlockRainbowSettings)
: GuiBetterAchievements.colourCantUnlock);
int colourCanUnlock = !userColourOverride && customColours ? ((ICustomArrows) page).getColourForCanUnlockArrow()
: (GuiBetterAchievements.colourCanUnlockRainbow
? ColourHelper.getRainbowColour(GuiBetterAchievements.colourCanUnlockRainbowSettings)
: GuiBetterAchievements.colourCanUnlock);
int colourUnlocked = !userColourOverride && customColours ? ((ICustomArrows) page).getColourForUnlockedArrow()
: (GuiBetterAchievements.colourUnlockedRainbow
? ColourHelper.getRainbowColour(GuiBetterAchievements.colourUnlockedRainbowSettings)
: GuiBetterAchievements.colourUnlocked);
Collections.reverse(achievements);
GlStateManager.pushMatrix();
float inverseScale = 1.0F / scale;
GlStateManager.scale(inverseScale, inverseScale, 1.0F);
for (Achievement achievement : achievements)
if (achievement.parentAchievement != null && achievements.contains(achievement.parentAchievement))
this.drawArrow(achievement, colourCantUnlock, colourCanUnlock, colourUnlocked);
for (Achievement achievement : achievements) {
drawAchievement(achievement);
if (onAchievement(achievement, mouseX, mouseY))
this.hoveredAchievement = achievement;
}
GlStateManager.popMatrix();
}
private void drawAchievement(Achievement achievement) {
int achievementXPos = achievement.displayColumn * achievementSize - this.xPos;
int achievementYPos = achievement.displayRow * achievementSize - this.yPos;
if (!onScreen(achievementXPos, achievementYPos))
return;
int depth = this.statisticsManager.countRequirementsUntilAvailable(achievement);
boolean unlocked = this.statisticsManager.hasAchievementUnlocked(achievement);
boolean canUnlock = this.statisticsManager.canUnlockAchievement(achievement);
boolean special = achievement.getSpecial();
float brightness;
if (unlocked)
brightness = 0.75F;
else if (canUnlock)
brightness = 1.0F;
else if (depth < 3)
brightness = 0.3F;
else if (depth < 4)
brightness = 0.2F;
else if (depth < 5)
brightness = 0.1F;
else
return;
if (achievement instanceof ICustomBackgroundColour) {
int colour = ((ICustomBackgroundColour) achievement).recolourBackground(brightness);
GlStateManager.color((colour >> 16 & 255) / 255.0F, (colour >> 8 & 255) / 255.0F, (colour & 255) / 255.0F,
1.0F);
} else
GlStateManager.color(brightness, brightness, brightness, 1.0F);
this.mc.getTextureManager().bindTexture(Resources.GUI.SPRITES);
GlStateManager.enableBlend();
if (special)
this.drawTexturedModalRect(achievementXPos - achievementOffset, achievementYPos - achievementOffset,
achievementX + achievementTextureSize, achievementY, achievementTextureSize,
achievementTextureSize);
else
this.drawTexturedModalRect(achievementXPos - achievementOffset, achievementYPos - achievementOffset,
achievementX, achievementY, achievementTextureSize, achievementTextureSize);
if (achievement instanceof ICustomIconRenderer) {
GlStateManager.pushMatrix();
((ICustomIconRenderer) achievement).renderIcon(achievementXPos, achievementYPos);
GlStateManager.popMatrix();
} else {
RenderItem renderItem = RenderHelper.getRenderItem();
if (!canUnlock) {
GlStateManager.color(0.1F, 0.1F, 0.1F, 1.0F);
renderItem.isNotRenderingEffectsInGUI(false);
}
net.minecraft.client.renderer.RenderHelper.enableGUIStandardItemLighting();
GlStateManager.enableCull();
renderItem.renderItemAndEffectIntoGUI(achievement.theItemStack, achievementXPos + 3, achievementYPos + 3);
if (!canUnlock)
renderItem.isNotRenderingEffectsInGUI(true);
}
GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GlStateManager.disableLighting();
}
private void drawMouseOverAchievement(int mouseX, int mouseY) {
if (this.hoveredAchievement == null || !inInnerScreen(mouseX, mouseY))
return;
if (Mouse.isButtonDown(1)) {
this.pause = false;
MessageHandler.INSTANCE.sendToServer(new AchievementUnlockMessage(this.hoveredAchievement));
} else {
this.pause = true;
}
if (iconReset && Mouse.isButtonDown(2)) {
AchievementRegistry.instance().registerIcon(this.pages.get(this.currentPage).getName(),
this.hoveredAchievement.theItemStack, true);
}
int tooltipX = mouseX + 12;
int tooltipY = mouseY - 4;
if (this.hoveredAchievement instanceof ICustomTooltip)
((ICustomTooltip) this.hoveredAchievement).renderTooltip(mouseX, mouseY, this.statisticsManager);
else {
String title = this.hoveredAchievement.getStatName().getUnformattedText();
String desc = this.hoveredAchievement.getDescription();
int depth = this.statisticsManager.countRequirementsUntilAvailable(this.hoveredAchievement);
boolean unlocked = this.statisticsManager.hasAchievementUnlocked(this.hoveredAchievement);
boolean canUnlock = this.statisticsManager.canUnlockAchievement(this.hoveredAchievement);
boolean special = this.hoveredAchievement.getSpecial();
int tooltipWidth = defaultTooltipWidth;
if (!canUnlock) {
if (depth > 3)
return;
else
desc = this.getChatComponentTranslation("achievement.requires",
this.hoveredAchievement.parentAchievement.getStatName());
if (depth == 3)
title = I18n.format("achievement.unknown");
}
tooltipWidth = Math.max(this.fontRendererObj.getStringWidth(title), tooltipWidth);
int tooltipHeight = this.fontRendererObj.splitStringWidth(desc, tooltipWidth);
if (unlocked)
tooltipHeight += lineSize;
this.drawGradientRect(tooltipX - achievementTooltipOffset, tooltipY - achievementTooltipOffset,
tooltipX + tooltipWidth + achievementTooltipOffset,
tooltipY + tooltipHeight + achievementTooltipOffset + lineSize, -1073741824, -1073741824);
this.fontRendererObj.drawStringWithShadow(title, tooltipX, tooltipY,
canUnlock ? (special ? -128 : -1) : (special ? -8355776 : -8355712));
this.fontRendererObj.drawSplitString(desc, tooltipX, tooltipY + lineSize, tooltipWidth, -6250336);
if (unlocked)
this.fontRendererObj.drawStringWithShadow(I18n.format("achievement.taken"), tooltipX,
tooltipY + tooltipHeight + 4, -7302913);
}
this.hoveredAchievement = null;
}
private void drawMouseOverTab(int mouseX, int mouseY) {
int onTab = onTab(mouseX, mouseY);
if (onTab == -1 || this.pages.size() <= onTab)
return;
AchievementPage page = pages.get(onTab);
List<String> tooltip = new LinkedList<String>();
tooltip.add(page.getName());
drawHoveringText(tooltip, mouseX, mouseY, this.fontRendererObj);
}
private void handleMouseClick(int mouseX, int mouseY) {
int onTab = onTab(mouseX, mouseY);
if (onTab == -1 || this.pages.size() <= onTab || this.currentPage == onTab)
return;
this.currentPage = onTab;
AchievementPage page = this.pages.get(this.currentPage);
if (page instanceof ICustomScale && ((ICustomScale) page).resetScaleOnLoad())
this.scale = ((ICustomScale) page).setScale();
if (page instanceof ICustomPosition) {
Achievement center = ((ICustomPosition) page).setPositionOnLoad();
this.xPos = center.displayColumn * achievementSize + achievementSize * 3;
this.yPos = center.displayRow * achievementSize + achievementSize;
}
}
private void doTabScroll() {
int dWheel = Mouse.getDWheel();
if (dWheel < 0)
this.tabsOffset--;
else if (dWheel > 0)
this.tabsOffset++;
if (this.tabsOffset > this.pages.size() - maxTabs / 3 * 2)
this.tabsOffset = this.pages.size() - maxTabs / 3 * 2;
if (this.tabsOffset < 0)
this.tabsOffset = 0;
}
private void doZoom(AchievementPage page) {
int dWheel = Mouse.getDWheel();
float prevScale = this.scale;
if (dWheel < 0)
this.scale += scaleJump;
else if (dWheel > 0)
this.scale -= scaleJump;
boolean customScale = page instanceof ICustomScale;
float minZoom = customScale ? ((ICustomScale) page).getMinScale() : GuiBetterAchievements.minZoom;
float maxZoom = customScale ? ((ICustomScale) page).getMaxScale() : GuiBetterAchievements.maxZoom;
this.scale = MathHelper.clamp_float(this.scale, minZoom, maxZoom);
if (this.scale != prevScale) {
float prevScaledWidth = prevScale * this.width;
float prevScaledHeight = prevScale * this.height;
float newScaledWidth = this.scale * this.width;
float newScaledHeight = this.scale * this.height;
this.xPos -= (newScaledWidth - prevScaledWidth) / 2;
this.yPos -= (newScaledHeight - prevScaledHeight) / 2;
}
}
private void doDrag(int mouseX, int mouseY) {
if (Mouse.isButtonDown(0)) {
if (inInnerScreen(mouseX, mouseY)) {
if (this.newDrag)
this.newDrag = false;
else {
this.xPos -= (mouseX - this.prevMouseX) * scale;
this.yPos -= (mouseY - this.prevMouseY) * scale;
}
this.prevMouseX = mouseX;
this.prevMouseY = mouseY;
}
} else {
this.newDrag = true;
}
}
private boolean inInnerScreen(int mouseX, int mouseY) {
return mouseX > this.left + borderWidthX && mouseX < this.left + guiWidth - borderWidthX
&& mouseY > this.top + borderWidthY && mouseY < this.top + guiHeight - borderWidthY;
}
private boolean onAchievement(Achievement achievement, int mouseX, int mouseY) {
int achievementXPos = achievement.displayColumn * achievementSize - this.xPos;
int achievementYPos = achievement.displayRow * achievementSize - this.yPos + achievementInnerSize;
return mouseX > this.left + achievementXPos / scale
&& mouseX < this.left + (achievementXPos + achievementInnerSize) / scale
&& mouseY > this.top + achievementYPos / scale
&& mouseY < this.top + (achievementYPos + achievementInnerSize) / scale;
}
/**
* Get the index of the tab the mouse is on
*
* @param mouseX
* x coord of the mouse
* @param mouseY
* y coord of the mouse
* @return -1 if not on a tab otherwise the index
*/
private int onTab(int mouseX, int mouseY) {
if (mouseX > this.left + tabOffsetX && mouseX < this.left + guiWidth && mouseY > this.top + tabOffsetY
&& mouseY < this.top + tabOffsetY + tabHeight) {
return ((mouseX - (this.left + tabOffsetX)) / tabWidth) + tabsOffset;
}
return -1;
}
private boolean onScreen(int x, int y) {
return x > 0 && x < guiWidth * scale - achievementSize && y > 0 && y < guiHeight * scale - achievementSize;
}
private String getChatComponentTranslation(String s, Object... objects) {
return (new TextComponentTranslation(s, objects)).getUnformattedText();
}
}
<file_sep>/src/main/java/betterthanachievements/achievements/ReloadSyncCommand.java
package betterthanachievements.achievements;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import betterachievements.handler.MessageHandler;
import betterachievements.handler.message.ConfigFetchMessage;
import betterthanachievements.BetterThanAchievements;
import betterthanachievements.Config;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.UserListOpsEntry;
import net.minecraft.util.math.BlockPos;
public class ReloadSyncCommand implements ICommand {
@Override
public int compareTo(ICommand o) {
return 0;
}
@Override
public String getCommandName() {
return "achreload";
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "/achreload";
}
@Override
public List<String> getCommandAliases() {
ArrayList aliases = new ArrayList();
aliases.add("rsc");
return aliases;
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
Config.loadConfig(BetterThanAchievements.confpath);
File x = new File(BetterThanAchievements.confpath + "/betterthanachievements/betterthanachievements.cfg");
try {
String data = BetterThanAchievements.readFile(x.getAbsolutePath(), StandardCharsets.UTF_8);
MessageHandler.INSTANCE.sendToAll(new ConfigFetchMessage(data));
} catch (IOException e) {
}
}
@Override
public boolean checkPermission(MinecraftServer server, ICommandSender sender) {
if (sender instanceof EntityPlayerMP) {
EntityPlayerMP x = (EntityPlayerMP) sender;
UserListOpsEntry i = server.getPlayerList().getOppedPlayers().getEntry(x.getGameProfile());
if (i != null && i.getPermissionLevel() > 0) {
return true;
}
}
return false;
}
@Override
public List<String> getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args,
BlockPos pos) {
return null;
}
@Override
public boolean isUsernameIndex(String[] args, int index) {
return false;
}
}
<file_sep>/src/main/java/betterthanachievements/AchievementsCheckBlockTilentity.java
package betterthanachievements;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.stats.Achievement;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class AchievementsCheckBlockTilentity extends TileEntity {
private int achievement;
private Long timestamp;
private boolean isGiveBlock;
public AchievementsCheckBlockTilentity() {
this.achievement = 0;
this.isGiveBlock = true;
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
achievement = tag.getInteger("achievement");
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag) {
tag.setInteger("achievement", achievement);
return super.writeToNBT(tag);
}
@Override
public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState) {
return oldState.getBlock() != newState.getBlock();
}
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
NBTTagCompound syncData = new NBTTagCompound();
syncData.setInteger("achievement", this.achievement);
return new SPacketUpdateTileEntity(this.pos, this.getBlockMetadata(), syncData);
}
void setAchievementInt(Integer i) {
this.achievement = i;
}
Integer getAchievementInt() {
return this.achievement;
}
boolean onCollision(EntityPlayerMP player) {
if (timestamp == null || BetterThanAchievements.unixtime() - timestamp >= 1L) {
timestamp = BetterThanAchievements.unixtime();
Achievement unlockable = BetterThanAchievements.getAchievement(achievement);
if (unlockable != null) {
if (!player.getStatFile().hasAchievementUnlocked(unlockable)) {
player.addStat(unlockable, 1);
player.worldObj.playSound(null, getPos(), BetterThanAchievements.proxy.achievement_hitblock,
SoundCategory.RECORDS, 0.5F, 1F);
return false;
} else {
return true;
}
}
}
return false;
}
}
<file_sep>/src/main/java/betterthanachievements/proxy/CommonProxy.java
package betterthanachievements.proxy;
import java.io.File;
import betterachievements.handler.AchievementHandler;
import betterachievements.handler.ConfigHandler;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class CommonProxy {
public static SoundEvent achievement_hitblock;
public void setupTextures() {
}
public void registerHandlers() {
MinecraftForge.EVENT_BUS.register(AchievementHandler.getInstance());
}
public void initConfig(String configDir) {
}
/**
* Register the {@link SoundEvent}s.
*/
public static void registerSounds() {
achievement_hitblock = registerSound("achievement.hitblock");
}
/**
* Register a {@link SoundEvent}.
*
* @param soundName
* The SoundEvent's name without the testmod3 prefix
* @return The SoundEvent
*/
private static SoundEvent registerSound(String soundName) {
final ResourceLocation soundID = new ResourceLocation(betterachievements.reference.Reference.RESOURCE_ID,
soundName);
return GameRegistry.register(new SoundEvent(soundID).setRegistryName(soundID));
}
}
<file_sep>/src/main/java/betterachievements/gui/ModGuiConfig.java
package betterachievements.gui;
import betterachievements.handler.ConfigHandler;
import betterachievements.reference.Reference;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.client.config.GuiConfig;
public class ModGuiConfig extends GuiConfig {
public ModGuiConfig(GuiScreen guiScreen) {
super(guiScreen, ConfigHandler.getConfigElements(), Reference.RESOURCE_ID, false, false,
GuiConfig.getAbridgedConfigPath(ConfigHandler.config.toString()));
}
}
|
9cb8c0bed0351cb878af7bc8881724a6a9a2e617
|
[
"Java"
] | 19 |
Java
|
alekso56/BetterThanAchievements
|
3b0d6f3d1966a861c8c8c7ffdfd5ec8d0b084072
|
a40d8384742c98ba3a54f7a6beaedc09c13753fc
|
refs/heads/master
|
<file_sep>import React from 'react'
import {Navbar,NavbarBrand,NavItem,NavLink,Nav} from "reactstrap"
import "../node_modules/bootstrap/dist/css/bootstrap.min.css"
export default function App() {
return (
<div>
<Navbar color="warning">
<NavbarBrand>
ARTOCART
</NavbarBrand>
<Nav className="ml-auto" navbar>
<NavItem>
<NavLink>Login</NavLink>
<NavLink>signup</NavLink>
</NavItem>
</Nav>
</Navbar>
</div>
)
}
|
fde0853415619c0c13b335e6707875cef55ff6b2
|
[
"JavaScript"
] | 1 |
JavaScript
|
github-byte/artocart
|
aa396489bc322f8aea4011b44f94cc6a79b6ff8d
|
c5c551ed8d79f78b6225a5919048b6c2b13ae224
|
refs/heads/master
|
<file_sep>export interface IGoal {
goal: string,
currency: string,
funds: string,
status: string
}<file_sep>export const Colors = {
white: '#ffffff',
green: '#2fd490',
primary: '#34495e',
offWhite: '#bdc3c7',
cloud: '#ecf0f1',
grey: '#95a5a6',
danger: '#e74c3c'
}
export const Spacing = {
general: 8
}
export const FontSize = {
normal: 14,
title: 24,
SectionTitle: 20,
miniTitle: 18,
footNote: 12
}
export const Sizing = {
buttonHeight: 44
}
<file_sep>export interface IGoal {
goal: string,
currency: string,
funds: string,
status: string
}
export const GoalsData: IGoal[] = [
{
goal: 'Goal 1',
currency: 'KES',
funds: '12,000',
status: 'Finish Goal'
},
{
goal: 'Goal 2',
currency: 'KES',
funds: '12,000',
status: 'Finish Goal'
},
]
export const StaticText = {
toastFullText: "This is an in-app notification snackbar to show the user when they perform an action. Clicking it should change the text.",
toastShotText: "User clicked snackbar"
}
|
05ba7da5ff350292e8d7086c5732932399388915
|
[
"TypeScript"
] | 3 |
TypeScript
|
kwesihackman/cashlet-app
|
b1f3f7e3b531a47d93b76c205c45e28957f1bd6f
|
9e2f8cd2c5cf919bde5875ea97de32f54187bc12
|
refs/heads/master
|
<repo_name>sandrahfiestas/Spotify-clon<file_sep>/src/components/ListOfSongs.jsx
import React from 'react';
function ListOfSong() {
return (
<>
<h1>Lista de canciones</h1>
</>
);
}
export default ListOfSong;
<file_sep>/src/components/CardsPlaylists.jsx
/* eslint-disable no-unused-vars */
import React from 'react';
import { Link } from 'react-router-dom';
import { useDataLayerValue } from '../DataLayer';
import { ReactComponent as PlayIcon } from '../images/icons/play.svg';
function CardsPlaylist() {
const [{ weekly }, dispatch] = useDataLayerValue();
// console.log('semanal', weekly);
// Top artists
// const [{ topArtists }, dispatch] = useDataLayerValue();
// console.log('Artistas Top 🤯👉 ', topArtists);
// const [{ topTracks }, dispatch] = useDataLayerValue();
// console.log('Pistas principales 🎶', topTracks);
// const [{ categories }, dispatch] = useDataLayerValue();
// console.log('Categorias 💪', categories);
return (
<section className="container-cardsPlaylist">
<div className="container-cardsPlaylist__title">
<Link to="/allsongs" className="container-cardsPlaylist__title-p">
{/* Tus Mejores Artistas */}
{weekly?.name}
</Link>
<Link to="/allCards" className="container-cardsPlaylist__title-all">
VER TODO
</Link>
</div>
<div className="container-cardsPlaylist__cards">
{/* {topArtists?.items?.map((topArtist) => (
<div className="container-cardsPlaylist__card" key={topArtist.id}> */}
<div className="container-cardsPlaylist__card">
<img
// src={topArtist.images[0].url}
src={weekly?.images[0].url}
className="container-cardsPlaylist__card-img"
// alt={topArtist.name}
alt=""
/>
<PlayIcon className="container-cardsPlaylist__card-icon container-cardsPlaylist__card-icon--disabled" />
<p className="container-cardsPlaylist__card-name">
{/* {topArtist.name} */}
{weekly?.name}
</p>
<p className="container-cardsPlaylist__card-p">
{/* {topArtist.genres.join(', ')} */}
{weekly?.description}
</p>
</div>
{/* ))} */}
</div>
</section>
);
}
export default CardsPlaylist;
<file_sep>/src/components/Header.jsx
/* eslint-disable no-unused-vars */
import React from 'react';
import { useHistory } from 'react-router-dom';
import Time from './Time';
import { ReactComponent as HistoryIcon } from '../images/icons/history.svg';
import { ReactComponent as SettingsIcon } from '../images/icons/settings.svg';
import { ReactComponent as PreviousBtnIcon } from '../images/icons/btn-left.svg';
import { ReactComponent as NextBtnIcon } from '../images/icons/btn-right.svg';
import profile from '../images/profile.png';
import { useDataLayerValue } from '../DataLayer';
function Header() {
const [{ user }, dispatch] = useDataLayerValue();
const history = useHistory();
return (
<header className="header">
<div className="header__left">
<Time />
</div>
<div className="header__right">
<HistoryIcon className="header__right-icon" />
<SettingsIcon className="header__right-icon" />
</div>
<div className="header__queries header__queries--disabled">
<div className="header__queries-btns">
<PreviousBtnIcon
className="header__queries-btns-previous"
onClick={history.goBack}
/>
<NextBtnIcon
className="header__queries-btns-next"
onClick={history.goForward}
/>
</div>
<div className="header__queries-user">
<img
src={user?.images[0]?.url}
onError={(e) => {
e.target.onerror = null;
e.target.src = { profile };
}}
// src={profile}
alt="Profile"
className="header__queries-user-photo"
/>
<p className="header__queries-user-name">{user?.display_name}</p>
</div>
</div>
</header>
);
}
export default Header;
<file_sep>/src/components/Time.jsx
import React from 'react';
function time() {
const date = new Date();
const hours = date.getHours();
let current = '';
if (hours >= 0 && hours < 12) { current = 'Buenos días'; }
if (hours >= 12 && hours < 18) { current = 'Buenas tardes'; }
if (hours >= 18 && hours < 24) { current = 'Buenas noches'; }
return (
<p className="time-current">{current}</p>
);
}
export default time;
<file_sep>/src/components/Sidebar.jsx
import React from 'react';
import { NavLink } from 'react-router-dom';
import { ReactComponent as PremiumIcon } from '../images/icons/logo.svg';
import { ReactComponent as HomeIcon } from '../images/icons/home.svg';
import { ReactComponent as SearchIcon } from '../images/icons/search.svg';
import { ReactComponent as LibraryIcon } from '../images/icons/library.svg';
import LibraryList from './LibraryList';
function Sidebar() {
return (
<aside className="sidebar sidebar--disabled">
<NavLink
exact
to="/"
>
<div className="sidebar__title">
<PremiumIcon className="sidebar__title-icon" />
<p className="sidebar__title-text">Spotifu</p>
<span className="sidebar__title-trademark ">®</span>
</div>
</NavLink>
<div className="sidebar__menu">
<nav>
<ul>
<li>
<NavLink
exact
to="/"
className="sidebar__item"
activeClassName="sidebar__item--active"
>
<HomeIcon className="sidebar__item-icon" />
<p className="sidebar__item-text">Inicio</p>
</NavLink>
</li>
<li>
<NavLink
exact
to="/search"
className="sidebar__item"
activeClassName="sidebar__item--active"
>
<SearchIcon className="sidebar__item-icon" />
<p className="sidebar__item-text">Buscar</p>
</NavLink>
</li>
<li>
<NavLink
to="/library"
className="sidebar__item"
activeClassName="sidebar__item--active"
>
<LibraryIcon className="sidebar__item-icon" />
<p className="sidebar__item-text">Tu Biblioteca</p>
</NavLink>
</li>
</ul>
</nav>
</div>
<LibraryList />
</aside>
);
}
export default Sidebar;
<file_sep>/src/pages/Library.jsx
import React from 'react';
import { NavLink } from 'react-router-dom';
import Header from '../components/Header';
import Sidebar from '../components/Sidebar';
import Footer from '../components/Footer';
function Library() {
return (
<div className="wrapper">
<Header />
<Sidebar />
<div className="container-library">
<div className="container-library__menu">
<NavLink
to="/library/playlists"
className="container-library__menu-item"
activeClassName="container-library__menu-item--active"
>
Playlists
</NavLink>
<NavLink
to="/library/podcasts"
className="container-library__menu-item"
activeClassName="container-library__menu-item--active"
>
Podcasts
</NavLink>
<NavLink
to="/library/artists"
className="container-library__menu-item"
activeClassName="container-library__menu-item--active"
>
Artistas
</NavLink>
<NavLink
to="/library/albums"
className="container-library__menu-item"
activeClassName="container-library__menu-item--active"
>
Álbunes
</NavLink>
</div>
{/* <h1>Biblioteca</h1> */}
</div>
<Footer />
</div>
);
}
export default Library;
<file_sep>/src/components/LibraryContent.jsx
import React from 'react';
function LibraryContent() {
return (
<div>
CONTENIDO
</div>
);
}
export default LibraryContent;
<file_sep>/README.md
<div align="center">
<img width="120px" src="https://github.com/no-te-rindas/logo/raw/main/Logo/LeonidasEsteban-destello-envolvente-cuadrada.png" />
</div>
# Spotifu
Maquetación de la Plataforma líder a nivel global en consumo de música bajo demanda, permite a miles de usuarios escuchar sus canciones favoritas, crear playlist personalizadas y ayudales a descubrir nuevas canciones.
## Desktop
Aplicación de escritorio.

## Mobile
Aplicación para celulares.



***
<file_sep>/src/App.js
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect } from 'react';
import './css/Styles.css';
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from 'react-router-dom';
import SpotifyWebApi from 'spotify-web-api-js';
import { getTokenFromUrl } from './spotify';
import { useDataLayerValue } from './DataLayer';
import Login from './pages/Login';
import Home from './pages/Home';
import AllCards from './pages/AllCards';
import Search from './pages/Search';
import LibraryRouter from './routers/LibraryRouter';
import AllSongs from './pages/AllSongs';
const spotify = new SpotifyWebApi();
function App() {
const [{ token }, dispatch] = useDataLayerValue();
useEffect(() => {
const hash = getTokenFromUrl();
window.location.hash = '';
// eslint-disable-next-line no-underscore-dangle
const _token = hash.access_token;
if (_token) {
dispatch({
type: 'SET_TOKEN',
token: _token,
});
spotify.setAccessToken(_token);
// eslint-disable-next-line no-shadow
spotify.getMe().then((user) => {
dispatch({
type: 'SET_USER',
user,
});
});
spotify.getUserPlaylists().then((playlists) => {
dispatch({
type: 'SET_PLAYLISTS',
playlists,
});
});
spotify.getPlaylist('37i9dQZEVXcJZyENOWUFo7').then((response) => {
dispatch({
type: 'SET_DISCOVER_WEEKLY',
discover_weekly: response,
});
});
spotify.getPlaylist('37i9dQZEVXcJS1p21VGSBi').then((response) => {
dispatch({
type: 'SET_WEEKLY',
weekly: response,
});
});
spotify.getMyTopArtists().then((response) => {
dispatch({
type: 'SET_TOP_ARTISTS',
topArtists: response,
});
});
spotify.getMyRecentlyPlayedTracks().then((response) => {
dispatch({
type: 'SET_RECENTLY_PLAYED_TRACKS',
recentlyPlayedTracks: response,
});
});
spotify.getMyTopTracks().then((response) => {
dispatch({
type: 'SET_TOP_TRACKS',
topTracks: response,
});
});
// spotify.getCategories().then((response) => {
// dispatch({
// type: 'SET_CATEGORIES',
// categories: response,
// });
// });
// spotify.().then((response) => {
// dispatch({
// type: 'SET_SAVED_ALBUMS',
// savedAlbums: response,
// });
// });
}
}, []);
// console.log('usuario 🧡', user);
// console.log('token 😱', token);
return (
<Router>
<Switch>
<Route exact path="/">
{token ? <Home spotify={spotify} /> : <Login />}
</Route>
<Route exact path="/home" component={Home} />
<Route exact path="/allCards" component={AllCards} />
<Route exact path="/allsongs" component={AllSongs} />
<Route exact path="/search" component={Search} />
<Route path="/library" component={LibraryRouter} />
<Route path="/404">
<h1>404 Not found</h1>
</Route>
<Route path="*">
<Redirect to="/404" />
</Route>
</Switch>
</Router>
);
}
export default App;
<file_sep>/src/pages/AllCards.jsx
/* eslint-disable no-unused-vars */
import React from 'react';
import Header from '../components/Header';
import Sidebar from '../components/Sidebar';
import Footer from '../components/Footer';
import { useDataLayerValue } from '../DataLayer';
import { ReactComponent as PlayIcon } from '../images/icons/play.svg';
function AllCards() {
const [{ topArtists }, dispatch] = useDataLayerValue();
return (
<div className="wrapper">
<Header />
<Sidebar />
<div className="container-allCards">
<p className="container-allCards-title">Tus Mejores Artistas</p>
<div className="container-allCards__allcards">
{topArtists?.items?.map((topArtist) => (
<div className="container-allCards__card" key={topArtist.id}>
<img
src={topArtist.images[0].url}
className="container-allCards__card-img"
alt={topArtist.name}
/>
<PlayIcon className="container-allCards__card-icon container-allCards__card-icon--disabled" />
<div className="container-allCards__card-detail">
<p className="container-allCards__card-detail-name">{topArtist.name}</p>
<p className="container-allCards__card-detail-p">
{topArtist.genres.join(', ')}
</p>
</div>
</div>
))}
</div>
</div>
<Footer />
</div>
);
}
export default AllCards;
<file_sep>/src/routers/LibraryRouter.js
import React from 'react';
// import { NavLink, Route, Switch } from 'react-router-dom';
import Header from '../components/Header';
import Sidebar from '../components/Sidebar';
import Footer from '../components/Footer';
// import LibraryContent from '../components/LibraryContent';
import { ReactComponent as LibraryIcon } from '../images/icons/library.svg';
function LibraryRouter() {
return (
<>
<div className="wrapper">
<Header />
<Sidebar />
<div className="library">
<div className="library__divImg">
<LibraryIcon className="library__divImg-icon" />
</div>
</div>
{/* <div className="container-library">
<div className="container-library__menu">
<NavLink
to="/library/playlists"
className="container-library__menu-item"
activeClassName="container-library__menu-item--active"
>
Playlists
</NavLink>
<NavLink
to="/library/podcasts"
className="container-library__menu-item"
activeClassName="container-library__menu-item--active"
>
Podcasts
</NavLink>
<NavLink
to="/library/artists"
className="container-library__menu-item"
activeClassName="container-library__menu-item--active"
>
Artistas
</NavLink>
<NavLink
to="/library/albums"
className="container-library__menu-item"
activeClassName="container-library__menu-item--active"
>
Álbunes
</NavLink>
</div>
<h1>Biblioteca</h1>
</div> */}
<Footer />
</div>
{/* <Switch>
<Route exact path="/library/playlists" component={LibraryContent} />
</Switch> */}
</>
);
}
export default LibraryRouter;
<file_sep>/src/components/CardsPlaylistRecently.jsx
/* eslint-disable no-unused-vars */
import React from 'react';
import { useDataLayerValue } from '../DataLayer';
import { ReactComponent as PlayIcon } from '../images/icons/play.svg';
function CardsPlaylist() {
const [{ recentlyPlayedTracks }, dispatch] = useDataLayerValue();
// console.log('Recientemente 😃', recentlyPlayedTracks);
// const [{ topArtists }, dispatch] = useDataLayerValue();
// console.log('Artistas Top 🤯👉 ', topArtists);
// const [{ topTracks }, dispatch] = useDataLayerValue();
// console.log('Pistas principales 🎶', topTracks);
// const [{ categories }, dispatch] = useDataLayerValue();
// console.log('Categorias 💪', categories);
return (
<section className="container-cardsPlaylist">
<div className="container-cardsPlaylist__title">
<p>Escuchado recientemente</p>
</div>
<div className="container-cardsPlaylist__cards">
{recentlyPlayedTracks?.items?.map((recentlyPlayedTrack) => (
<div
className="container-cardsPlaylist__card"
key={recentlyPlayedTrack.track.id}
>
<img
src={recentlyPlayedTrack.track.album.images[0].url}
className="container-cardsPlaylist__card-img"
alt={recentlyPlayedTrack.track.name}
/>
<PlayIcon className="container-cardsPlaylist__card-icon container-cardsPlaylist__card-icon--disabled" />
<p className="container-cardsPlaylist__card-name">
{recentlyPlayedTrack.track.name}
</p>
<p className="container-cardsPlaylist__card-p">
{recentlyPlayedTrack.track.album.name}
</p>
</div>
))}
</div>
</section>
);
}
export default CardsPlaylist;
<file_sep>/src/reducer.js
/* eslint-disable max-len */
export const initialState = {
user: null,
playlists: [],
playing: false,
item: null,
topArtists: null,
recentlyPlayedTracks: null,
topTracks: null,
categories: null,
savedAlbums: null,
// token: null,
// token:
// // eslint-disable-next-line max-len
// '<KEY>',
};
const reducer = (state, action) => {
// console.log('reducer_action👉', action);
// Action -> type, [payload]
switch (action.type) {
case 'SET_USER':
return {
...state,
user: action.user,
};
case 'SET_TOKEN':
return {
...state,
token: action.token,
};
case 'SET_PLAYLISTS':
return {
...state,
playlists: action.playlists,
};
case 'SET_DISCOVER_WEEKLY':
return {
...state,
discover_weekly: action.discover_weekly,
};
case 'SET_WEEKLY':
return {
...state,
weekly: action.weekly,
};
case 'SET_TOP_ARTISTS':
return {
...state,
topArtists: action.topArtists,
};
case 'SET_RECENTLY_PLAYED_TRACKS':
return {
...state,
recentlyPlayedTracks: action.recentlyPlayedTracks,
};
case 'SET_TOP_TRACKS':
return {
...state,
topTracks: action.topTracks,
};
// case 'SET_CATEGORIES':
// return {
// ...state,
// categories: action.categories,
// };
// case 'SET_SAVED_ALBUMS':
// return {
// ...state,
// savedAlbums: action.savedAlbums,
// };
default:
return state;
}
};
export default reducer;
<file_sep>/src/pages/Login.jsx
import React from 'react';
import { ReactComponent as Logo } from '../images/icons/logo.svg';
import { loginUrl } from '../spotify';
function Login() {
return (
<div className="login">
<Logo className="login__logo" />
<p className="login__title">
Millones de canciones.
<br />
Gratis en Spotify.
</p>
<a href={loginUrl} className="login__button">
Login with Spotify
</a>
</div>
);
}
export default Login;
<file_sep>/src/components/LibraryList.jsx
/* eslint-disable no-unused-vars */
import React from 'react';
import { useDataLayerValue } from '../DataLayer';
function LibraryList() {
const [{ playlists }, dispatch] = useDataLayerValue();
// console.log('playlist✨', playlists);
return (
<div className="container-libraryList">
{playlists?.items?.map((playlist) => (
<div key={playlist.id}>
<p className="container-libraryList__text">{playlist.name}</p>
</div>
))}
</div>
);
}
export default LibraryList;
|
5afbb24c30abb4dd65ac3dc420c6397fb540827c
|
[
"JavaScript",
"Markdown"
] | 15 |
JavaScript
|
sandrahfiestas/Spotify-clon
|
2766d1fe1e9715b9cecd12b15cccdb9f8905566e
|
c785c5cfa497dd9a8b85562db1fda6b48756c703
|
refs/heads/main
|
<repo_name>seungho-jo/Review<file_sep>/javareview/src/main/java/javareview/project3/TravelLogin_Service.java
package javareview.project3;
public class TravelLogin_Service {
}
<file_sep>/javareview/src/main/webapp/project6/js/login.js
/**
*
*/
function checkValue(){
var id = document.querySelector("[name = id]");
var pass = document.querySelector("[name = pass]");
var form = document.querySelector("form");
if(!id.value){
alert("아이디를 작성해주세요.");
id.focus();
return false;
}
else if(!pass.value){
alert("비밀번호를 작성해주세요.");
pass.focus();
return false;
} else{
form.submit();
}
}<file_sep>/javareview/src/main/java/javareview/project5/table2.sql
--상품테이블
CREATE TABLE sproduct(
pcode varchar2(8) PRIMARY KEY,
pname varchar2(70) CONSTRAINT sproduct_pname_nn NOT NULL,
pbrand varchar2(50) CONSTRAINT sproduct_pbrand_nn NOT NULL,
color varchar2(50),
price NUMBER,
pdate DATE
);
DROP TABLE SPRODUCT;
SELECT * FROM SPRODUCT P, STOCK S WHERE P.PCODE = S.PCODE;
--아우터
INSERT INTO sproduct VALUES('OT001','스탠다드 후드 스웨트 집업','멜란지','그레이',39900,TO_DATE('2021-06-01', 'yyyy-mm-dd'));
INSERT INTO sproduct VALUES('OT002','2WAY 스웻 후드 집업','토피','블랙',45000,TO_DATE('2021-06-02', 'yyyy-mm-dd'));
INSERT INTO sproduct VALUES('OT003','오버사이즈 트렌치 코트','드로우핏','블랙',189000,TO_DATE('2021-06-03', 'yyyy-mm-dd'));
--상의
INSERT INTO sproduct VALUES('TP001','어센틱 로고 티셔츠','커버낫','블랙',39000,TO_DATE('2021-06-01', 'yyyy-mm-dd'));
INSERT INTO sproduct VALUES('TP002','빅 트위치 로고 티셔츠','리','화이트',35000,TO_DATE('2021-06-02', 'yyyy-mm-dd'));
INSERT INTO sproduct VALUES('TP003','쿠퍼 로고 티셔츠','커버낫','네이비',39000,TO_DATE('2021-06-03', 'yyyy-mm-dd'));
INSERT INTO sproduct VALUES('TP004','에디 오버핏 반팔 티셔츠','제멋','블랙',35800,TO_DATE('2021-06-04', 'yyyy-mm-dd'));
INSERT INTO sproduct VALUES('TP005','사인로고 반팔 티셔츠','마크 곤잘레스','블랙',35000,TO_DATE('2021-06-05', 'yyyy-mm-dd'));
--재고테이블
CREATE TABLE stock(
pcode varchar2(8) CONSTRAINT sproduct_pcode_fk REFERENCES sproduct(pcode),
psize varchar2(8),
stock NUMBER
);
-- 품절 테이블
CREATE TABLE soldOut(
pcode varchar2(8) CONSTRAINT soldOut_pcode_fk REFERENCES sproduct(pcode),
pname varchar2(70) CONSTRAINT soldOut_pname_nn NOT NULL,
pbrand varchar2(50) CONSTRAINT soldOut_pbrand_nn NOT NULL,
color varchar2(50),
psize varchar2(8)
);
-- 삭제 상품
CREATE TABLE dropProduct(
pcode varchar2(8) PRIMARY KEY,
pname varchar2(70) CONSTRAINT dropProduct_pname_nn NOT NULL,
pbrand varchar2(50) CONSTRAINT dropProduct_pbrand_nn NOT NULL,
color varchar2(50),
price NUMBER,
pdate DATE
);
select count(p.pcode) from sproduct p,stock s where p.pcode = s.pcode;
ALTER TABLE DROPPRODUCT
DROP COLUMN stock;
SELECT * FROM dropProduct;
INSERT INTO dropProduct values('TP006','쿨 코튼 2-PACK 티셔츠','커버 낫','블랙',34000,sysdate);
select count(pcode) from dropPrduct;
INSERT INTO soldOut values('OT002','2WAY 스웻 후드 집업','토피','블랙','L');
SELECT count(p.pcode) FROM sproduct p, stock t WHERE p.pcode = t.pcode AND stock != '0';
SELECT sum(stock) FROM sproduct p, stock t WHERE p.pcode = t.pcode;
SELECT p.pcode,pname,sum(stock) FROM sproduct p, stock t WHERE p.pcode = t.pcode GROUP BY p.pcode,PNAME ;
INSERT INTO stock VALUES('OT001','S','10');
INSERT INTO stock VALUES('OT001','M','10');
INSERT INTO stock VALUES('OT001','L','10');
INSERT INTO stock VALUES('OT002','S','10');
INSERT INTO stock VALUES('OT002','M','10');
INSERT INTO stock VALUES('OT002','L','0');
INSERT INTO stock VALUES('OT003','M','10');
INSERT INTO stock VALUES('OT003','L','10');
INSERT INTO stock VALUES('TP001','S','10');
INSERT INTO stock VALUES('TP001','M','10');
INSERT INTO stock VALUES('TP001','L','10');
INSERT INTO stock VALUES('TP002','S','10');
INSERT INTO stock VALUES('TP002','M','10');
INSERT INTO stock VALUES('TP002','L','10');
INSERT INTO stock VALUES('TP003','S','10');
INSERT INTO stock VALUES('TP003','M','10');
INSERT INTO stock VALUES('TP003','L','10');
INSERT INTO stock VALUES('TP004','S','10');
INSERT INTO stock VALUES('TP004','M','10');
INSERT INTO stock VALUES('TP004','L','10');
INSERT INTO stock VALUES('TP005','S','10');
INSERT INTO stock VALUES('TP005','M','10');
INSERT INTO stock VALUES('TP005','L','10');
SELECT * FROM stock;
SELECT * FROM SPRODUCT;
SELECT * FROM sorder;
SELECT * FROM SARUWA_MEM;
--주문조회 sql
SELECT o.ordercode 주문번호,m.memid 아이디,p.pname 상품명,m.phone 번호,p.pbrand 브랜드,p.color 색상,p.price 가격,s.psize 사이즈,o.cnt 수량,o.address 주소,o.orderdate 주문일자
FROM sproduct p, stock s, saruwa_mem m, sorder o
WHERE p.pname = o.pname
AND m.memid = o.memid
AND s.psize = o.psize
AND o.ORDERCODE = '11111111';
--구매테이블 (주문번호, 아이디, 이름, 폰, 브랜드, 색상, 가격, 갯수, 주소, 주문일)
DROP TABLE sorder;
create table sorder (
ordercode number(8) NOT NULL,
memid varchar2(15) NOT NULL,
address varchar2(20) not null,
pname varchar2(70) NOT NULL,
color varchar2(50) NOT NULL,
psize varchar2(8) NOT NULL,
cnt NUMBER not null,
orderdate Date default sysdate
);
INSERT INTO sorder VALUES(11111111,'265926','서울시송파구','어센틱 로고 티셔츠','블랙','L',1,TO_DATE('2021-06-20', 'yyyy-mm-dd'));
INSERT INTO sorder VALUES(11111112,'hihiman','서울시강남구','빅 트위치 로고 티셔츠','화이트','M',3,TO_DATE('2021-06-21', 'yyyy-mm-dd'));
INSERT INTO sorder VALUES(11111113,'goodgirl','부천시원미구','쿠퍼 로고 티셔츠','네이비','L',4,TO_DATE('2021-06-22', 'yyyy-mm-dd'));
INSERT INTO sorder VALUES(11111114,'tjddnjs12','인천시계양구','오버사이즈 트렌치 코트','블랙','M',5,TO_DATE('2021-06-23', 'yyyy-mm-dd'));
INSERT INTO sorder VALUES(11111115,'soisoi99','서울시강동구','스탠다드 후드 스웨트 집업','그레이','L',6,TO_DATE('2021-06-24', 'yyyy-mm-dd'));
INSERT INTO sorder VALUES(11111116,'soisoi99','서울시강동구','어센틱 로고 티셔츠','블랙','L',7,TO_DATE('2021-06-24', 'yyyy-mm-dd'));
SELECT * FROM sorder;
SELECT * FROM SARUWA_MEM;
SELECT *
FROM SARUWA_MEM s , sorder o
WHERE s.MEMID = o.MEMID ;
--상품필터
--신상품순
SELECT pcode, pname, pbrand, color, price, pdate
FROM sproduct
ORDER BY pdate DESC ;
--가격낮은순
SELECT pcode, pname, pbrand, color, price, pdate
FROM sproduct
ORDER BY price;
--가격높은순
SELECT pcode, pname, pbrand, color, price, pdate
FROM sproduct
ORDER BY price DESC ;
--판매량 높은순
SELECT pcode, pname, pbrand, color, price, pdate
FROM sproduct;
SELECT sum(cnt), pname
FROM (
SELECT cnt, pname
FROM sorder s)
group BY pname
ORDER BY sum(cnt) desc;
SELECT pcode, pname, pbrand, color, price, pdate
FROM sproduct;
SELECT * FROM sorder;
SELECT a.pname, pcode, pbrand,color,price,pdate,b.cnt
FROM sproduct a,(SELECT cnt, pname
FROM (SELECT sum(cnt) cnt, pname
FROM sorder
GROUP BY pname)) b
WHERE a.pname = b.pname
ORDER BY cnt desc;
SELECT cnt, pname
FROM (SELECT sum(cnt) cnt, pname
FROM sorder
GROUP BY pname);
/*SELECT cnt, pname
FROM SORDER s2
WHERE pname = '어센틱 로고 티셔츠';
SELECT sum(cnt)
FROM (
SELECT cnt, pname
FROM SORDER s2
WHERE pname = '어센틱 로고 티셔츠');*/
-- 좋아요
CREATE TABLE saruwa_like(
pcode varchar2(8) CONSTRAINT saruwa_like_pcode_fk REFERENCES sproduct(pcode),
memid varchar2(15) CONSTRAINT saruwa_like_memid_fk REFERENCES saruwa_mem(memid)
);
SELECT * FROM sorder;
create table sorder (
ordercode number(8) NOT NULL,
memid varchar2(15) NOT NULL,
address varchar2(20) not null,
pname varchar2(70) NOT NULL,
color varchar2(50) NOT NULL,
psize varchar2(8) NOT NULL,
cnt NUMBER not null,
orderdate Date default sysdate
);
DELETE FROM SPRODUCT
WHERE pcode = 'OT005';
<file_sep>/javareview/src/main/java/project6/page/Controller.java
package project6.page;
import java.util.ArrayList;
public class Controller {
Service sv = new Service();
ArrayList<Board> blist = null;
ArrayList<Collections> clist = null;
String bcode = null;
// 게시물 작성
public String writeBoard(Model d,Board b) {
d.addAttribute("게시글 작성", sv.writeBoard(b));
return "mypage.jsp";
}
// 게시물 수정
public String updateBoard(Model d, Board b) {
b.setBcode(bcode);
d.addAttribute("게시글 수정", sv.updateBoard(b));
return "mypage.jsp";
}
// 게시물 리스트
public String boardList(Model d,String email) {
d.addAttribute("게시글 리스트",blist= sv.boardList(email));
return "mypage.jsp";
}
// 게시물 삭제
public String deleteBoard(Model d,String id,String bcode) {
d.addAttribute("게시글 삭제", sv.deleteBoard(id, bcode));
return "mypage.jsp";
}
// 선택 게시물 보기
public String setBoard(Model d,int choice,String id) {
d.addAttribute("게시글 수정", sv.setBoard(bcode = blist.get(choice-1).getBcode(), id));
return "mypage.jsp";
}
// 태그된 게시물 리스트
public String tagBoard(Model d,String tag) {
d.addAttribute("태그된 게시물 리스트", sv.tagBoard(tag));
return "mypage.jsp";
}
// 컬랙션 생성
public String createCollection(Model d,String id,String colname) {
d.addAttribute("컬랙션 생성", sv.createCollection(id, colname));
return "mypage.jsp";
}
// 나의 컬랙션 리스트
public String colList(Model d,String id) {
d.addAttribute("컬랙션 리스트", clist = sv.colList(id));
return "mypage.jsp";
}
// 컬랙션 내용
public String colBoard(Model d,int num) {
d.addAttribute("컬랙션 내용", sv.colBoard(clist.get(num-1).getColcode()));
return "mypage.jsp";
}
// 게시물 저장
public String saveBoard(Model d,int num) {
d.addAttribute("게시물 저장", sv.saveBoard(clist.get(num-1).getColcode(), bcode));
return "mypage.jsp";
}
}
<file_sep>/javareview/src/main/java/project6/like/LikeController.java
package project6.like;
import java.util.ArrayList;
public class LikeController {
LikeService service = new LikeService();
ArrayList<Board> blist = null;
String bcode = null;
// 게시물리스트
public String boardListall(Model d) {
d.addAttribute("게시글 리스트",blist= service.boardListall());
return "mypage.jsp";
}
// 선택 게시물 보기
public String setBoard(Model d,int choice) {
d.addAttribute("게시글 선택", service.setBoard(bcode = blist.get(choice-1).getBcode()));
return "mypage.jsp";
}
//좋아요 클릭
public String like(Model d,String id) {
System.out.println("# 좋아요 #");
d.addAttribute("좋아요 출력", service.clicklike(id,bcode));
return "호출될 화면";
}
}
<file_sep>/javareview/src/main/java/javareview/a05_4week/A05_25.java
package javareview.a05_4week;
import javareview.a05_4week.vo.A05_25_Vo;
public class A05_25 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// static,final,static final
Dog.tot = 100;
Dog d1 = new Dog("이름1");
Dog d2 = new Dog("이름2");
Dog d3 = new Dog("이름3");
d1.eat();
d1.buy();
d1.buy();
d1.buy();
d1.buy();
d2.eat();
d2.eat();
d2.eat();
d2.buy();
d2.eat();
d3.eat();
d3.eat();
d3.buy();
d3.buy();
d1.show();
d2.show();
d3.show();
//접근제어자
Vo v1 = new Vo();
v1.name1 = "홍길동";
v1.name2 = "가길동";
v1.name3 = "나길동";
// v1.name4 = "다길동";
A05_25_Vo v2 = new A05_25_Vo();
System.out.println(v2.name1);
// System.out.println(v2.name2);
// System.out.println(v2.name3);
// v1.name4 = "다길동";
}
}
class Dog{
String name;
static int tot;
int foods;
final String kind="치와와";
static final int date = 0;
public Dog(String name) {
this.name = name;
}
public void eat() {
foods--;
tot--;
// date++; --> date는 static final 이기에 변할수가 없다
}
public void buy() {
foods++;
tot++;
// date++; --> date는 static final 이기에 변할수가 없다
}
public void show() {
System.out.println("견종: " + kind);
System.out.println("이름: " + name);
System.out.println("사료량: " + foods);
System.out.println("총 남은 사료량: " + tot);
}
}<file_sep>/javareview/src/main/java/database/a01_0527.sql
SELECT * FROM emp;
SELECT empno, ename FROM emp;
SELECT empno AS "사원번호", ename "사원명" FROM emp;
SELECT '사원번호: ' || empno || ', 사원명: ' || ename FROM emp;
SELECT '보너스(연봉10%): ' || sal*0.1 "보너스" FROM emp;
-- 한줄 주석
/*
* 다중 주석
*/
<file_sep>/javareview/src/main/java/javareview/project3/TravelLogin_Dao.java
package javareview.project3;
public class TravelLogin_Dao {
}
<file_sep>/javareview/src/main/java/javareview/project3/TravelLogin_Controller.java
package javareview.project3;
public class TravelLogin_Controller {
}
<file_sep>/javareview/src/main/java/javareview/a05_4week/vo/A05_25_Vo.java
package javareview.a05_4week.vo;
public class A05_25_Vo {
public String name1 = "홍";
String name2 = "가";
protected String name3="나";
private String name4="다";
}
<file_sep>/javareview/src/main/java/javareview/project3/table.sql
CREATE TABLE travel(
nation varchar2(20),
korName varchar2(50),
engName varchar2(50),
loc varchar2(100),
clip NUMBER,
content varchar(1000),
category varchar(50),
pnum varchar2(20),
web varchar2(50)
);
INSERT INTO travel VALUES ('하와이','와이키키 해변','Waikiki Beach','2353 Kalakaua Avenue, Honolulu, HI 96815, USA',
449,'호놀룰루 남쪽 해안에 자리 잡은 하와이의 랜드마크 해변이다. 하와이 말로 용솟음치는 물 로 알려진 와이키키는 오아후의 주요 호텔과 리조트들이 들어서 있는 중심 지역이 되었다.',
'랜드마크, 해변/항구',NULL,'');
INSERT INTO travel VALUES ('하와이','하나우마 베이','Hanauma Bay','Catafalque Drive, Honolulu, HI 96825, USA',
329,'영화 블루 하와이의 촬영지로 바닷물의 투명도가 높은덕에 최고의 스노클링 포인트이다.',
'해변/항구',1-808-396-4229,'');
SELECT * FROM travel;
DELETE FROM travel WHERE korName = '하나우마 베이';
ALTER TABLE travel MODIFY pnum VARCHAR2(20);
INSERT INTO travel VALUES ('하와이','하나우마 베이','Hanauma Bay','Catafalque Drive, Honolulu, HI 96825, USA',
329,'영화 블루 하와이의 촬영지로 바닷물의 투명도가 높은덕에 최고의 스노클링 포인트이다.',
'해변/항구','1-808-396-4229','');
INSERT INTO travel VALUES ('하와이','다이아몬드 헤드','Diamond Head','4302 Diamond Head Road, Honolulu, HI 96816, USA',
292,'오아후섬 남동 해안에 있는 화산으로 높이는 232m이다. 바닷물의 침식작용으로 형성된 낭떠러지가 발달되어 경치가 아름답고, 정상에 오르면 와이키키와 호놀룰루시 전경이 한눈에 들어온다. 분화구 꼭대기의 암석들이 햇빛을 받아 반짝이는 것이 다이아몬드처럼 보인다 해서 붙여졌다.',
'랜드마크, 산/숲','1-808-587-0300','');
INSERT INTO travel VALUES ('하와이','지오반니 새우 트럭 (할레이와점)','Giovanni'||chr(39)||'s Shrimp Truck (Haleiwa Branch)','Catafalque Drive, Honolulu, HI 96825, USA',
245,'하와이에서 꼭 먹어봐야 할 음식 중 하나인 지오반니 새우 트럭. 양념에 조리한 새우를 밥에 곁들여 먹는 음식이다.',
'해산물','1-808-293-1839','www.giovannisshrimptruck.com');
UPDATE travel SET loc = '4302 Diamond Head Road, Honolulu, HI 96816, USA' WHERE korName = '다이아몬드 헤드';
INSERT INTO travel VALUES ('하와이','와이켈레 프리미엄 아울렛','Waikele Premium Outlets','94 Paioa Place, Waipahu, HI 96797, USA',
255,'미국 브랜드를 중심으로 저렴하게 구매할 수 있다.',
'아울렛','1-808-676-5656','www.premiumoutlets.com');
CREATE TABLE country(
name varchar2(50),
city varchar2(50),
location varchar2(50),
Introduce varchar2(300)
);
INSERT INTO country values('영국','런던','북아일랜드','영국의 수도는 런던이고 영국의 정식명칭은 그레이트브리튼 및 북아일랜드 연합왕국이며, 약칭으로 브리튼이라고 한다');
INSERT INTO country values('뉴질랜드','오클랜드 ','남서태평양','뉴질랜드 또는 아오테아로아는 남서 태평양에 있는 섬나라이고 수도는 웰링턴이다');
INSERT INTO country values('브라질','상파울루','남아메리카','브라질 연방 공화국 줄여서 브라질 또는 파서국은 남아메리카에 있는 연방 공화국이며 수도는 브라질리아이다');
INSERT INTO country values('일본','도쿄','동아시아','일본국 약칭 일본은 동아시아에 있는 국가이다. 태평양에 있는 일본 열도의 네 개의 큰 섬과 이들 주변에 산재한 작은 섬들로 구성되어 있고 수도는 도쿄이다');
INSERT INTO country values('미국','뉴욕','북아메리카','미합중국 약칭 합중국 또는 미국은 주 50개와 특별구 1개로 이루어진 연방제 공화국이다 수도는 워싱턴DC이다');
SELECT * FROM COUNTRY;
SELECT * FROM travel;
INSERT INTO travel VALUES ('하와이','알라모아나 비치 파크','Ala Moana Beach Park','163 Ala Moana Park Drive, Honolulu, HI 96814, USA',
260,'하와이 최대의 가족공원으로 넓은 잔디밭이 드넓게 펼쳐져 있으며, 백사장도 1km나 펼쳐져 있다. 테니스장과 간단한 운동기구, 조깅코스도 있어 관광객뿐만 아니라 현지인들도 많이 찾는 곳이다.',
'해변/항구',' 1-808-768-4611',null);
CREATE TABLE changingInfo(
name varchar2(50),
category varchar2(50),
content varchar2(300)
);
SELECT * FROM changingInfo;
INSERT INTO changingInfo values('와이키키 해변','명칭','이름이 와이키키3번지로 변경되었어요');
INSERT INTO changingInfo values('와이키키 해변','주소','주소가 ###시로 변경되었어요');
INSERT INTO changingInfo values('와이키키 해변','기타','웹 사이트가 폐쇠되었어요');
CREATE TABLE travelUser(
email varchar2(100),
pass varchar2(50),
name varchar2(50),
gender char(1)
);
CREATE TABLE question(
writer varchar2(50),
name varchar2(50),
title varchar2(50),
content varchar2(1000),
tag varchar2(50),
writeDate date
);
INSERT INTO question values('나길동','와이키키 해변','여행','일정에 추가할만 한가요?','주변',sysdate);
INSERT INTO question values('고길동','에펠탑','여행지','야경이 좋은곳이 어딘가요','주변',sysdate);
INSERT INTO question values('조승호','와이키키 해변','서핑','서핑할수 있나요?','주변',sysdate);
INSERT INTO question values('다길동','와이키키 해변','','이곳 근처에 괜찮은 맛집 있나요?','주변',sysdate);
SELECT * FROM question JOIN travel ON travel.KORNAME = question.NAME ;
INSERT INTO travelUser VALUES('<EMAIL>','1111','조승호','M');
INSERT INTO travelUser VALUES('<EMAIL>','0000','홍길동','M');
SELECT * FROM QUESTION Q JOIN TRAVELUSER T ON Q.writer = T.name;
CREATE TABLE travelReview(
name varchar2(50),
wdate DATE,
feeling varchar2(30),
place varchar2(50),
review varchar2(2000)
);
INSERT INTO travelReview values('조승호',sysdate,'좋아요!','와이키키 해변','바다 뷰가 너무 좋아요!!');
INSERT INTO travelReview values('홍길동',sysdate,'괜찮아요!','와이키키 해변','좋긴한데 지저분하네요.');
INSERT INTO travelReview values('고길동',sysdate,'별로에요!','와이키키 해변','쓰레기가 너무 많고 사람이 너무 많이 붐벼요');
INSERT INTO travelReview values('가길동',sysdate,'좋아요!','와이키키 해변','서핑을 즐길수 있어서 좋네요');
INSERT INTO travelReview values('나길동',sysdate,'좋아요!','에펠탑','매시 정각,반짝이는 불빛의 에펠탑을 놓치치마세요!!');
SELECT * FROM QUESTION;
CREATE TABLE country(
name varchar2(20),
city varchar2(20),
location varchar2(20)
);
SELECT * FROM QUESTION q ;
SELECT * FROM emp;<file_sep>/javareview/src/main/java/javareview/project5/Service.java
package javareview.project5;
import java.util.ArrayList;
public class Service {
Dao dao = new Dao();
// 로그인
public boolean login(String i, int p) {
boolean result = dao.login(i, p);
if (result) {
System.out.println("로그인 성공");
return true;
} else {
System.out.println("로그인 실패");
return false;
}
}
// 회원정보 통계 - 최근회원가입자 정보
public String thisWeekMemberInfo() {
ArrayList<Member> mlist = dao.thisWeekMemberInfo();
String result = "";
System.out.println("가입날자\t아이디\t이메일\t동의여부");
for(Member list:mlist) {
if(list.getMrkAgree() == 1) {
result = "동의";
}else {
result = "비동의";
}
System.out.print(list.getMdate()+"\t");
System.out.print(list.getMemId()+"\t");
System.out.print(list.getMemEmail()+"\t");
System.out.println(result);
System.out.println("-------------------------");
}
return "출력완료";
}
// 회원정보 통계
public String total() {
int[] list = dao.total();
System.out.println("신규회원\t주간회원\t탈퇴회원\t총 회원수");
for(int i=0;i<list.length;i++) {
System.out.print(list[i]+"\t");
}
return "출력완료";
}
// 회원정보 나열/정렬
public String memberInfo(String s) {
if(s.equals("내림차순")) {
s = "desc";
}else if(s.equals("오름차순")) {
s = "asc";
}
ArrayList<Member> mlist = dao.memberInfo(s);
String result = "";
int i = 1;
System.out.println("번호\t아이디\t이메일\t휴대폰번호\t동의여부\t가입날자");
for(Member list:mlist) {
if(list.getMrkAgree() == 1) {
result = "동의";
}else {
result = "비동의";
}
StringBuffer phone = new StringBuffer(list.getPhoneNum());
phone.insert(4, "-");
System.out.print(i+"\t");
System.out.print(list.getMemId()+"\t");
System.out.print(list.getMemEmail()+"\t");
System.out.print("010-"+phone+"\t");
System.out.print(result+"\t");
System.out.println(list.getMdate().substring(0,10));
System.out.println("-------------------------");
i++;
}
return "출력완료";
}
// 상품 통계
public String pTotal() {
int[] list = dao.pTotal();
System.out.println("총상품\t판매중\t품절\t삭제상품");
for(int i=0;i<list.length;i++) {
System.out.print(list[i]+"\t");
}
return "출력완료";
}
// 상품정보 통계 - 최근등록한 상품정보
public String latelyProduct() {
ArrayList<Product> plist = dao.latelyProduct();
System.out.println("등록날자\t상품코드\t상품명\t가격");
for(Product list: plist) {
System.out.print(list.getPdate()+"\t");
System.out.print(list.getPcode()+"\t");
System.out.print(list.getPname()+"\t");
System.out.println(list.getPrice());
System.out.println("-------------------------");
}
return "출력완료";
}
// 상품 등록
public String insertPoduct(String s,String n,String b,String c,int p,String d,String size,int cnt) {
if(s.equals("아우터")) {
s = "OT";
}else if(s.equals("상의")) {
s = "TP";
}
String[] sizes = size.split(",");
dao.insertProduct(s, n, b, c, p, d,sizes,cnt);
return "입력완료";
}
// 상품 리스트
public String proList() {
ArrayList<Product> list = dao.proList();
System.out.println("상품번호\t상품명\t가격\t재고");
for(Product pro: list) {
System.out.print(pro.getPcode()+"\t");
System.out.print(pro.getPname()+"\t");
System.out.print(pro.getPrice()+"\t");
System.out.println(pro.getCnt());
}
return "출력완료";
}
// 상품 불러오기
public Product showProduct(String n) {
Product pro = dao.showProduct(n);
System.out.println("상품코드: "+pro.getPcode());
System.out.println("상품명: "+pro.getPname());
System.out.println("상품 브랜드: "+pro.getPbrand());
System.out.println("색상: "+pro.getColor());
System.out.println("가격: "+pro.getPrice());
System.out.println("사이즈: "+pro.getSize());
System.out.println("재고량: "+pro.getCnt());
return pro;
}
// 상품 수정
public String updateProduct(ArrayList a,ArrayList b,String c) {
for(int i=0;i<a.size();i++) {
if(a.get(i).equals("상품명")) {
a.set(i, "pname");
}else if(a.get(i).equals("브랜드")) {
a.set(i, "pbrand");
}else if(a.get(i).equals("색상")) {
a.set(i, "color");
}else if(a.get(i).equals("가격")) {
a.set(i, "price");
}
}
dao.updateProduct(a,b,c);
return "출력완료";
}
// 상품 삭제
public String deleteProduct(String c) {
dao.deleteProduct(c);
return "출력완료";
}
}
<file_sep>/javareview/src/main/java/javareview/a05_2week/array/Example.java
package javareview.a05_2week.array;
public class Example {
private String name;
private int age;
private int rank;
public Example(String name,int age, int rank) {
this.name = name;
this.age = age;
this.rank = rank;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
}
<file_sep>/javareview/src/main/java/project6/loginPage/MemberService.java
package project6.loginPage;
import java.util.Scanner;
public class MemberService {
//로그인
Scanner sc = new Scanner(System.in);
MemberDao dao = new MemberDao();
public boolean login(Member m) {
if(dao.login(m)) {
System.out.println("로그인 성공");
return true;
}else {
System.out.println("아이디/비밀번호를 재확인해주세요.");
return false;
}
}
public boolean register(Member m) {
boolean memck = true;
// 중복아이디 체크
while(memck) {
if (dao.crtId(m)) {
System.out.println("중복되는 아이디가 있습니다.");
System.out.print("아이디: ");
m.setEmail(sc.nextLine());
}
// 중복 전화번호 체크
if(dao.crtPhone(m)) {
System.out.println("중복되는 전화번호가 있습니다.");
System.out.print("전화번호: ");
m.setPhone(sc.nextLine());
}else {
memck = false;
System.out.println("회원 정보 중복 체크 완료.");
}
}
return dao.register(m);
}
public boolean deleteMember(Member m) {
System.out.print("아이디를 정말 삭제하십니까?");
System.out.print("비밀번호를 재 입력하세요 : ");
String pass = sc.nextLine();
if(m.getPass().equals(pass)) {
return dao.deleteMember(m);
}else {
System.out.println("비밀번호가 틀렸습니다. 다시 입력하세요.");
return false;
}
}
}
<file_sep>/javareview/src/main/java/jspexp/a01_start/A01_Movie.java
package jspexp.a01_start;
// jspexp.a01_start.A01_Movie
public class A01_Movie {
private String title;
private int visitCnt;
public A01_Movie() {
super();
// TODO Auto-generated constructor stub
}
public A01_Movie(String title, int visitCnt) {
super();
this.title = title;
this.visitCnt = visitCnt;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getVisitCnt() {
return visitCnt;
}
public void setVisitCnt(int visitCnt) {
this.visitCnt = visitCnt;
}
}
<file_sep>/javareview/src/main/java/javareview/project3/Travel_Dao.java
package javareview.project3;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
public class Travel_Dao {
public ArrayList<Travel> list = new ArrayList<Travel>();
public ArrayList<ChangingInfo> clist = new ArrayList<ChangingInfo>();
public ArrayList<Question_Travel> qlist = new ArrayList<Question_Travel>();
public ArrayList<TravelUser> ulist = new ArrayList<TravelUser>();
public ArrayList<Ratings> listt = new ArrayList<Ratings>();
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
public ArrayList<Travel> insertTravel(Travel t) {
Travel tbean = new Travel();
tbean.setNation(t.getNation());
tbean.setKorName(t.getKorName());
tbean.setEngName(t.getEngName());
tbean.setLoc(t.getLoc());
tbean.setClip(t.getClip());
tbean.setContent(t.getContent());
tbean.setCategory(t.getCategory());
tbean.setPnum(t.getPnum());
tbean.setWeb(t.getWeb());
list.add(tbean);
return list;
}
public ArrayList<Travel> insertTravel2(Travel t) {
Travel tbean = new Travel();
tbean.setNation(t.getNation());
tbean.setKorName(t.getKorName());
tbean.setEngName(t.getEngName());
tbean.setLoc(t.getLoc());
tbean.setClip(t.getClip());
tbean.setContent(t.getContent());
tbean.setCategory(t.getCategory());
tbean.setPnum(t.getPnum());
tbean.setWeb(t.getWeb());
list.add(tbean);
return list;
}
public ArrayList<Travel> showList() {
System.out.println("# 전체 정보 전달");
return list;
}
public ArrayList<Travel> search(String s) {
ArrayList<Travel> lists = new ArrayList<Travel>();
for (Travel t : list) {
if (t.getKorName().equals(s)) {
lists.add(t);
}
}
return lists;
}
public ArrayList<Travel> delete(String s) {
int choice = Integer.parseInt(s) - 1;
list.remove(choice);
return list;
}
public ArrayList<Travel> modify(String s) {
ArrayList<Travel> lists = new ArrayList<Travel>();
int choice = Integer.parseInt(s) - 1;
lists.add(list.get(choice));
return lists;
}
public ArrayList<Travel> detail(String s) {
ArrayList<Travel> lists = new ArrayList<Travel>();
int cho = Integer.parseInt(s)-1;
lists.add(list.get(cho));
return lists;
}
public Travel clip(String s){
Travel lists = new Travel();
lists = list.get(Integer.parseInt(s)-1);
return lists;
}
public ArrayList<ChangingInfo> changingInfo(String r,String s,String m){
ChangingInfo c = new ChangingInfo();
c.setName(r);
c.setCategory(s);
c.setContent(m);
clist.add(c);
return clist;
}
public ArrayList<Question_Travel> question(Question_Travel q, String s,String n){
Question_Travel qbean = new Question_Travel();
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss");
String format_time = format.format(cal.getTime());
qbean.setWriter(s);
qbean.setName(n);
qbean.setTitle(q.getTitle());
qbean.setContent(q.getContent());
qbean.setTag(q.getTag());
qbean.setDate(format_time);
qlist.add(qbean);
return qlist;
}
public ArrayList<Question_Travel> questionList(){
return qlist;
}
public boolean login(String e,String p){
boolean flag = false;
try {
String sql = "SELECT * FROM travelUser where email = ? and pass = ?";
conn = DBConnection.getConnection();
pstm = conn.prepareStatement(sql);
pstm.setString(1, e);
pstm.setString(2, p);
rs = pstm.executeQuery();
flag = rs.next();
} catch (SQLException e1) {
System.out.println("예외발생");
e1.printStackTrace();
} finally{
try {
if (rs != null) {
rs.close();
}
if (pstm != null) {
pstm.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e1) {
throw new RuntimeException(e1.getMessage());
}
}
return flag;
}
public TravelUser member(String e){
TravelUser user = null;
try {
String sql = "SELECT * FROM travelUser where email = ?";
conn = DBConnection.getConnection();
pstm = conn.prepareStatement(sql);
pstm.setString(1, e);
rs = pstm.executeQuery();
if(rs.next()) {
user = new TravelUser();
user.setName(rs.getString("name"));
user.setPass(rs.getString("pass"));
user.setGender(rs.getString("gender"));
}
} catch (SQLException e1) {
System.out.println("예외발생");
e1.printStackTrace();
} finally{
try {
if (rs != null) {
rs.close();
}
if (pstm != null) {
pstm.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e1) {
throw new RuntimeException(e1.getMessage());
}
}
return user;
}
public ArrayList<Ratings> insertRatings(Ratings r) {
Ratings tbea = new Ratings();
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss");
String format_time = format.format(cal.getTime());
tbea.setName(r.getName());
tbea.setDate(format_time);
tbea.setFeeling(r.getFeeling());
tbea.setPlace(r.getPlace());
tbea.setReview(r.getReview());
listt.add(tbea);
return listt;
}
public ArrayList<Ratings> rshowList() {
return listt;
}
public ArrayList<Ratings> modify1(String s) {
ArrayList<Ratings> lists = new ArrayList<Ratings>();
int choice = Integer.parseInt(s) - 1;
lists.add(listt.get(choice));
return lists;
}
public ArrayList<Ratings> delete1(String s) {
int choice = Integer.parseInt(s) - 1;
listt.remove(choice);
return listt;
}
}
<file_sep>/javareview/src/main/java/database/a08_0630.sql
/*
# 테이블 구조 변경
작성한 테이블에서 구조를 변경하는경우 사용
종류
- 컬럼 추가
- 컬럼 삭제
- 컬럼 변경
- 제약조건 변경
*/
-- 컬럼 추가
-- alter table 테이블명 add 컬럼명 데이터유형 [default 디퐅트데이터 제약조건]
CREATE TABLE emp116
AS SELECT * FROM emp;
ALTER TABLE emp116
ADD testcol NUMBER DEFAULT 0;
SELECT * FROM emp116;
-- 컬럼 제거
-- alter table 테이블명 drop column 컬럼명
ALTER TABLE emp116
DROP COLUMN testcol;
SELECT * FROM emp116;<file_sep>/javareview/src/main/java/project6/like/LikeMain.java
package project6.like;
import java.util.Scanner;
public class LikeMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
LikeController ctrl = new LikeController();
Board board = new Board();
Scanner sc = new Scanner(System.in);
String id ="";
String pass = "";
String bcode = "";
boolean x = true;
while(x) {
System.out.println("## scrollBook 피드 ##");
System.out.println("[1] 좋아요 클릭");
System.out.println("한번 더 누를 시 취소됩니다.");
System.out.println("");
int cho = Integer.parseInt(sc.nextLine());
switch(cho) {
case 1:
System.out.print("아이디: ");
id = sc.nextLine();
System.out.print("비밀번호: ");
pass = sc.nextLine();
System.out.println("게시물 리스트");
ctrl.boardListall(new Model());
System.out.println("-게시물 선택-");
System.out.println("게시물 선택");
int choice = Integer.parseInt(sc.nextLine());
ctrl.setBoard(new Model(), choice);
System.out.println("# 좋아요클릭 #");
ctrl.like(new Model(),id);
break;
}
}
}
}
<file_sep>/javareview/src/main/java/database/a10_0707.sql
/*
# 집합관계
종류
union - 합집합, 중복된 데이터 출력x
sql1 union sql2
union all - 합집합이지만 중복된 데이터도 출력
sql1 union all sql2
intersect - 교집합
sql1 intersect sql2
minus - 먼저 위치한 조회문을 기준으로 다른 조회문과 공통된 데이터를 제외한 항목만 출력
sql1 minus sql2
*/
-- union
SELECT '홍길동' name, 75 kor FROM dual
union
SELECT '김길동' name, 80 kor FROM dual
union
SELECT '신길동' name, 90 kor FROM dual
union
SELECT '홍길동' name, 75 kor FROM dual;
--union all
SELECT '홍길동' name, 75 kor FROM dual
UNION all
SELECT '김길동' name, 80 kor FROM dual
UNION all
SELECT '신길동' name, 90 kor FROM dual
UNION all
SELECT '홍길동' name, 75 kor FROM dual;
-- intersect
SELECT ename, job, deptno, sal
FROM emp
WHERE sal BETWEEN 1000 AND 3000
INTERSECT
SELECT ename, job, deptno, sal
FROM emp
WHERE sal BETWEEN 2000 AND 5000;
-- minus
SELECT ename, job, deptno, sal
FROM emp
WHERE sal BETWEEN 1000 AND 3000
MINUS
SELECT ename, job, deptno, sal
FROM emp
WHERE sal BETWEEN 2000 AND 5000;
/*
# view
- 하나 이상의 기본 테이블이나 다른 view를 이용하여 생성되는 가상 테이블
- 권한이 있는 사람만이 전체 테이블을 보고 그 외는 뷰를 통해서 허용된 테이블만 볼수있어서 데이터 보호에 좋다
query결과로 view를 만들었기 떄문에 가상테이블로 sql을 조회할 수 있다
생성
create [or replace] view 뷰이름
as (subquery - select * from ***)
종류
- 단순view
하나의 테이블로 생성
그룹 함수의 사용이 불가능 - 실제테이블의 데이터가 아니기에
distinct 사용일때 불가능
dml(insert, update, delete) 사용가능
- 복합view
여러 개의 테이블로 설정
그룹 함수의 사용이 가능
distinct 사용이 가능
dml(insert, update, delete)사용 불가능
*/
-- 단순view
DROP TABLE emp31;
CREATE TABLE emp31
AS SELECT * FROM emp;
CREATE VIEW view_emp31
AS SELECT empno, ename, sal, deptno
FROM emp31
WHERE deptno = 10;
SELECT * FROM view_emp31;
-- 복합view
DROP TABLE dept31;
CREATE TABLE dept31
AS SELECT * FROM dept;
CREATE VIEW view_emp_dept
AS
SELECT e.empno,e.ename,e.sal,e.deptno,d.dname,d.loc
FROM emp31 e, dept31 d
WHERE e.deptno = d.deptno
ORDER BY empno DESC;
SELECT * FROM view_emp_dept;<file_sep>/javareview/src/main/java/javareview/project5/Controller.java
package javareview.project5;
import java.util.ArrayList;
import java.util.Scanner;
public class Controller {
Service s = new Service();
Scanner sc = new Scanner(System.in);
Product pro = new Product();
// 로그인
public String login(Model d) {
System.out.print("아이디: ");
String id = sc.nextLine();
System.out.print("비밀번호: ");
String pass = sc.nextLine();
d.addAttribute("로그인", s.login(id, Integer.parseInt(pass)));
return "main.jsp";
}
// 회원정보 통계 - 최근회원가입자 정보
public String thisWeekMemberInfo(Model d) {
d.addAttribute("최근회원가입자 정보", s.thisWeekMemberInfo());
return "member.jsp";
}
// 회원정보 통계
public String total(Model d) {
d.addAttribute("회원정보 통계", s.total());
return "member.jsp";
}
// 회원정보 나열/정렬
public String memberInfo(Model d) {
System.out.print("정렬방식: ");
String choice = sc.nextLine();
d.addAttribute("회원정보", s.memberInfo(choice));
return "member.jsp";
}
// 상품 통계
public String pTotal(Model d) {
d.addAttribute("상품 통계", s.pTotal());
return "ptotal.html";
}
// 상품 통계 - 최근 등록한 상품
public String latelyProduct(Model d) {
d.addAttribute("최근 등록한 상품", s.latelyProduct());
return "ptotal.html";
}
// 상품 등록
public String insertProduct(Model d,Product p) {
d.addAttribute("상품등록", s.insertPoduct(p.getPcode(), p.getPname(), p.getPbrand(), p.getColor(), p.getPrice(), p.getPdate(),p.getSize(),p.getCnt()));
return "insertProduct.html";
}
// 상품 리스트
public String proList(Model d) {
d.addAttribute("상품 리스트", s.proList());
return "showProduct.html";
}
// 상품 불러오기
public String showProduct(Model d,String p) {
pro = s.showProduct(p);
d.addAttribute("상품 불러오기", pro);
return "showProduct.html";
}
// 상품 수정
public String updateProduct(Model d,ArrayList list1,ArrayList list2) {
d.addAttribute("상품수정", s.updateProduct(list1, list2, pro.getPcode()));
return "showProduct.html";
}
// 상품 삭제
public String deleteProduct(Model d) {
d.addAttribute("상품삭제", s.deleteProduct(pro.getPcode()));
return "showProduct.html";
}
}
<file_sep>/javareview/src/main/java/javareview/project4/table.sql
CREATE TABLE BookStore(
kind varchar2(10),
name varchar2(50),
pnum varchar2(20),
loc varchar2(100),
web varchar2(100),
sns varchar2(100)
);
INSERT INTO BookStore values('새책방','1984','02-325-1984','마포구 마포구 동교로 194 혜원빌딩 1층','','https://www.instagram.com/1984store');
INSERT INTO BookStore values('새책방','21세기문고','02-3463-1880','강남구 강남구 남부순환로359길 31','','');
INSERT INTO BookStore values('새책방','C&S서점','02-2190-2178','강남구 강남구 남부순환로 2806 군인공제회관 지하 1층','','');
INSERT INTO BookStore values('새책방','Poetic Humans Club(PHC)','','마포구 성미산로 127 2층','','');
INSERT INTO BookStore values('새책방','SK문고','02-945-1959','강북구 솔샘로 205 2층','','');
INSERT INTO BookStore values('헌책방','Yes24 중고매장(강서NC점)','1566-4295','강서구 강서로56길 17 NC백화점 강서점 8, 9층',
'http://www.yes24.com/Mall/UsedStore/Det','');
INSERT INTO BookStore values('헌책방','강동헌책방','02-471-0272','강동구 강동구 구천면로 257','','');
INSERT INTO BookStore values('헌책방','개똥이네(가양점)','02-2658-2982','강서구 강서구 양천로 431 지하 1층','','');
INSERT INTO BookStore values('헌책방','고시책사랑','02-871-5550','관악구 관악구 호암로26길 27','','');
INSERT INTO BookStore values('헌책방','공씨책방(성수점)','010-4350-4970','성동구 광나루로 130 106호-라','','');
SELECT kind,name,nvl(pnum,'-') pnum,nvl(loc,'-') loc,nvl(web,'-') web,nvl(sns,'-') sns FROM bookStore
WHERE upper(name) LIKE upper('%%') AND kind like '%%' AND loc like '%%';
CREATE TABLE evtDataPrg(
title varchar2(50),
writer varchar2(20),
wdate DATE,
visit NUMBER,
evtyear NUMBER,
content varchar2(2000)
);
SELECT * FROM evtDataPrg;
ALTER TABLE evtDataPrg MODIFY title varchar2(500);
INSERT INTO evtDataPrg values('서울지식이음축제 -Link Revolution(아이디어톤대회)','김OO',sysdate,0,
2019,'아이디어톤 대회 11.24(일) 10:00-19:30 서울시청 다목적홀','이미지.PNG');
INSERT INTO evtDataPrg values('서울지식이음축제- 이색독서 외','김OO',to_Date('2021-01-21','YYYY-MM-DD'),0,
2019,'이글루프탑 11.23(토),24(일) 10:00-20:00 서울도서관 5층 하늘뜰','이미지.PNG');
INSERT INTO evtDataPrg values('서울지식이음축제-체험 및 전시 프로그램','김OO',to_Date('2021-01-21','YYYY-MM-DD'),255,
2019,'지식랜드 11.23(토),24(일) 11:00-18:00 서울도서관 3층 서울자료실','이미지.PNG');
INSERT INTO evtDataPrg values('서울지식이음축제- 각종 강연 프로그램','김OO',to_Date('2021-01-21','YYYY-MM-DD'),261,
2019,'워킹&토킹 11.23(토) 14:00-18:00 서울도서관 일반자료실1,2','이미지.PNG');
ALTER TABLE evtDataPrg ADD kind varchar2(50);
INSERT INTO evtDataPrg(kind) values('프로그램');
DELETE evtDataPrg WHERE kind = '프로그램';
update evtDataPrg set kind = '프로그램' where writer = '김OO';
INSERT INTO evtDataPrg VALUES('[news1] 공연·전시가 있는 ''시끌벅적'' 도서관…서울도서관 축제','김OO',to_date('2020-01-17','YYYY-MM-DD'),210,
2019,'공연·전시가 있는 ''시끌벅적'' 도서관…서울도서관 축제 /2019.11.17
서울도서관이 각종 공연과 전시를 함께 펼치는 책 읽기 축제를 개최한다.
서울시는 2008년부터 지난해까지 열린 ''서울 북 페스티벌''을 개편한 ''2019 서울지식이음축제''를 오는 23~24일 서울도서관에서 개최한다.
올해 주제는 도서관에 대한 기존 고정관념에 도전하며 도서관의 혁신과 사회적 역할을 모색하기 위해 ''비욘드 라이브러리''(Beyond Library)로 정했다.
출처 : [news1] http://news1.kr/articles/?3770863','','보도자료');
UPDATE evtDataPrg SET visit = visit+1 WHERE title = '서울지식이음축제- 이색독서 외';
SELECT to_date('','YYYY-MM-DD') FROM dual;
SELECT * FROM EVTDATAPRG;
select * from evtDataPrg where evtyear LIKE 2019 AND title like '%%' AND content like '%%' AND
wdate between to_date('2021-01-01','YYYY-MM-DD') and to_date('2021-06-17','YYYY-MM-DD');
CREATE TABLE library(
kind varchar2(10),
name varchar2(50),
usetime varchar2(40),
closedDay varchar2(40),
pnum varchar2(20),
web varchar2(100),
loc varchar2(100),
bookjoin varchar2(30)
);
SELECT * FROM library;
ALTER TABLE library MODIFY closedDay varchar2(70);
INSERT INTO library values('대표도서관','서울도서관','평일 : 09:00~21:00, 주말 : 09:00~18:00','월요일 및 법정공휴일','02-2133-0300',
'https://lib.seoul.go.kr/','서울특별시 중구 세종대로 110 태평로1가','참여');
INSERT INTO library values('국립도서관','국립어린이청소년도서관','평일 : 09:00~18:00, 주말 : 09:00~18:00','매월 둘째넷째 월요일, 일요일을 제외한 공휴일','02-3413-4800 ',
'http://www.nlcy.go.kr/','서울특별시 강남구 테헤란로7길 21','미참여');
INSERT INTO library values('국립도서관','국립중앙도서관','평일 : 09:00~18:00, 주말 : 09:00~18:00','둘째,넷째 월요일/법정공휴일(일요일제외)','02-535-4142',
'http://www.nl.go.kr','서울특별시 서초구 반포대로 201','미참여');
INSERT INTO library values('공공도서관','4.19혁명기념도서관','평일 : 09:00~17:00, 주말 : 09:00~12:30','정부지정 공휴일(일요일 포함)','02-730-4190',
'http://library.419revolution.org','서울특별시 종로구 새문안로 17','미참여');
INSERT INTO library values('공공도서관','가락몰도서관','평일 : 09:00~18:00, 주말 : 09:00~18:00','매주 월요일 및 법정공휴일','02-3435-0950, 0956',
'http://www.splib.or.kr','서울특별시 송파구 양재대로 932 서울시농수산식품공사 가락몰 업무동 4층','참여');
INSERT INTO library values('작은 도서관','&Lounge작은도서관','평일 : 09:00~18:00, 주말 : 10:00~18:00','둘째·넷째 일요일, 공휴일','070-4239-2722',
'-','서울특별시 동대문구 고산자로36길 3, 경동시장 신관 2층','미참여');
INSERT INTO library values('작은 도서관','7단지 작은도서관','평일 : 13;00~17:30','토,일,공휴일','02-2646-2367',
'-','서울특별시 양천구 목동로 212(목동)','미참여');
INSERT INTO library values('장애인 도서관','IT로 열린도서관','평일 : 09:00~18:00','토,일,공휴일','02-3471-3434',
'http://www.itlo.org/','서울특별시 서초구 방배로 36, 이삭빌딩 301호','미참여');
INSERT INTO library values('장애인 도서관','강서점자도서관','평일 : 09:30~17:30, 주말 : 09:30~13:00','토요일(첫째, 셋째주), 일요일, 법정공휴일','02-2661-2278,2291',
'http://www.ksbl.or.kr/','서울특별시 강서구 공항대로 206 801~803호','미참여');
INSERT INTO library values('전문 도서관','(사)국민문화연구소 자료실','-','-','02-765-7651~2',
'-','서울특별시 종로구 이화동 율곡로13가길 19-5','미참여');
INSERT INTO library values('전문 도서관','KBS도서관','평일 : 09:00~20:00, 주말 : 휴관일','토요일, 일요일, 법정공휴일','02-781-1661',
'-','서울특별시 영등포구 여의공원로 13 한국방송공사 내','미참여');
CREATE TABLE books(
name varchar2(100),
writer varchar2(50),
pdate NUMBER,
ISBN NUMBER,
publisher varchar2(100),
datatype varchar2(30),
loc varchar2(100),
libname varchar2(100),
loan varchar2(100),
lib varchar2(100)
);
INSERT INTO books VALUES('Java의 정석:최신 Java 8.0 포함.1','남궁성 지음',2016,9788994492032,'도우','도서','005.135-ㄴ48ㅈ3-1','쌍문태움도서관','대출가능',
'도봉구 25개 도서관');
INSERT INTO books VALUES('Java 프로그래밍 면접, 이렇게 준비한다','마크엄,노엘',2015,null,'서울:한빛미디어,2015','일반단행본','005.135 마877ㅈ','개봉도서관','대출가능',
'구로구 36개 도서관');
INSERT INTO books VALUES('Java 프로그래밍 = Java programming','정재현',2017,9788920020346,'Knou Press','단행본','005.135 김97ㅈ2','등빛도서관','대출가능',
'강서구 35개 도서관');
INSERT INTO books VALUES('Java의 정석:기초편','남궁성 지음',2019,9788994492049,'도우','','[솔샘]종합자료실','솔샘문화정보도서관','대출가능',
'강북구 8개 도서관');
INSERT INTO books VALUES('맛있는 MongoDB:Javascript와 함꼐하는 NoSQL DBMS','정승호 지음',2019,9791190014687,'','','금나래종합자료실','금나래도서관','',
'금천구립금나래도서관');
SELECT * FROM Books where name like '%Java%' AND writer LIKE '%남궁성%' and pdate between 1984 and 2021;
SELECT * FROM Books where name like '%Java%' and writer like '%남궁성%' and pdate between 1984 and 2021;
CREATE TABLE smlmember (
loginmail varchar2(50),
loginpass varchar2(50),
name varchar2(50),
phonenum varchar2(50),
address varchar2(70),
mobilememnum varchar2(50)
);
INSERT INTO smlmember VALUES ('himan','112233445566','홍길동','010-2222-3333','서울시 송파구','11112333356666');
INSERT INTO smlmember VALUES ('goodman','qwerty12345','김길동','010-2255-4444','서울시 중구','11112333356667');
INSERT INTO smlmember VALUES ('primera','asdfgh12345','이자바','010-2266-5555','서울시 강동구','11112333356668');
INSERT INTO smlmember VALUES ('emulsion','zxcvbn12345','김워터','010-2277-6666','부천시 원미구',null);
INSERT INTO smlmember VALUES ('sssjdw','qazwsx12345','임토너','010-2288-7777','인천시 계양구','11112333356669');
CREATE TABLE mysearch(
loginmail varchar2(50),
searchname varchar2(100),
library varchar2(50)
);
SELECT * FROM mysearch;
SELECT * FROM emp where ename LIKE '%SM%' AND JOB LIKE '%%';
ALTER TABLE mysearch MODIFY library varchar2(4000);
update mysearch set library = library||',서초도서관' where loginmail = 'himan';
<file_sep>/javareview/src/main/webapp/project6/js/mypage.js
/**
*
*/
var listImg = document.querySelectorAll("#list ul li img");
var li = document.querySelectorAll("#list ul li");
li[0].style.borderBottom = "1px solid black";
function click(idx){
li[idx].onclick = function(){
for(var i=0;i<li.length;i++){
li[i].style.borderBottom = "none";
}
li[idx].style.borderBottom = "1px solid black";
}
}
for(var idx=0;idx<li.length;idx++){
click(idx);
}
var picture = document.querySelectorAll(".picture");
var moreDiv = document.querySelectorAll(".morediv");
var up_del = document.querySelectorAll(".up_del");
function shows(idx){
picture[idx].onmouseover = function(){
moreDiv[idx].style.display = "inline-block";
}
moreDiv[idx].onmouseover = function(){
moreDiv[idx].style.display = "inline-block";
}
picture[idx].onmouseout = function(){
moreDiv[idx].style.display = "none";
up_del[idx].style.display = "none";
}
moreDiv[idx].onclick = function(){
up_del[idx].style.display = "inline-block";
}
}
for(var idx=0;idx<picture.length;idx++){
shows(idx);
}<file_sep>/javareview/src/main/java/javareview/project3/Ratings.java
package javareview.project3;
public class Ratings {
private String name;
private String date;
private String feeling;
private String place;
private String review;
public Ratings(String name, String feeling, String place, String review) {
super();
this.name = name;
this.feeling = feeling;
this.place = place;
this.review = review;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFeeling() {
return feeling;
}
public void setFeeling(String feeling) {
this.feeling = feeling;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public Ratings() {
super();
// TODO Auto-generated constructor stub
}
}
<file_sep>/javareview/src/main/webapp/project6/js/join.js
/**
*
*/
function checkValue(){
var id = document.querySelector("[name = id]");
var pass = document.querySelector("[name = pass]");
var repass = document.querySelector("[name=repass]");
var pullname = document.querySelector("[name=name]");
if(!id.value){
alert("아이디를 입력하세요!");
id.focus();
return false;
}
if(!pass.value){
alert("비밀번호를 입력하세요!");
pass.focus();
return false;
}
if(!repass.value){
alert("비밀번호를 다시한번 입력하세요!");
repass.focus();
return false;
}else{
if(pass.value != repass.value){
alert("입력한 비밀번호가 일치하지 않습니다.");
return false;
}
}
if(!pullname.value){
alert("사용자의 이름을 입력해주세요.");
pullname.focus();
return false;
} else{
form.submit();
}
alert("회원가입 완료");
}<file_sep>/javareview/src/main/java/javareview/project4/Books.java
package javareview.project4;
public class Books {
private String name;
private String writer;
private int pdate;
private int ISBN;
private String publisher;
private String datatype;
private String loc;
private String libname;
private String loan;
private String lib;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public int getPdate() {
return pdate;
}
public void setPdate(int pdate) {
this.pdate = pdate;
}
public int getISBN() {
return ISBN;
}
public void setISBN(int iSBN) {
ISBN = iSBN;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getDatatype() {
return datatype;
}
public void setDatatype(String datatype) {
this.datatype = datatype;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public String getLibname() {
return libname;
}
public void setLibname(String libname) {
this.libname = libname;
}
public String getLoan() {
return loan;
}
public void setLoan(String loan) {
this.loan = loan;
}
public String getLib() {
return lib;
}
public void setLib(String lib) {
this.lib = lib;
}
}
<file_sep>/javareview/src/main/java/javareview/project3/Question_Travel.java
package javareview.project3;
public class Question_Travel {
private String writer;
private String name;
private String title;
private String content;
private String tag;
private String date;
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Question_Travel(String title, String content, String tag) {
super();
this.title = title;
this.content = content;
this.tag = tag;
}
public Question_Travel() {
}
}
<file_sep>/javareview/src/main/java/javareview/project4/BookStore.java
package javareview.project4;
public class BookStore {
private String kind;
private String name;
private String pnum;
private String loc;
private String web;
private String sns;
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPnum() {
return pnum;
}
public void setPnum(String pnum) {
this.pnum = pnum;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public String getWeb() {
return web;
}
public void setWeb(String web) {
this.web = web;
}
public String getSns() {
return sns;
}
public void setSns(String sns) {
this.sns = sns;
}
}
<file_sep>/javareview/src/main/java/javareview/project5/Main.java
package javareview.project5;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Controller c = new Controller();
Scanner sc = new Scanner(System.in);
Product pro = new Product();
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
//c.login(new Model());
//c.totalMember(new Model());
//c.total(new Model());
//c.thisWeekMemberInfo(new Model());
//c.memberInfo(new Model());
/*
System.out.println("상품을 등록합니다");
System.out.print("상품종류: ");
pro.setPcode(sc.nextLine());
System.out.print("상품이름: ");
pro.setPname(sc.nextLine());
System.out.print("상품브랜드: ");
pro.setPbrand(sc.nextLine());
System.out.print("상품색깔: ");
pro.setColor(sc.nextLine());
System.out.print("상품가격: ");
pro.setPrice(Integer.parseInt(sc.nextLine()));
System.out.print("입고일: ");
pro.setPdate(sc.nextLine());
System.out.print("사이즈: ");
pro.setSize(sc.nextLine());
System.out.print("재고량: ");
pro.setCnt(Integer.parseInt(sc.nextLine()));
c.insertProduct(new Model(), pro);
*/
//c.pTotal(new Model());
//c.latelyProduct(new Model());
c.proList(new Model());
/*
System.out.println("상품을 선택해주세요: ");
String name = sc.nextLine();
c.showProduct(new Model(), name);
System.out.println("선택헤주세요[수정] [삭제]");
String choice = sc.nextLine();
switch(choice) {
case "수정" :
while(true) {
System.out.print("수정하고싶은 항목을 적어주세요: ");
list1.add(sc.nextLine());
System.out.print("변경 사항을 적어주세요: ");
list2.add(sc.nextLine());
System.out.print("종료하시겠습니까?(Y/N) : ");
if(sc.nextLine().equals("Y")) {
break;
}
}
c.updateProduct(new Model(), list1,list2);
break;
case "삭제" :
c.deleteProduct(new Model());
break;
}
*/
}
}
<file_sep>/javareview/src/main/java/project6/sch/SchMain.java
package project6.sch;
public class SchMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
SchController ctrl = new SchController();
System.out.println(" # 검색 # ");
ctrl.schid(new Model());
ctrl.schtag(new Model());
}
}
<file_sep>/javareview/src/main/java/database/a06_0628.sql
/*
데이터 삭제
delete문을 사용하여 테이블에 저장된 데이터 삭제
where 조건문을 붙이지 않는다면 테이블의 모든 데이터 삭제
delete from 테이블명
where 조건명
*/
CREATE TABLE emp105
AS SELECT * FROM emp;
SELECT * FROM emp105;
DELETE FROM emp105
WHERE nvl(comm,0) = 0;
/*
merge
한번의 조건에 따라 여러가지 dml을 분기적으로 사용할때 사용 - oracle에서만 지원하는 sql
merge into 테이블 a
using 테이블 b
on a.컬럼 = b.컬럼
when matched then
update set 수정할 구문
when not matched then
insert values
*/
CREATE TABLE emp106
AS SELECT * FROM emp
WHERE to_char(hiredate,'Q') IN ('1','2');
MERGE INTO emp106 a
USING emp b
ON (a.empno = b.empno)
WHEN MATCHED THEN
UPDATE SET a.job = b.job,
a.sal = b.sal,
a.hiredate = to_date(to_char(sysdate,'YYYY')||to_char(hiredate,'MMDD'),'YYYYMMDD')
WHEN NOT MATCHED THEN
INSERT (empno,job,sal,hiredate)
VALUES (b.empno,b.job,b.sal,sysdate);
SELECT * FROM emp106;
/*
merge
가상테이블로 외부에서 입력된 데이터를 처리할수 있다
입력된 데이터가 있으면 update, 없을때는 insert
*/
-- 입력된 데이터와 일치할때
CREATE TABLE emp107
AS SELECT * FROM emp;
MERGE INTO emp107 e
USING dual
ON (e.empno = 7499)
WHEN MATCHED THEN
UPDATE SET ename = '홍길동',
sal = 3000,
comm = sal*0.1
WHEN NOT MATCHED THEN
INSERT (empno,ename,sal,comm)
-- 입력된 데이터와 불일치할때
CREATE TABLE emp107
AS SELECT * FROM emp;
MERGE INTO emp107 e
USING dual
ON (e.empno = 9000)
WHEN MATCHED THEN
UPDATE SET ename = '홍길동',
sal = 3000,
comm = sal*0.1
WHEN NOT MATCHED THEN
INSERT (empno,ename,sal,comm)
values (9000,'고길동',2800,500);
SELECT * FROM emp107;<file_sep>/javareview/src/main/java/javareview/project4/BookStore_Controller.java
package javareview.project4;
import java.util.Scanner;
public class BookStore_Controller {
BookStore_Service bss = new BookStore_Service();
MemberService service = new MemberService();
Scanner sc = new Scanner(System.in);
String Loginmail = "";
boolean result;
// 책방 리스트
public String bookStoreList(Model d) {
d.addAttribute("리스트 출력", bss.bookStoreList());
return "호출될 화면";
}
// 책방 검색
public String searchList(Model d) {
System.out.print("책방구분:");
String kind = sc.nextLine();
System.out.print("자치구:");
String loc = sc.nextLine();
System.out.print("책방이름:");
String name = sc.nextLine();
d.addAttribute("검색", bss.searchList(kind, loc, name));
return "호출될 화면";
}
// 연도별 행사자료 리스트, 상세보기,조회수증가,필터링검색
public String programList(Model d) {
System.out.print("볼 자료를 선택해 주세요(프로그램/축제사진/보도자료):");
String choice = sc.nextLine();
System.out.print("연도를 선택해주세요:");
String year = sc.nextLine();
d.addAttribute("리스트 출력", bss.eventList(choice, Integer.parseInt(year)));
searchEvent(d, year, choice);
detailEvent(d);
return "호출될 화면";
}
// 연도별 행사자료 상세보기, 조회수 증가
public String detailEvent(Model d) {
System.out.println("상세히 볼 게시물의 제목을 입력해주세요");
String title = sc.nextLine();
bss.upCount(title);
d.addAttribute("상세보기", bss.detailEvent(title));
return "호출될 화면";
}
// 연도별 행사자료 필터링 검색
public String searchEvent(Model d, String y, String k) {
System.out.print("연도:");
String year = sc.nextLine();
System.out.print("제목:");
String title = sc.nextLine();
System.out.print("내용:");
String content = sc.nextLine();
System.out.print("작성일(ㅁ~ㅁ):");
String d1 = sc.nextLine();
String d2 = sc.nextLine();
if (year.equals("")) {
year = y;
}
d.addAttribute("검색", bss.searchEvent(Integer.parseInt(year), title, content, d1, d2, k));
return "호출될 화면";
}
// 도서관 리스트
public String libraryList(Model d) {
d.addAttribute("리스트 출력", bss.libraryList());
return "호출될 화면";
}
// 책방 검색
public String searchLib(Model d) {
System.out.print("도서관구분:");
String kind = sc.nextLine();
System.out.print("자치구:");
String loc = sc.nextLine();
System.out.print("도서관명:");
String name = sc.nextLine();
d.addAttribute("검색", bss.searchLib(kind, loc, name));
return "호출될 화면";
}
// 도서 자료 상세 검색
public String searchBooks(Model d) {
System.out.print("종류1 ");
String k1 = sc.nextLine();
System.out.print("검색어1 ");
String sw1 = sc.nextLine();
System.out.print("논리선택 ");
String logic = sc.nextLine();
System.out.print("종류2 ");
String k2 = sc.nextLine();
System.out.print("검색어2 ");
String sw2 = sc.nextLine();
System.out.print("연도1 ");
String year1 = sc.nextLine();
if (year1.equals("")) {
year1 = "1984";
}
System.out.print("연도2 ");
String year2 = sc.nextLine();
if (year2.equals("")) {
year2 = "2021";
}
d.addAttribute("상세검색",
bss.searchBooks(k1, sw1, logic, k2, sw2, Integer.parseInt(year1), Integer.parseInt(year2)));
return "호출될 화면";
}
// 나의 검색 리스트 만들기
public String searchset(Model d) {
System.out.println("로그인이 필요합니다");
login(d);
System.out.print("리스트 이름을 지어주세요 : ");
String name = sc.nextLine();
System.out.print("넣을 도서관을 적어주세요 : ");
String lib = sc.nextLine();
d.addAttribute("설정 만들기", bss.searchset(Loginmail, name, lib));
return "호출될 화면";
}
// 나의 검색 리스트 도서관추가
public String addLibrary(Model d) {
showSearchSet(d);
System.out.print("검색 리스트를 선택해주세요 :");
String name = sc.nextLine();
System.out.print("넣을 도서관을 적어주세요 : ");
String lib = sc.nextLine();
d.addAttribute("도서관 추가", bss.addLibrary(lib, Loginmail, name));
return "호출될 화면";
}
// 나의 검색 설정 보기
public String showSearchSet(Model d) {
System.out.println("로그인이 필요합니다");
login(d);
d.addAttribute("리스트 출력", bss.showSearchSet(Loginmail));
return "호출될 화면";
}
// 회원가입
public String joinMember(Model d) {
Member me = new Member();
System.out.print("도서관 아이디:");
me.setLoginmail(sc.nextLine());
System.out.print("비밀번호:");
me.setLoginpass(sc.nextLine());
System.out.print("이름:");
me.setName(sc.nextLine());
System.out.print("휴대폰번호:");
me.setPhonenum(sc.nextLine());
System.out.print("주소:");
me.setAddress(sc.nextLine());
System.out.println("모바일회원번호: -");
me.setMobilememnum(null);
d.addAttribute("회원가입결과", service.joinmember(me));
return "호출될 화면";
}
// 로그인
public String login(Model d) {
System.out.println("# 로그인 #");
System.out.print("이메일: ");
Loginmail = sc.nextLine();
System.out.print("비밀번호: ");
String pass = sc.nextLine();
result = service.login(Loginmail, pass);
d.addAttribute("로그인결과", result);
return "화면호출";
}
}
<file_sep>/javareview/src/main/webapp/project6/js/memberInfo.js
/**
*
*/
var memberprofile = document.querySelector("#memberprofile");
var memberout = document.querySelector("#memberout");
memberprofile.onclick = function(){
location.href = "memberInfo.jsp";
}
memberout.onclick = function(){
location.href = "memberout.jsp";
}<file_sep>/javareview/src/main/java/jspexp/a01_start/A02_Entertainer.java
package jspexp.a01_start;
public class A02_Entertainer {
private String name;
private String birth;
private String field;
public A02_Entertainer() {
super();
// TODO Auto-generated constructor stub
}
public A02_Entertainer(String name, String birth, String field) {
super();
this.name = name;
this.birth = birth;
this.field = field;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
}
<file_sep>/javareview/src/main/java/database/a02_0528.sql
/*
select문의 표준 형식
select 컬럼명, ... : 열 단위로 나타날 데이터(컬럼명)
from 테이블명 : 대상 테이블
where 조건문 : 행 단위로 나타날 데이터 필터링처리
group by 그룹화 컬럼지정 : 특정 컬럼 기준으로 합산, 갯수, 최대/최소
having 그룹의 조건 지정 : 그룹 컬럼의 조건
order by 정렬할 우선순위 컬럼 - desc(역순정렬), 없을경우 정순졍렬
where 조건문
관계대수(=,<=,>=,<,>),and,or,subquery(중첩질의),비교연산자(!=,is not null,is null)들을 사용하여 행 단위로 나타낼 데이터 정렬
*/
SELECT * FROM emp;
SELECT * FROM emp
WHERE sal >= 2000;
SELECT * FROM emp
WHERE sal < 5000;
SELECT * FROM emp
WHERE sal >= 2000 AND sal < 5000;
SELECT * FROM emp
WHERE ename != 'JONES';
SELECT comm FROM emp
WHERE deptno IS NOT null;
<file_sep>/javareview/src/main/java/project6/page/Main.java
package project6.page;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
Controller ctl = new Controller();
Board board = new Board();
System.out.println("로그인");
System.out.print("아이디: ");
String id = sc.nextLine();
System.out.print("비밀번호: ");
String pass = sc.nextLine();
// 게시물 조회
ctl.boardList(new Model(), id);
// 게시물 선택 후 보기
System.out.println("게시물 선택");
int choice = Integer.parseInt(sc.nextLine());
ctl.setBoard(new Model(), choice, id);
// 게시물 수정
System.out.println("#게시글 작성#");
System.out.println("내용");
String contents = sc.nextLine();
board.setContents(contents);
System.out.println("사진 등록");
String img = sc.nextLine();
board.setImg(img);
System.out.println("태그 등록");
String tag = sc.nextLine();
board.setTag(tag);
System.out.println("위치 등록");
String loc = sc.nextLine();
board.setLoc(loc);
System.out.println("공개 범위");
String pubRange = sc.nextLine();
board.setPubRange(pubRange);
board.setID(id);
ctl.updateBoard(new Model(), board);
/*
// 로그인 이후 게시물 작성
System.out.println("#게시글 작성#");
System.out.println("내용");
String contents = sc.nextLine();
board.setContents(contents);
System.out.println("사진 등록");
String img = sc.nextLine();
board.setImg(img);
System.out.println("태그 등록");
String tag = sc.nextLine();
board.setTag(tag);
System.out.println("위치 등록");
String loc = sc.nextLine();
board.setLoc(loc);
System.out.println("공개 범위");
String pubRange = sc.nextLine();
board.setPubRange(pubRange);
board.setID(id);
ctl.writeBoard(new Model(),board);
*/
/*
// 태그된 게시글 리스트
System.out.print("태그입력: ");
String tag = sc.nextLine();
ctl.tagBoard(new Model(), tag);
*/
/*
// 컬랙션 생성
System.out.print("컬랙션 이름을 지어주세요: ");
String colname = sc.nextLine();
ctl.createCollection(new Model(), id, colname);
*/
// 게시물 저장
System.out.println("게시물을 저장하시겠습니까?");
String sel = sc.nextLine();
if(sel.equals("Y")) {
ctl.colList(new Model(), id);
System.out.println("컬랙션 선택 : ");
int num = Integer.parseInt(sc.nextLine());
ctl.saveBoard(new Model(), num);
}
ctl.colList(new Model(), id);
System.out.println("컬랙션 선택 : ");
int num = Integer.parseInt(sc.nextLine());
ctl.colBoard(new Model(), num);
}
}
<file_sep>/javareview/src/main/java/project6/like/Model.java
package project6.like;
//화면에 넘겨줄 임시 모델 객체
public class Model {
public void addAttribute(String key,Object ob) {
System.out.println("# 모델 데이터 처리");
System.out.println("key:"+key);
System.out.println("객체:"+ob);
}
}
<file_sep>/javareview/src/main/java/database/a04_0617.sql
/*
# join
sql 명령문에서 하나의 테이블만 검색하는것이 아니라 2개이상의 테이블을
사용하여 조회할수 있는 기능이다
기본 구성
select 컬럼명
from 테이블 별칭, 테이블 별칭
where 별칭.컬럼 = 별칭.컬럼
*/
SELECT *
FROM emp e,dept d
WHERE e.deptno = d.deptno;
/*
기본 구성에 추가로 조건을 걸거나, 그룹화하여 사용가능
*/
SELECT dname, loc, ename, to_char(hiredate,'Q') 분기
FROM emp e, dept d
WHERE e.deptno = d.deptno
AND to_char(hiredate,'Q') = '1';
SELECT loc, avg(sal)
FROM emp e,dept d
WHERE e.DEPTNO = d.DEPTNO
GROUP BY loc;
/*
non equl join
컬럼값이 완전일치하지 않아도 범위 안에 존재한다면 결합되는 join문이다
*/
SELECT ename, sal, grade
FROM emp e, salgrade s
WHERE sal BETWEEN losal AND hisal;
/*
outer join
기본 join에서는 두 테이블간 컬럼값이 일치하여야 join이 되고 null이 존재할경우 그 데이터를
제외하고 출력하지만 outer join의 경우 null이 존재하더라도 우선 결합시키는 방식이다
*/
SELECT e.ename, e.deptno, d.deptno, dname
FROM emp e, dept d
WHERE e.DEPTNO(+) = d.DEPTNO ;
/*
self join
하나의 테이블에서 상관관계가 존재하는 컬럼끼리를 비교하여 결과를 도출하는 join이다
*/
SELECT e.empno,e.ename,e.mgr,m.ename msg
FROM emp e, emp m
where e.mgr = m.empno;
/*
# subquery
하나의 SQL 명령문의 결과를 다른 SQL 명령문에 전달하기 위해 두 개 이상의 SQL 명령문을
하나의 SQL명령문으로 연결하여 처리하는 방법
*/
SELECT *
FROM EMP
WHERE deptno = (
SELECT deptno
from emp
WHERE ename = 'SMITH'
);
/*
단일행비교 : 비교연산자( = , > , < , >= , <= )
다중행비교 : in, any, some, all, exists
*/
-- 단일행비교
SELECT *
FROM emp
WHERE sal = (
SELECT max(sal)
FROM emp
WHERE deptno = 10
);
-- 다중행 비교
SELECT *
FROM emp
WHERE sal = (
SELECT max(sal)
FROM emp
WHERE deptno = 10
);
-- 다중행 비교
SELECT *
FROM emp
WHERE (deptno, sal) in (
SELECT deptno, max(sal)
FROM emp
GROUP BY deptno
);
SELECT *
FROM emp
WHERE exists(
SELECT *
FROM emp
WHERE comm = 2422
);
-- 그외 subquery
SELECT *
FROM (
SELECT deptno,ename,empno, sal
FROM emp
WHERE sal BETWEEN 2000 AND 4000
) a, dept d
WHERE a.deptno = d.deptno;<file_sep>/javareview/src/main/java/javareview/project5/table.sql
CREATE TABLE adMember(
id varchar2(16),
pass <PASSWORD>,
name varchar2(50),
adrank varchar2(30)
);
INSERT INTO adMember values('himan',1111,'홍길동','마스터');
INSERT INTO adMember values('higirl',1111,'마길동','중간관리자');
INSERT INTO adMember values('admin',1111,'고길동','하위관리자');
SELECT * FROM ADMEMBER;
COMMIT;
CREATE TABLE saruwa_mem(
memid varchar2(15),
mpass varchar2(30) NOT NULL,
email varchar2(50),
phone number(8),
mkagr number(1) check(mkagr IN (1,2)),
PRIMARY key(memid, email, phone)
);
-- mkagr 이벤트 수신 동의여부 1:수신동의 2:수신비동의
SELECT * FROM saruwa_mem;
INSERT INTO saruwa_mem values('265926', 'qlalfqjsgh1*', '<EMAIL>', 12345678, 1);
INSERT INTO saruwa_mem values('hihiman', 'qlalfqlal55*', '<EMAIL>', 28193729, 1);
INSERT INTO saruwa_mem values('goodgirl', 'rntrjfdla22!', '<EMAIL>', 10284718, 2);
INSERT INTO saruwa_mem values('tjddnjs12', 'tjddnjsdl10$', '<EMAIL>', 35917293, 1);
INSERT INTO saruwa_mem values('soisoi99', 'thgnldla5;', '<EMAIL>', 29938102, 2);
INSERT INTO saruwa_mem values('admin','')
ALTER TABLE saruwa_mem ADD mdate date;
UPDATE saruwa_mem
SET mdate = sysdate
WHERE mdate IS null;
UPDATE saruwa_mem
SET mdate = SYSDATE - 20
WHERE memid = 'tjddnjs12';
SELECT * FROM saruwa_mem;
SELECT *
FROM saruwa_mem
wheRE mdate BETWEEN trunc(sysdate,'MM') AND trunc(sysdate+(INTERVAL '1' MONTH),'MM') ; -- 월간
SELECT * FROM SARUWA_MEM;
SELECT COUNT(memid), FROM saruwa_mem;
select TRUNC(sysdate,'iw')-1,trunc(sysdate,'iw')+5 from dual;
SELECT *
FROM saruwa_mem
wheRE mdate BETWEEN TRUNC(sysdate,'iw') AND trunc(sysdate+7,'iw')-(0.5/12/60/60); -- 주간
SELECT trunc(sysdate,'YY'), trunc(sysdate+(INTERVAL '1' YEAR),'YY')-(0.5/12/60/60) FROM dual; -- 1년간 가입자
CREATE TABLE drop_saruwa_mem(
memid varchar2(15),
mpass varchar2(30) NOT NULL,
email varchar2(50),
phone number(8),
mdate DATE NOT NULL,
PRIMARY key(memid, email, phone)
);
INSERT INTO drop_saruwa_mem values('jsh95320','154792135%','<EMAIL>',45791249,sysdate);
INSERT INTO drop_saruwa_mem values('shr57813','3278321sd$','<EMAIL>',03354897,sysdate-20);
INSERT INTO drop_saruwa_mem values('024drsts','jhjh12348s','<EMAIL>',12347893,sysdate-(INTERVAL '1' YEAR));
INSERT INTO drop_saruwa_mem values('BinChu','1268aw413','<EMAIL>',22648792,sysdate-31);
INSERT INTO drop_saruwa_mem values('WindDog','0554park1','<EMAIL>',21783124,sysdate-(INTERVAL '5' MONTH));
SELECT * FROM DROP_SARUWA_MEM ;
SELECT * FROM
(SELECT *
FROM saruwa_mem
ORDER BY mdate desc)
WHERE rownum <=3;
select * from saruwa_mem where to_char(mdate,'YYYY/MM/DD') = to_char(sysdate,'YYYY/MM/DD');
SELECT * FROM saruwa_mem ORDER BY mdate;
SELECT COUNT(PCODE) FROM sproduct WHERE pcode like 'OT%';
CREATE TABLE cp_sproduct
AS SELECT * FROM sproduct WHERE 1=0;
CREATE TABLE cp_stock
AS SELECT * FROM stock WHERE 1=0;
SELECT * FROM sproduct;
SELECT * FROM cp_stock;
INSERT ALL
INTO cp_sproduct values('OT001','스탠다드 후드 스웨트 집업','멜란지','그레이',39900,TO_DATE('2021-06-01', 'yyyy-mm-dd'))
INTO cp_stock vales('OT001','S','10')
SELECT * FROM dual;
select p.*, s.psize, s.stock from sproduct p,stock s where p.pcode = s.pcode and pname like '%어센틱%';
select p.pcode, pname, price, stock
from sproduct p,(
SELECT pcode, sum(stock) stock
FROM stock
GROUP BY pcode) s
where p.pcode = s.pcode;<file_sep>/javareview/src/main/java/javareview/a05_2week/A05_10.java
package javareview.a05_2week;
import java.util.Calendar;
import javareview.a05_2week.array.Example;
public class A05_10 {
public enum WEEK{SUN,MON,THU,WEN,THR,FRI,SAT};
public static void main(String[] args) {
// TODO Auto-generated method stub
//캘린더
Calendar cal = Calendar.getInstance();
System.out.println(Calendar.YEAR + " = " + cal.get(Calendar.YEAR) + "년");
System.out.println(Calendar.MONTH + " = " + (cal.get(Calendar.MONTH)+1) + "월");
System.out.println(Calendar.DAY_OF_MONTH + " = " + cal.get(Calendar.DAY_OF_MONTH) + "일");
String[] weekend = {"일요일","월요일","화요일","수요일","목요일","금요일","토요일"};
System.out.println(Calendar.DAY_OF_WEEK + " = " + weekend[(cal.get(Calendar.DAY_OF_WEEK)-1)]);
//enum
WEEK week = WEEK.MON;
System.out.println(week);
WEEK[] weekAry = week.values();
System.out.println(weekAry[0]);
System.out.println(weekAry[1]);
System.out.println(weekAry[2]);
for(WEEK w:weekAry) {
System.out.println(w.name() + "," +w.ordinal());
}
//배열과 forEach
String[] hobby1 = new String[5];
String[] hobby2 = {"축구","사진","여행","노래"};
System.out.println(hobby1.length);
System.out.println(hobby2.length);
Example[] e1 = {new Example("철수",17,2),
new Example("영희",19,8),
new Example("민수",18,40)
};
for(Example ee:e1) {
System.out.print(ee.getName()+"\t");
System.out.print(ee.getAge()+"\t");
System.out.println(ee.getRank());
}
}
}
<file_sep>/javareview/src/main/java/project6/like/LikeService.java
package project6.like;
import java.util.ArrayList;
public class LikeService {
LikeDao dao = new LikeDao();
// 게시물 리스트
public ArrayList<Board> boardListall() {
ArrayList<Board> blist = dao.boardListall();
int num = 1;
for(Board b:blist) {
System.out.print(num++ + " ");
System.out.println(b.getImg());
System.out.println("---------------------------------------");
}
return blist;
}
// 게시물 불러오기
public String setBoard(String bcode) {
Board brd = dao.setBoard(bcode);
System.out.println("아이디: "+brd.getID());
System.out.println("공개범위: "+brd.getPubRange());
System.out.println("게시글 내용: "+brd.getContents());
System.out.println(brd.getImg());
System.out.println(brd.getLoc());
return "출력완료";
}
//좋아요 클릭
public String clicklike(String id,String bcode) {
dao.clicklike(id, bcode);
System.out.println("-----------------------------------------------");
System.out.println("아이디: "+id);
System.out.println("-----------------------------------------------");
System.out.println("");
return "출력완료";
}
}
<file_sep>/javareview/src/main/java/javareview/a05_4week/Vo.java
package javareview.a05_4week;
public class Vo {
public String name1;
String name2;
protected String name3;
private String name4;
}
<file_sep>/javareview/src/main/java/javareview/project5/Member.java
package javareview.project5;
public class Member {
private String memId;
private String memPass;
private String memEmail;
private String phoneNum;
private String mdate;
private int mrkAgree;
private String cerId;
private String cerEmail;
private String cerPhone;
public String getMemId() {
return memId;
}
public void setMemId(String memId) {
this.memId = memId;
}
public String getMemPass() {
return memPass;
}
public void setMemPass(String memPass) {
this.memPass = memPass;
}
public String getMemEmail() {
return memEmail;
}
public void setMemEmail(String memEmail) {
this.memEmail = memEmail;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public int getMrkAgree() {
return mrkAgree;
}
public void setMrkAgree(int mrkAgree) {
this.mrkAgree = mrkAgree;
}
public String getCerId() {
return cerId;
}
public void setCerId(String cerId) {
this.cerId = cerId;
}
public String getCerEmail() {
return cerEmail;
}
public void setCerEmail(String cerEmail) {
this.cerEmail = cerEmail;
}
public String getCerPhone() {
return cerPhone;
}
public void setCerPhone(String cerPhone) {
this.cerPhone = cerPhone;
}
public String getMdate() {
return mdate;
}
public void setMdate(String mdate) {
this.mdate = mdate;
}
}
<file_sep>/javareview/src/main/java/javareview/project5/DropMember.java
package javareview.project5;
public class DropMember {
private String memid;
private String mpass;
private String email;
private int phone;
private String mdate;
public String getMemid() {
return memid;
}
public void setMemid(String memid) {
this.memid = memid;
}
public String getMpass() {
return mpass;
}
public void setMpass(String mpass) {
this.mpass = mpass;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
public String getMdate() {
return mdate;
}
public void setMdate(String mdate) {
this.mdate = mdate;
}
}
<file_sep>/javareview/src/main/java/database/a05_0624.sql
/*
데이터 조작
insert : 데이터 입력
update : 데이터 수정
delete : 데이터 삭제
merge : 병합 처리
insert
단일행 추가 : 테이블에 한 행 추가
insert into 테이블명 values(데이터1,데이터2,...)
insert into 테이블명(컬럼1,컬럼2...) values(데이터1,데이터2,...)
다중행 추가 : 테이블에 다중 행 추가
insert into 테이블명 select 컬럼1,컬럼2... from 테이블명
insert all
first insert
복제 테이블 만들기
create table 테이블명
as select 컬럼1,컬럼2...
from 테이블명
*/
CREATE TABLE emp100
AS SELECT * FROM emp
WHERE 1=0;
SELECT * FROM emp100;
INSERT INTO emp100 values(1001,'홍길동','Pro',9999,sysdate,3000,300,10);
INSERT INTO emp100(ename,job,sal) values('고길동','leader',6000);
INSERT INTO emp100
SELECT * FROM emp
WHERE sal>3000;
INSERT ALL
INTO emp100 values(empno,ename,job,mgr,hiredate,sal,comm,deptno)
SELECT * FROM emp;
/*
update : 데이터를 수정할떄 사용,where 조건문이 없을경우 테이블의 모든 데이터를 변경
update 테이블명
set 컬럼 = 데이터
컬럼 = 데이터
컬럼 = 데이터
where 조건문
null 값 조건문
is null : null인경우
is not null : null 이 아닌경우
*/
UPDATE emp100
SET comm = 100
WHERE comm is null;
SELECT * FROM emp100;
COMMIT;<file_sep>/javareview/src/main/java/javareview/project5/Login.java
package javareview.project5;
public class Login {
private String id;
private int pass;
private String name;
private String adrank;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getPass() {
return pass;
}
public void setPass(int pass) {
this.pass = pass;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdrank() {
return adrank;
}
public void setAdrank(String adrank) {
this.adrank = adrank;
}
}
<file_sep>/javareview/src/main/java/javareview/project3/Travel.java
package javareview.project3;
public class Travel {
private String nation;
private String korName;
private String engName;
private String loc;
private int clip;
private String content;
private String category;
private String pnum;
private String web;
public Travel() {
}
public Travel(String nation, String korName, String engName, String loc, int clip, String content, String category,
String pnum, String web) {
super();
this.nation = nation;
this.korName = korName;
this.engName = engName;
this.loc = loc;
this.clip = clip;
this.content = content;
this.category = category;
this.pnum = pnum;
this.web = web;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
public String getKorName() {
return korName;
}
public void setKorName(String korName) {
this.korName = korName;
}
public String getEngName() {
return engName;
}
public void setEngName(String engName) {
this.engName = engName;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public int getClip() {
return clip;
}
public void setClip(int clip) {
this.clip = clip;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPnum() {
return pnum;
}
public void setPnum(String pnum) {
this.pnum = pnum;
}
public String getWeb() {
return web;
}
public void setWeb(String web) {
this.web = web;
}
}
<file_sep>/javareview/src/main/java/javareview/a05_1week/A05_1week.java
package javareview.a05_1week;
import javareview.a05_1week.cl.Classes;
public class A05_1week {
public static void main(String[] args) {
// 변수와 데이터 유형
int num = 27;
String name = "조승호";
System.out.println(num);
System.out.println(name);
// 연산자의 종류 : 사칙연산자,나머지 연산자
int num1 = 20;
int num2 = 4;
System.out.println("num1 + num2 = " + (num1+num2));
System.out.println("num1 - num2 = " + (num1-num2));
System.out.println("num1 * num2 = " + (num1*num2));
System.out.println("num1 / num2 = " + (num1/num2));
System.out.println("num1 % num2 = " + (num1%num2));
//비교연산자
System.out.println(num1 + " == " + num2 + " ==> " + (num1==num2));
System.out.println(num1 + " != " + num2 + " ==> " + (num1!=num2));
System.out.println(num1 + " >= " + num2 + " ==> " + (num1>=num2));
System.out.println(num1 + " <= " + num2 + " ==> " + (num1<=num2));
System.out.println(num1 + " > " + num2 + " ==> " + (num1>num2));
System.out.println(num1 + " < " + num2 + " ==> " + (num1<num2));
//조건문과 반복문
int age = 27;
if(age <= 19) {
System.out.println("미성년자입니다");
}else {
System.out.println("성인입니다.");
}
int rcp = 2;
switch(rcp) {
case 0:
System.out.println("추먹");
break;
case 1 :
System.out.println("가위");
break;
case 2 :
System.out.println("보");
break;
default : break;
}
for(int i = 1; i <= 10; i++ ) {
System.out.println(1);
}
//메서드와 배열
test();
minus(15, 5);
int [] array1 = new int [3];
int [] array2 = {3,6,9};
System.out.println(array1);
System.out.println(array2);
System.out.println(array2[0]);
System.out.println(array2[1]);
System.out.println(array2[2]);
//클래스
A05_1week method1 = new A05_1week();
Person p1 = new Person();
System.out.println(p1.name);
System.out.println(p1.age);
System.out.println(p1.address);
Classes c1 = new Classes();
System.out.println(c1.name);
System.out.println(c1.age);
System.out.println(c1.address);
Classes c2 = new Classes("조승호",27,"경기도 수원시");
Classes c3 = new Classes();
//System.out.println(c3.test1);
//System.out.println(c3.test2);
//System.out.println(c3.test3);
System.out.println(c3.test4);
//상속
Piano piano = new Piano();
piano.play();
System.out.println(piano.sound);
//추상클래스
Ridding car1 = new Car();
car1.ride();
//인터페이스
PublicTransport p2 = new PublicTransport();
p2.setRide(new Bus());
p2.Public();
//예외처리
try {
System.out.println("예외처리 시작");
System.out.println(10/0);
}catch(Exception e) {
System.out.println("오류발생");
} finally {
System.out.println("프로그램 종료");
}
}
//메서드와 배열
public static void test() {
System.out.println("리턴없는 메서드");
}
public static int minus(int num01, int num02) {
int tot = num01+num02;
return tot;
}
}
class Person{
String name = "조승호";
int age = 27;
String address = "경기도 수원시";
}
class Sound{
String sound = "소리가 들린다";
void soundding() {
System.out.print("소리가 난다");
}
}
class Piano extends Sound{
void play() {
System.out.println("피아노에서");
soundding();
}
}
abstract class Ridding{
abstract void ride();
}
class Car extends Ridding{
@Override
void ride() {
// TODO Auto-generated method stub
System.out.println("자동차에 타다");
}
}
interface RideWay{
void ridding();
}
class Bus implements RideWay{
@Override
public void ridding() {
// TODO Auto-generated method stub
System.out.println("버스를 타다");
}
}
class PublicTransport{
private RideWay ridding;
public void setRide(RideWay ridding) {
this.ridding = ridding;
}
public void Public(){
if(ridding != null) {
ridding.ridding();
}
else {
System.out.println("대중교통이 없습니다");
}
}
}<file_sep>/javareview/src/main/webapp/project6/js/popup.js
/**
*
*/
function Sharefb(){
window.open(
'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent('http://172.16.58.3:7080/scrollBook/main.jsp')
);
}
function Sharett(){
var sendText = "scrollBook";
var sendUrl = "http://172.16.58.3:7080/scrollBook/main.jsp";
window.open("https://twitter.com/intent/tweet?text=" + sendText + "&url=" + sendUrl);
}
Kakao.init('e132a3811afb598bd7dd12e4683143bc');
function Sharekk(){
var sh_title = "scrollBook";
var sh_desc = "5조의 scrollBook";
Kakao.Link.sendDefault({
objectType: 'feed',
content: {
title: sh_title,
description: sh_desc,
imageUrl: "https://ifh.cc/g/3JWKOt.png",
link: { mobileWebUrl: "http://172.16.58.3:7080/scrollBook/main.jsp",
webUrl: "http://172.16.58.3:7080/scrollBook/main.jsp"
}
},
});
}
<file_sep>/javareview/src/main/java/javareview/project3/Travel_Controller.java
package javareview.project3;
import java.util.Scanner;
public class Travel_Controller {
Scanner sc = new Scanner(System.in);
String email = "";
boolean result;
private Travel_Service ser_t = new Travel_Service();
//관리자 영역
public String insertTravel(Travel t,Model d) {
d.addAttribute("정보등록", ser_t.insert(t));
return "호출될 화면";
}
public String insertTravel2(Travel t, Model d) {
d.addAttribute("정보등록", ser_t.insert2(t));
return "호출될 화면";
}
public String deleteTravel(Model d) {
System.out.print("* 삭제할 관광명소 번호를 입력해 주세요 : ");
String msg = sc.nextLine();
d.addAttribute("삭제결과", ser_t.delete(msg));
return "호출될 화면";
}
public String modifyTravel(Model d) {
System.out.print("* 수정할 관광명소 번호를 입력해 주세요 : ");
String num = sc.nextLine();
d.addAttribute("수정결과", ser_t.modify(num));
return "호출될 화면";
}
// 사용자 영역
public String listTravel2(Model d) {
d.addAttribute("정보출력", ser_t.showList());
return "호출될 화면";
}
public String searchTravel(Model d) {
System.out.print("* 검색어를 입력하세요 : ");
String msg = sc.nextLine();
d.addAttribute("검색결과", ser_t.search(msg));
return "호출될 화면";
}
public String detail(Model d) {
System.out.println("상세히 볼 관광명소를 선택해주세요");
String cho = sc.nextLine();
d.addAttribute("상세보기", ser_t.detail(cho));
questionList(d);
listRatings(d);
System.out.println("추가행동을 입력해 주세요");
System.out.println("정보수정업데이트\t리뷰남기기\t질문하기\t클립");
switch(sc.nextLine()) {
case "정보수정업데이트" :
changingInfoTravel(ser_t.detail(cho).get(0).getKorName(),d);
break;
case "리뷰남기기" :
login(d);
if(result==false) {
System.out.println("다시 로그인 하세요");
break;
}else{
insertRatings(ser_t.member(email).getName(),ser_t.detail(cho).get(0).getKorName(),d);
break;
}
case "질문하기" :
login(d);
if(result==false) {
System.out.println("다시 로그인 하세요");
break;
}else{
question(ser_t.member(email).getName(),ser_t.detail(cho).get(0).getKorName(),d);
break;
}
case "클립" :
login(d);
if(result==false) {
System.out.println("다시 로그인 하세요");
break;
}else{
clip(cho,d);
break;
}
}
return "호출될 화면";
}
public String clip(String n,Model d) {
System.out.println("클립을 추가하시겠습니까?(Y/N)");
String cho = sc.nextLine();
d.addAttribute("클립따기", ser_t.clip(cho,n));
return "호출될 화면";
}
public String changingInfoTravel(String s,Model d) {
System.out.println("요청할 카테고리를 선택해 주세요");
String cate = sc.nextLine();
System.out.println("수정할 내용을 적어주세요");
String content = sc.nextLine();
d.addAttribute("정보수정 요청", ser_t.changingInfo(s,cate,content));
return "호출될 화면";
}
public String question(String s,String n,Model d) {
System.out.println("제목: ");
String title = sc.nextLine();
System.out.println("내용: ");
String content = sc.nextLine();
System.out.println("태그: ");
String tag = sc.nextLine();
d.addAttribute("질문하기", ser_t.question(new Question_Travel(title,content,tag), s, n));
return "호출될 화면";
}
public String questionList(Model d) {
d.addAttribute("질문리스트", ser_t.questionList());
return "호출될 화면";
}
public String login(Model d) {
System.out.println("로그인");
System.out.print("이메일: ");
email = sc.nextLine();
System.out.print("비밀번호: ");
String pass = sc.nextLine();
result = ser_t.login(email, pass);
d.addAttribute("로그인",result );
return "호출될 화면";
}
public String insertRatings(String s,String n,Model d) {
System.out.println("만족도 선택");
System.out.println("좋아요! 괜찮아요! 별로에요!");
String feeling = sc.nextLine();
System.out.println("리뷰입력");
String review = sc.nextLine();
d.addAttribute("정보등록", ser_t.rinsert(new Ratings(s,feeling,n,review)));
return "호출될 화면";
}
public String listRatings(Model d) {
d.addAttribute("정보출력", ser_t.rshowList());
return "호출될 화면";
}
public String deleteRatings(Model d) {
System.out.print("* 삭제할 리뷰번호를 입력해 주세요 : ");
String msg = sc.nextLine();
d.addAttribute("삭제결과", ser_t.delete1(msg));
return "호출될 화면";
}
public String modifyRatings(Model d) {
System.out.print("* 수정할 리뷰번호를 입력해 주세요 : ");
String num = sc.nextLine();
d.addAttribute("수정결과", ser_t.modify1(num));
return "호출될 화면";
}
}
<file_sep>/javareview/src/main/java/project6/comment/Controller.java
package project6.comment;
import java.util.ArrayList;
import project6.page.Board;
public class Controller {
Dao dao = new Dao();
Service sv = new Service();
ArrayList<Board> blist = null;
// 댓글 작성
public String writeComment(Model d,Comment c) {
d.addAttribute("댓글 작성", dao.writeComment(c));
return "post.jsp";
}
// 작성된 댓글 보기(게시글 단위)
public String commentList(Model d,String code) {
d.addAttribute("댓글 보기", sv.commentList(code));
return "post.jsp";
}
// 게시글 리스트
public String boardList(Model d) {
d.addAttribute("게시글 리스트", blist= sv.boardList());
return "mypage.jsp";
}
}
<file_sep>/javareview/src/main/java/project6/sch/SchDao.java
package project6.sch;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class SchDao {
//아이디검색
public ArrayList<Member> schmem(String name) {
ArrayList<Member> list = new ArrayList<Member>();
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String sql = "SELECT name from scrollBook_mem where name like ?";
conn = DBConnection.getConnection();
pstm = conn.prepareStatement(sql);
pstm.setString(1, "%" + name + "%");
rs = pstm.executeQuery();
while (rs.next()) {
Member sl = new Member();
sl.setEmail(rs.getString("name"));
list.add(sl);
}
} catch (SQLException e) {
System.out.println("예외발생");
e.printStackTrace();
} finally {
// DB 연결을 종료한다.
try {
if (rs != null) rs.close();
if (pstm != null) pstm.close();
if (conn != null) conn.close();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
return list;
}
//태그검색
public ArrayList<Board> schtag(String contents) {
ArrayList<Board> list = new ArrayList<Board>();
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String sql = "SELECT img from Board WHERE contents LIKE ?";
conn = DBConnection.getConnection();
pstm = conn.prepareStatement(sql);
pstm.setString(1, "%" + contents + "%");
rs = pstm.executeQuery();
while (rs.next()) {
Board sl = new Board();
sl.setImg(rs.getString("img"));
list.add(sl);
}
} catch (SQLException e) {
System.out.println("예외발생");
e.printStackTrace();
} finally {
// DB 연결을 종료한다.
try {
if (rs != null) rs.close();
if (pstm != null) pstm.close();
if (conn != null) conn.close();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
return list;
}
}
<file_sep>/javareview/src/main/java/project6/like/LikeDao.java
package project6.like;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class LikeDao {
// 모든 게시물 리스트
public ArrayList<Board> boardListall() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<Board> list = new ArrayList<Board>();
try {
String sql = "select bcode,img from Board order by wdate desc";
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
Board b = new Board();
b.setBcode(rs.getString("bcode"));
b.setImg(rs.getString("img"));
list.add(b);
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
try {
if(pstmt!=null) pstmt.close();
if(conn!=null) conn.close();
}catch(Exception e) {
e.printStackTrace();
}
}
return list;
}
// 게시물 선택
public Board setBoard(String bcode) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Board brd = new Board();
try {
String sql = "select * from Board where bcode = ?";
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, bcode);
rs = pstmt.executeQuery();
if(rs.next()) {
brd.setBcode(rs.getString("bcode"));
brd.setContents(rs.getString("contents"));
brd.setImg(rs.getString("img"));
brd.setLoc(rs.getString("loc"));
brd.setPubRange(rs.getString("pubRange"));
brd.setWdate(rs.getDate("wdate"));
brd.setID(rs.getString("id"));
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
try {
if(rs!=null) rs.close();
if(pstmt!=null) pstmt.close();
if(conn!=null) conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return brd;
}
//좋아요 클릭(넣기/취소)
public void clicklike(String id,String bcode) {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String sql = "select * from scrollbook_like where bcode = ? and id = ?";
conn = DBConnection.getConnection();
pstm = conn.prepareStatement(sql);
pstm.setString(1, bcode);
pstm.setString(2, id);
rs = pstm.executeQuery();
if(rs.next()) {
sql = "delete from scrollbook_like where id = ? and bcode = ?";
conn = DBConnection.getConnection();
conn.setAutoCommit(false);
pstm = conn.prepareStatement(sql);
pstm.setString(1, id);
pstm.setString(2, bcode);
pstm.executeUpdate();
conn.commit();
}else {
sql = "insert into scrollbook_like values(?,?)";
conn = DBConnection.getConnection();
conn.setAutoCommit(false);
pstm = conn.prepareStatement(sql);
pstm.setString(1, bcode);
pstm.setString(2, id);
pstm.executeUpdate();
conn.commit();
}
} catch (SQLException e1) {
System.out.println("예외발생");
e1.printStackTrace();
try {
conn.rollback();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally{
try {
if(rs!=null) {
rs.close();
}
if (pstm != null) {
pstm.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e1) {
throw new RuntimeException(e1.getMessage());
}
}
}
}
<file_sep>/javareview/src/main/java/javareview/project4/Library.java
package javareview.project4;
public class Library {
private String kind;
private String name;
private String usetime;
private String closedDay;
private String pnum;
private String web;
private String loc;
private String bookjoin;
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsetime() {
return usetime;
}
public void setUsetime(String usetime) {
this.usetime = usetime;
}
public String getClosedDay() {
return closedDay;
}
public void setClosedDay(String closedDay) {
this.closedDay = closedDay;
}
public String getPnum() {
return pnum;
}
public void setPnum(String pnum) {
this.pnum = pnum;
}
public String getWeb() {
return web;
}
public void setWeb(String web) {
this.web = web;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public String getBookjoin() {
return bookjoin;
}
public void setBookjoin(String bookjoin) {
this.bookjoin = bookjoin;
}
}
<file_sep>/javareview/src/main/java/project6/comment/Dao.java
package project6.comment;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import project6.page.Board;
public class Dao {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
// 댓글 등록
public String writeComment(Comment c) {
try {
String sql = "insert into scrollbook_comment values(?,?,?,sysdate)";
conn = DBConnection.getConnection();
conn.setAutoCommit(false);
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, c.getBcode());
pstmt.setString(2, c.getId());
pstmt.setString(3, c.getContent());
pstmt.executeUpdate();
conn.commit();
}catch(SQLException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally {
try {
if(pstmt!=null) pstmt.close();
if(conn!=null) conn.close();
}catch(Exception e) {
e.printStackTrace();
}
}
return "작성완료";
}
// 댓글 보기
public ArrayList<Comment> commentList(String code) {
ArrayList<Comment> list = new ArrayList<Comment>();
SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String sql = "select id, content, cdate from scrollbook_comment where bcode = ?";
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, code);
rs = pstmt.executeQuery();
while(rs.next()){
Comment c = new Comment();
c.setId(rs.getString("id"));
c.setContent(rs.getString("content"));
String cdate = transFormat.format(rs.getDate("cdate"));
c.setCdate(cdate);
list.add(c);
}
}catch(SQLException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally {
try {
if(pstmt!=null) pstmt.close();
if(conn!=null) conn.close();
}catch(Exception e) {
e.printStackTrace();
}
}
return list;
}
// 게시물 리스트
public ArrayList<Board> boardList() {
ArrayList<Board> list = new ArrayList<Board>();
try {
String sql = "select bcode,img from Board";
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
Board b = new Board();
b.setBcode(rs.getString("bcode"));
b.setImg(rs.getString("img"));
list.add(b);
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
try {
if(pstmt!=null) pstmt.close();
if(conn!=null) conn.close();
}catch(Exception e) {
e.printStackTrace();
}
}
return list;
}
}<file_sep>/javareview/src/main/java/database/a09_0701.sql
/*
# 테이블 구조 변경
컬럼 타입,크기,기본값 변경 가능
데이터가 있는경우에는 다른 타입으로 변경 불가능,char -> varchar2는 가능
데이터가 없는경우는 변환이 자유롭다
형식 - alter table 테이블명 modify 컬럼명
*/
-- 데이터가 없는경우
CREATE TABLE emp0001
AS SELECT * FROM emp WHERE 1=0;
-- 크기 변경
ALTER TABLE emp0001
MODIFY ename varchar2(3000);
-- 타입 변경
ALTER TABLE emp0001
MODIFY empno varchar2(50);
-- 데이터가 있느 경우
CREATE TABLE emp0002
AS SELECT * FROM emp;
-- 크기 변경(단 기존의 값보다 작은수로는 불가능)
ALTER TABLE emp0002
MODIFY ename varchar2(100);
-- 컬럼의 최대 크기구하느법
SELECT max(LENGTH(ename)) FROM emp0002; -- 6
-- 카피테이블을 만든후 데이터유형을 바꾼후 update하여 다시 데이터를 넣는법
-- 1. 카피테이블 만들기(가져올 컬럼과, join할 컬럼 1개이상 필수)
CREATE TABLE cp_emp0002
AS SELECT empno, sal FROM emp0002;
-- 2. update 로 데이터유형을 바꾸려는 컬럼의 데이터들을 null 처리
UPDATE emp0002
SET sal = NULL;
-- 3. 데이터 유형 변경
ALTER TABLE emp0002
MODIFY sal varchar2(4);
-- 4. update로 데이터 입력
UPDATE emp0002 a
SET sal = (
SELECT sal
FROM cp_emp0002 b
WHERE a.empno = b.empno
);
SELECT * FROM emp0002;
/*
# 컬럼 이름변경, 테이블 이름변경
rename 테이블명 to 변경할 테이블명
alter table 테이블명
rename column 컬럼명 to 변경할 컬럼명
*/
RENAME emp0002 TO emp0003;
ALTER TABLE emp0003
RENAME COLUMN sal TO salary;
SELECT * FROM emp0003;
/*
# index(인덱스)
조회성 데이터의 처리 속도를 향상시키기 위해 컬럼에 대해 생성하는 객체
형식
create index 인덱스명
on table(컬럼명)
index정보를 확인하는 sql
select *
from user_ind_columns
where table_name = 테이블명
*/
select *
from user_ind_columns
where table_name = 'EMP';
CREATE INDEX idx_emp0003_empno
ON emp0003(empno);
select *
from user_ind_columns
where table_name = 'EMP0003';
/*
고유 인덱스
유일한 값을 가지는 컬럼에 대해 생성하는 인덱스로 모든 테이블에 하나씩은 연결됨
형식
create unique index 인덱스명
on table(컬럼명)
index정보를 확인하는 sql
*/
CREATE TABLE emp0004
AS SELECT * FROM emp;
CREATE UNIQUE INDEX idx_emp0004_empno
ON emp0004(empno);
/*
단일인덱스 - 하나의 컬럼만 들어간 경우
결합인덱스 - 두 개 이상의 컬럼을 결합하여 생성하는 인덱스
형식
create index 인덱스명
on 테이블명(컬럼명1, 컬럼명2)
*/
CREATE TABLE emp0005
AS SELECT * FROM emp;
CREATE INDEX idx_emp0005_ename_hiredate
ON emp0005(ename, hiredate);
select *
from user_ind_columns
where table_name = 'EMP0005';
/*
descending index
컬럼별로 정렬 순서를 별도로 지정하여 결합 인덱스
형식
create index 인덱스명
on 테이블명(컬럼명1 desc, 컬럼명2 asc);
*/
CREATE TABLE emp0006
AS SELECT * FROM emp;
CREATE INDEX idx_emp0005_empno_sal
ON emp0005(empno desc, sal asc);
select *
from user_ind_columns
where table_name = 'EMP0006';
/*
함수기반 인덱스
컬럼에 대한 연산이나 함수의 계산 결과를 인덱스로 생성하는 것
2insert, update시에 새로운 값을 인덱스에 추가
형식
create index 인덱스명 on 테이블(함수(컬럼))
*/
CREATE TABLE emp0007
AS SELECT * FROM emp;
CREATE INDEX lowercase_idx
ON emp0007(lower(job));
select *
from user_ind_columns
where table_name = 'EMP0007';
/*
# 데이터 베이스 사용자 생성과 권한 생성
사용자를 생성하려면 관리자 계정이나 사용자 생성권한을 가진 계정으로 접근하여 생성/권한을 부여한다
사용자 생성 형식
create user 사용자명 indentified by 비밀번호
권한 종류
1. create user : 사용자를 새롭게 생성하는 권한
2. drop user : 사용자를 삭제하는 권한
3. drop any table : 테이블을 삭제하는 권한
4. query rewrite : 함수 기반 인덱스 생성 권한
5. backup any table : 테이블 백업 권한
6 .create session : 데이터베이스에 접속할 수 있는 권한
7. create table/view/sequence/procedure 데이터베이스의 객체들을 생성하는 권한
권한 부여 방법
1. 테이블 생성 권한 부여
grant create table to 계정명
ex) grant create table to orauser01;
2. 전체 oracle에서 사용되는 여러객체(테이블,index,sequence..)에 대한 권한 부여
grant resource to 계정명;
3. 전체적인 계정에 대한 권한 부여 내용 확인하는 테이블
dba_users
4. tablespace - 저장공간을 할당
alter user 사용자명 default tablespace users; - 사용자가 사용할 tablespace 설정
alter user 사용자명 quota unlimited on users; - 사용자가 사용할 tablespace의 용량을 설정
*/<file_sep>/javareview/src/main/webapp/project6/js/header.js
/**
*
*/
var ref = document.querySelector("#refresh");
ref.onclick = function(){
location.reload();
}
var prof = document.querySelector("#profile");
prof.onclick = function(){
location.href = "mypage.jsp";
}<file_sep>/javareview/src/main/webapp/project6/js/collectionBoard.js
/**
*
*/
var top = document.querySelector("#top");
top.onclick = function(){
history.back();
}
|
ae7caa3bf5d27aee5c9129209aa2af544ff93620
|
[
"JavaScript",
"Java",
"SQL"
] | 57 |
Java
|
seungho-jo/Review
|
e36f3bae1d73dec36c1260dbe567f6f3fc747b8f
|
d6eca08023a3fa952b897c465c156f5183543abb
|
refs/heads/master
|
<file_sep>package com.eemf.sirgoingfar.core.custom
import android.app.ProgressDialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import com.eemf.sirgoingfar.core.R
class ProgressBarDialog(context: Context) : ProgressDialog(context) {
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
window!!.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
setContentView(R.layout.dialog_progress_bar)
}
}<file_sep>package com.eemf.sirgoingfar.core.custom
import android.app.Activity
import android.support.annotation.IdRes
import android.support.v4.app.Fragment
import android.view.View
/**
*
* The class is the Base class for all the App's ViewHolders
*
* */
abstract class AbsViewHolder {
protected lateinit var fragment: Fragment
protected var container: View? = null
protected lateinit var activity: Activity
constructor(container: View) {
this.container = container
}
constructor(fragment: Fragment) {
this.fragment = fragment
}
constructor(activity: Activity) {
this.activity = activity
}
protected abstract fun init(container: View)
fun gone(v: View) {
v.visibility = View.GONE
}
fun hide(v: View) {
v.visibility = View.INVISIBLE
}
fun show(v: View) {
v.visibility = View.VISIBLE
}
fun show(@IdRes viewId: Int) {
val view = getViewById(viewId)
if (view != null)
show(view)
}
fun hide(@IdRes viewId: Int) {
val view = getViewById(viewId)
if (view != null)
hide(view)
}
fun gone(@IdRes viewId: Int) {
val view = getViewById(viewId)
if (view != null)
gone(view)
}
fun getViewById(@IdRes viewId: Int): View? {
var view: View? = null
if (container != null) {
view = container!!.findViewById(viewId)
}
return view
}
interface AbsViewState {
fun setBlank()
fun setNoData()
fun setHasData()
fun setLoading(tag: String)
fun setLoaded(tag: String)
fun setLoading()
fun setLoaded()
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.viewmodels
import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import com.eemf.sirgoingfar.core.utils.App
import com.eemf.sirgoingfar.core.utils.AppExecutors
import com.eemf.sirgoingfar.database.AppDatabase
/**
*
* This is the Base Class for the Application ViewModels
*
* @property mApplication is the Application instance of the Caller or the LifeCycle owner
* that's instantiating the ViewModel
*
* @property mDb is the app database reference
* @property mExecutors is the instance of the Threading provider class
* @property uiState gives the current state of the UI
*
*
* */
open class BaseViewModel(mApplication: Application) : AndroidViewModel(mApplication) {
protected var mDb: AppDatabase? = AppDatabase.getInstance(mApplication)
protected var mExecutors: AppExecutors? = App.getsExecutors()
private val uiState = MutableLiveData<Int>()
protected fun setUiState(state: Int) {
uiState.postValue(state)
}
fun getUiStateObserver(): LiveData<Int> {
return uiState
}
companion object {
val STATE_LOADING = 0
val STATE_LOADED = 1
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.adapters
import android.content.Context
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import com.eemf.sirgoingfar.core.utils.Helper
import com.eemf.sirgoingfar.database.Routine
import com.eemf.sirgoingfar.routinechecker.R
import java.util.*
/**
* @property mContext is the context of the caller
* @property mListener is the action callback listener
* */
class RoutineListRecyclerViewAdapter(private val mContext: Context, private val mListener: OnRoutineClickListener) :
RecyclerView.Adapter<RoutineListRecyclerViewAdapter.ViewHolder>() {
private lateinit var mDataList: ArrayList<Routine>
override fun onCreateViewHolder(container: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_routine, container, false))
}
override fun getItemCount(): Int {
return mDataList.size
}
override fun onBindViewHolder(viewHolder: ViewHolder, viewType: Int) {
val currentItem: Routine = viewHolder.currentItem()
viewHolder.tvRoutineName?.text = currentItem.name
viewHolder.tvRoutineDesc?.text = currentItem.desc
viewHolder.tvRoutineTime?.text = Helper.getTimeStringFromDate(mContext, currentItem.date)
viewHolder.tvRoutineFreq?.text = Helper.getFreqById(currentItem.freqId)?.label ?: ""
viewHolder.cvContainer?.setOnClickListener { mListener.onRoutineClick(viewHolder.adapterPosition, currentItem) }
}
fun setData(data: ArrayList<Routine>?) {
if (data == null)
return
mDataList = data
notifyDataSetChanged()
}
/**
* @property itemView is a container of a Routine card
* @constructor creates a RecyclerView ViewHolder
* */
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@BindView(R.id.tv_routine_name)
@JvmField
var tvRoutineName: TextView? = null
@BindView(R.id.tv_routine_desc)
@JvmField
var tvRoutineDesc: TextView? = null
@BindView(R.id.tv_routine_time)
@JvmField
var tvRoutineTime: TextView? = null
@BindView(R.id.tv_routine_freq)
@JvmField
var tvRoutineFreq: TextView? = null
@BindView(R.id.container)
@JvmField
var cvContainer: CardView? = null
init {
ButterKnife.bind(this, itemView)
tvRoutineName = itemView.findViewById(R.id.tv_routine_name)
tvRoutineDesc = itemView.findViewById(R.id.tv_routine_desc)
tvRoutineTime = itemView.findViewById(R.id.tv_routine_time)
tvRoutineFreq = itemView.findViewById(R.id.tv_routine_freq)
cvContainer = itemView.findViewById(R.id.container)
}
fun currentItem(): Routine {
return mDataList[adapterPosition]
}
}
interface OnRoutineClickListener {
fun onRoutineClick(position: Int, clickedRoutine: Routine)
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.activities
import android.arch.lifecycle.Lifecycle
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v7.app.ActionBar
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.widget.FrameLayout
import android.widget.Toast
import com.eemf.sirgoingfar.core.utils.Prefs
abstract class BaseActivity : AppCompatActivity() {
private var actionBar: ActionBar? = null
private val currentFragment: Fragment? = null
protected var fragmentManager: FragmentManager? = supportFragmentManager
protected lateinit var prefs: Prefs
private var root: FrameLayout? = null
val isActivityStarted: Boolean
get() = lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
prefs = Prefs.getsInstance()
root = findViewById(android.R.id.content)
}
fun setActionBarTitle(title: String) {
if (actionBar == null)
actionBar = supportActionBar
actionBar!!.title = title
}
fun toast(msg: Any?) {
if (msg == null) {
return
}
Toast.makeText(applicationContext, msg.toString(), Toast.LENGTH_SHORT).show()
}
fun toastLong(msg: Any?) {
if (msg == null) return
Toast.makeText(applicationContext, msg.toString(), Toast.LENGTH_LONG).show()
}
protected fun createAlertDialog(message: String): AlertDialog.Builder {
return AlertDialog.Builder(this)
.setMessage(message)
}
}<file_sep>package com.eemf.sirgoingfar.database
import android.arch.lifecycle.LiveData
import android.arch.persistence.room.*
/**
*
* This class contains the functions for Database access
*
* */
@Dao
interface RoutineCheckerAppDao {
@Query("SELECT * FROM routine WHERE id=:id")
fun getRoutineById(id: Int): LiveData<Routine>
@Query("SELECT * FROM routine WHERE id=:id")
fun getRoutineByIdAsync(id: Int): Routine
@Query("SELECT * FROM routine")
fun getAllRoutine(): LiveData<List<Routine>>
@Query("SELECT * FROM routine_occurrence WHERE alarm_id=:id")
fun getRoutineOccurrenceByAlarmId(id: Int): RoutineOccurrence
@Insert
fun addRoutine(routine: Routine)
@Update(onConflict = OnConflictStrategy.REPLACE)
fun updateRoutine(routine: Routine)
@Query("SELECT * FROM routine_occurrence WHERE routine_id = :id AND NOT status=0")
fun getAllRoutineOccurrences(id: Int): LiveData<List<RoutineOccurrence>>
@Insert
fun addOccurrence(occurrence: RoutineOccurrence)
@Update(onConflict = OnConflictStrategy.REPLACE)
fun updateOccurrence(currentOccurrence: RoutineOccurrence)
@Delete
fun deleteRoutine(routine: Routine)
}
<file_sep>package com.eemf.sirgoingfar.core.utils
import android.content.Context
import android.content.SharedPreferences
/**
*
* The class routes access to the App's SharedPreference
*
* @param context is the context of the Caller
*
* */
class Prefs private constructor(context: Context) {
private val APP_PREFS = "app_prefs"
private val PREF_ALARM_ID = "pref_alarm_id"
private val mPrefs: SharedPreferences
private val editor: SharedPreferences.Editor
get() = mPrefs.edit()
private val lastAlarmId: Int
get() = mPrefs.getInt(PREF_ALARM_ID, -1)
val nextAlarmId: Int
get() {
val lastAlarmId = lastAlarmId
val nextAlarmId = lastAlarmId + 1
saveNextAlarmId(nextAlarmId)
return nextAlarmId
}
init {
sInstance = this
mPrefs = context.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE)
}
private fun saveNextAlarmId(id: Int) {
editor.putInt(PREF_ALARM_ID, id).apply()
}
companion object {
private var sInstance: Prefs? = null
fun getsInstance(): Prefs {
if (sInstance == null)
sInstance = Prefs(App.getsInstance()!!.appContext)
return sInstance as Prefs
}
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.viewmodels
import android.app.Application
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Observer
import com.eemf.sirgoingfar.database.Routine
/**
*
* This is the ViewModel for the RoutineList page
*
* @property mApplication is the Application instance of the Caller or the LifeCycle owner
* that's instantiating the ViewModel
*
* @property lifecycleOwner is the instance of the ViewModel lifecycle owner
*
* @property mRoutineListMutableLiveData is the livedata object of the list of
* Routines
*
* @property mRoutineMutableLiveData is the livedata object of a requested by Id Routine
*
* */
class RoutineListActivityViewModel(mApplication: Application, private val lifecycleOwner: LifecycleOwner) : BaseViewModel(mApplication) {
private val mRoutineMutableLiveData: MutableLiveData<Routine> = MutableLiveData()
private val mRoutineListMutableLiveData: MutableLiveData<List<Routine>> = MutableLiveData()
fun getRoutineObserver(): LiveData<Routine> {
return mRoutineMutableLiveData
}
fun getRoutineListObserver(): LiveData<List<Routine>> {
return mRoutineListMutableLiveData
}
private fun setRoutine(routine: Routine?) {
setUiState(STATE_LOADED)
mRoutineMutableLiveData.postValue(routine)
}
private fun setRoutineList(routineList: List<Routine>?) {
setUiState(STATE_LOADED)
mRoutineListMutableLiveData.postValue(routineList)
}
fun getRoutineById(routineId: Int) {
setUiState(STATE_LOADING)
mExecutors?.diskIO()?.execute {
mDb?.dao?.getRoutineById(routineId)?.observe(lifecycleOwner, Observer {
setRoutine(it)
})
}
}
fun getAllRoutines() {
setUiState(STATE_LOADING)
mExecutors?.diskIO()?.execute {
mDb?.dao?.getAllRoutine()?.observe(lifecycleOwner, Observer {
setRoutineList(it)
})
}
}
fun addRoutine(routine: Routine) {
mExecutors?.diskIO()?.execute {
mDb?.dao?.addRoutine(routine)
}
}
fun editRoutine(routine: Routine) {
mExecutors?.diskIO()?.execute {
mDb?.dao?.updateRoutine(routine)
}
}
fun deleteRoutine(routine: Routine) {
mExecutors?.diskIO()?.execute {
mDb?.dao?.deleteRoutine(routine)
}
}
}<file_sep>package com.eemf.sirgoingfar.routinechecker.adapters
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import com.eemf.sirgoingfar.core.utils.Constants
import com.eemf.sirgoingfar.core.utils.Helper
import com.eemf.sirgoingfar.database.RoutineOccurrence
import com.eemf.sirgoingfar.routinechecker.R
import java.util.*
/**
* @property mContext is the context of the caller
* @property mListener is the action callback on the ViewHolder
* @constructor creates a new RoutineOccurrenceRecyclerViewAdapter
* */
class RoutineOccurrenceRecyclerViewAdapter(private val mContext: Context, private val mListener: OnStatusButtonClickListener) :
RecyclerView.Adapter<RoutineOccurrenceRecyclerViewAdapter.ViewHolder>() {
private lateinit var mDataList: ArrayList<RoutineOccurrence>
override fun onCreateViewHolder(container: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_routine_occurrence, container, false))
}
override fun getItemCount(): Int {
return mDataList.size
}
override fun onBindViewHolder(viewHolder: ViewHolder, viewType: Int) {
val currentItem: RoutineOccurrence = viewHolder.currentItem()
viewHolder.tvOccurrenceDate?.text = Helper.getDateString(currentItem.occurrenceDate)
?: mContext.getString(R.string.text_unavailable)
viewHolder.tvOccurrenceStatus?.text = Constants.Status.getStatusById(currentItem.status)?.label
if (currentItem.status == Constants.Status.DONE.id)
viewHolder.tvOccurrenceStatus?.setTextColor(ContextCompat.getColor(mContext, R.color.colorDone))
else
viewHolder.tvOccurrenceStatus?.setTextColor(ContextCompat.getColor(mContext, R.color.colorMissed))
if (currentItem.status == Constants.Status.PROGRESS.id) {
viewHolder.btnDone?.visibility = View.VISIBLE
viewHolder.btnMissed?.visibility = View.VISIBLE
viewHolder.divider?.visibility = View.VISIBLE
viewHolder.btnDone?.setOnClickListener { mListener.onDoneBtnClick(viewHolder.adapterPosition, currentItem) }
viewHolder.btnMissed?.setOnClickListener { mListener.onMissedBtnClick(viewHolder.adapterPosition, currentItem) }
} else {
viewHolder.btnDone?.visibility = View.GONE
viewHolder.btnMissed?.visibility = View.GONE
viewHolder.divider?.visibility = View.GONE
}
}
fun setData(data: ArrayList<RoutineOccurrence>?) {
if (data == null)
return
mDataList = data
notifyDataSetChanged()
}
/**
* @property itemView is a container of a Routine Occurrence card
* @constructor creates a ViewHolder instance of the RecyclerView
* */
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@BindView(R.id.tv_occurrence_date)
@JvmField
var tvOccurrenceDate: TextView? = null
@BindView(R.id.tv_occurrence_status)
@JvmField
var tvOccurrenceStatus: TextView? = null
@BindView(R.id.btn_done)
@JvmField
var btnDone: TextView? = null
@BindView(R.id.btn_missed)
@JvmField
var btnMissed: TextView? = null
@BindView(R.id.horizontal_rule)
@JvmField
var divider: View? = null
init {
ButterKnife.bind(this, itemView)
tvOccurrenceDate = itemView.findViewById(R.id.tv_occurrence_date)
tvOccurrenceStatus = itemView.findViewById(R.id.tv_occurrence_status)
btnDone = itemView.findViewById(R.id.btn_done)
btnMissed = itemView.findViewById(R.id.btn_missed)
divider = itemView.findViewById(R.id.horizontal_rule)
}
fun currentItem(): RoutineOccurrence {
return mDataList[adapterPosition]
}
}
interface OnStatusButtonClickListener {
fun onDoneBtnClick(position: Int, clickedRoutineOccurrence: RoutineOccurrence)
fun onMissedBtnClick(position: Int, clickedRoutineOccurrence: RoutineOccurrence)
}
}<file_sep>package com.eemf.sirgoingfar.core.custom
import android.content.Context
import android.support.v4.content.ContextCompat
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import com.eemf.sirgoingfar.core.R
class CustomSpinnerArrayAdapter(private val mContext: Context, private val resourceId: Int, data: ArrayList<String>) : ArrayAdapter<String>(mContext, resourceId, data) {
private var data = ArrayList<String>()
private var unselectablePosition: Int = 0
private var unselectableItemColor: Int = 0
private var selectedItemColor: Int = 0
private var selectedItemTextSize: Float = 0.toFloat()
init {
this.data = data
//set default values
setUnselectablePosition(R.color.colorBlack_transluscent)
setSelectedItemColor(R.color.colorBlack)
setSelectedItemTextSize(12f)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
try {
val view = super.getView(position, convertView, parent) as TextView
view.textSize = selectedItemTextSize
if (position == unselectablePosition)
view.setTextColor(ContextCompat.getColor(mContext, unselectableItemColor))
else
view.setTextColor(ContextCompat.getColor(mContext, selectedItemColor))
return view
} catch (ex: Exception) {
ex.printStackTrace()
return super.getView(position, convertView, parent)
}
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
try {
val textView = super.getDropDownView(position, convertView, parent) as TextView
if (position == unselectablePosition) {
// Set the hint text color gray
textView.setTextColor(ContextCompat.getColor(mContext, unselectableItemColor))
} else {
textView.setTextColor(ContextCompat.getColor(mContext, selectedItemColor))
}
return textView
} catch (ex: Exception) {
ex.printStackTrace()
return super.getDropDownView(position, convertView, parent)
}
}
override fun isEnabled(position: Int): Boolean {
return position != unselectablePosition && super.isEnabled(position)
}
fun setUnselectablePosition(unselectablePosition: Int) {
this.unselectablePosition = unselectablePosition
}
fun setUnselectableItemColor(unselectableItemColor: Int) {
this.unselectableItemColor = unselectableItemColor
}
fun setSelectedItemColor(selectedItemColor: Int) {
this.selectedItemColor = selectedItemColor
}
fun setSelectedItemTextSize(selectedItemTextSize: Float) {
this.selectedItemTextSize = selectedItemTextSize
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.viewmodels
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
/**
*
* This is the App ViewModels Factory
*
* @property mProviderMap is the map of ViewModel-ViewModel Provider for all the
* app's ViewModels
*
*
* */
class ViewModelFactory @Inject
constructor(private val mProviderMap: Map<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory {
/**
*
* @return a factory of a given ViewModel class from the Provider map
*
* */
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return (mProviderMap[modelClass] ?: error("")).get() as T
}
}
<file_sep>package com.eemf.sirgoingfar.database
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Ignore
import android.arch.persistence.room.PrimaryKey
import android.os.Parcel
import android.os.Parcelable
import java.util.*
@Entity
class Routine() : Parcelable {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
var name: String? = null
var desc: String? = null
var freqId: Int = 0
@ColumnInfo(name = "routine_time")
var date: Date? = null
@ColumnInfo(name = "last_routine_date")
var nextRoutineDate: Date? = null
constructor(parcel: Parcel) : this() {
id = parcel.readInt()
name = parcel.readString()
desc = parcel.readString()
freqId = parcel.readInt()
date = Date(parcel.readLong())
nextRoutineDate = Date(parcel.readLong())
}
constructor(id: Int, name: String?, desc: String?, freqId: Int, date: Date?, lastRoutineDate: Date?) : this() {
this.id = id
this.name = name
this.desc = desc
this.freqId = freqId
this.date = date
this.nextRoutineDate = lastRoutineDate
}
@Ignore
constructor(name: String?, desc: String?, freqId: Int, date: Date?, lastRoutineDate: Date?) : this() {
this.name = name
this.desc = desc
this.freqId = freqId
this.date = date
this.nextRoutineDate = lastRoutineDate
}
@Ignore
constructor(name: String?, desc: String?, freqId: Int, date: Date?) : this() {
this.name = name
this.desc = desc
this.freqId = freqId
this.date = date
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(id)
parcel.writeString(name)
parcel.writeString(desc)
parcel.writeInt(freqId)
parcel.writeLong(date?.time ?: 0)
parcel.writeLong(nextRoutineDate?.time ?: 0)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Routine> {
override fun createFromParcel(parcel: Parcel): Routine {
return Routine(parcel)
}
override fun newArray(size: Int): Array<Routine?> {
return arrayOfNulls(size)
}
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.viewmodels
import android.app.Application
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.ViewModel
import dagger.MapKey
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoMap
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import javax.inject.Provider
import kotlin.reflect.KClass
/**
*
* The class has the declaration of all the app's viewmodel classes that needs to be injected to function.
*
*The ViewModelModule is essential to avoid writing different Factories for all the ViewModels that need to be injected
*
* @constructor creates an instance of the ViewModelModule
*
* */
@Module
class ViewModelModule {
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@Retention(RetentionPolicy.RUNTIME)
@MapKey
internal annotation class ViewModelKey(val value: KClass<out ViewModel>)
@Provides
internal fun getViewModelFactory(providerMap: Map<Class<out ViewModel>, Provider<ViewModel>>): ViewModelFactory {
return ViewModelFactory(providerMap)
}
@Provides
@IntoMap
@ViewModelKey(RoutineListActivityViewModel::class)
fun getRoutineListActivityViewModel(application: Application, lifecycleOwner: LifecycleOwner): ViewModel {
return RoutineListActivityViewModel(application, lifecycleOwner)
}
@Provides
@IntoMap
@ViewModelKey(RoutineDetailOccurrenceListViewModel::class)
fun getRoutineOccurenceListViewModel(application: Application, lifecycleOwner: LifecycleOwner): ViewModel {
return RoutineDetailOccurrenceListViewModel(application, lifecycleOwner)
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.alarm
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.support.v4.app.NotificationCompat
import com.eemf.sirgoingfar.core.utils.Constants
import com.eemf.sirgoingfar.core.utils.Helper
import com.eemf.sirgoingfar.core.utils.ParcelableUtil
import com.eemf.sirgoingfar.core.utils.Prefs
import com.eemf.sirgoingfar.database.AppDatabase
import com.eemf.sirgoingfar.database.RoutineOccurrence
import com.eemf.sirgoingfar.routinechecker.R
import com.eemf.sirgoingfar.routinechecker.activities.RoutineListActivity
import com.eemf.sirgoingfar.routinechecker.jobs.SimulatedJob
import com.eemf.sirgoingfar.routinechecker.notification.NotificationHelper
import com.eemf.sirgoingfar.routinechecker.notification.NotificationParam
import com.eemf.sirgoingfar.timely.alarm.AlarmHelper
import kotlinx.coroutines.*
/**
* This is the Alarm trigger listener for the scheduled routine occurrences
*
* It coordinates the actions to be performed when a routine occurrence goes off
*
* @constructor creates an instance of the AlarmReceiver
* */
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (!intent.hasExtra(AlarmHelper.KEY_EXTRA_OCCURRENCE))
return
val occurrenceByte = intent.getByteArrayExtra(AlarmHelper.KEY_EXTRA_OCCURRENCE)
val occurrence = ParcelableUtil.unmarshall(occurrenceByte, RoutineOccurrence.CREATOR)
//trigger PUSH: clear previous ones first
val param = NotificationParam()
val notifHelper = NotificationHelper(context)
param.setRemovePreviousNotif(true)
param.title = context.getString(R.string.text_push_title)
param.body = getNotifBody(context, occurrence)
param.priorityType = NotificationCompat.PRIORITY_HIGH
param.btnOneText = context.getString(R.string.text_push_btn_two_label)
param.btnOnePendingIntent = getRoutineUpdatePendingIntent(context, occurrence)
param.bodyPendingIntent = getLaunchAppPendingIntent(context, occurrence.alarmId)
param.isAutoCancel = true
notifHelper.notifyUser(param)
GlobalScope.launch(Dispatchers.Default) {
updateOccurrence(context, occurrence)
}
}
private suspend fun updateOccurrence(context: Context, occurrence: RoutineOccurrence) = coroutineScope {
withContext(Dispatchers.IO) {
//update Routines's Status and update the database
val mDb = AppDatabase.getInstance(context)
val currentOccurrence: RoutineOccurrence? = mDb?.dao?.getRoutineOccurrenceByAlarmId(occurrence.alarmId)
//update Routines's Status and update the database
if (currentOccurrence?.status == Constants.Status.UNKNOWN.id) {
//If the user hasn't changed the status, toggle it
currentOccurrence.status = Constants.Status.PROGRESS.id
mDb.dao.updateOccurrence(currentOccurrence)
}
delay(Constants.MINIMUM_NOTIF_TIME_TO_START_TIME_MILLIS.toLong())
//schedule for the next routine
val nextOccurrencePeriod = Helper.computeNextRoutineTime(currentOccurrence!!.freqId, currentOccurrence.occurrenceDate)
val nextOccurrence = RoutineOccurrence(currentOccurrence.routineId, Constants.Status.UNKNOWN.id,
nextOccurrencePeriod, Prefs.getsInstance().nextAlarmId, currentOccurrence.name, currentOccurrence.desc, currentOccurrence.freqId)
//schedule next routine
AlarmHelper().execute(nextOccurrence, AlarmHelper.ACTION_SCHEDULE_ALARM)
//start Simulated Job
withContext(Dispatchers.Default) {
SimulatedJob(context, currentOccurrence).runJob()
}
}
}
private fun getNotifBody(context: Context, occurrence: RoutineOccurrence): String {
return context.getString(R.string.notif_body, occurrence.name, occurrence.desc,
Helper.getTimeStringFromDate(context, occurrence.occurrenceDate))
}
private fun getRoutineUpdatePendingIntent(context: Context, occurrence: RoutineOccurrence): PendingIntent {
val intent = Intent(context, NotificationActionService::class.java)
intent.action = NotificationActionService.ACTION_UPDATE_ROUTINE
val occurrenceByte = ParcelableUtil.marshall(occurrence)
intent.putExtra(AlarmHelper.KEY_EXTRA_OCCURRENCE, occurrenceByte)
return PendingIntent.getService(context, occurrence.alarmId, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun getLaunchAppPendingIntent(context: Context, alarmId: Int): PendingIntent {
return PendingIntent.getActivity(context, alarmId, Intent(context, RoutineListActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
}
companion object {
const val EXTRA_KEY_ALARM_RECEIVER_ACTION = "key_update_alarm"
const val ALARM_ACTION_UPDATE_ALARM = "action_update_alarm"
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.dialog_fragments
import android.app.Dialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.*
import butterknife.BindView
import butterknife.ButterKnife
import com.eemf.sirgoingfar.core.custom.CustomSpinnerArrayAdapter
import com.eemf.sirgoingfar.core.utils.Constants
import com.eemf.sirgoingfar.core.utils.Frequency
import com.eemf.sirgoingfar.core.utils.Helper
import com.eemf.sirgoingfar.database.Routine
import com.eemf.sirgoingfar.routinechecker.R
import java.io.Serializable
import java.lang.String.format
import java.util.*
class AddActivityDialogFragment : BaseDialogFragment(), TimePickerDialog.OnTimeSetListener, AdapterView.OnItemSelectedListener {
@BindView(R.id.tv_header_text)
@JvmField
var headerText: TextView? = null
@BindView(R.id.et_routine_title)
@JvmField
var title: EditText? = null
@BindView(R.id.et_routine_desc)
@JvmField
var desc: EditText? = null
@BindView(R.id.tv_routine_start_time)
@JvmField
var time: TextView? = null
@BindView(R.id.spinner_routine_freq)
@JvmField
var freqSpinner: Spinner? = null
@BindView(R.id.btn_add_routine)
@JvmField
var btnAddActivity: Button? = null
@BindView(R.id.btn_add_another_routine)
@JvmField
var btnAddAnother: Button? = null
private var selectedFrequencyIndex: Int = 0
private var selectedRoutineTime: Calendar = Calendar.getInstance()
private var titleText: String? = null
private var descText: String? = null
private var isEdit: Boolean = false
private var is24Hour: Boolean = false
private var isTimeSelected: Boolean = false
private lateinit var mListener: OnSaveOccurrence
private var mRoutine: Routine? = null
private lateinit var mTimePicker: TimePickerDialog
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.dialog_add_routine, container, false)
ButterKnife.bind(this, view)
return view
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
if (savedInstanceState != null) {
selectedRoutineTime.timeInMillis = savedInstanceState.getLong(Constants.ARG_TIME)
titleText = savedInstanceState.getString(Constants.ARG_ROUTINE_TITLE)
descText = savedInstanceState.getString(Constants.ARG_ROUTINE_DESC)
selectedRoutineTime.time = Date(savedInstanceState.getLong(Constants.ARG_TIME))
isTimeSelected = savedInstanceState.getBoolean(Constants.ARG_IS_TIME_SELECTED, false)
selectedFrequencyIndex = savedInstanceState.getInt(Constants.ARG_ROUTINE_PRIORITY)
mListener = savedInstanceState.getSerializable(Constants.ARG_LISTENER) as OnSaveOccurrence
if (isEdit)
mRoutine = savedInstanceState.getParcelable<Parcelable>(Constants.ARG_CURRENT_ROUTINE) as Routine
}
val dialog = super.onCreateDialog(savedInstanceState)
//get device width and height
val metrics = resources.displayMetrics
val deviceWidth = metrics.widthPixels
val deviceHeight = metrics.heightPixels
val width = (deviceWidth * 0.9).toInt()
val height: Int = (deviceHeight * 0.6).toInt()
val window = dialog.window
if (window != null) {
//remove window title
window.requestFeature(Window.FEATURE_NO_TITLE)
//set Width and Height
dialog.setContentView(R.layout.dialog_add_routine)
window.setLayout(width, height)
//set window layout
dialog.setContentView(R.layout.dialog_add_routine)
}
return dialog
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initializeViews(view)
}
private fun initializeViews(container: View) {
headerText = container.findViewById(R.id.tv_header_text)
title = container.findViewById(R.id.et_routine_title)
desc = container.findViewById(R.id.et_routine_desc)
time = container.findViewById(R.id.tv_routine_start_time)
freqSpinner = container.findViewById(R.id.spinner_routine_freq)
btnAddActivity = container.findViewById(R.id.btn_add_routine)
btnAddAnother = container.findViewById(R.id.btn_add_another_routine)
if (isEdit) {
val cal = Calendar.getInstance()
cal.time = mRoutine?.date
var hr = if (is24Hour) cal.get(Calendar.HOUR_OF_DAY) else cal.get(Calendar.HOUR)
if (!is24Hour && cal.get(Calendar.AM_PM) == Calendar.PM)
hr += 12
val min = cal.get(Calendar.MINUTE)
selectedRoutineTime = Calendar.getInstance()
selectedRoutineTime.time = mRoutine?.date
title?.setText(mRoutine?.name)
desc?.setText(mRoutine?.desc)
time?.text = getTimeText(is24Hour, hr, min)
selectedFrequencyIndex = mRoutine?.freqId?.plus(1) ?: 0
headerText!!.text = appCompatActivity.getString(R.string.text_edit_routine)
btnAddAnother?.visibility = View.GONE
btnAddActivity?.text = appCompatActivity.getString(R.string.text_done)
isTimeSelected = true
}
val freqList = ArrayList<String>()
freqList.add(appCompatActivity.getString(R.string.text_select_a_frequency))
freqList.add(Frequency.HOURLY.label)
freqList.add(Frequency.DAILY.label)
freqList.add(Frequency.WEEKLY.label)
freqList.add(Frequency.MONTHLY.label)
freqList.add(Frequency.YEARLY.label)
val spinnerArrayAdapter = CustomSpinnerArrayAdapter(appCompatActivity, R.layout.spinner_selected_item_look, freqList)
spinnerArrayAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item)
spinnerArrayAdapter.setSelectedItemColor(R.color.colorBlack)
spinnerArrayAdapter.setUnselectableItemColor(R.color.colorBlack_transluscent)
spinnerArrayAdapter.setUnselectablePosition(0)
spinnerArrayAdapter.setSelectedItemTextSize(16f)
freqSpinner?.adapter = spinnerArrayAdapter
freqSpinner?.prompt = appCompatActivity.getString(R.string.text_select_a_frequency)
freqSpinner?.setSelection(selectedFrequencyIndex)
freqSpinner?.onItemSelectedListener = this@AddActivityDialogFragment
if (!TextUtils.isEmpty(titleText))
title?.setText(titleText)
if (!TextUtils.isEmpty(descText))
desc?.setText(descText)
time?.setOnClickListener {
val hour = if (is24Hour) selectedRoutineTime.get(Calendar.HOUR_OF_DAY) else selectedRoutineTime.get(Calendar.HOUR)
mTimePicker = TimePickerDialog(appCompatActivity, this, hour,
selectedRoutineTime.get(Calendar.MINUTE), is24Hour)
mTimePicker.show()
}
if (isTimeSelected)
time?.text = getTimeText(is24Hour, selectedRoutineTime.get(Calendar.HOUR_OF_DAY), selectedRoutineTime.get(Calendar.MINUTE))
btnAddActivity?.setOnClickListener { saveRoutine(true) }
btnAddAnother?.setOnClickListener { saveRoutine(false) }
}
private fun saveRoutine(dismissDialog: Boolean) {
val routine = getRoutineObject() ?: return
mListener.onSaveRoutine(routine, isEdit)
if (dismissDialog) {
if (isAdded)
dismiss()
} else {
resetViews()
}
}
private fun getRoutineObject(): Routine? {
titleText = title?.text.toString()
if (TextUtils.isEmpty(titleText)) {
title?.error = "Title cannot be empty"
return null
}
descText = desc?.text.toString()
if (TextUtils.isEmpty(descText)) {
desc?.error = "Description cannot be empty"
return null
}
if (!isTimeSelected) {
toast("Select time")
return null
}
if (selectedFrequencyIndex < 0) {
toast("Select a frequency")
return null
}
if (isEdit) {
mRoutine?.name = titleText
mRoutine?.desc = descText
mRoutine?.freqId = selectedFrequencyIndex
mRoutine?.date = selectedRoutineTime.time
return mRoutine
} else {
return Routine(titleText, descText, selectedFrequencyIndex, selectedRoutineTime.time, selectedRoutineTime.time)
}
}
private fun resetViews() {
title?.setText("")
desc?.setText("")
time?.text = ""
freqSpinner?.setSelection(0)
if (isEdit)
selectedRoutineTime.time = mRoutine?.date
}
override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
isTimeSelected = true
if (is24Hour) {
selectedRoutineTime.set(Calendar.HOUR_OF_DAY, hourOfDay)
selectedRoutineTime.set(Calendar.MINUTE, minute)
} else {
selectedRoutineTime.set(Calendar.HOUR, hourOfDay % 12)
selectedRoutineTime.set(Calendar.MINUTE, minute)
selectedRoutineTime.set(Calendar.AM_PM, if (hourOfDay >= 12) Calendar.PM else Calendar.AM)
}
time?.text = getTimeText(is24Hour, hourOfDay, minute)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
selectedFrequencyIndex = position - 1
}
private fun getTimeText(is24Hour: Boolean, hourOfDay: Int, minute: Int): String {
return if (is24Hour)
String.format(Locale.getDefault(), "%02d", hourOfDay) + ":" + minute.toString()
else
(if (hourOfDay % 12 == 0) 12 else hourOfDay % 12).toString() + ":" + format(Locale.getDefault(), "%02d", minute) + if (hourOfDay >= 12) " PM" else " AM"
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putSerializable(Constants.ARG_LISTENER, mListener)
outState.putInt(Constants.ARG_ROUTINE_PRIORITY, selectedFrequencyIndex)
titleText = title?.text.toString()
descText = desc?.text.toString()
if (!TextUtils.isEmpty(titleText))
outState.putString(Constants.ARG_ROUTINE_TITLE, titleText)
if (!TextUtils.isEmpty(descText))
outState.putString(Constants.ARG_ROUTINE_DESC, descText)
if (mRoutine != null)
outState.putParcelable(Constants.ARG_CURRENT_ROUTINE, mRoutine)
if (isTimeSelected) {
outState.putLong(Constants.ARG_TIME, selectedRoutineTime.timeInMillis)
outState.putBoolean(Constants.ARG_IS_TIME_SELECTED, true)
}
}
interface OnSaveOccurrence : Serializable {
fun onSaveRoutine(routine: Routine, isEdit: Boolean)
}
companion object {
fun newInstance(routine: Routine, listener: OnSaveOccurrence, isEdit: Boolean): AddActivityDialogFragment {
val args = Bundle()
val fragment = AddActivityDialogFragment()
fragment.mRoutine = routine
fragment.mListener = listener
fragment.isEdit = isEdit
fragment.arguments = args
return fragment
}
fun newInstance(listener: OnSaveOccurrence, isEdit: Boolean): AddActivityDialogFragment {
val args = Bundle()
val fragment = AddActivityDialogFragment()
fragment.mListener = listener
fragment.isEdit = isEdit
fragment.arguments = args
return fragment
}
}
}
<file_sep>package com.eemf.sirgoingfar.database
import android.arch.persistence.room.*
import android.os.Parcel
import android.os.Parcelable
import java.util.*
@Entity(tableName = "routine_occurrence",
foreignKeys = [ForeignKey(
entity = Routine::class, parentColumns = ["id"],
childColumns = ["routine_id"],
onDelete = ForeignKey.CASCADE)],
indices = [Index("routine_id")])
class RoutineOccurrence() : Parcelable {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@ColumnInfo(name = "routine_id")
var routineId: Int = 0
var status: Int = 0
@ColumnInfo(name = "occurrence_date")
var occurrenceDate: Date? = null
@ColumnInfo(name = "alarm_id")
var alarmId: Int = 0
var name: String? = null
var desc: String? = null
@ColumnInfo(name = "frequency_id")
var freqId: Int = 0
@Ignore
constructor(parcel: Parcel) : this() {
id = parcel.readInt()
routineId = parcel.readInt()
status = parcel.readInt()
occurrenceDate = Date(parcel.readLong())
alarmId = parcel.readInt()
name = parcel.readString()
desc = parcel.readString()
freqId = parcel.readInt()
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(id)
parcel.writeInt(routineId)
parcel.writeInt(status)
parcel.writeLong(occurrenceDate?.time ?: 0)
parcel.writeInt(alarmId)
parcel.writeString(name)
parcel.writeString(desc)
parcel.writeInt(freqId)
}
constructor(id: Int, routineId: Int, status: Int, occurrenceDate: Date?, alarmId: Int, name: String?, desc: String?, freqId: Int) : this() {
this.id = id
this.routineId = routineId
this.status = status
this.occurrenceDate = occurrenceDate
this.alarmId = alarmId
this.name = name
this.desc = desc
this.freqId = freqId
}
@Ignore
constructor(routineId: Int, status: Int, occurrenceDate: Date?, alarmId: Int, name: String?, desc: String?, freqId: Int) : this() {
this.routineId = routineId
this.status = status
this.occurrenceDate = occurrenceDate
this.alarmId = alarmId
this.name = name
this.desc = desc
this.freqId = freqId
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<RoutineOccurrence> {
override fun createFromParcel(parcel: Parcel): RoutineOccurrence {
return RoutineOccurrence(parcel)
}
override fun newArray(size: Int): Array<RoutineOccurrence?> {
return arrayOfNulls(size)
}
}
}
<file_sep>package com.eemf.sirgoingfar.core.utils
import android.content.Context
import android.support.multidex.MultiDexApplication
import java.util.*
/**
*
* The App class is the point of entry/instantiation of the App
*
* App-wide static objects are initialized here
*
* */
class App : MultiDexApplication() {
val appContext: Context
get() = this
override fun onCreate() {
super.onCreate()
//init class static instance
if (sInstance == null)
sInstance = this
//init crucial instances
initInstances()
}
private fun initInstances() {
//init App Executors
sExecutors = AppExecutors.instance
//init color codes
colorCodes = ColorUtil.getColorCode(this)
}
companion object {
val NOTIF_CHANNEL_ID = "channel_general"
val NOTIF_CHANNEL_NAME = "General"
val NOTIF_ID = 123
val APP_GROUP_KEY = "com.eemf.sirgoingfar.android"
private var sInstance: App? = null
private var sExecutors: AppExecutors? = null
var colorCodes: ArrayList<Int>? = null
private set
fun getsInstance(): App? {
return sInstance
}
fun getsExecutors(): AppExecutors? {
return sExecutors
}
}
}
<file_sep>package com.eemf.sirgoingfar.core.models
import android.os.Parcel
import android.os.Parcelable
/**
*
* @property name is the name of the Routine
*
* @property estimate is the estimated elapsed time (in String) of the next occurrence of the Routine
*
* @constructor creates an instance of the NextUpRoutine
*
* */
class NextUpRoutine() : Parcelable {
var name: String? = null
var estimate: String? = null
constructor(parcel: Parcel) : this() {
name = parcel.readString()
estimate = parcel.readString()
}
constructor(name: String?, estimate: String?) : this() {
this.name = name
this.estimate = estimate
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(name)
parcel.writeString(estimate)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<NextUpRoutine> {
override fun createFromParcel(parcel: Parcel): NextUpRoutine {
return NextUpRoutine(parcel)
}
override fun newArray(size: Int): Array<NextUpRoutine?> {
return arrayOfNulls(size)
}
}
}<file_sep>package com.eemf.sirgoingfar.database
import android.arch.persistence.room.TypeConverter
import java.util.*
/**
*
* The class enables Room to convert Date field(s) in the Entity classes to Long and vice versa
*
* */
class DateConverter {
@TypeConverter
fun toTimeStamp(date: Date?): Long? {
return date?.time
}
@TypeConverter
fun toDate(timeStamp: Long?): Date? {
return if (timeStamp != null) Date(timeStamp) else null
}
}
<file_sep>package com.eemf.sirgoingfar.core.utils
import android.content.Context
import com.eemf.sirgoingfar.core.R
import java.util.*
object ColorUtil {
fun getColorCode(context: Context): ArrayList<Int> {
val typedArray = context.resources.obtainTypedArray(R.array.progress_color_codes)
return ArrayList(Helper.convertTypedArrayToIntegerArrayList(typedArray))
}
fun getColor(position: Int): Int {
val colorCodes = App.colorCodes
return colorCodes!![position % colorCodes.size]
}
}
<file_sep>package com.eemf.sirgoingfar.core.utils
import android.content.Context
import android.content.res.Configuration
import android.util.DisplayMetrics
import android.util.TypedValue
class DisplayUtil(private val mContext: Context) {
val displayMetrics: DisplayMetrics
get() = mContext.resources.displayMetrics
private val configuration: Configuration
get() = mContext.resources.configuration
val width: Int
get() = displayMetrics.widthPixels
val height: Int
get() = displayMetrics.heightPixels
val xdpi: Float
get() = displayMetrics.xdpi
val ydpi: Float
get() = displayMetrics.ydpi
val density: Float
get() = displayMetrics.density
val densityDpi: Int
get() = displayMetrics.densityDpi
val densityDpiString: String
get() {
val dpi = densityDpi
if (dpi <= DisplayMetrics.DENSITY_LOW) {
return "low"
}
if (dpi <= DisplayMetrics.DENSITY_MEDIUM) {
return "medium"
}
if (dpi <= DisplayMetrics.DENSITY_HIGH) {
return "high"
}
if (dpi <= DisplayMetrics.DENSITY_XHIGH) {
return "xhigh"
}
return if (dpi <= DisplayMetrics.DENSITY_XXHIGH) {
"xxhigh"
} else "xxxhigh"
}
val scaledDensity: Float
get() = displayMetrics.scaledDensity
val screenWidth: Int
get() = configuration.screenWidthDp
val screenHeight: Int
get() = configuration.screenHeightDp
val screenSizeType: String
get() {
val type: String
when (configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK) {
Configuration.SCREENLAYOUT_SIZE_SMALL -> type = "small"
Configuration.SCREENLAYOUT_SIZE_NORMAL -> type = "normal"
Configuration.SCREENLAYOUT_SIZE_LARGE -> type = "large"
Configuration.SCREENLAYOUT_SIZE_XLARGE -> type = "xlarge"
else -> type = "unknown"
}
return type
}
fun dp(f: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, f, displayMetrics)
}
fun dp(i: Int): Float {
return dp(i.toFloat())
}
fun sp(f: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, f, displayMetrics)
}
fun sp(i: Int): Float {
return sp(i.toFloat())
}
fun px(f: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, f, displayMetrics)
}
fun px(i: Int): Float {
return px(i.toFloat())
}
}
<file_sep>package com.eemf.sirgoingfar.core.utils
import android.content.Context
import android.text.format.DateUtils
object TimeUtil {
fun getDuration(start: Long, end: Long): String {
validateIllegalArgument(start, end)
var diff = end - start
val VALUE_0: Long = 0
if (diff < VALUE_0)
return "-"
val secondsInMillis: Long = 1000
val minutesInMillis = secondsInMillis * 60
val hoursInMillis = minutesInMillis * 60
val daysInMillis = hoursInMillis * 24
val weeksInMillis = daysInMillis * 7
val monthInMillis = weeksInMillis * 4
val yearInMillis = monthInMillis * 12
val elapsedYears = diff / yearInMillis
diff %= yearInMillis
val elapsedMonths = diff / monthInMillis
diff %= monthInMillis
val elapsedWeeks = diff / weeksInMillis
diff %= weeksInMillis
val elapsedDays = diff / daysInMillis
diff %= daysInMillis
val elapsedHours = diff / hoursInMillis
diff %= hoursInMillis
val elapsedMinutes = diff / minutesInMillis
diff %= minutesInMillis
val elapsedSeconds = diff / secondsInMillis
//resolve duration
var duration = ""
if (elapsedYears > 0) {
duration += elapsedYears.toString()
duration += "y "
}
if (elapsedMonths > 0) {
duration += elapsedMonths.toString()
duration += "m "
}
if (elapsedWeeks > 0) {
duration += elapsedWeeks.toString()
duration += "w "
}
if (elapsedDays > 0) {
duration += elapsedDays.toString()
duration += "d "
}
if (elapsedHours > 0) {
duration += elapsedHours.toString()
duration += "h "
}
if (elapsedMinutes > 0) {
duration += elapsedMinutes.toString()
duration += "m "
}
if (elapsedSeconds > 0) {
duration += elapsedSeconds.toString()
duration += "s"
}
return duration.trim { it <= ' ' }
}
fun getTimeRange(context: Context, start: Long, end: Long): String {
validateIllegalArgument(start, end)
return DateUtils.formatDateRange(context, start, end, DateUtils.FORMAT_SHOW_TIME)
}
private fun validateIllegalArgument(start: Long, end: Long) {
val VALUE_0: Long = 0
if (start < VALUE_0 || end < VALUE_0)
throw IllegalArgumentException("Invalid 'start' or 'end' value")
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.jobs
import android.content.Context
import com.eemf.sirgoingfar.core.utils.Constants
import com.eemf.sirgoingfar.database.AppDatabase
import com.eemf.sirgoingfar.database.RoutineOccurrence
import com.eemf.sirgoingfar.routinechecker.notification.NotificationHelper
import kotlinx.coroutines.delay
/**
*
* @property context is the job Caller context
* @property occurrence is the routine occurrence instance that's in process
*@constructor creates an instance of a SimulatedJob
*
* */
class SimulatedJob(private val context: Context, private val occurrence: RoutineOccurrence) {
/**
*
* This function simulates a long running task that's taking place as an
* instance of a routine goes off.
*
* After a wait time (15 minutes for the routine + 5 minutes user's routines categorization window),
* it marks @param occurrence as a MISSED routine occurrence.
*
*
* Afterwards, it clears the notification tray.
*
*
* */
suspend fun runJob() {
//update Routines occurrence Status and update the database
val mDb = AppDatabase.getInstance(context)
val currentOccurrence: RoutineOccurrence? = mDb?.dao?.getRoutineOccurrenceByAlarmId(occurrence.alarmId)
delay((Constants.MAXIMUM_ROUTINE_DURATION_MILLIS + Constants.WAITING_TIME_BEFORE_MARKED_AS_MISSED).toLong())
if (currentOccurrence?.status != Constants.Status.DONE.id) {
//If the user hasn't changed the status, toggle it to MISSED
currentOccurrence!!.status = Constants.Status.MISSED.id
mDb.dao.updateOccurrence(currentOccurrence)
}
NotificationHelper(context).removeNotification()
}
}<file_sep>package com.eemf.sirgoingfar.database
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.arch.persistence.room.TypeConverters
import android.content.Context
/**
*
* This class handles the initialization of the Room Database
*
* */
@Database(entities = [Routine::class, RoutineOccurrence::class], version = 1, exportSchema = false)
@TypeConverters(DateConverter::class)
abstract class AppDatabase : RoomDatabase() {
companion object {
private val LOCK = Any()
private val DATABASE_NAME = "routine_app_db"
private var sInstance: AppDatabase? = null
fun getInstance(context: Context): AppDatabase? {
if (sInstance == null) {
synchronized(LOCK) {
sInstance = Room.databaseBuilder<AppDatabase>(context.applicationContext,
AppDatabase::class.java, DATABASE_NAME)
.build()
}
}
return sInstance
}
}
abstract val dao: RoutineCheckerAppDao
}
<file_sep>package com.eemf.sirgoingfar.core.custom
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewTreeObserver
import android.view.animation.DecelerateInterpolator
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.eemf.sirgoingfar.core.R
import com.eemf.sirgoingfar.core.utils.AppUtil
import com.eemf.sirgoingfar.core.utils.DisplayUtil
/*
*@author: www.reach.af<EMAIL>
*/
class CircularProgressView @JvmOverloads constructor(private var mContext: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayout(mContext, attrs, defStyleAttr) {
private var mTitle: String? = null
private var mSubtext: String? = null
private var mProgressPercent: Int = 0
private var mRingThickness: Float = 0.toFloat()
private var mRingDiameter: Float = 0.toFloat()
private var mSubtextSize: Float = 0.toFloat()
private var mPercentTextSize: Float = 0.toFloat()
private var mTitleTextSize: Float = 0.toFloat()
private var mProgressColor: Int = 0
private var mSubtextColor: Int = 0
private var mTitleColor: Int = 0
private var mSubtextMargin: Int = 0
private val DEFAULT_SUBTEXT_MARGIN = 5
private val DEFAULT_TITLE_TEXT_SIZE = 10.0f
private val DEFAULT_RING_THICKNESS = 12.0f
private val DEFAULT_PROGRESS_COLOR = Color.RED
private val DEFAULT_SUBTEXT_COLOR = Color.BLACK
private val DEFAULT_TITLE_COLOR = Color.BLACK
private val DEFAULT_RING_DIAMETER = 80.0f
private val DEFAULT_SUBTEXT_SIZE = 10.0f
private val DEFAULT_PERCENT_TEXT_SIZE = 17.0f
private lateinit var ringView: CircularProgressBar
private lateinit var ringFrame: RelativeLayout
private lateinit var textsContainer: LinearLayout
private lateinit var tv_title: TextView
private lateinit var tv_subtext: TextView
private lateinit var tv_progressText: TextView
private var displayUtil: DisplayUtil
private var isAttached = false
private val maxW: Int
get() = (mRingDiameter - mRingThickness * 2 - displayUtil.dp(8)).toInt()
private val maxWSubtext: Int
get() = (mRingDiameter - mRingThickness * 2 - displayUtil.dp(18)).toInt()
init {
displayUtil = DisplayUtil(mContext)
if (attrs != null) {
val ta = mContext.obtainStyledAttributes(attrs, R.styleable.CircularProgressView)
if (ta.hasValue(R.styleable.CircularProgressView_percent)) {
mProgressPercent = ta.getInt(R.styleable.CircularProgressView_percent, 0)
}
if (ta.hasValue(R.styleable.CircularProgressView_title)) {
mTitle = ta.getString(R.styleable.CircularProgressView_title)
}
if (ta.hasValue(R.styleable.CircularProgressView_subtext)) {
mSubtext = ta.getString(R.styleable.CircularProgressView_subtext)
}
mRingThickness = ta.getDimension(R.styleable.CircularProgressView_thickness, DEFAULT_RING_THICKNESS)
mProgressColor = ta.getColor(R.styleable.CircularProgressView_progressColor, DEFAULT_PROGRESS_COLOR)
mSubtextColor = ta.getColor(R.styleable.CircularProgressView_subtextColor, DEFAULT_SUBTEXT_COLOR)
mTitleColor = ta.getColor(R.styleable.CircularProgressView_titleColor, DEFAULT_TITLE_COLOR)
mRingDiameter = ta.getDimension(R.styleable.CircularProgressView_ringDiameter, DEFAULT_RING_DIAMETER)
mSubtextSize = ta.getDimension(R.styleable.CircularProgressView_subtextSize, DEFAULT_SUBTEXT_SIZE)
mPercentTextSize = ta.getDimension(R.styleable.CircularProgressView_percentTextSize, DEFAULT_PERCENT_TEXT_SIZE)
mTitleTextSize = ta.getDimension(R.styleable.CircularProgressView_titleTextSize, DEFAULT_TITLE_TEXT_SIZE)
mSubtextMargin = ta.getInt(R.styleable.CircularProgressView_subtextMargin, DEFAULT_SUBTEXT_MARGIN)
ta.recycle()
} else {
// Set defaults
mRingThickness = displayUtil.dp(DEFAULT_RING_THICKNESS)
mProgressColor = DEFAULT_PROGRESS_COLOR
mSubtextColor = DEFAULT_SUBTEXT_COLOR
mTitleColor = DEFAULT_TITLE_COLOR
mRingDiameter = displayUtil.dp(DEFAULT_RING_DIAMETER)
mSubtextSize = DEFAULT_SUBTEXT_SIZE
mPercentTextSize = DEFAULT_PERCENT_TEXT_SIZE
mTitleTextSize = DEFAULT_TITLE_TEXT_SIZE
mSubtextMargin = DEFAULT_SUBTEXT_MARGIN
}
orientation = LinearLayout.VERTICAL
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
isAttached = true
attachViews()
}
private fun attachViews() {
attachRingFrame()
attachRing()
attachTextsContainer()
if (!TextUtils.isEmpty(mTitle)) {
attachTitle()
}
}
private fun attachRingFrame() {
ringFrame = RelativeLayout(mContext)
val lp_ringFrame = LinearLayout.LayoutParams(mRingDiameter.toInt(), mRingDiameter.toInt())
lp_ringFrame.gravity = Gravity.CENTER_HORIZONTAL
addView(ringFrame, lp_ringFrame)
}
private fun attachRing() {
ringView = CircularProgressBar(mContext)
ringView.id = R.id.ring_view
ringView.resetProgress()
ringView.setProgressWidth(mRingThickness.toInt())
ringView.setProgress(mProgressPercent)
ringView.setProgressColor(mProgressColor)
ringView.setTextColor(Color.BLACK)
ringView.showProgressText(false)
val lp_ring = RelativeLayout.LayoutParams(mRingDiameter.toInt(), mRingDiameter.toInt())
ringFrame.addView(ringView, lp_ring)
}
private fun attachTextsContainer() {
textsContainer = LinearLayout(mContext)
textsContainer.orientation = LinearLayout.VERTICAL
val lp_textsContainer = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
lp_textsContainer.addRule(RelativeLayout.CENTER_IN_PARENT)
ringFrame.addView(textsContainer, lp_textsContainer)
attachPercentText()
if (!TextUtils.isEmpty(mSubtext)) {
attachSubtext()
}
}
private fun attachPercentText() {
tv_progressText = TextView(mContext)
tv_progressText.id = AppUtil.generateViewId()
// tv_progressText.setTypeface(FontUtils.selectTypeface(mContext, FontUtils.STYLE_BOLD));
tv_progressText.setTextColor(Color.BLACK)
tv_progressText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPercentTextSize)
tv_progressText.setLineSpacing(0f, 0.9f)
tv_progressText.maxLines = 1
tv_progressText.ellipsize = TextUtils.TruncateAt.END
tv_progressText.gravity = Gravity.CENTER
val lp_progressText = LinearLayout.LayoutParams(maxW, RelativeLayout.LayoutParams.WRAP_CONTENT)
textsContainer.addView(tv_progressText, lp_progressText)
fn_setProgressPercent()
}
private fun attachSubtext() {
tv_subtext = TextView(mContext)
tv_subtext.id = AppUtil.generateViewId()
tv_subtext.setTextColor(mSubtextColor)
// tv_subtext.setTypeface(FontUtils.selectTypeface(mContext, FontUtils.STYLE_MEDIUM));
tv_subtext.setTextSize(TypedValue.COMPLEX_UNIT_PX, mSubtextSize)
tv_subtext.setLineSpacing(0f, 0.9f)
tv_subtext.gravity = Gravity.CENTER
fn_setSubtext()
val lp_subtext = LinearLayout.LayoutParams(maxWSubtext, RelativeLayout.LayoutParams.WRAP_CONTENT)
lp_subtext.width = maxW
lp_subtext.topMargin = mSubtextMargin
textsContainer.addView(tv_subtext, lp_subtext)
}
private fun attachTitle() {
tv_title = TextView(mContext)
tv_title.text = mTitle
tv_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTitleTextSize)
tv_title.setTextColor(mTitleColor)
// tv_title.setTypeface(FontUtils.selectTypeface(mContext, FontUtils.STYLE_MEDIUM));
tv_title.gravity = Gravity.CENTER
tv_title.maxLines = 2
tv_title.setLineSpacing(0f, 0.9f)
val lp_title = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
lp_title.gravity = Gravity.CENTER_HORIZONTAL
lp_title.topMargin = displayUtil.dp(4).toInt()
addView(tv_title, lp_title)
}
private fun fn_setProgressPercent() {
tv_progressText.text = "0%"
val animator = ValueAnimator.ofInt(0, mProgressPercent)
animator.interpolator = DecelerateInterpolator()
animator.duration = 1500
animator.addUpdateListener { valueAnimator ->
val i = valueAnimator.animatedValue as Int
tv_progressText.text = "$i%"
}
animator.start()
}
private fun fn_setSubtext() {
tv_subtext.text = mSubtext
tv_subtext.setTextColor(mSubtextColor)
tv_subtext.maxLines = 2
tv_subtext.ellipsize = TextUtils.TruncateAt.END
tv_subtext.maxWidth = maxWSubtext
tv_subtext.setPadding(14, 0, 14, 0)
tv_subtext.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
tv_subtext.text = mSubtext
tv_subtext.maxWidth = maxWSubtext
tv_subtext.setPadding(16, 0, 16, 0)
tv_subtext.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
}
fun setTitleColor(mTitleColor: Int) {
this.mTitleColor = mTitleColor
}
fun setTitle(title: String) {
mTitle = title
if (isAttached) {
tv_title.text = mTitle
}
}
fun setSubtext(subtext: String) {
mSubtext = subtext
if (isAttached) {
fn_setSubtext()
}
}
fun setProgressPercent(percent: Int) {
mProgressPercent = percent
if (isAttached) {
fn_setProgressPercent()
ringView.resetProgress()
ringView.setProgress(mProgressPercent)
ringView.showProgressText(false)
}
}
fun setProgressColor(color: Int) {
this.mProgressColor = color
if (isAttached) {
ringView.setProgressColor(mProgressColor)
}
}
fun setRingDiameter(ringDiameter: Float) {
this.mRingDiameter = ringDiameter
if (isAttached) {
val lp_ring = ringView.layoutParams as RelativeLayout.LayoutParams
lp_ring.width = mRingDiameter.toInt()
lp_ring.height = mRingDiameter.toInt()
ringView.layoutParams = lp_ring
ringView.invalidate()
}
}
fun setRingThickness(ringThickness: Float) {
this.mRingThickness = ringThickness
if (isAttached) {
this.ringView.setProgressWidth(displayUtil.dp(ringThickness).toInt())
}
}
fun setPercentTextSize(textSize: Float) {
mPercentTextSize = textSize
if (isAttached) {
tv_progressText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPercentTextSize)
}
}
fun setSubtextSize(textSize: Float) {
mSubtextSize = textSize
if (isAttached) {
tv_subtext.setTextSize(TypedValue.COMPLEX_UNIT_PX, mSubtextSize)
}
}
fun setTitleTextSize(textSize: Float) {
mTitleTextSize = textSize
if (isAttached) {
tv_title.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTitleTextSize)
}
}
fun setSubtextMargin(margin: Int) {
mSubtextMargin = margin
if (isAttached) {
val lp_subtext = tv_subtext.layoutParams as LinearLayout.LayoutParams
lp_subtext.topMargin = mSubtextMargin
tv_subtext.layoutParams = lp_subtext
}
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.notification
import android.app.PendingIntent
import android.graphics.Color
import android.media.RingtoneManager
import android.net.Uri
import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes
import com.eemf.sirgoingfar.routinechecker.R
/**
*
* @constructor creates an object of NotificationParam - a notification property
*
* */
class NotificationParam {
var id: Int = 0
var priorityType: Int = 0
@DrawableRes
var smallIcon = R.drawable.ic_alarm_raven
@DrawableRes
var largeIcon = R.drawable.ic_alarm_raven
@DrawableRes
var btnOneIconResId: Int = 0
@DrawableRes
var btnTwoIconResId: Int = 0
@DrawableRes
var btnThreeIconResId: Int = 0
@ColorRes
var bodyTextColor = R.color.colorBlack
var lightColor = Color.RED
var title = "Timely"
var body: String? = null
var btnOneText: String? = null
var btnTwoText: String? = null
var btnThreeText: String? = null
private var shouldVibrate: Boolean = false
private var shouldSound: Boolean = false
var isDismissable: Boolean = false
var isAutoCancel: Boolean = false
private var removePreviousNotif: Boolean = false
var soundUri: Uri = DEFAULT_SOUND
var bodyPendingIntent: PendingIntent? = null
var btnOnePendingIntent: PendingIntent? = null
var btnTwoPendingIntent: PendingIntent? = null
var btnThreePendingIntent: PendingIntent? = null
fun shouldVibrate(): Boolean {
return shouldVibrate
}
fun setShouldVibrate(shouldVibrate: Boolean) {
this.shouldVibrate = shouldVibrate
}
fun shouldSound(): Boolean {
return shouldSound
}
fun setShouldSound(shouldSound: Boolean) {
this.shouldSound = shouldSound
}
fun shouldRemovePreviousNotif(): Boolean {
return removePreviousNotif
}
fun setRemovePreviousNotif(removePreviousNotif: Boolean) {
this.removePreviousNotif = removePreviousNotif
}
companion object {
var DEFAULT_SOUND = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
}
}
<file_sep>package com.eemf.sirgoingfar.timely.alarm
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.KITKAT
import com.eemf.sirgoingfar.core.utils.App
import com.eemf.sirgoingfar.core.utils.Constants
import com.eemf.sirgoingfar.core.utils.Helper
import com.eemf.sirgoingfar.core.utils.ParcelableUtil
import com.eemf.sirgoingfar.database.AppDatabase
import com.eemf.sirgoingfar.database.Routine
import com.eemf.sirgoingfar.database.RoutineOccurrence
import com.eemf.sirgoingfar.routinechecker.R
import com.eemf.sirgoingfar.routinechecker.alarm.AlarmReceiver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
*
* This class handles the scheduling (creating, removing and updating) of routine occurrence instances.
*
* It is trigger when a new routine is added to the Routine List
*
* @constructor creates an instance of the AlarmHelper
*
* */
class AlarmHelper {
private var mAlarmManager: AlarmManager? = null
private var mContext: Context? = null
init {
if (mContext == null)
mContext = App.getsInstance()?.appContext
if (mAlarmManager == null)
mAlarmManager = App.getsInstance()?.appContext
?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
}
/**
* @param occurrence is an instance of the Routine next to be scheduled/removed/updated
* @param action is the unique identifier for the operation to be performed on the routine occurrence
* */
fun execute(occurrence: RoutineOccurrence?, action: Int) {
GlobalScope.launch(Dispatchers.Default) {
withContext(Dispatchers.IO) {
if (action < 0)
throw IllegalArgumentException(mContext?.getString(R.string.text_invalid_action_identifier))
when (action) {
ACTION_SCHEDULE_ALARM -> schedule(occurrence, false)
ACTION_UPDATE_ALARM -> update(occurrence)
ACTION_DELETE_ALARM -> delete(occurrence)
}
}
}
}
private fun delete(occurrence: RoutineOccurrence?) {
val pendingIntent = getPendingIntentFor(occurrence, false)
mAlarmManager?.cancel(pendingIntent)
}
private fun update(occurrence: RoutineOccurrence?) {
//delete the previously scheduled alarm for this occurrence
delete(occurrence)
//re-schedule
schedule(occurrence, true)
}
private fun schedule(occurrence: RoutineOccurrence?, isUpdate: Boolean) {
if (Helper.hasTimePassed(occurrence?.occurrenceDate!!)) {
occurrence.occurrenceDate = Helper.computeNextRoutineTime(occurrence.freqId, occurrence.occurrenceDate)
}
val pendingIntent = getPendingIntentFor(occurrence, isUpdate)
val alarmTime = (occurrence.occurrenceDate!!.time - Constants.MINIMUM_NOTIF_TIME_TO_START_TIME_MILLIS)
when {
SDK_INT >= Build.VERSION_CODES.M -> mAlarmManager?.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent)
SDK_INT >= KITKAT -> mAlarmManager?.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent)
else -> mAlarmManager?.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent)
}
//create the Occurrence
val mDb = AppDatabase.getInstance(mContext!!)
mDb?.dao?.addOccurrence(occurrence)
//Update the routine date
val routineInstance: Routine = mDb?.dao!!.getRoutineByIdAsync(occurrence.routineId)
routineInstance.date = occurrence.occurrenceDate
mDb.dao.updateRoutine(routineInstance)
}
private fun getPendingIntentFor(occurrence: RoutineOccurrence?, isUpdate: Boolean): PendingIntent {
val alarmIntent = Intent(mContext, AlarmReceiver::class.java)
val occurrenceByte = ParcelableUtil.marshall(occurrence!!)
alarmIntent.putExtra(KEY_EXTRA_OCCURRENCE, occurrenceByte)
alarmIntent.data = Uri.parse(mContext?.getString(R.string.prefix_text) + occurrence.alarmId)
alarmIntent.action = occurrence.alarmId.toString()
if (isUpdate) {
alarmIntent.putExtra(AlarmReceiver.EXTRA_KEY_ALARM_RECEIVER_ACTION, AlarmReceiver.ALARM_ACTION_UPDATE_ALARM)
}
return PendingIntent.getBroadcast(mContext, occurrence.alarmId, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
companion object {
const val ACTION_SCHEDULE_ALARM = 0
const val ACTION_UPDATE_ALARM = 1
const val ACTION_DELETE_ALARM = 2
const val KEY_EXTRA_OCCURRENCE = "key_extra_occurrence"
}
}
<file_sep>package com.eemf.sirgoingfar.core.utils
object Constants {
const val ARG_START_DATE = "arg_start_date"
const val ARG_TIME = "arg_time"
const val ARG_IS_TIME_SELECTED = "arg_is_time_selected"
const val ARG_ROUTINE_DESC = "arg_routine_desc"
const val ARG_ROUTINE_TITLE = "arg_routine_title"
const val ARG_ROUTINE_PRIORITY = "arg_routine_priority"
const val ARG_LISTENER = "arg_listener"
const val ARG_CURRENT_ROUTINE = "arg_current_routine"
const val MINIMUM_PASS_MARK = 70
const val MINIMUM_NOTIF_TIME_TO_START_TIME_MILLIS = 5 * 60 * 1000 //notify when it's 5 minutes to a routine
const val WAITING_TIME_BEFORE_MARKED_AS_MISSED = 5 * 60 * 1000 //wait for 5 minutes after routine has expired before marking as MISSED routine
const val MAXIMUM_ROUTINE_DURATION_MILLIS = 15 * 60 * 1000 //all routine have a maximum execution time of 15 minutes
const val TWELVE_HOURS_IN_MILLIS = 12 * 60 * 60 * 1000
enum class Status(val id: Int, val label: String) {
UNKNOWN(0, "Unknown"),
PROGRESS(1, "In Progress"),
DONE(2, "Done"),
MISSED(3, "Missed");
companion object {
fun getStatusById(id: Int): Status? {
return when (id) {
0 -> UNKNOWN
1 -> PROGRESS
2 -> DONE
3 -> MISSED
else -> null
}
}
}
}
}
<file_sep>package com.eemf.sirgoingfar.core.utils
enum class Frequency(public val id: Int, public val label: String) {
HOURLY(0, "Hourly"),
DAILY(1, "Daily"),
WEEKLY(2, "Weekly"),
MONTHLY(3, "Monthly"),
YEARLY(4, "Yearly");
companion object {
fun getFrequency(id: Int): Frequency? {
when (id) {
0 -> return HOURLY
1 -> return DAILY
2 -> return WEEKLY
3 -> return MONTHLY
4 -> return YEARLY
else -> return null
}
}
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.activities
import android.arch.lifecycle.Observer
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.eemf.sirgoingfar.core.custom.AbsViewHolder
import com.eemf.sirgoingfar.core.utils.ColorUtil
import com.eemf.sirgoingfar.core.utils.Constants
import com.eemf.sirgoingfar.core.utils.Helper
import com.eemf.sirgoingfar.database.Routine
import com.eemf.sirgoingfar.database.RoutineOccurrence
import com.eemf.sirgoingfar.routinechecker.R
import com.eemf.sirgoingfar.routinechecker.adapters.RoutineOccurrenceRecyclerViewAdapter
import com.eemf.sirgoingfar.routinechecker.dialog_fragments.AddActivityDialogFragment
import com.eemf.sirgoingfar.routinechecker.viewmodels.BaseViewModel
import com.eemf.sirgoingfar.routinechecker.viewmodels.RoutineDetailOccurrenceListViewModel
import com.eemf.sirgoingfar.routinechecker.viewmodels.RoutineListActivityViewModel
import com.eemf.sirgoingfar.routinechecker.viewmodels.ViewModelModule
import kotlinx.android.synthetic.main.activity_routine_detail.*
import java.util.*
/**
* RoutineDetailActivity gives the general overview of a routine
* */
class RoutineDetailActivity : BaseActivity(), RoutineOccurrenceRecyclerViewAdapter.OnStatusButtonClickListener, AddActivityDialogFragment.OnSaveOccurrence {
/**
*@property mContainer is the parent layout view
* @constructor creates an instance of the activity view
* */
inner class ViewHolder(private val mContainer: View) : AbsViewHolder(mContainer) {
private var mContext: RoutineDetailActivity = this@RoutineDetailActivity
private var mState: State
private lateinit var adapter: RoutineOccurrenceRecyclerViewAdapter
init {
mState = State()
init(mContainer)
}
override fun init(container: View) {
//set state: Loading
mState.setLoading()
refreshHeader()
//set up other views
adapter = RoutineOccurrenceRecyclerViewAdapter(mContext, mContext)
rv_routine_occurrences_list?.layoutManager = LinearLayoutManager(mContext,
LinearLayoutManager.VERTICAL, false)
rv_routine_occurrences_list?.setHasFixedSize(true)
rv_routine_occurrences_list?.isFocusable = true
rv_routine_occurrences_list?.clipToPadding = false
rv_routine_occurrences_list?.adapter = adapter
}
fun refreshHeader() {
tv_routine_title.text = mRoutine.name
tv_routine_desc.text = mRoutine.desc
tv_routine_freq_detail.text = Helper.getRoutineTimeDetail(mContext, mRoutine.date, mRoutine.freqId)
?: mContext.getString(R.string.text_unavailable)
pb_routine_progress.setProgressColor((ContextCompat.getColor(mContext, ColorUtil.getColor(mRoutine.id))))
mContext.setSupportActionBar(toolbar)
toolbar.title = Helper.getNextRoutineOccurrenceText(mContext, mRoutine.freqId, mRoutine.date)
?: mContext.getString(R.string.text_unavailable)
}
fun switchScreenState(state: Int) {
when (state) {
BaseViewModel.STATE_LOADING -> mState.setLoading()
BaseViewModel.STATE_LOADED -> mState.setLoaded()
}
}
fun refreshPage(list: List<RoutineOccurrence>) {
if (list.isEmpty()) {
mState.setNoData()
} else {
adapter.setData(list as ArrayList<RoutineOccurrence>)
val percentDone = getPercentageDone(list)
pb_routine_progress.setProgressPercent(percentDone)
if (percentDone >= Constants.MINIMUM_PASS_MARK) {
iv_routine_progress_emoji.setImageResource(R.drawable.ic_thumb_up)
} else {
iv_routine_progress_emoji.setImageResource(R.drawable.ic_frown)
}
mState.setHasData()
}
}
private fun getPercentageDone(list: List<RoutineOccurrence>): Int {
var doneCount = 0
for (routine: RoutineOccurrence in list) {
if (routine.status == Constants.Status.DONE.id)
doneCount++
}
return (doneCount.toDouble().div(list.size) * 100).toInt()
}
inner class State : AbsViewState {
override fun setBlank() {
}
override fun setNoData() {
show(tv_empty_state)
gone(pb_loading)
gone(ns_filled_state)
}
override fun setHasData() {
show(ns_filled_state)
gone(tv_empty_state)
gone(pb_loading)
}
override fun setLoading(tag: String) {
}
override fun setLoaded(tag: String) {
}
override fun setLoading() {
show(pb_loading)
gone(tv_empty_state)
gone(ns_filled_state)
}
override fun setLoaded() {
}
}
}
/**
* @constructor creates an instance of the model
* */
inner class Model {
private var mActivity: RoutineDetailActivity = this@RoutineDetailActivity
private var mRoutineViewModel: RoutineListActivityViewModel = ViewModelModule().getRoutineListActivityViewModel(
mActivity.application, mActivity) as RoutineListActivityViewModel
private var mOccurrenceViewModel: RoutineDetailOccurrenceListViewModel = ViewModelModule().getRoutineOccurenceListViewModel(
mActivity.application, mActivity) as RoutineDetailOccurrenceListViewModel
init {
//observe for Routine Change
mRoutineViewModel.getRoutineObserver().observe(mActivity, Observer {
if (it == null) {
performAction(true)
} else {
mRoutine = it
performAction(false)
}
})
//observe for data change
mOccurrenceViewModel.getRoutineOccurrenceListObserver().observe(mActivity, Observer {
if (it == null)
return@Observer
refreshPage(it)
})
//Observe for UI state change
mOccurrenceViewModel.getUiStateObserver().observe(mActivity, Observer {
if (it == null)
return@Observer
switchScreenState(it)
})
}
fun getRoutine(routineId: Int) {
if (routineId < 1)
performAction(true)
mRoutineViewModel.getRoutineById(routineId)
}
fun getRoutineOccurrences() {
mOccurrenceViewModel.getAllRoutineOccurrences(mRoutine.id)
}
fun updateRoutine(routine: Routine) {
mRoutineViewModel.editRoutine(routine)
}
fun updateRoutineOccurrence(clickedRoutineOccurrence: RoutineOccurrence) {
mOccurrenceViewModel.updateRoutineOccurrence(clickedRoutineOccurrence)
}
}
private lateinit var mRoutine: Routine
private lateinit var views: ViewHolder
private lateinit var model: Model
private var isEdit: Boolean = false //Todo: Set this to true when there's an edit to the routine
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_routine_detail)
val intent = intent
if (intent.hasExtra(EXTRA_ROUTINE_ID)) {
model = Model()
model.getRoutine(intent.getIntExtra(EXTRA_ROUTINE_ID, -1))
} else {
//no Routine object, close this activity
finish()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_routine_detail, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return if (item?.itemId == R.id.action_edit_routine) {
openEditDialog()
true
} else
super.onOptionsItemSelected(item)
}
private fun openEditDialog() {
AddActivityDialogFragment.newInstance(mRoutine, this, true).show(this.fragmentManager,
AddActivityDialogFragment::class.java.name)
}
override fun onSaveRoutine(routine: Routine, isEdit: Boolean) {
this.isEdit = isEdit
model.updateRoutine(routine)
}
override fun onDoneBtnClick(position: Int, clickedRoutineOccurrence: RoutineOccurrence) {
clickedRoutineOccurrence.status = Constants.Status.DONE.id
model.updateRoutineOccurrence(clickedRoutineOccurrence)
}
override fun onMissedBtnClick(position: Int, clickedRoutineOccurrence: RoutineOccurrence) {
clickedRoutineOccurrence.status = Constants.Status.MISSED.id
model.updateRoutineOccurrence(clickedRoutineOccurrence)
}
private fun performAction(closeActivity: Boolean) {
if (closeActivity)
finish()
if (isEdit) {
views.refreshHeader()
isEdit = false
} else {
views = ViewHolder(window.decorView.rootView)
model.getRoutineOccurrences()
}
}
private fun refreshPage(routineOccurrenceList: List<RoutineOccurrence>) {
views.refreshPage(routineOccurrenceList)
}
private fun switchScreenState(status: Int) {
views.switchScreenState(status)
}
companion object {
const val EXTRA_ROUTINE_ID: String = "extra_routine_object"
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.alarm
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.text.TextUtils
import com.eemf.sirgoingfar.core.utils.Constants
import com.eemf.sirgoingfar.core.utils.ParcelableUtil
import com.eemf.sirgoingfar.core.utils.Prefs
import com.eemf.sirgoingfar.database.AppDatabase
import com.eemf.sirgoingfar.database.RoutineOccurrence
import com.eemf.sirgoingfar.routinechecker.notification.NotificationHelper
import com.eemf.sirgoingfar.timely.alarm.AlarmHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
*
* This class handles the notification action buttons click actions
*
*
* @constructor creates an instance of the NotificationActionService
*
* */
class NotificationActionService : Service() {
private var pref: Prefs? = null
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
pref = Prefs.getsInstance()
if (TextUtils.isEmpty(intent.action))
return START_NOT_STICKY
val serviceAction = intent.action
if (TextUtils.isEmpty(serviceAction))
return START_NOT_STICKY
if (!intent.hasExtra(AlarmHelper.KEY_EXTRA_OCCURRENCE))
return START_STICKY
val occurrenceByte = intent.getByteArrayExtra(AlarmHelper.KEY_EXTRA_OCCURRENCE)
val occurrence = ParcelableUtil.unmarshall(occurrenceByte, RoutineOccurrence.CREATOR)
when (serviceAction) {
ACTION_UPDATE_ROUTINE -> {
GlobalScope.launch {
updateRoutineOccurrence(occurrence)
}
}
}
return START_NOT_STICKY
}
/**
*
* @param occurrence is the occurrence instance of a Routine that is currently in process
*
* The function handles the DONE action button click:
* it marks the current routine occurrence as DONE
*
*
* */
private suspend fun updateRoutineOccurrence(occurrence: RoutineOccurrence) {
val job = GlobalScope.launch {
withContext(Dispatchers.IO) {
//update Routines's Status and update the database
val mDb = AppDatabase.getInstance(this@NotificationActionService)
val currentOccurrence: RoutineOccurrence? = mDb?.dao?.getRoutineOccurrenceByAlarmId(occurrence.alarmId)
if (currentOccurrence?.status == Constants.Status.PROGRESS.id) {
//If the user hasn't changed the status, toggle it
currentOccurrence.status = Constants.Status.DONE.id
mDb.dao.updateOccurrence(currentOccurrence)
NotificationHelper(this@NotificationActionService).removeNotification()
}
}
}
job.join()
}
companion object {
const val ACTION_UPDATE_ROUTINE = "action_update_routine"
}
}<file_sep>package com.eemf.sirgoingfar.routinechecker.activities
import android.content.Intent
import android.os.Bundle
import android.support.annotation.IdRes
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.Menu
import android.view.MenuItem
import android.view.View
import butterknife.ButterKnife
import com.eemf.sirgoingfar.core.custom.AbsViewHolder
import com.eemf.sirgoingfar.core.models.NextUpRoutine
import com.eemf.sirgoingfar.core.utils.Constants
import com.eemf.sirgoingfar.core.utils.Frequency
import com.eemf.sirgoingfar.core.utils.Helper
import com.eemf.sirgoingfar.core.utils.Prefs
import com.eemf.sirgoingfar.database.Routine
import com.eemf.sirgoingfar.database.RoutineOccurrence
import com.eemf.sirgoingfar.routinechecker.R
import com.eemf.sirgoingfar.routinechecker.adapters.RoutineListRecyclerViewAdapter
import com.eemf.sirgoingfar.routinechecker.dialog_fragments.AddActivityDialogFragment
import com.eemf.sirgoingfar.routinechecker.viewmodels.BaseViewModel
import com.eemf.sirgoingfar.routinechecker.viewmodels.RoutineListActivityViewModel
import com.eemf.sirgoingfar.routinechecker.viewmodels.ViewModelModule
import com.eemf.sirgoingfar.timely.alarm.AlarmHelper
import kotlinx.android.synthetic.main.activity_routine_list.*
import java.util.*
class RoutineListActivity : BaseActivity(), RoutineListRecyclerViewAdapter.OnRoutineClickListener,
AddActivityDialogFragment.OnSaveOccurrence {
/**
*@property mContainer is the parent layout view
* @constructor creates an instance of the activity view
* */
inner class ViewHolder(private val mContainer: View) : AbsViewHolder(mContainer) {
private lateinit var adapter: RoutineListRecyclerViewAdapter
private var mState: State
init {
ButterKnife.bind(this, mContainer)
mState = State()
init(mContainer)
}
override fun init(container: View) {
//setup FAB
fab_add_routine!!.setOnClickListener {
openAddRoutineDialog()
}
//setup RecyclerView
adapter = RoutineListRecyclerViewAdapter(this@RoutineListActivity, this@RoutineListActivity)
rv_rountine_list?.layoutManager = LinearLayoutManager(this@RoutineListActivity,
LinearLayoutManager.VERTICAL, false)
rv_rountine_list?.setHasFixedSize(true)
rv_rountine_list?.isFocusable = true
rv_rountine_list?.clipToPadding = false
rv_rountine_list?.adapter = adapter
ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT or ItemTouchHelper.LEFT) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
deleteRoutine(viewHolder.adapterPosition)
}
}).attachToRecyclerView(rv_rountine_list)
}
fun refreshPage(routineList: List<Routine>) {
addOrRemoveMenuOption(model.mNextUpList.isNotEmpty(), R.id.action_next_up)
if (routineList.isEmpty()) {
mState.setNoData()
} else {
adapter.setData(routineList as java.util.ArrayList<Routine>)
mState.setHasData()
}
}
fun switchScreenState(state: Int) {
when (state) {
BaseViewModel.STATE_LOADING -> mState.setLoading()
BaseViewModel.STATE_LOADED -> mState.setLoaded()
}
}
private fun addOrRemoveMenuOption(isVisible: Boolean, @IdRes menuId: Int) {
if (mMenu == null)
return
val option = mMenu?.findItem(menuId) ?: return
option.isVisible = isVisible
}
inner class State : AbsViewState {
override fun setBlank() {
}
override fun setNoData() {
show(tv_empty_state)
gone(rv_rountine_list)
gone(pb_loading)
}
override fun setHasData() {
show(rv_rountine_list)
gone(tv_empty_state)
gone(pb_loading)
}
override fun setLoading(tag: String) {
show(pb_loading)
gone(tv_empty_state)
gone(rv_rountine_list)
}
override fun setLoaded(tag: String) {
}
override fun setLoading() {
}
override fun setLoaded() {
}
}
}
/**
* @constructor creates an instance of the model
* */
inner class Model {
private var mActivity: RoutineListActivity = this@RoutineListActivity
private var mViewModel: RoutineListActivityViewModel = ViewModelModule().getRoutineListActivityViewModel(
mActivity.application, mActivity) as RoutineListActivityViewModel
private var mRoutineList: List<Routine>? = null
lateinit var mNextUpList: ArrayList<NextUpRoutine>
init {
//observe for Routine List data
mViewModel.getRoutineListObserver().observe(mActivity, android.arch.lifecycle.Observer {
if (it == null)
return@Observer
mRoutineList = it
mNextUpList = getNextUpRoutinelist(mRoutineList!!)
refreshPage(it)
if (isAddition) {
isAddition = false
val addedRoutine = it[it.size - 1]
var date = addedRoutine.date
if (addedRoutine.freqId != Frequency.HOURLY.id)
date = Helper.computeNextRoutineTime(addedRoutine.freqId, addedRoutine.date)
val occurrence = RoutineOccurrence(addedRoutine.id, Constants.Status.UNKNOWN.id, date,
Prefs.getsInstance().nextAlarmId, addedRoutine.name, addedRoutine.desc, addedRoutine.freqId)
AlarmHelper().execute(occurrence, AlarmHelper.ACTION_SCHEDULE_ALARM)
}
})
//Observe for UI state change
mViewModel.getUiStateObserver().observe(mActivity, android.arch.lifecycle.Observer {
if (it == null)
return@Observer
switchScreenState(it)
})
//Query for data
mViewModel.getAllRoutines()
}
fun saveRoutine(routine: Routine) {
mViewModel.addRoutine(routine)
}
fun getCurrentRoutineList(): List<Routine> {
return mRoutineList!!
}
fun deleteRoutine(index: Int) {
mViewModel.deleteRoutine(mRoutineList!![index])
}
}
private lateinit var views: ViewHolder
private lateinit var model: Model
private var mMenu: Menu? = null
private var isAddition: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_routine_list)
views = ViewHolder(window.decorView.findViewById(android.R.id.content))
model = Model()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
mMenu = menu
menuInflater.inflate(R.menu.menu_routine_list, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when (item?.itemId) {
R.id.action_add_routine -> {
openAddRoutineDialog()
true
}
R.id.action_next_up -> {
openNextUpActivity()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onRoutineClick(position: Int, clickedRoutine: Routine) {
val intent = Intent(this, RoutineDetailActivity::class.java)
intent.putExtra(RoutineDetailActivity.EXTRA_ROUTINE_ID, clickedRoutine.id)
startActivity(intent)
}
override fun onSaveRoutine(routine: Routine, isEdit: Boolean) {
isAddition = !isEdit
model.saveRoutine(routine)
}
fun openAddRoutineDialog() {
AddActivityDialogFragment.newInstance(this, false).show(this.fragmentManager,
AddActivityDialogFragment::class.java.name)
}
private fun openNextUpActivity() {
val intent = Intent(this, NextUpActivity::class.java)
intent.putParcelableArrayListExtra(NextUpActivity.EXTRA_NEXT_UP_ROUTINE_LIST, model.mNextUpList)
startActivity(intent)
}
fun getNextUpRoutinelist(routineList: List<Routine>): ArrayList<NextUpRoutine> {
val list: ArrayList<NextUpRoutine> = ArrayList()
for (routine: Routine in routineList) {
val nextTime = routine.date!!.time
val now = Calendar.getInstance().timeInMillis
val diff = nextTime - now
if (diff > 0 && diff <= Constants.TWELVE_HOURS_IN_MILLIS) {
list.add(NextUpRoutine(routine.name, Helper.getUpNext(routine.freqId, routine.date)))
}
}
return list
}
private fun switchScreenState(state: Int) {
views.switchScreenState(state)
}
private fun refreshPage(routineList: List<Routine>) {
views.refreshPage(routineList)
}
private fun deleteRoutine(index: Int) {
createAlertDialog(getString(R.string.text_delete_routine))
.setNegativeButton(getString(R.string.alert_dialog_negative_button_label)) { dialog, which -> refreshPage(model.getCurrentRoutineList()) }
.setPositiveButton(getString(R.string.alert_dialog_positive_button_label)) { dialog, which ->
model.deleteRoutine(index)
}.create().show()
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Color
import android.media.RingtoneManager
import android.os.Build
import android.support.v4.app.NotificationCompat
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import com.eemf.sirgoingfar.core.utils.App
import com.eemf.sirgoingfar.routinechecker.R
/**
*
* This class is a Helper class for setting the Notification Properties and sending the Notification
* to the device Notification tray.
*
*
* @property context is the caller context
* @constructor creates an instance of the NotificationHelper
*
*
* */
class NotificationHelper(private val context: Context) {
private var notificationManager: NotificationManager? = null
fun notifyUser(param: NotificationParam) {
//clear any notification from the app
if (param.shouldRemovePreviousNotif())
removeNotification()
notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val builder = NotificationCompat.Builder(context, App.NOTIF_CHANNEL_ID)
val sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
//Set Notification Channel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notifChannel = NotificationChannel(
App.NOTIF_CHANNEL_ID, App.NOTIF_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH
)
//create the channel for the Notification Manager
assert(notificationManager != null)
notificationManager!!.createNotificationChannel(notifChannel)
} else {
builder.priority = param.priorityType
}
val textColor = ContextCompat.getColor(context, param.bodyTextColor)
//Build the Notification
builder.setSmallIcon(param.smallIcon)
.setLargeIcon(BitmapFactory.decodeResource(
context.resources,
param.largeIcon))
.setContentText(param.body)
.setColor(if (textColor <= 0) Color.BLACK else textColor)
.setContentTitle(param.title)
.setContentIntent(param.bodyPendingIntent)
.setSound(if (param.shouldSound()) param.soundUri else null)
.setGroup(App.APP_GROUP_KEY)
.setLights(param.lightColor, 500, 1000)
.setSubText(context.getString(R.string.app_name))
.setVibrate(longArrayOf(0, 1000, 1000, 1000, 1000))
.setAutoCancel(param.isAutoCancel)
if (!TextUtils.isEmpty(param.btnOneText)) {
builder.addAction(param.btnOneIconResId, param.btnOneText, param.btnOnePendingIntent)
}
if (!TextUtils.isEmpty(param.btnTwoText)) {
builder.addAction(param.btnTwoIconResId, param.btnTwoText, param.btnTwoPendingIntent)
}
if (!TextUtils.isEmpty(param.btnThreeText)) {
builder.addAction(param.btnThreeIconResId, param.btnThreeText, param.btnThreePendingIntent)
}
try {
notificationManager!!.notify(App.NOTIF_ID, builder.build())
} catch (e: Exception) {
e.printStackTrace()
}
}
fun removeNotification() {
val manager = App.getsInstance()!!.appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.cancelAll()
}
}
<file_sep>package com.eemf.sirgoingfar.core.utils
import android.os.Build
import android.view.View
import java.util.concurrent.atomic.AtomicInteger
object AppUtil {
private val sNextGeneratedId = AtomicInteger(1)
fun generateViewId(): Int {
if (Build.VERSION.SDK_INT >= 17) {
return View.generateViewId()
}
/*
Using Android View internal implementation, to be compatible with version < 17.
Ref: https://gist.github.com/omegasoft7/fdf7225a5b2955a1aba8
*/
while (true) {
val result = sNextGeneratedId.get()
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
var newValue = result + 1
if (newValue > 0x00FFFFFF) newValue = 1 // Roll over to 1, not 0.
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result
}
}
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.dialog_fragments
import android.content.Context
import android.support.v4.app.DialogFragment
import android.support.v4.app.FragmentManager
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.eemf.sirgoingfar.core.custom.ProgressBarDialog
import com.eemf.sirgoingfar.core.utils.Prefs
import com.eemf.sirgoingfar.routinechecker.activities.BaseActivity
open class BaseDialogFragment : DialogFragment() {
protected lateinit var appCompatActivity: AppCompatActivity
protected lateinit var mBaseActivity: BaseActivity
protected lateinit var prefs: Prefs
private var progressDialog: ProgressBarDialog? = null
fun dismissAllDialogs(manager: FragmentManager) {
val fragments = manager.fragments
for (fragment in fragments) {
if (fragment is DialogFragment) {
fragment.dismissAllowingStateLoss()
}
val childFragmentManager = fragment.childFragmentManager
dismissAllDialogs(childFragmentManager)
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is AppCompatActivity)
appCompatActivity = context
if (context is BaseActivity)
mBaseActivity = context
prefs = Prefs.getsInstance()
}
fun toast(msg: Any?) {
if (msg == null) {
return
}
Toast.makeText(appCompatActivity.applicationContext, msg.toString(), Toast.LENGTH_SHORT).show()
}
fun toastLong(msg: Any?) {
if (msg == null) {
return
}
Toast.makeText(appCompatActivity.applicationContext, msg.toString(), Toast.LENGTH_LONG).show()
}
fun makeProgressDialog(isCancelable: Boolean) {
progressDialog = ProgressBarDialog(appCompatActivity)
progressDialog!!.setCancelable(isCancelable)
progressDialog!!.setCanceledOnTouchOutside(isCancelable)
}
fun showProgressDialog() {
if (progressDialog != null && !progressDialog!!.isShowing)
progressDialog!!.show()
}
fun dismissProgressDialog() {
if (progressDialog != null && progressDialog!!.isShowing)
progressDialog!!.dismiss()
}
interface OnDismissListener {
fun onDismiss()
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.activities
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import com.eemf.sirgoingfar.routinechecker.R
import com.eemf.sirgoingfar.routinechecker.adapters.NextUpRoutineRecyclerViewAdapter
import kotlinx.android.synthetic.main.activity_next_up.*
class NextUpActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_next_up)
if (intent.hasExtra(EXTRA_NEXT_UP_ROUTINE_LIST)) {
val adapter = NextUpRoutineRecyclerViewAdapter(intent.getParcelableArrayListExtra(EXTRA_NEXT_UP_ROUTINE_LIST))
rv_next_up_routine?.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
rv_next_up_routine?.setHasFixedSize(true)
rv_next_up_routine?.isFocusable = true
rv_next_up_routine?.clipToPadding = false
rv_next_up_routine?.adapter = adapter
} else {
finish()
}
}
companion object {
const val EXTRA_NEXT_UP_ROUTINE_LIST = "extra_next_up_routine_list"
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.adapters
import android.os.Parcelable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import com.eemf.sirgoingfar.core.models.NextUpRoutine
import com.eemf.sirgoingfar.routinechecker.R
/**
* @property routineList is a list of NextUpRoutine objects
* @constructor creates an instance of the NextUpRecyclerViewAdapter
* */
class NextUpRoutineRecyclerViewAdapter(private val routineList: ArrayList<Parcelable>) : RecyclerView.Adapter<NextUpRoutineRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(container: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(container.context).inflate(R.layout.item_next_up_routine, container, false))
}
override fun getItemCount(): Int {
return routineList.size
}
override fun onBindViewHolder(viewholder: ViewHolder, itemType: Int) {
val currentItem = viewholder.currentItem()
viewholder.tvRoutineName?.text = currentItem.name
viewholder.tvRoutineEstimate?.text = currentItem.estimate
}
/**
* @property itemView is a container of a NextUpRoutine card
* @constructor creates a RecyclerView ViewHolder
* */
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@BindView(R.id.tv_routine_name)
@JvmField
var tvRoutineName: TextView? = null
@BindView(R.id.tv_routine_estimate)
@JvmField
var tvRoutineEstimate: TextView? = null
init {
ButterKnife.bind(this, itemView)
tvRoutineName = itemView.findViewById(R.id.tv_routine_name)
tvRoutineEstimate = itemView.findViewById(R.id.tv_routine_estimate)
}
fun currentItem(): NextUpRoutine {
return routineList[adapterPosition] as NextUpRoutine
}
}
}
<file_sep>package com.eemf.sirgoingfar.core.custom
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.view.animation.DecelerateInterpolator
import com.eemf.sirgoingfar.core.utils.DisplayUtil
/*
*@author: www.reach.africa
*/
class CircularProgressBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {
private var mViewWidth: Int = 0
private var mViewHeight: Int = 0
private val mStartAngle = -90f
private var mSweepAngle = 0f
private val mMaxSweepAngle = 360f
private var mStrokeWidth = 20
private val mAnimationDuration = 1500
private val mMaxProgress = 100
private var mDrawText = true
private var mRoundedCorners = true
private var mProgressColor = Color.BLACK
private var mTextColor = Color.BLACK
private val mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var mSubtext: String? = null
private var mSubtextSize = 12.0f
private val displayUtil: DisplayUtil = DisplayUtil(context)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
initMeasurments()
drawBackgroundCircle(canvas)
drawOutlineArc(canvas)
if (mDrawText) {
drawText(canvas)
}
}
private fun initMeasurments() {
mViewWidth = width
mViewHeight = height
}
private fun drawBackgroundCircle(canvas: Canvas) {
val diameter = Math.min(mViewWidth, mViewHeight)
val pad = mStrokeWidth / 2.0f
val outerOval = RectF(pad, pad, diameter - pad, diameter - pad)
mPaint.color = Color.parseColor("#dadce0")
mPaint.strokeWidth = mStrokeWidth.toFloat()
mPaint.isAntiAlias = true
mPaint.strokeCap = if (mRoundedCorners) Paint.Cap.ROUND else Paint.Cap.BUTT
mPaint.style = Paint.Style.STROKE
canvas.drawArc(outerOval, 0f, 360f, false, mPaint)
}
private fun drawOutlineArc(canvas: Canvas) {
val diameter = Math.min(mViewWidth, mViewHeight)
val pad = mStrokeWidth / 2.0f
val outerOval = RectF(pad, pad, diameter - pad, diameter - pad)
mPaint.color = mProgressColor
mPaint.strokeWidth = mStrokeWidth.toFloat()
mPaint.isAntiAlias = true
mPaint.strokeCap = if (mRoundedCorners) Paint.Cap.ROUND else Paint.Cap.BUTT
mPaint.style = Paint.Style.STROKE
canvas.drawArc(outerOval, mStartAngle, mSweepAngle, false, mPaint)
}
private fun drawText(canvas: Canvas) {
mPaint.textSize = Math.min(mViewWidth, mViewHeight) / 6f
mPaint.textAlign = Paint.Align.CENTER
mPaint.strokeWidth = 0f
mPaint.color = mTextColor
// mPaint.setTypeface(FontUtils.selectTypeface(getContext(), FontUtils.STYLE_BOLD));
// Center text
val xPos = canvas.width / 2
var yPos = (canvas.height / 2 - (mPaint.descent() + mPaint.ascent()) / 2).toInt()
val balance = 20
if (!TextUtils.isEmpty(mSubtext)) {
yPos -= balance
}
canvas.drawText(calcProgressFromSweepAngle(mSweepAngle).toString() + "%", xPos.toFloat(), yPos.toFloat(), mPaint)
if (!TextUtils.isEmpty(mSubtext)) {
val y2 = (yPos.toFloat() + mPaint.descent() + balance.toFloat()).toInt()
mPaint.textSize = displayUtil.sp(mSubtextSize)
// mPaint.setTypeface(FontUtils.selectTypeface(getContext(), FontUtils.STYLE_MEDIUM));
canvas.drawText(mSubtext!!, xPos.toFloat(), y2.toFloat(), mPaint)
}
}
private fun calcSweepAngleFromProgress(progress: Int): Float {
return mMaxSweepAngle / mMaxProgress * progress
}
private fun calcProgressFromSweepAngle(sweepAngle: Float): Int {
return (sweepAngle * mMaxProgress / mMaxSweepAngle).toInt()
}
/**
* Set progress of the circular progress bar.
*
* @param progress progress between 0 and 100.
*/
fun setProgress(progress: Int) {
val animator = ValueAnimator.ofFloat(mSweepAngle, calcSweepAngleFromProgress(progress))
animator.interpolator = DecelerateInterpolator()
animator.duration = mAnimationDuration.toLong()
animator.addUpdateListener { valueAnimator ->
mSweepAngle = valueAnimator.animatedValue as Float
invalidate()
}
animator.start()
}
fun setSubText(subText: String) {
mSubtext = subText
invalidate()
}
fun setTextSize(f: Float) {
mSubtextSize = f
invalidate()
}
fun resetProgress() {
mSweepAngle = 0f
mTextColor = Color.BLACK
invalidate()
}
fun setProgressColor(color: Int) {
mProgressColor = color
invalidate()
}
fun setProgressWidth(width: Int) {
mStrokeWidth = width
invalidate()
}
fun setTextColor(color: Int) {
mTextColor = color
invalidate()
}
fun showProgressText(show: Boolean) {
mDrawText = show
invalidate()
}
/**
* Toggle this if you don't want rounded corners on progress bar.
* Default is true.
*
* @param roundedCorners true if you want rounded corners of false otherwise.
*/
fun useRoundedCorners(roundedCorners: Boolean) {
mRoundedCorners = roundedCorners
invalidate()
}
}
<file_sep>package com.eemf.sirgoingfar.routinechecker.viewmodels
import android.app.Application
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Observer
import com.eemf.sirgoingfar.database.RoutineOccurrence
/**
*
* This is the ViewModel for the RoutineDetail page
*
* @property mApplication is the Application instance of the Caller or the LifeCycle owner
* that's instantiating the ViewModel
*
* @property lifecycleOwner is the instance of the ViewModel lifecycle owner
*
* @property mRoutineOccurrenceListMutableLiveData is the livedata object of the list of
* Routine occurrences
*
*
* */
class RoutineDetailOccurrenceListViewModel(mApplication: Application, private val lifecycleOwner: LifecycleOwner) : BaseViewModel(mApplication) {
private val mRoutineOccurrenceListMutableLiveData: MutableLiveData<List<RoutineOccurrence>> = MutableLiveData()
fun getRoutineOccurrenceListObserver(): LiveData<List<RoutineOccurrence>> {
return mRoutineOccurrenceListMutableLiveData
}
private fun setRoutineOccurrenceList(routineList: List<RoutineOccurrence>?) {
setUiState(STATE_LOADED)
mRoutineOccurrenceListMutableLiveData.postValue(routineList)
}
fun getAllRoutineOccurrences(routineId: Int) {
setUiState(STATE_LOADING)
mExecutors?.diskIO()?.execute {
mDb?.dao?.getAllRoutineOccurrences(routineId)?.observe(lifecycleOwner, Observer {
setRoutineOccurrenceList(it)
})
}
}
fun updateRoutineOccurrence(clickedRoutineOccurrence: RoutineOccurrence) {
mExecutors?.diskIO()?.execute {
mDb?.dao?.updateOccurrence(clickedRoutineOccurrence)
}
}
}<file_sep>package com.eemf.sirgoingfar.core.utils
import android.content.Context
import android.content.res.TypedArray
import android.text.TextUtils
import com.eemf.sirgoingfar.core.R
import java.text.SimpleDateFormat
import java.util.*
object Helper {
fun convertTypedArrayToIntegerArrayList(typedArray: TypedArray): ArrayList<Int> {
val list = ArrayList<Int>()
for (i in 0 until typedArray.length()) {
list.add(typedArray.getResourceId(i, 0))
}
typedArray.recycle()
return list
}
fun hasTimePassed(date: Date): Boolean {
return Calendar.getInstance().timeInMillis >= date.time
}
fun getTimeStringFromDate(context: Context, date: Date?): String? {
val cal: Calendar = Calendar.getInstance()
cal.time = date
val min: Int = cal.get(Calendar.MINUTE)
var hour: Int = cal.get(Calendar.HOUR_OF_DAY)
val meridian: String = if (hour > 12) "PM" else "AM"
hour = hour % 12
if (hour == 0)
hour = 12
return context.getString(R.string.text_time, hour, String.format(Locale.getDefault(), "%02d", min), meridian)
}
fun getFreqById(freqId: Int): Frequency? {
return Frequency.getFrequency(freqId)
}
fun getRoutineTimeDetail(context: Context, date: Date?, freqId: Int): String? {
if (date == null)
return null
val routineTime = getTimeStringFromDate(context, date)
val freq = Frequency.getFrequency(freqId)?.label
?: context.getString(R.string.text_unavailable)
return context.getString(R.string.routine_detail_text, freq, routineTime)
}
fun getNextRoutineOccurrenceText(context: Context, freqId: Int, date: Date?): String? {
if (date == null)
return null
val timeText = getUpNext(freqId, date)
return context.getString(R.string.routine_next_occurrence_text, timeText)
}
fun computeNextRoutineTime(freqId: Int, date: Date?): Date? {
var cal: Calendar = Calendar.getInstance()
cal.isLenient = false
cal.time = date
when (freqId) {
Frequency.HOURLY.id -> cal.set(Calendar.HOUR_OF_DAY, (cal.get(Calendar.HOUR_OF_DAY) + 1))
Frequency.DAILY.id -> cal.set(Calendar.DAY_OF_MONTH, (cal.get(Calendar.DAY_OF_MONTH) + 1))
Frequency.WEEKLY.id -> cal.set(Calendar.WEEK_OF_YEAR, (cal.get(Calendar.WEEK_OF_YEAR) + 1))
Frequency.MONTHLY.id -> cal.set(Calendar.MONTH, (cal.get(Calendar.MONTH) + 1))
Frequency.YEARLY.id -> cal.set(Calendar.YEAR, (cal.get(Calendar.YEAR) + 1))
else -> return null
}
return cal.time
}
fun getUpNext(freqId: Int, date: Date?): String? {
return TimeUtil.getDuration(Calendar.getInstance().timeInMillis, date!!.time)
}
fun getDateString(date: Date?): String? {
return parseDateLong("EEE, d MMM yyyy", date?.time)
}
fun parseDateLong(patternString: String, timeInMillis: Long?): String? {
if (TextUtils.isEmpty(patternString) || timeInMillis == null || timeInMillis < 0) {
return null
}
val sdf = SimpleDateFormat(patternString, Locale.ENGLISH)
try {
return sdf.format(Date(timeInMillis))
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
}
|
ac24940b61fb65c3c40f9439c778ef11ff2a325b
|
[
"Kotlin"
] | 40 |
Kotlin
|
SirGoingFar/RoutineChecker
|
74ecd297d3a8b6b3a212a604f97ef8e227155bd5
|
bf8d4a7d598397d5c1b72208158c0c010abcdbbc
|
refs/heads/master
|
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Utilities\ThemeMods;
use My\Theme\Utilities\ThemeMods;
use GrottoPress\Jentil\Utilities\ThemeMods\AbstractThemeMod;
class Sample extends AbstractThemeMod
{
/**
* @var ThemeMods
*/
protected $themeMods;
/**
* @var string
*/
private $section;
/**
* @var string
*/
private $setting;
public function __construct(
ThemeMods $theme_mods,
string $section,
string $setting
) {
$this->themeMods = $theme_mods;
$this->section = \sanitize_key($section);
$this->setting = \sanitize_key($setting);
$this->id = "sample_{$this->section}_{$this->setting}";
$this->default = $this->defaults()[$this->setting] ?? '';
}
/**
* @return array<string, mixed>
*/
private function defaults(): array
{
$defaults = [
'text' => \esc_html('Text', 'jentil-theme'),
'color' => '#ffeedd',
'image' => '',
'select' => 1,
];
// if ('sample_section' === $this->section) {
// $defaults['color'] = '#f0f0f0';
// }
return $defaults;
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Views;
use My\Theme\AbstractTestCase;
use GrottoPress\Jentil\AbstractChildTheme;
use Codeception\Util\Stub;
use tad\FunctionMocker\FunctionMocker;
class HeaderTest extends AbstractTestCase
{
public function testRun()
{
$add_action = FunctionMocker::replace('add_action');
$header = new Header(Stub::makeEmpty(AbstractChildTheme::class));
$header->run();
$add_action->wasCalledTimes(2);
$add_action->wasCalledWithOnce([
'jentil_inside_header',
[$header, 'renderLogo'],
8
]);
$add_action->wasCalledWithOnce([
'jentil_after_after_header',
[$header, 'renderSample'],
8
]);
}
public function testRenderLogo()
{
$the_custom_logo = FunctionMocker::replace('the_custom_logo');
$header = new Header(Stub::makeEmpty(AbstractChildTheme::class));
$header->renderLogo();
$the_custom_logo->wasCalledOnce();
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Scripts;
use GrottoPress\Jentil\Setups\Scripts\AbstractScript;
use GrottoPress\Jentil\AbstractChildTheme;
/*
|-----------------------------------------------------------------
| Customize Preview Script Setup
|-----------------------------------------------------------------
|
| @see GrottoPress\Jentil\Setups\Scripts\CustomizePreview
|
*/
final class CustomizePreview extends AbstractScript
{
public function __construct(AbstractChildTheme $theme)
{
parent::__construct($theme);
$this->id = "{$this->app->meta['slug']}-customize-preview";
}
public function run()
{
// \add_action('after_setup_theme', [$this, 'dequeue']);
\add_action('customize_preview_init', [$this, 'enqueue']);
\add_action('customize_preview_init', [$this, 'addInlineScript']);
}
/**
* This is only an example. You probably don't want to
* dequeue this.
*
* @action after_setup_theme
*/
public function dequeue()
{
\remove_action('customize_preview_init', [
$this->app->parent->setups['Scripts\CustomizePreview'],
'enqueue'
]);
// OR
// @action wp_enqueue_scripts Use priority > 10 (eg: 20)
// \wp_dequeue_script(
// $this->app->parent->setups['Scripts\CustomizePreview']->id
// );
\remove_action('customize_preview_init', [
$this->app->parent->setups['Scripts\CustomizePreview'],
'addInlineScript'
]);
\remove_action('wp_enqueue_scripts', [
$this->app->parent->setups['Scripts\CustomizePreview'],
'addFrontEndInlineScript'
]);
}
/**
* @action customize_preview_init
*/
public function enqueue()
{
$file_system = $this->app->utilities->fileSystem;
$file = '/dist/js/customize-preview.js';
\wp_enqueue_script(
$this->id,
$file_system->themeDir('url', $file),
['customize-preview'],
\filemtime($file_system->themeDir('path', $file)),
true
);
}
/**
* @action customize_preview_init
*/
public function addInlineScript()
{
$script = 'var myThemeAwesomePostsHeadingModId = "'.
$this->app->setups['Customizer']
->sections['AwesomePosts']
->settings['Heading']->id.
'";';
\wp_add_inline_script($this->id, $script, 'before');
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\PostTypeTemplates;
use GrottoPress\Jentil\Setups\PostTypeTemplates\AbstractTemplate;
/*
|---------------------------------------------------------------------
| Example Post Type Template Setup
|---------------------------------------------------------------------
|
| In this case, we are removing Jentil's page-builder-blank.php
| template setup.
|
|
| @see GrottoPress\Jentil\Setups\PostTypeTemplates\PageBuilderBlank
*/
final class PageBuilderBlank extends AbstractTemplate
{
public function run()
{
\add_action('after_setup_theme', [$this, 'remove']);
}
public function remove()
{
\remove_action(
'wp_loaded',
[
$this->app->parent->setups['PostTypeTemplates\PageBuilderBlank'],
'load'
]
);
}
}
<file_sep>/// <reference path='./module.d.ts' />
export abstract class Base {
constructor(
protected readonly _j: JQueryStatic,
protected readonly _wp: WP,
protected readonly _mod_ids: string[],
) {
}
run(): void {
this.update()
}
protected abstract update(): void
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Utilities;
use My\Theme\Utilities;
use My\Theme\Utilities\ThemeMods\AwesomePosts as AwesomePostsMod;
class AwesomePosts
{
/**
* @var Utilities
*/
private $utilities;
public function __construct(Utilities $utilities)
{
$this->utilities = $utilities;
}
public function render(): string
{
$out = '';
if (($number = $this->themeMod('number')->get()) < 1) {
return $out;
}
$args = [
// 'id' => '',
'class' => 'layout-grid',
'title' => [
'tag' => 'h3',
'position' => 'side',
'length' => 12,
'after' => [
'types' => \explode(
',',
$this->themeMod('after_title')->get()
),
'separator' => $this->themeMod('after_title_sep')->get(),
],
],
'excerpt' => [
'length' => ($this->themeMod('excerpt')->get() ? 16 : 0),
'more_text' => $this->themeMod('more_text')->get(),
],
'wp_query' => [
'posts_per_page' => $number,
'ignore_sticky_posts' => 1,
'no_found_rows' => true,
'post_type' => $this->themeMod('post_type')->get(),
'meta_query' => [
[
'key' => $this->id(),
'value' => 1,
'type' => 'UNSIGNED',
],
],
],
];
if ('page' === $args['wp_query']['post_type']) {
$args['wp_query']['orderby']['menu_order'] = 'ASC';
}
$parent = $this->utilities->app->parent;
$posts = $parent->utilities->posts($args)->render();
if (!$posts && !$parent->utilities->page->is('customize_preview')) {
return $out;
}
if (($heading = $this->themeMod('heading')->get()) ||
$parent->utilities->page->is('customize_preview')
) {
$out .= '<h2 class="posts-heading heading">'.
$heading.
'</h2>';
}
return '<div id="awesome-posts" class="inner">'
.$out.$posts.
'</div>';
}
public function themeMod(string $setting): AwesomePostsMod
{
return $this->utilities->themeMods->awesomePosts($setting);
}
public function id(): string
{
return "_{$this->utilities->app->meta['slug']}-awesome-posts";
}
public function where(): bool
{
$page = $this->utilities->app->parent->utilities->page;
return ($page->is('front_page') /*&& $page->is('page')*/);
}
/**
* @return array<string, string>
*/
public function postTypes(): array
{
$types = \get_post_types(['public' => true], 'objects');
$return = \array_combine(
\array_map(function ($type): string {
return $type->name;
}, $types),
\array_map(function ($type): string {
return $type->labels->singular_name;
}, $types)
);
return \array_filter($return, function (string $type): bool {
return \post_type_supports($type, 'thumbnail');
}, ARRAY_FILTER_USE_KEY);
}
}
<file_sep><?php
namespace My\Theme\Setups\Customizer;
use My\Theme\Setups\Customizer;
use GrottoPress\Jentil\Setups\Customizer\AbstractPanel;
use WP_Customize_Manager as WPCustomizer;
final class SamplePanel extends AbstractPanel
{
public function __construct(Customizer $customizer)
{
parent::__construct($customizer);
$this->id = 'sample_panel';
$this->args['title'] = \esc_html__('Sample Panel', 'jentil-theme');
}
public function add(WPCustomizer $wp_customizer)
{
$this->sections['SampleSection'] = new SamplePanel\SampleSection($this);
parent::add($wp_customizer);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Utilities\ThemeMods;
use My\Theme\Utilities\ThemeMods;
use GrottoPress\Jentil\Utilities\ThemeMods\AbstractThemeMod;
class AwesomePosts extends AbstractThemeMod
{
/**
* @var ThemeMods
*/
protected $themeMods;
/**
* @var string
*/
private $setting;
public function __construct(ThemeMods $theme_mods, string $setting)
{
$this->themeMods = $theme_mods;
$this->setting = \sanitize_key($setting);
$this->id = "awesome_posts_{$this->setting}";
$this->default = $this->defaults()[$this->setting] ?? null;
}
/**
* @return array<string, mixed>
*/
private function defaults(): array
{
return [
'number' => 3,
'heading' => \esc_html__('Awesome Posts', 'jentil-theme'),
'excerpt' => 1,
'post_type' => 'post',
'after_title' => '',
'after_title_sep' => '|',
'more_text' => \esc_html__('Read more »', 'jentil-theme'),
];
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\AwesomePosts\Controls;
use My\Theme\Setups\Customizer\AwesomePosts;
final class Number extends AbstractControl
{
public function __construct(AwesomePosts $awesome_posts)
{
parent::__construct($awesome_posts);
$this->id = $awesome_posts->settings['Number']->id;
$this->args['type'] = 'select';
$this->args['label'] = \esc_html__('Number or posts', 'jentil-theme');
$this->args['choices'] = \array_combine(($num = \range(0, 6, 1)), $num);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\Footer\Settings;
use My\Theme\Setups\Customizer;
use GrottoPress\Jentil\Utilities\ThemeMods\Footer as FooterMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;
abstract class AbstractSetting extends Setting
{
public function __construct(Customizer $customizer)
{
parent::__construct($customizer);
}
protected function themeMod(string $setting): FooterMod
{
return $this->customizer->app->parent->utilities->themeMods->footer(
$setting
);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Translations;
use My\Theme\AbstractTestCase;
use My\Theme\Utilities;
use My\Theme\Utilities\FileSystem;
use GrottoPress\Jentil\AbstractChildTheme;
use Codeception\Util\Stub;
use tad\FunctionMocker\FunctionMocker;
class CoreTest extends AbstractTestCase
{
public function testRun()
{
$add_action = FunctionMocker::replace('add_action');
$translation = new Core(Stub::makeEmpty(AbstractChildTheme::class, [
'meta' => ['text_domain' => 'theme'],
]));
$translation->run();
$add_action->wasCalledOnce();
$add_action->wasCalledWithOnce([
'after_setup_theme',
[$translation, 'loadTextDomain']
]);
}
public function testLoadTextDomain()
{
$load = FunctionMocker::replace('load_theme_textdomain');
$theme = Stub::makeEmpty(AbstractChildTheme::class, [
'utilities' => Stub::makeEmpty(Utilities::class),
'meta' => ['text_domain' => 'theme', 'domain_path' => '/path'],
]);
$theme->utilities->fileSystem = Stub::makeEmpty(FileSystem::class, [
'themeDir' => function (string $type, string $append) {
return "/var/www/themes/my-theme{$append}";
}
]);
$translation = new Core($theme);
$translation->loadTextDomain();
$load->wasCalledOnce();
$load->wasCalledWithOnce([
$translation->textDomain,
'/var/www/themes/my-theme/path'
]);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\AwesomePosts\Settings;
use My\Theme\Setups\Customizer\AwesomePosts;
use My\Theme\Utilities\ThemeMods\AwesomePosts as AwesomePostsMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;
abstract class AbstractSetting extends Setting
{
public function __construct(AwesomePosts $awesome_posts)
{
parent::__construct($awesome_posts->customizer);
}
protected function themeMod(string $setting): AwesomePostsMod
{
return $this->customizer->app->utilities->themeMods->awesomePosts(
$setting
);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Utilities;
use My\Theme\Utilities;
use My\Theme\Utilities\ThemeMods\Sample as SampleMod;
/*
|------------------------------------------------------------------------
| Sample Utility
|------------------------------------------------------------------------
|
| @see My\Theme\Setups\Customizer\Sample
| @see My\Theme\Utilities\ThemeMods\Sample
|
*/
class Sample
{
/**
* @var Utilities
*/
private $utilities;
public function __construct(Utilities $utilities)
{
$this->utilities = $utilities;
}
public function render(): string
{
$sample_image = $this->themeMod('sample_section', 'image')->get();
// $another_image = $this->themeMod('another_section', 'image')->get();
return \wp_get_attachment_image(
\attachment_url_to_postid($sample_image),
'full',
false,
['class' => 'sample-image']
);
}
public function themeMod(string $section, string $setting): SampleMod
{
return $this->utilities->themeMods->sample($section, $setting);
}
/**
* @return array<string, string>
*/
public function dropdown(): array
{
return \array_combine(($num = \range(0, 5)), $num);
}
public function where(): bool
{
return $this->utilities->app->parent->utilities->page->is('front_page');
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My;
use My\Theme\Setups;
use My\Theme\Utilities;
use GrottoPress\Jentil\AbstractChildTheme;
/*
|---------------------------------------------------------------
| Main theme class
|---------------------------------------------------------------
|
| This is where you create your setup instances, ready for running
| in your theme's function.php
|
| @see GrottoPress\Jentil\AbstractChildTheme
| @see GrottoPress\Jentil
|
*/
final class Theme extends AbstractChildTheme
{
/**
* @var Utilities
*/
private $utilities;
/**
* @var array<string, string>
*/
private $meta;
protected function __construct()
{
$this->setUpMisc();
$this->setUpTranslations();
// $this->setUpThemeMods();
$this->setUpMetaBoxes();
// $this->setUpThumbnails();
$this->setUpStyles();
$this->setUpScripts();
// $this->setUpSidebars();
// $this->setUpPostTypeTemplates();
$this->setUpViews();
}
protected function getUtilities(): Utilities
{
return $this->utilities = $this->utilities ?: new Utilities($this);
}
/**
* @return array<string, string>
*/
protected function getMeta(): array
{
return $this->meta = $this->meta ?: $this->getParent()->themeData(
$this->getUtilities()->fileSystem->themeDir('path')
);
}
private function setUpMisc()
{
$this->setups['Customizer'] = new Setups\Customizer($this);
// $this->setups['Background'] = new Setups\Background($this);
// $this->setups['FeaturedImage'] = new Setups\FeaturedImage($this);
$this->setups['Logo'] = new Setups\Logo($this);
}
private function setUpTranslations()
{
$this->setups['Translations\Core'] =
new Setups\Translations\Core($this);
}
private function setUpThemeMods()
{
$this->setups['ThemeMods\Footer'] = new Setups\ThemeMods\Footer($this);
}
private function setUpMetaBoxes()
{
// $this->setups['MetaBoxes\Sample'] =
// new Setups\MetaBoxes\Sample($this);
$this->setups['MetaBoxes\Featured'] =
new Setups\MetaBoxes\Featured($this);
}
private function setUpThumbnails()
{
$this->setups['Thumbnails\Micro'] = new Setups\Thumbnails\Micro($this);
$this->setups['Thumbnails\Small'] = new Setups\Thumbnails\Small($this);
}
private function setUpStyles()
{
$this->setups['Styles\Core'] = new Setups\Styles\Core($this);
$this->setups['Styles\Editor'] = new Setups\Styles\Editor($this);
}
private function setUpScripts()
{
$this->setups['Scripts\Core'] = new Setups\Scripts\Core($this);
$this->setups['Scripts\CustomizePreview'] =
new Setups\Scripts\CustomizePreview($this);
}
private function setUpSidebars()
{
$this->setups['Sidebars\Tertiary'] =
new Setups\Sidebars\Tertiary($this);
$this->setups['Sidebars\Secondary'] =
new Setups\Sidebars\Secondary($this);
}
private function setUpPostTypeTemplates()
{
$this->setups['PostTypeTemplates\Sample'] =
new Setups\PostTypeTemplates\Sample($this);
$this->setups['PostTypeTemplates\PageBuilderBlank'] =
new Setups\PostTypeTemplates\PageBuilderBlank($this);
}
private function setUpViews()
{
$this->setups['Views\Header'] = new Setups\Views\Header($this);
$this->setups['Views\Page'] = new Setups\Views\Page($this);
$this->setups['Views\Footer'] = new Setups\Views\Footer($this);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups;
use My\Theme\AbstractTestCase;
use GrottoPress\Jentil\AbstractChildTheme;
use Codeception\Util\Stub;
use tad\FunctionMocker\FunctionMocker;
class LogoTest extends AbstractTestCase
{
public function testRun()
{
$add_action = FunctionMocker::replace('add_action');
$logo = new Logo(Stub::makeEmpty(AbstractChildTheme::class));
$logo->run();
$add_action->wasCalledOnce();
$add_action->wasCalledWithOnce([
'after_setup_theme',
[$logo, 'addSupport']
]);
}
public function testAddSupport()
{
$add_theme_support = FunctionMocker::replace('add_theme_support');
$logo = new Logo(Stub::makeEmpty(AbstractChildTheme::class));
$logo->addSupport();
$add_theme_support->wasCalledOnce();
$add_theme_support->wasCalledWithOnce(['custom-logo', [
'height' => 30,
'width' => 160,
'flex-width' => false,
'flex-height' => false,
]]);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Thumbnails;
use GrottoPress\Jentil\AbstractChildTheme;
use GrottoPress\Jentil\Setups\Thumbnails\AbstractThumbnail;
/*
|-----------------------------------------------------------------
| Thumbnails Setup
|-----------------------------------------------------------------
|
| Set post thumbnail sizes here, and add new thumbnail sizes for your theme.
|
| You may remove sizes added by Jentil that you do not need here.
|
| @see GrottoPress\Jentil\Setups\Thumbnails\
|
*/
final class Small extends AbstractThumbnail
{
public function __construct(AbstractChildTheme $theme)
{
parent::__construct($theme);
$this->id = "{$this->app->meta['slug']}-small";
}
public function run()
{
\add_action('after_setup_theme', [$this, 'addSize']);
}
/**
* @action after_setup_theme
*/
public function addSize()
{
\add_image_size($this->id, 150, 150, true);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Views;
use GrottoPress\Jentil\Setups\AbstractSetup;
/*
|----------------------------------------------------------------------
| Header Setup
|----------------------------------------------------------------------
|
| @see GrottoPress\Jentil\Setups\Views\Header
|
*/
final class Header extends AbstractSetup
{
public function run()
{
// \add_action('after_setup_theme', [$this, 'removeMenu']);
\add_action('jentil_inside_header', [$this, 'renderLogo'], 8);
\add_action('jentil_after_after_header', [$this, 'renderSample'], 8);
}
/**
* @action after_setup_theme
*/
public function removeMenu()
{
\remove_action(
'jentil_inside_header',
[$this->app->parent->setups['Views\Header'], 'renderMenu']
);
\remove_action(
'jentil_inside_header',
[$this->app->parent->setups['Views\Header'], 'renderMenuToggle']
);
}
/**
* @action jentil_inside_header
*/
public function renderLogo()
{
\the_custom_logo();
}
/**
* @action jentil_after_after_header
*/
public function renderSample()
{
$utility = $this->app->utilities->sample;
if (!$utility->where()) {
return;
}
echo $utility->render();
}
}
<file_sep>/// <reference path='./module.d.ts' />
import { Base } from './base'
export class BackgroundColor extends Base {
constructor(j: JQueryStatic, wp: WP) {
super(j, wp, ['background_color'])
}
protected update(): void {
this._wp.customize(this._mod_ids[0], (from): void => {
from.bind((to: string): void => {
if (-1 === ['#fff', '#ffffff'].indexOf(to)) {
this._j('body').removeClass('no-background-color')
.addClass('has-background-color')
} else {
this._j('body').removeClass('has-background-color')
.addClass('no-background-color')
}
})
})
}
}
<file_sep>/// <reference path='./module.d.ts' />
import { Base } from './base'
export class AnotherClass extends Base {
run(): void {
// this.doAnotherThing()
}
private doAnotherThing(): void {
this._j('body').html('Doing another thing')
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\ThemeMods;
use GrottoPress\Jentil\Setups\AbstractSetup;
/*
|----------------------------------------------------------------------
| Footer Theme Mod Setup
|----------------------------------------------------------------------
|
| Filter Jentil's Footer theme mods utility here, to add our own
| theme's footer setting id and default.
|
| This is possible via the filter hook `jentil_footer_mod_id`
|
| @see GrottoPress\Jentil\Utilities\ThemeMods\Footer
|
*/
final class Footer extends AbstractSetup
{
public function run()
{
\add_filter('jentil_footer_mod_id', [$this, 'addLogoId'], 10, 2);
\add_filter(
'jentil_footer_mod_default',
[$this, 'addLogoDefault'],
10,
2
);
}
/**
* @filter jentil_footer_mod_id
*/
public function addLogoId(string $id, string $setting): string
{
if ('logo' !== $setting) {
return $id;
}
return "footer_logo";
}
/**
* @filter jentil_footer_mod_default
*/
public function addLogoDefault($default, string $setting)
{
if ('logo' !== $setting) {
return $default;
}
return 0;
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Utilities;
use My\Theme\Utilities;
use GrottoPress\Jentil\Utilities\ThemeMods\Footer as FooterMod;
/*
|------------------------------------------------------------------------
| Footer Utility
|------------------------------------------------------------------------
|
|
*/
class Footer
{
/**
* @var Utilities
*/
private $utilities;
public function __construct(Utilities $utilities)
{
$this->utilities = $utilities;
}
public function renderLogo(): string
{
return \wp_get_attachment_image(
$this->themeMod('logo')->get(),
'full',
true,
['class' => 'footer-logo']
);
}
public function themeMod(string $setting): FooterMod
{
return $this->utilities->app->parent
->utilities->themeMods->footer($setting);
}
}
<file_sep>ARG PHP_VERSION=7.4
ARG WORDPRESS_VERSION=6.1
FROM prooph/composer:${PHP_VERSION} AS vendor
WORKDIR /tmp
COPY composer.json composer.json
COPY composer.lock composer.lock
RUN composer update \
--no-autoloader \
--no-dev \
--no-interaction \
--no-scripts \
--prefer-dist
RUN composer dump-autoload \
--no-dev \
--no-interaction \
--no-scripts \
--optimize
FROM wordpress:${WORDPRESS_VERSION}-php${PHP_VERSION}-apache
ARG THEME_NAME=jentil-theme
ENV THEME_NAME=${THEME_NAME}
ENV WORDPRESS_DIR=/var/www/html
ENV THEME_DIR=${WORDPRESS_DIR}/wp-content/themes/${THEME_NAME}
COPY --chown=www-data . /usr/src/${THEME_NAME}/
COPY --chown=www-data --from=vendor /tmp/vendor/ /usr/src/${THEME_NAME}/vendor/
COPY docker/docker-entrypoint.sh /tmp/
RUN cat /usr/local/bin/docker-entrypoint.sh | \
sed '/^\s*exec "$@"/d' > \
/usr/local/bin/docker-main-entrypoint.sh; \
cat /tmp/docker-entrypoint.sh >> \
/usr/local/bin/docker-main-entrypoint.sh; \
chmod +x /usr/local/bin/docker-main-entrypoint.sh
ENTRYPOINT ["docker-main-entrypoint.sh"]
CMD ["apache2-foreground"]
<file_sep><?php
declare (strict_types = 1);
use My\Theme;
function MyTheme(): Theme
{
return Theme::getInstance();
}
<file_sep># Jentil Theme
A starter for building WordPress themes with [Jentil](https://www.grottopress.com/jentil/).
## Documentation
- [Features](https://github.com/grottopress/jentil#features)
- [Requirements](https://github.com/grottopress/jentil#requirements)
- [Installation](https://github.com/grottopress/jentil#installation)
- [Developing your theme](https://github.com/grottopress/jentil#developing-your-theme)
- [Architecture](https://github.com/grottopress/jentil#architecture)
- [Showcase](https://github.com/grottopress/jentil#showcase)
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer;
use My\Theme\Setups\Customizer;
use GrottoPress\Jentil\Setups\Customizer\AbstractSection;
use WP_Customize_Manager as WPCustomizer;
final class AwesomePosts extends AbstractSection
{
public function __construct(Customizer $customizer)
{
parent::__construct($customizer);
$this->id = 'awesome_posts';
$this->args['title'] = \esc_html__('Awesome Posts', 'jentil-theme');
$this->args['priority'] = 150; // Before sticky posts
$this->args['panel'] = $this->customizer->app->parent
->setups['Customizer']->panels['Posts']->id;
$this->args['active_callback'] = function (): bool {
return $this->customizer->app->utilities->awesomePosts->where();
};
}
public function add(WPCustomizer $wp_customizer)
{
$this->settings['Number'] = new AwesomePosts\Settings\Number($this);
$this->controls['Number'] = new AwesomePosts\Controls\Number($this);
$this->settings['Heading'] = new AwesomePosts\Settings\Heading($this);
$this->controls['Heading'] = new AwesomePosts\Controls\Heading($this);
$this->settings['PostType'] = new AwesomePosts\Settings\PostType($this);
$this->controls['PostType'] = new AwesomePosts\Controls\PostType($this);
$this->settings['Excerpt'] = new AwesomePosts\Settings\Excerpt($this);
$this->controls['Excerpt'] = new AwesomePosts\Controls\Excerpt($this);
$this->settings['MoreText'] = new AwesomePosts\Settings\MoreText($this);
$this->controls['MoreText'] = new AwesomePosts\Controls\MoreText($this);
$this->settings['AfterTitle'] =
new AwesomePosts\Settings\AfterTitle($this);
$this->controls['AfterTitle'] =
new AwesomePosts\Controls\AfterTitle($this);
$this->settings['AfterTitleSep'] =
new AwesomePosts\Settings\AfterTitleSep($this);
$this->controls['AfterTitleSep'] =
new AwesomePosts\Controls\AfterTitleSep($this);
parent::add($wp_customizer);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\AwesomePosts\Settings;
use My\Theme\Setups\Customizer\AwesomePosts;
final class Heading extends AbstractSetting
{
public function __construct(AwesomePosts $awesome_posts)
{
parent::__construct($awesome_posts);
$theme_mod = $this->themeMod('heading');
$this->id = $theme_mod->id;
$this->args['default'] = $theme_mod->default;
$this->args['sanitize_callback'] = 'sanitize_text_field';
$this->args['transport'] = 'postMessage';
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups;
use GrottoPress\Jentil\Setups\Customizer\AbstractCustomizer;
use WP_Customize_Manager as WPCustomizer;
/*
|---------------------------------------------------------------------
| Customizer Setup
|---------------------------------------------------------------------
|
| This is where you add your own setting, sections, panels to the
| theme customizer.
|
| Jentil provides a handy API for setting these up. It comes with
| `AbstractCustomizer`, `AbstractPanel`, `AbstractSection`,
| `AbstractSetting` which your own classes can inherit.
|
| @see GrottoPress\Jentil\Setups\Customizer for how
| Jentil's own customizer is set up.
|
*/
final class Customizer extends AbstractCustomizer
{
public function run()
{
\add_action('customize_register', [$this, 'register']);
// \add_action('customize_register', [$this, 'removeItems'], 20);
\add_action('customize_register', [$this, 'hideItems'], 20);
}
/**
* @action customize_register
*/
public function removeItems(WPCustomizer $wp_customizer)
{
$this->app->parent->setups['Customizer']
->panels['Posts']->sections['Sticky_post']
->remove($wp_customizer);
$this->app->parent->setups['Customizer']
->sections['Title']->controls['PostType_post']
->remove($wp_customizer);
$this->app->parent->setups['Customizer']
->sections['Title']->settings['PostType_post']
->remove($wp_customizer);
$this->app->parent->setups['Customizer']
->sections['Footer']/*->settings['colophon']*/
->remove($wp_customizer);
}
/**
* @action customize_register
*/
public function hideItems(WPCustomizer $wp_customizer)
{
$parent = $this->app->parent;
$single_page_active_cb = $parent->setups['Customizer']
->panels['Posts']
->sections['Singular_page']
->get($wp_customizer)
->active_callback;
$related_page_active_cb = $parent->setups['Customizer']
->panels['Posts']
->sections['Related_page']
->get($wp_customizer)
->active_callback;
$parent->setups['Customizer']
->panels['Posts']
->sections['Singular_page']
->get($wp_customizer)
->active_callback =
function () use ($single_page_active_cb, $parent): bool {
if ('page' === \get_option('show_on_front')) {
return $parent->utilities->page->is('page') &&
!$parent->utilities->page->is('front_page');
}
return (bool)$single_page_active_cb();
};
$parent->setups['Customizer']
->panels['Posts']
->sections['Related_page']
->get($wp_customizer)
->active_callback =
function () use ($related_page_active_cb, $parent): bool {
if ('page' === \get_option('show_on_front')) {
return $parent->utilities->page->is('page') &&
!$parent->utilities->page->is('front_page');
}
return (bool)$related_page_active_cb();
};
}
/**
* @action customize_register
*/
public function register(WPCustomizer $wp_customizer)
{
$this->panels['SamplePanel'] = new Customizer\SamplePanel($this);
$this->sections['AwesomePosts'] = new Customizer\AwesomePosts($this);
$this->settings['Footer\Settings\Logo'] =
new Customizer\Footer\Settings\Logo($this);
$this->controls['Footer\Controls\Logo'] =
new Customizer\Footer\Controls\Logo($this);
parent::register($wp_customizer);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\AwesomePosts\Controls;
use My\Theme\Setups\Customizer\AwesomePosts;
final class Excerpt extends AbstractControl
{
public function __construct(AwesomePosts $awesome_posts)
{
parent::__construct($awesome_posts);
$this->id = $awesome_posts->settings['Excerpt']->id;
$this->args['type'] = 'checkbox';
$this->args['label'] = \esc_html__('Show excerpt?', 'jentil-theme');
}
}
<file_sep>/// <reference path='../../../vendor/grottopress/jentil/assets/js/core/module.d.ts' />
/*
|--------------------------------------------------------------------------
| Declaration files
|--------------------------------------------------------------------------
|
| A declaration is how you tell the Typescript compiler that you are going
| to use an item not defined or imported in the current module.
|
| They are sort of like C/C++ header files, and consists only of member
| signatures.
|
| See `assets/scripts/customize-preview/module.d.ts` in Jentil for examples.
|
| Add `/// <reference path="./module.d.ts" />` in any new `.ts` file, to use
| the declarations here in that file.
|
| Read more:
| https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.html
|
*/
// declare const myVar: string
<file_sep>/// <reference path='./module.d.ts' />
import { Base } from './base'
export class AwesomePostsHeading extends Base {
constructor(j: JQueryStatic, wp: WP, mod_id: string) {
super(j, wp, [mod_id])
}
protected update(): void {
this._wp.customize(this._mod_ids[0], (from): void => {
from.bind((to: string): void => {
this._j('#awesome-posts .heading').html(to)
})
})
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\Footer\Controls;
use My\Theme\Setups\Customizer;
use WP_Customize_Cropped_Image_Control as CroppedImageControl;
use WP_Customize_Manager as WPCustomizer;
final class Logo extends AbstractControl
{
public function __construct(Customizer $customizer)
{
parent::__construct($customizer);
$this->id = $customizer->settings['Footer\Settings\Logo']->id;
$this->args['label'] = \esc_html__('Logo', 'jentil-theme');
$this->args['width'] = 200;
$this->args['height'] = 60;
}
public function add(WPCustomizer $wp_customizer)
{
$this->object = new CroppedImageControl(
$wp_customizer,
$this->id,
$this->args
);
parent::add($wp_customizer);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Views;
use GrottoPress\Jentil\Setups\AbstractSetup;
/*
|----------------------------------------------------------------------------
| Example Singular Setup
|----------------------------------------------------------------------------
|
| @see GrottoPress\Jentil\Setups\Views\Singular
|
*/
final class Singular extends AbstractSetup
{
public function run()
{
// \add_action('after_setup_theme', [$this, 'removeRelatedPosts']);
\add_action(
'jentil_after_after_content',
[$this, 'renderTertiarySidebar']
);
}
/**
* @action after_setup_theme
*/
public function removeRelatedPosts()
{
\remove_action(
'jentil_after_content',
[$this->app->parent->setups['Views\Singular'], 'renderRelatedPosts']
);
}
/**
* @action jentil_after_after_content
*/
public function renderTertiarySidebar()
{
if (!$this->app->parent->utilities->page->is('singular')) {
return;
}
if (!\is_active_sidebar(
$id = $this->app->setups['Sidebars\Tertiary']->id
)) {
return;
} ?>
<aside id="tertiary-widget-area" class="widget-area">
<?php \dynamic_sidebar($id); ?>
</aside><!-- .widget-area -->
<?php }
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\AwesomePosts\Controls;
use My\Theme\Setups\Customizer\AwesomePosts;
use GrottoPress\Jentil\Setups\Customizer\AbstractControl as Control;
abstract class AbstractControl extends Control
{
public function __construct(AwesomePosts $awesome_posts)
{
parent::__construct($awesome_posts->customizer);
$this->args['section'] = $awesome_posts->id;
}
}
<file_sep>if [[ "$1" == apache2* ]] || [ "$1" == php-fpm ]; then
[[ ! -f "${THEME_DIR}/functions.php" ]] && \
echo >&2 "'${THEME_NAME}' theme not found. Installing..." && \
cp -rf "/usr/src/${THEME_NAME}/" "${THEME_DIR}/" &&
rm -rf "${THEME_DIR}/docker/" && \
echo >&2 "Done! Theme installed successfully to '${THEME_DIR}'"
fi
exec "$@"
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\SamplePanel\Settings;
use My\Theme\Setups\Customizer\SamplePanel\AbstractSection;
use My\Theme\Utilities\ThemeMods\Sample as SampleMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;
abstract class AbstractSetting extends Setting
{
/**
* @var AbstractSection
*/
protected $section;
public function __construct(AbstractSection $section)
{
$this->section = $section;
parent::__construct($this->section->customizer);
}
protected function themeMod(string $setting): SampleMod
{
return $this->customizer->app->utilities->themeMods->sample(
$this->section->id,
$setting
);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Utilities;
use My\Theme\Utilities;
use My\Theme\AbstractTestCase;
use GrottoPress\Jentil\AbstractChildTheme;
use GrottoPress\Jentil\AbstractTheme;
use GrottoPress\Jentil\Utilities as JUtilities;
use GrottoPress\Jentil\Utilities\FileSystem as JFileSystem;
use Codeception\Util\Stub;
use tad\FunctionMocker\FunctionMocker;
class FileSystemTest extends AbstractTestCase
{
/**
* @dataProvider themeDirProvider
*/
public function testThemeDir(
string $type,
string $append,
string $parent_is,
string $expected
) {
FunctionMocker::replace(
'get_stylesheet_directory',
'/var/www/themes/my-theme'
);
FunctionMocker::replace(
'get_stylesheet_directory_uri',
'http://my.site/themes/my-theme'
);
$theme = new class extends AbstractChildTheme {
public $parent;
function __construct()
{
}
};
$theme->parent = new class ($parent_is) extends AbstractTheme {
private $mode;
function __construct($mode)
{
$this->mode = $mode;
}
function is(string $mode): bool
{
return ($this->mode === $mode);
}
};
$theme->parent->utilities = Stub::makeEmpty(JUtilities::class);
$theme->parent->utilities->fileSystem = Stub::makeEmpty(
JFileSystem::class,
['themeDir' => (
'path' === $type ?
"/var/www/my-theme{$append}" :
"http://my.site/my-theme{$append}"
)]
);
$utilities = Stub::makeEmpty(Utilities::class);
$utilities->app = $theme;
$fileSystem = new FileSystem($utilities);
$this->assertSame($expected, $fileSystem->themeDir($type, $append));
}
public function themeDirProvider(): array
{
return [
'parent is package, type is path' => [
'path',
'/hi',
'package',
'/var/www/my-theme/hi',
],
'parent is theme, type is path' => [
'path',
'/hi',
'theme',
'/var/www/themes/my-theme/hi',
],
'parent is package, type is url' => [
'url',
'/hello',
'package',
'http://my.site/my-theme/hello',
],
'parent is theme, type is url' => [
'url',
'/hello',
'theme',
'http://my.site/themes/my-theme/hello',
]
];
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Sidebars;
use GrottoPress\Jentil\Setups\AbstractSetup;
/*
|-----------------------------------------------------------------
| Just an example sidebar setup
|-----------------------------------------------------------------
|
| In this case, we're removing the secondary sidebar added by
| Jentil.
|
| @see GrottoPress\Jentil\Setups\Sidebars\Secondary
|
*/
final class Secondary extends AbstractSetup
{
public function run()
{
\add_action('after_setup_theme', [$this, 'remove']);
}
/**
* @action after_setup_theme
*/
public function remove()
{
\remove_action(
'widgets_init',
[$this->app->parent->setups['Sidebars\Secondary'], 'register']
);
// OR
// @action widgets_init Use priority > 10 (eg: 20)
// \unregister_sidebar(
// $this->app->parent->setups['Sidebars\Secondary']->id
// );
}
}
<file_sep>/// <reference path='../../../vendor/grottopress/jentil/assets/js/customize-preview/module.d.ts' />
declare const myThemeAwesomePostsHeadingModId: string
<file_sep>/// <reference path='./module.d.ts' />
import { Base } from './base'
export class BackgroundImage extends Base {
constructor(j: JQueryStatic, wp: WP) {
super(j, wp, ['background_image'])
}
protected update(): void {
this._wp.customize(this._mod_ids[0], (from): void => {
from.bind((to: string): void => {
if (to) {
this._j('body').removeClass('no-background-image')
.addClass('has-background-image')
} else {
this._j('body').removeClass('has-background-image')
.addClass('no-background-image')
}
})
})
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\SamplePanel\Controls;
use My\Theme\Setups\Customizer\SamplePanel\AbstractSection;
use WP_Customize_Image_Control as ImageControl;
use WP_Customize_Manager as WPCustomizer;
final class Image extends AbstractControl
{
public function __construct(AbstractSection $section)
{
parent::__construct($section);
$this->id = $section->settings['Image']->id;
$this->args['label'] = \esc_html__('Image', 'jentil-theme');
}
public function add(WPCustomizer $wp_customizer)
{
$this->object = new ImageControl(
$wp_customizer,
$this->id,
$this->args
);
parent::add($wp_customizer);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Utilities;
use My\Theme\Utilities;
class ThemeMods
{
/**
* @var Utilities
*/
private $utilities;
public function __construct(Utilities $utilities)
{
$this->utilities = $utilities;
}
public function sample(string $section, string $setting): ThemeMods\Sample
{
return new ThemeMods\Sample($this, $section, $setting);
}
public function awesomePosts(string $setting): ThemeMods\AwesomePosts
{
return new ThemeMods\AwesomePosts($this, $setting);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\AwesomePosts\Controls;
use My\Theme\Setups\Customizer\AwesomePosts;
final class PostType extends AbstractControl
{
public function __construct(AwesomePosts $awesome_posts)
{
parent::__construct($awesome_posts);
$this->id = $awesome_posts->settings['PostType']->id;
$this->args['type'] = 'select';
$this->args['label'] = \esc_html__('Post type', 'jentil-theme');
$this->args['choices'] = $this->customizer->app
->utilities->awesomePosts->postTypes();
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Sidebars;
use GrottoPress\Jentil\Setups\Sidebars\AbstractSidebar;
use GrottoPress\Jentil\AbstractChildTheme;
/*
|-----------------------------------------------------------------
| Just an example sidebar setup
|-----------------------------------------------------------------
|
| @see GrottoPress\Jentil\Setups\Sidebars\
|
*/
final class Tertiary extends AbstractSidebar
{
public function __construct(AbstractChildTheme $theme)
{
parent::__construct($theme);
$this->id = "{$this->app->meta['slug']}-tertiary";
}
public function run()
{
\add_action('widgets_init', [$this, 'register']);
}
/**
* @action widgets_init
*/
public function register()
{
\register_sidebar([
'id' => $this->id,
'name' => \esc_html__('Tertiary', 'jentil-theme'),
'description' => \esc_html__(
'Tertiary widget area',
'jentil-theme'
),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
]);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\MetaBoxes;
use GrottoPress\Jentil\Setups\MetaBoxes\AbstractMetaBox;
use GrottoPress\Jentil\AbstractChildTheme;
use WP_Post;
final class Featured extends AbstractMetaBox
{
public function __construct(AbstractChildTheme $theme)
{
parent::__construct($theme);
$this->id = "{$this->app->meta['slug']}-featured";
$this->context = 'side';
}
public function run()
{
\add_action('add_meta_boxes', [$this, 'add'], 10, 2);
\add_action('save_post', [$this, 'save']);
\add_action('edit_attachment', [$this, 'save']);
}
/**
* @return array<string, mixed>
*/
protected function box(WP_Post $post): array
{
if (!\current_user_can('edit_others_posts')) {
return [];
}
if ((int)$post->ID === (int)\get_option('page_on_front') &&
'page' === \get_option('show_on_front')
) {
return [];
}
$fields = [];
$utilities = $this->app->utilities;
if ($post->post_type ===
$utilities->themeMods->awesomePosts('post_type')->get()
) {
$fields[] = [
'id' => $utilities->awesomePosts->id(),
'type' => 'checkbox',
'label' => \esc_html__('Add to Awesome Posts', 'jentil-theme'),
];
}
if ($fields) {
return [
'id' => $this->id,
'context' => $this->context,
'title' => \esc_html__('Featured', 'jentil-theme'),
'priority' => 'default',
'callbackArgs' => ['__block_editor_compatible_meta_box' => true],
'fields' => $fields,
];
}
return [];
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups;
use GrottoPress\Jentil\Setups\AbstractSetup;
/*
|-------------------------------------------------------------------------
| Background Setup
|-------------------------------------------------------------------------
|
|
|
*/
final class Background extends AbstractSetup
{
const DEFAULT_COLOR = 'f1f1f1';
public function run()
{
\add_action('after_setup_theme', [$this, 'addSupport']);
\add_filter('body_class', [$this, 'addBodyClasses']);
}
/**
* @action after_setup_theme
*/
public function addSupport()
{
\add_theme_support('custom-background', [
'default-color' => '#'.self::DEFAULT_COLOR,
]);
}
/**
* @filter body_class
* @param string[] $classes
* @return string[]
*/
public function addBodyClasses(array $classes): array
{
if (\sanitize_key(\get_theme_mod('background_image'))) {
$classes[] = 'has-background-image';
} else {
$classes[] = 'no-background-image';
}
if (\in_array(\sanitize_key(\get_theme_mod(
'background_color',
self::DEFAULT_COLOR
)), ['fff', 'ffffff'])) {
$classes[] = 'no-background-color';
} else {
$classes[] = 'has-background-color';
}
return $classes;
}
}
<file_sep>/// <reference path='./module.d.ts' />
export abstract class Base {
constructor(protected readonly _j: JQueryStatic) { }
abstract run(): void
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Scripts;
use GrottoPress\Jentil\Setups\Scripts\AbstractScript;
use GrottoPress\Jentil\AbstractChildTheme;
/*
|-----------------------------------------------------------------
| Main theme script setup
|-----------------------------------------------------------------
|
| @see GrottoPress\Jentil\Setups\Scripts\Core
|
*/
final class Core extends AbstractScript
{
public function __construct(AbstractChildTheme $theme)
{
parent::__construct($theme);
$this->id = $this->app->meta['slug'];
}
public function run()
{
// \add_action('after_setup_theme', [$this, 'dequeue']);
\add_action('wp_enqueue_scripts', [$this, 'enqueue']);
}
/**
* @action wp_enqueue_scripts
*/
public function enqueue()
{
$file_system = $this->app->utilities->fileSystem;
$file = '/dist/js/core.js';
\wp_enqueue_script(
$this->id,
$file_system->themeDir('url', $file),
['jquery'],
\filemtime($file_system->themeDir('path', $file)),
true
);
}
/**
* This is only an example. You probably do not
* want to dequeue Jentil's script.
*
* @action after_setup_theme
*/
public function dequeue()
{
\remove_action(
'wp_enqueue_scripts',
[$this->app->parent->setups['Scripts\Core'], 'enqueue']
);
// OR
// @action wp_enqueue_scripts Use priority > 10 (eg: 20)
// \wp_dequeue_script($this->app->parent->setups['Scripts\Core']->id);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\SamplePanel;
use My\Theme\Setups\Customizer\SamplePanel;
use GrottoPress\Jentil\Setups\Customizer\AbstractSection as Section;
use WP_Customize_Manager as WPCustomizer;
abstract class AbstractSection extends Section
{
public function __construct(SamplePanel $sample_panel)
{
parent::__construct($sample_panel->customizer);
$this->args['panel'] = $sample_panel->id;
}
public function add(WPCustomizer $wp_customizer)
{
$this->setSettings();
parent::add($wp_customizer);
}
protected function setSettings()
{
$this->settings['Text'] = new Settings\Text($this);
$this->controls['Text'] = new Controls\Text($this);
$this->settings['Select'] = new Settings\Select($this);
$this->controls['Select'] = new Controls\Select($this);
$this->settings['Color'] = new Settings\Color($this);
$this->controls['Color'] = new Controls\Color($this);
$this->settings['Image'] = new Settings\Image($this);
$this->controls['Image'] = new Controls\Image($this);
}
}
<file_sep>/// <reference path='./customize-preview/module.d.ts' />
import { Base } from './customize-preview/base'
import { AwesomePostsHeading } from './customize-preview/awesome-posts-heading'
import { BackgroundColor } from './customize-preview/background-color'
import { BackgroundImage } from './customize-preview/background-image'
const previews = [
new AwesomePostsHeading(jQuery, wp, myThemeAwesomePostsHeadingModId),
// new BackgroundColor(jQuery, wp),
// new BackgroundImage(jQuery, wp),
]
jQuery.each(previews, (_, preview: Base): void => preview.run())
<file_sep>/// <reference path='./core/module.d.ts' />
/*
|-----------------------------------------------------------------------
| About Typescript
|-----------------------------------------------------------------------
|
| Typescript is a statically-typed language developed by Microsoft,
| as a superset of JavaScript. This means you can go ahead and paste
| regular JS code here, and they should work OK.
|
| Typescript adds classical object oriented features on top of JS, eg:
| classes, abstract classes, interfaces and the like.
|
| It compiles to plain JavaScript. You could write your code using the
| latest JS features (think ES6), and it should compile down to a more
| compatible version of JS.
|
| Try it; you will love it!
|
| Read more: https://www.typescriptlang.org
|
*/
/*
|----------------------------------------------------------------------
| Build and watch
|----------------------------------------------------------------------
|
| Build assets with:
| `npm run build`
|
| Watch assets to automatically build whenever you make changes with:
| `npm run watch`
|
*/
import { Base } from './core/base'
import { SomeClass } from './core/some-module'
import { AnotherClass } from './core/another-module'
const cores = [new SomeClass(jQuery), new AnotherClass(jQuery)]
jQuery.each(cores, (_, core: Base): void => core.run())
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\SamplePanel;
use My\Theme\Setups\Customizer\SamplePanel;
final class SampleSection extends AbstractSection
{
public function __construct(SamplePanel $sample_panel)
{
parent::__construct($sample_panel);
$this->id = 'sample_section';
$this->args['title'] = \esc_html__('Sample Section', 'jentil-theme');
$this->args['active_callback'] = function (): bool {
return $this->customizer->app->utilities->sample->where();
};
}
protected function setSettings()
{
parent::setSettings();
unset(
$this->settings['Text'],
$this->controls['Text']
);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups;
use GrottoPress\Jentil\Setups\AbstractSetup;
/*
|--------------------------------------------------------------------
| Logo Setup
|--------------------------------------------------------------------
|
|
|
*/
final class Logo extends AbstractSetup
{
public function run()
{
\add_action('after_setup_theme', [$this, 'addSupport']);
}
/**
* @action after_setup_theme
*/
public function addSupport()
{
\add_theme_support('custom-logo', [
'height' => 30,
'width' => 160,
'flex-width' => false,
'flex-height' => false,
]);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme;
use My\Theme;
use My\Theme\Utilities\ThemeMods;
use GrottoPress\Getter\GetterTrait;
use GrottoPress\WordPress\MetaBox;
/*
|------------------------------------------------------------------------
| Utilities
|------------------------------------------------------------------------
|
| Create single instances of utilities you would need throughout your
| theme here, or define public methods for creating instances for
| utilities that may need more than one instance, or utilities that
| accept args via their constructor.
|
| They should be accessible from other objects via:
| `$this->app->utilities->sampleUtiltity` or
| `$this->app->utilities->anotherSampleUtility($args...)`,
| for utilities that take args.
|
| @see GrottoPress\Jentil\Utilities
|
*/
class Utilities
{
use GetterTrait;
/**
* @var Theme
*/
private $app;
/**
* @var Utilities\FileSystem
*/
private $fileSystem;
/**
* @var Utilities\ThemeMods
*/
private $themeMods;
/**
* @var Utilities\Sample
*/
private $sample;
/**
* @var Utilities\AwesomePosts
*/
private $awesomePosts;
/**
* @var Utilities\Footer
*/
private $footer;
public function __construct(Theme $theme)
{
$this->app = $theme;
}
private function getApp(): Theme
{
return $this->app;
}
private function getFileSystem(): Utilities\FileSystem
{
return $this->fileSystem = $this->fileSystem ?:
new Utilities\FileSystem($this);
}
private function getThemeMods(): Utilities\ThemeMods
{
return $this->themeMods = $this->themeMods ?:
new Utilities\ThemeMods($this);
}
private function getSample(): Utilities\Sample
{
return $this->sample = $this->sample ?: new Utilities\Sample($this);
}
private function getAwesomePosts(): Utilities\AwesomePosts
{
return $this->awesomePosts = $this->awesomePosts ?:
new Utilities\AwesomePosts($this);
}
private function getFooter(): Utilities\Footer
{
return $this->footer = $this->footer ?: new Utilities\Footer($this);
}
/**
* @param array<string, mixed> $args
*/
public function metaBox(array $args): MetaBox
{
return $this->app->parent->utilities->metaBox($args);
}
}
<file_sep>/// <reference path='./module.d.ts' />
import { Base } from './base'
export class SomeClass extends Base {
run(): void {
// this.doSomething()
}
private doSomething(): void {
this._j('body').html('Doing something')
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups;
use GrottoPress\Jentil\Setups\AbstractSetup;
/*
|-----------------------------------------------------------------
| Featured Image Setup
|-----------------------------------------------------------------
|
| @see GrottoPress\Jentil\Setups\FeaturedImage
|
*/
final class FeaturedImage extends AbstractSetup
{
public function run()
{
// \add_action('after_setup_theme', [$this, 'unsetSize']);
\add_action('after_setup_theme', [$this, 'setSize']);
}
/**
* @action after_setup_theme
*/
public function unsetSize()
{
\remove_action(
'after_setup_theme',
[$this->app->parent->setups['FeaturedImage'], 'setSize']
);
}
/**
* @action after_setup_theme
*/
public function setSize()
{
\set_post_thumbnail_size(700, 350, true);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\Footer\Settings;
use My\Theme\Setups\Customizer;
final class Logo extends AbstractSetting
{
public function __construct(Customizer $customizer)
{
parent::__construct($customizer);
$theme_mod = $this->themeMod('logo');
$this->id = $theme_mod->id;
$this->args['default'] = $theme_mod->default;
$this->args['sanitize_callback'] = 'absint';
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Thumbnails;
use GrottoPress\Jentil\Setups\AbstractSetup;
/*
|-----------------------------------------------------------------
| Thumbnail Setup
|-----------------------------------------------------------------
|
| @see GrottoPress\Jentil\Setups\Thumbnails\Micro
|
*/
final class Micro extends AbstractSetup
{
public function run()
{
\add_action('after_setup_theme', [$this, 'removeSize'], 8);
}
/**
* @action after_setup_theme
*/
public function removeSize()
{
\remove_action(
'after_setup_theme',
[$this->app->parent->setups['Thumbnails\Micro'], 'addSize']
);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups;
use My\Theme\AbstractTestCase;
use GrottoPress\Jentil\AbstractChildTheme;
use Codeception\Util\Stub;
use tad\FunctionMocker\FunctionMocker;
class BackgroundTest extends AbstractTestCase
{
public function testRun()
{
$add_action = FunctionMocker::replace('add_action');
$add_filter = FunctionMocker::replace('add_filter');
$background = new Background(Stub::makeEmpty(
AbstractChildTheme::class
));
$background->run();
$add_action->wasCalledOnce();
$add_filter->wasCalledOnce();
$add_action->wasCalledWithOnce([
'after_setup_theme',
[$background, 'addSupport']
]);
$add_filter->wasCalledWithOnce([
'body_class',
[$background, 'addBodyClasses']
]);
}
public function testAddSupport()
{
$add_theme_support = FunctionMocker::replace('add_theme_support');
$background = new Background(Stub::makeEmpty(AbstractChildTheme::class));
$background->addSupport();
$add_theme_support->wasCalledOnce();
$add_theme_support->wasCalledWithOnce(['custom-background', [
'default-color' => '#f1f1f1',
]]);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\Footer\Controls;
use My\Theme\Setups\Customizer;
use GrottoPress\Jentil\Setups\Customizer\AbstractControl as Control;
abstract class AbstractControl extends Control
{
public function __construct(Customizer $customizer)
{
parent::__construct($customizer);
$this->args['section'] = $this->customizer->app
->parent->setups['Customizer']->sections['Footer']->id;
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\MetaBoxes;
use GrottoPress\Jentil\Setups\MetaBoxes\AbstractMetaBox;
use GrottoPress\Jentil\AbstractChildTheme;
use WP_Post;
/*
|------------------------------------------------------------
| Sample Meta Box Setup
|------------------------------------------------------------
|
| @see GrottoPress\Jentil\Setups\Metaboxes\
|
*/
final class Sample extends AbstractMetaBox
{
public function __construct(AbstractChildTheme $theme)
{
parent::__construct($theme);
$this->id = "{$this->app->meta['slug']}-sample";
$this->context = 'side';
}
public function run()
{
\add_action('add_meta_boxes', [$this, 'add'], 10, 2);
\add_action('save_post', [$this, 'save']);
\add_action('edit_attachment', [$this, 'save']);
}
/**
* @return array<string, mixed>
*/
protected function box(WP_Post $post): array
{
if (!\current_user_can('edit_others_posts')) {
return [];
}
if ('post' !== $post->post_type) {
return [];
}
return [
'id' => $this->id,
'context' => $this->context,
'title' => \esc_html__('Sample Meta Box', 'jentil-theme'),
'priority' => 'default',
'callbackArgs' => ['__block_editor_compatible_meta_box' => true],
'fields' => [
[
'id' => 'sample-text-field',
'type' => 'text',
'label' => \esc_html__('Type anything', 'jentil-theme'),
'labelPos' => 'before_field',
],
[
'id' => 'sample-select-field',
'type' => 'select',
'choices' => ['a' => 'A', 'b' => 'B', 'c' => 'C'],
'label' => \esc_html__('Select any', 'jentil-theme'),
'labelPos' => 'before_field',
],
],
'notes' => '<p>'.\esc_html__(
'This is just an example meta box.',
'jentil-theme'
).'</p>',
];
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Views;
use GrottoPress\Jentil\Setups\AbstractSetup;
/*
|----------------------------------------------------------------------
| Footer Setup
|----------------------------------------------------------------------
|
| @see GrottoPress\Jentil\Setups\Views\Footer
|
*/
final class Footer extends AbstractSetup
{
public function run()
{
\add_action('jentil_inside_footer', [$this, 'renderLogo']);
}
/**
* @action jentil_inside_footer
*/
public function renderLogo()
{
echo $this->app->utilities->footer->renderLogo();
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Utilities;
use My\Theme\Utilities;
/*
|------------------------------------------------------------------------
| File System Utility
|------------------------------------------------------------------------
|
| @see GrottoPress\Jentil\Utilities\FileSystem
|
*/
class FileSystem
{
/**
* @var Utilities
*/
private $utilities;
public function __construct(Utilities $utilities)
{
$this->utilities = $utilities;
}
public function themeDir(string $type, string $append = ''): string
{
$parent = $this->utilities->app->parent;
if ($parent->is('package')) {
return $parent->utilities->fileSystem->themeDir($type, $append);
}
$stylesheet = $type === 'path'
? \get_stylesheet_directory()
: \get_stylesheet_directory_uri();
return $stylesheet.$append;
}
}
<file_sep><?php
/**
* IMPORTANT: Keep code in this file compatible with PHP 5.2
*/
define('MY_THEME_MIN_PHP', '7.0');
define('MY_THEME_MIN_WP', '5.3');
if (version_compare(PHP_VERSION, MY_THEME_MIN_PHP, '<') ||
version_compare(get_bloginfo('version'), MY_THEME_MIN_WP, '<')
) {
add_action('admin_notices', 'printMyThemeNotice');
deactivateMyTheme();
} else {
require __DIR__.'/vendor/autoload.php';
add_action('after_setup_theme', 'runMyTheme', 2);
}
function runMyTheme()
{
MyTheme()->run();
}
function printMyThemeNotice()
{
echo '<div class="notice notice-error">
<p>'.
sprintf(
esc_html__(
'%1$s theme has been deactivated as it requires PHP >= %2$s and WordPress >= %3$s',
'jentil-theme'
),
'<code>jentil-theme</code>',
'<strong>'.MY_THEME_MIN_PHP.'</strong>',
'<strong>'.MY_THEME_MIN_WP.'</strong>'
).
'</p>
</div>';
}
function deactivateMyTheme()
{
$themes = wp_get_themes(['allowed' => true]);
unset($themes['jentil-theme'], $themes['jentil']);
$theme = reset($themes);
$name = null === key($themes) ? '' : $theme->get_stylesheet();
$parent = $name ? $theme->get_template() : '';
update_option('stylesheet', $name);
update_option('template', $parent);
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\SamplePanel\Controls;
use My\Theme\Setups\Customizer\SamplePanel\AbstractSection;
use WP_Customize_Color_Control as ColorControl;
use WP_Customize_Manager as WPCustomizer;
final class Color extends AbstractControl
{
public function __construct(AbstractSection $section)
{
parent::__construct($section);
$this->id = $section->settings['Color']->id;
$this->args['label'] = \esc_html__('Color', 'jentil-theme');
// if ('sample_section' === $section->context) {
// $this->args['active_callback'] = function (): bool {
// return !$this->customizer->app->utilities->someUtility->where();
// };
// }
}
public function add(WPCustomizer $wp_customizer)
{
$this->object = new ColorControl(
$wp_customizer,
$this->id,
$this->args
);
parent::add($wp_customizer);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Scripts;
use My\Theme\AbstractTestCase;
use My\Theme\Utilities;
use My\Theme\Utilities\FileSystem;
use GrottoPress\Jentil\AbstractChildTheme;
use GrottoPress\Jentil\AbstractTheme;
use Codeception\Util\Stub;
use tad\FunctionMocker\FunctionMocker;
class CoreTest extends AbstractTestCase
{
public function testRun()
{
$add_action = FunctionMocker::replace('add_action');
$script = new Core(Stub::makeEmpty(AbstractChildTheme::class, [
'meta' => ['slug' => 'theme'],
]));
$script->run();
$add_action->wasCalledOnce();
$add_action->wasCalledWithOnce([
'wp_enqueue_scripts',
[$script, 'enqueue']
]);
}
public function testEnqueue()
{
$wp_enqueue_script = FunctionMocker::replace('wp_enqueue_script');
$test_js = \codecept_data_dir('scripts/test.js');
$theme = Stub::makeEmpty(AbstractChildTheme::class, [
'utilities' => Stub::makeEmpty(Utilities::class),
'parent' => Stub::makeEmpty(AbstractTheme::class),
'meta' => ['slug' => 'theme']
]);
$theme->utilities->fileSystem = Stub::makeEmpty(FileSystem::class, [
'themeDir' => function (
string $type,
string $append
) use ($test_js): string {
return 'path' === $type ? $test_js : "http://my.url/test.js";
},
]);
$script = new Core($theme);
$script->enqueue();
$wp_enqueue_script->wasCalledOnce();
$wp_enqueue_script->wasCalledWithOnce([
$script->id,
'http://my.url/test.js',
['jquery'],
\filemtime($test_js),
true
]);
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Customizer\SamplePanel\Controls;
use My\Theme\Setups\Customizer\SamplePanel\AbstractSection;
use WP_Customize_Color_Control as ColorControl;
use WP_Customize_Manager as WPCustomizer;
final class Text extends AbstractControl
{
public function __construct(AbstractSection $section)
{
parent::__construct($section);
$this->id = $section->settings['Text']->id;
$this->args['type'] = 'text';
$this->args['label'] = \esc_html__('Text', 'jentil-theme');
}
}
<file_sep><?php
declare (strict_types = 1);
namespace My\Theme\Setups\Views;
use GrottoPress\Jentil\Setups\AbstractSetup;
final class Page extends AbstractSetup
{
public function run()
{
\add_action('jentil_before_content', [$this, 'renderAwesomePosts']);
}
/**
* @action jentil_before_content
*/
public function renderAwesomePosts()
{
$utility = $this->app->utilities->awesomePosts;
if (!$utility->where()) {
return;
}
echo $utility->render();
}
}
|
c465c4b46228e810477f510dd1dd4aebc5169b53
|
[
"Markdown",
"PHP",
"TypeScript",
"Dockerfile",
"Shell"
] | 67 |
PHP
|
GrottoPress/jentil-theme
|
86277444b2e71367274d6f7bc103060b36330c18
|
172ee8ed613784f245fb9397298a3df016cd4c9c
|
refs/heads/master
|
<file_sep><h4 align="center">
<img src="web/src/assets/logo.svg" width="250px" />
</h4>
<p align="center">
<a href="https://github.com/gabriel2413/EcoletaNlw/blob/master/LICENSE">
<img alt="GitHub license" src="https://img.shields.io/github/license/gabriel2413/EcoletaNlw?color=sucess">
</a>
<a href="https://github.com/gabriel2413/EcoletaNlw">
<img src="https://img.shields.io/badge/author-gabriel2413-purple">
</a>
<a href="https://github.com/gabriel2413/EcoletaNlw/search?l=typescript">
<img src="https://img.shields.io/badge/made%20with-TypeScript-blue">
</a>
</p>
# About 🧾
Bom.. basicamente, o **Ecoleta** é um projeto que foi desenvolvido durante a semana nacional do meio ambiente, e possui como principal **objetivo**, conectar as pessoas a empresas que coletam resíduos específicos, como lâmpadas, baterias, óleo de cozinha etc.
O projeto foi dividido em **três seções**, a **primeira** consiste na aplicação web, que possui a funcionalidade de cadastrar pontos de coleta. A **segunda** seção representa a aplicação mobile, onde o usuário pode encontrar os pontos de coleta existentes, organizados por região, e acessar os detalhes dos mesmos. Já a **terceira** é constituída pela API, que possibilita o contato com o banco de dados, para armazenar e consultar informações.
# Tecnologias utilizadas 🧰
- [**Node.js**](https://nodejs.org/en/)
- [**Expo**](https://expo.io/)
- [**Express**](https://expressjs.com/pt-br/)
- [**React**](https://pt-br.reactjs.org/)
- [**React Native**](https://reactnative.dev/)
- [**TypeScript**](https://www.typescriptlang.org/)
# Principais libs 📚
- [**Express**](https://expressjs.com/pt-br/)
- [**KnexJS**](http://knexjs.org/)
- [**SQLite3**](https://www.sqlite.org/index.html)
- [**Axios**](https://github.com/axios/axios)
- [**Leaflet**](https://leafletjs.com/)
- [**Expo Google Fonts**](https://github.com/expo/google-fonts)
- [**Picker Select**](https://github.com/lawnstarter/react-native-picker-select)
- [**Multer**](https://github.com/expressjs/multer)
- [**Celebrate**](https://github.com/arb/celebrate)
<h4 align="center">
<img src="web/src/assets/capa.svg" width="500px" />
</h4>
<file_sep>import express from 'express'
import cors from 'cors'
import path from 'path'
import { errors } from 'celebrate'
import routes from './routes'
const app = express()
app.use(cors())
/**
* Use está incluindo um plugin/funcionalidade, nesse caso express.json, para que
* o express possa entender o corpo da requisição no formato JSON.
*/
app.use(express.json())
app.use(routes)
app.use('/uploads', express.static(path.resolve(__dirname, '..', 'tmp')))
app.use(errors)
app.listen(3333)
|
dfad4cb5594d95ffb42911d3501b04d64b6fb7d5
|
[
"Markdown",
"TypeScript"
] | 2 |
Markdown
|
ggabriel2413/EcoletaNlw
|
f470dc0da677ba2b21221e886de42690d3314f0a
|
90ecb20c7b3eb7625ece68a2dccedca9c041201e
|
refs/heads/master
|
<file_sep>import math
from unittest import TestCase
class MySampleTest(TestCase):
def test_math_in_a_loop(self):
for n in xrange(2 ** 8):
math.sqrt(n)
<file_sep>pytest-call-tracer
==================
Based on `nose-performance <https://github.com/disqus/nose-performance>`_.
<file_sep>from __future__ import absolute_import
import py
import json
from time import time
from pytest_call_tracer.util import PatchContext
from pytest_call_tracer.wrappers.base import FunctionWrapper
def pytest_addoption(parser):
group = parser.getgroup("call tracing")
group.addoption(
'--tracing', action="store_true", dest="tracing", default=False)
group.addoption(
'--trace-output', action="store", dest="trace_output")
def pytest_configure(config):
if not config.option.tracing:
return
config._tracer = TracingPlugin(config.option.trace_output)
config.pluginmanager.register(config._tracer)
def pytest_unconfigure(config):
tracer = getattr(config, '_tracer', None)
if not tracer:
return
del config._tracer
config.pluginmanager.unregister(tracer)
class TracingPlugin(object):
def __init__(self, logfile=None):
self.logfile = logfile
self.tests = []
self.context_stack = []
def pytest_runtest_setup(self, item):
self.begin_tracing(item)
def pytest_runtest_teardown(self, item):
self.end_tracing(item)
def pytest_sessionstart(self):
self.suite_start_time = time()
def pytest_sessionfinish(self):
if not self.logfile:
return
if py.std.sys.version_info[0] < 3:
logfile = py.std.codecs.open(self.logfile, 'w', encoding='utf-8')
else:
logfile = open(self.logfile, 'w', encoding='utf-8')
logfile.write(json.dumps(self.tests, indent=2))
logfile.close()
def pytest_terminal_summary(self, terminalreporter):
if self.logfile:
terminalreporter.write_sep("-", "generated tracing report file: %s" % (self.logfile))
return
def trim(string, length):
s_len = len(string)
if s_len < length:
return string
return '...' + string[s_len - length:]
print
print 'Highest call counts'
print '-' * 80
for test in sorted(self.tests, key=lambda x: len(x['calls']), reverse=True)[:25]:
print '%-74s %d' % (trim(test['id'], 70), len(test['calls']))
def patch_interfaces(self):
self._calls = []
try:
__import__('redis')
except ImportError:
pass
else:
self.patch_redis_interfaces()
try:
__import__('MySQLdb')
except ImportError:
pass
else:
self.patch_mysqldb_interfaces()
try:
__import__('kazoo')
except ImportError:
pass
else:
self.patch_kazoo_interfaces()
def patch_redis_interfaces(self):
from pytest_call_tracer.wrappers.redis import RedisWrapper, RedisPipelineWrapper
self.add_context(PatchContext('redis.client.StrictRedis.execute_command', RedisWrapper(self._calls)))
self.add_context(PatchContext('redis.client.BasePipeline.execute', RedisPipelineWrapper(self._calls)))
def patch_mysqldb_interfaces(self):
self.add_context(PatchContext('MySQLdb.connections.Connection.query', FunctionWrapper(self._calls, 'mysql')))
def patch_kazoo_interfaces(self):
self.add_context(PatchContext('kazoo.client.KazooClient._call', FunctionWrapper(self._calls, 'kazoo')))
def add_context(self, ctx):
ctx.__enter__()
self.context_stack.append(ctx)
def clear_context(self):
while self.context_stack:
self.context_stack.pop().__exit__(None, None, None)
def begin_tracing(self, item):
self.patch_interfaces()
def end_tracing(self, item):
self.clear_context()
data = {
'id': item.nodeid,
'calls': self._calls,
}
self.tests.append(data)
<file_sep>from setuptools import setup, find_packages
tests_require = [
'mysql-python',
'redis',
]
install_requires = [
'pytest',
]
setup(
name='pytest-call-tracer',
version='0.1.0',
packages=find_packages(exclude=['tests']),
zip_safe=False,
install_requires=install_requires,
# tests_require=tests_require,
# test_suite='runtests.runtests',
license='Apache License 2.0',
include_package_data=True,
entry_points={
'pytest11': [
'call_tracer = pytest_call_tracer.plugin',
]
},
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
<file_sep>from __future__ import absolute_import
import redis
import time
from unittest import TestCase
class RedisSampleTest(TestCase):
def setUp(self):
self.client = redis.Redis()
self.key = 'pytest_call_tracer:hashtest'
def tearDown(self):
self.client.delete(self.key)
def test_setting_lots_of_hashes(self):
for n in xrange(2 ** 5):
self.client.hset(self.key, str(n), time.time())
def test_pipeline_hashes(self):
with self.client.pipeline() as conn:
for n in xrange(2 ** 5):
conn.hset(self.key, str(n), time.time())
conn.execute()
<file_sep>from __future__ import absolute_import
import time
from pytest_call_tracer.wrappers.base import Wrapper
class RedisPipelineWrapper(Wrapper):
name = 'redis'
def __call__(self, func, pipeline, *args, **kwargs):
__traceback_hide__ = True # NOQA
command_stack = pipeline.command_stack[:]
start = time.time()
try:
return func(pipeline, *args, **kwargs)
finally:
end = time.time()
data = {
'name': 'pipeline',
'args': repr(command_stack),
'kwargs': repr({}),
'start': start,
'end': end,
}
self.record(data)
class RedisWrapper(Wrapper):
name = 'redis'
def __call__(self, func, *args, **kwargs):
__traceback_hide__ = True # NOQA
start = time.time()
try:
return func(*args, **kwargs)
finally:
end = time.time()
data = {
'name': args[1],
'args': repr(args[2:]),
'kwargs': repr(kwargs),
'start': start,
'end': end,
}
self.record(data)
<file_sep>from __future__ import absolute_import
def _dot_lookup(thing, comp, import_path):
try:
return getattr(thing, comp)
except AttributeError:
__import__(import_path)
return getattr(thing, comp)
def import_string(target):
components = target.split('.')
import_path = components.pop(0)
thing = __import__(import_path)
for comp in components:
import_path += ".%s" % comp
thing = _dot_lookup(thing, comp, import_path)
return thing
class PatchContext(object):
def __init__(self, target, callback):
target, attr = target.rsplit('.', 1)
target = import_string(target)
self.func = getattr(target, attr)
self.target = target
self.attr = attr
self.callback = callback
def __enter__(self):
func = getattr(self.target, self.attr)
def wrapped(*args, **kwargs):
__traceback_hide__ = True # NOQA
return self.callback(self.func, *args, **kwargs)
wrapped.__name__ = func.__name__
if hasattr(func, '__doc__'):
wrapped.__doc__ = func.__doc__
if hasattr(func, '__module__'):
wrapped.__module__ = func.__module__
setattr(self.target, self.attr, wrapped)
return self
def __exit__(self, exc_type, exc_value, traceback):
setattr(self.target, self.attr, self.func)
<file_sep>from __future__ import absolute_import
import MySQLdb
from unittest import TestCase
class MySQLdbSampleTest(TestCase):
def setUp(self):
self.client = MySQLdb.connect()
def test_simple(self):
self.client.query('select 1')
r = self.client.use_result()
assert r.fetch_row() == ((1,), )
<file_sep>from __future__ import absolute_import
from time import time
class Wrapper(object):
"""Wraps methods and logs the results """
name = None
def __init__(self, data, name=None):
self.data = data
if name is not None:
self.name = name
def record(self, data):
if 'type' not in data:
data['type'] = self.name
self.data.append(data)
class FunctionWrapper(Wrapper):
def __call__(self, func, *args, **kwargs):
__traceback_hide__ = True # NOQA
start = time()
try:
return func(*args, **kwargs)
finally:
end = time()
if getattr(func, 'im_class', None):
arg_str = repr(args[1:])
else:
arg_str = repr(args)
data = {
'type': self.name or func.__name__,
'name': func.__name__,
'args': arg_str,
'kwargs': repr(kwargs),
'start': start,
'end': end,
}
self.record(data)
|
33fd25a2501a84d514474fb1d5ce70428f86c3da
|
[
"Python",
"reStructuredText"
] | 9 |
Python
|
isabella232/pytest-call-tracer
|
4e4dac7ffe0e955193f2ef113b1cb6c9472248e2
|
13110a8582c371c17c9f4e2a818c40e9c8d4523f
|
refs/heads/master
|
<repo_name>Doweidu/DWDQiniuSdkBundle<file_sep>/Exception/QiniuPutException.php
<?php
namespace DWD\QiniuSdkBundle\Exception;
class QiniuPutException extends QiniuException
{
}
<file_sep>/README.md
# 七牛PHP-SDK Bundle #
在symfony2中使用七牛的SDK
## 安装 ##
编辑```composer.json```,添加bundle的地址,并添加依赖:
```
...
"repositories": [
...
{
"type": "vcs",
"url": "<EMAIL>:duoweidu/dwdqiniubundle.git"
}
],
...
"require": {
...
"dwd/qiniu-sdk-bundle": "dev-master",
...
}
...
```
修改配置文件 ```app/config/parameters.yml.dist```添加以下几项配置项:
```
parameters:
...
qiniu_sdk_accessKey: ~
qiniu_sdk_secretKey: ~
qiniu_sdk_bucket: ~
qiniu_sdk_domain: ~
```
更新依赖:
```
$ composer update dwd/qiniu-sdk-bundle
```
修改```app/AppKernel.php```,加载```DWDQiniuSdkBundle```:
```
$bundles = array(
...
new DWD\QiniuSdkBundle\DWDQiniuSdkBundle(),
);
```
清除缓存:
```
app/console cache:clear
```
## 使用 ##
PHP中:
```
$qiniu = $this->container->get('dwd_qiniu_sdk');
$rs = $qiniu->put('<key-name>', '<Content>'); //上传文本内容,可以直接把内容上传,使用key可以取到一个文本资源
$rs = $qiniu->putFile('<key-name>', '<file-path>'); //上传本地文件,指定文件路径即可
$rs = $qiniu->delete('<key-name>'); //从七牛删除一个资源
$rs = $qiniu->batchDelete('<key1-name>'[, '<key2-name>', ...]); //从七牛删除同一个bucket的多个资源
$rs = $qiniu->mv('<old-key-name>', 'new-key-name', '<new-bucket-name>'); //移动一个资源,第三个参数可选,默认是同一个bucket内移动
$rs = $qiniu->batchMv(array('old'=>'<old-key1-name>', 'new'=>'new-key1-name')[, array('old'=>'<old-key2-name>', 'new'=>'new-key2-name'), ...]); //移动同一个bucket的多个资源
$rs = $qiniu->copy('<from-key-name>', 'to-key-name', '<new-bucket-name>'); //复制一个资源,第三个参数可选,默认是同一个bucket内复制
$rs = $qiniu->batchCopy(array('from'=>'<from-key1-name>', 'to'=>'to-key1-name')[, array('from'=>'<from-key2-name>', 'to'=>'to-key2-name'), ...]); //复制同一个bucket的多个资源
$rs = $qiniu->stat('<key-name>'); //获取资源信息,包括文件大小(fsize),哈希值(hash),类型(mimeType),上传时间(putTime)
$rs = $qiniu->batchStat('<key1-name>'[, '<key2-name>', ...]); //批量获取文件信息,返回一个数组,code是指资源状态,正常资源是200,data中是和stat相同字段的列表数组
```
<file_sep>/DWDQiniuSdkBundle.php
<?php
namespace DWD\QiniuSdkBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class DWDQiniuSdkBundle extends Bundle
{
}
<file_sep>/Exception/QiniuStatException.php
<?php
namespace DWD\QiniuSdkBundle\Exception;
class QiniuStatException extends QiniuException
{
}
<file_sep>/Exception/QiniuDeleteException.php
<?php
namespace DWD\QiniuSdkBundle\Exception;
class QiniuDeleteException extends QiniuException
{
}
<file_sep>/Exception/QiniuCopyException.php
<?php
namespace DWD\QiniuSdkBundle\Exception;
class QiniuCopyException extends QiniuException
{
}
<file_sep>/Exception/QiniuMoveException.php
<?php
namespace DWD\QiniuSdkBundle\Exception;
class QiniuMoveException extends QiniuException
{
}
<file_sep>/Twig/Extension/QiniuExtension.php
<?php
namespace DWD\QiniuSdkBundle\Twig\Extension;
use DWD\QiniuSdkBundle\Util\Qiniu;
/**
* Twig extension for the bundle.
*/
class QiniuExtension extends \Twig_Extension
{
/**
* @var Qiniu
*
* Qiniu Sdk Util
*/
private $qiniu;
/**
* Main constructor
*
* @param Qiniu $qiniu Qiniu Sdk Util
*/
public function __construct( Qiniu $qiniu )
{
$this->qiniu = $qiniu;
}
/**
* Getter.
*
* @return array
*/
public function getFilters()
{
return array(
'qiniu_url' => new \Twig_Filter_Method($this, 'getBaseUrl'),
'qnu' => new \Twig_Filter_Method($this, 'getBaseUrl'),
);
}
/**
* Getter.
*
* @return array
*/
public function getFunctions()
{
return array(
'qiniu_url' => new \Twig_Function_Method($this, 'getBaseUrl'),
'qnu' => new \Twig_Function_Method($this, 'getBaseUrl'),
);
}
/**
* Getter.
*
* @return string
*/
public function getBaseUrl( $key )
{
$url = call_user_func_array(array($this->qiniu, 'getBaseUrl'), array( $key ));
return $url;
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'qiniu_extension';
}
}
<file_sep>/Util/Qiniu.php
<?php
/*
* register qiniu php sdk as a service into symfony 2
*
* you can get it with $this->container->get("dwd_qiniu_sdk");
*
* see more qiniu php-sdk, read: https://github.com/qiniu/php-sdk/tree/develop/docs
*
* error codes table: http://developer.qiniu.com/docs/v6/api/reference/codes.html
*
*/
namespace DWD\QiniuSdkBundle\Util;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use DWD\QiniuSdkBundle\Exception\QiniuPutException;
use DWD\QiniuSdkBundle\Exception\QiniuDeleteException;
use DWD\QiniuSdkBundle\Exception\QiniuMoveException;
use DWD\QiniuSdkBundle\Exception\QiniuCopyException;
use DWD\QiniuSdkBundle\Exception\QiniuStatException;
class Qiniu
{
private $accessKey;
private $secretKey;
private $bucket;
private $domain;
private $putPolicy = null;
public $client;
/*
* you need add some parameters in your app/config/parameters.yml.dist
*
* ...
*
* qiniu_sdk_accessKey: <YOUR_ACCESS_KEY>
* qiniu_sdk_secretKey: <YOUR_SECRET_KEY>
* qiniu_sdk_bucket: <YOUR_BUCKET_NAME>
* qiniu_sdk_domain: <YOUR_BUCKET_DOMAIN>
*
* then run composer update and follow the tip and enter your qiniu config
*
*/
public function __construct( ContainerInterface $container, $accessKey, $secretKey, $bucket, $domain )
{
$this->container = $container;
$this->accessKey = $accessKey;
$this->secretKey = $secretKey;
$this->bucket = $bucket;
$this->domain = $domain;
Qiniu_SetKeys( $this->accessKey, $this->secretKey );
$this->client = new \Qiniu_MacHttpClient(null);
}
/*
* get current bucket name
*/
public function getBucket()
{
return $this->bucket;
}
/*
* set current bucket name
*/
public function setBucket( $bucket )
{
$this->bucket = $bucket;
return $this;
}
/*
* get resource url with qiniu key
*/
public function getBaseUrl( $key )
{
return Qiniu_RS_MakeBaseUrl( $this->domain, $key );
}
/*
* get upload token
*
* read more: https://github.com/qiniu/php-sdk/tree/develop/docs#12-%E4%B8%8A%E4%BC%A0%E7%AD%96%E7%95%A5
*/
public function getUpToken( $expire = 1800, $callbackUrl = null, $callbackBody = null )
{
if( $this->putPolicy === null ) {
$this->putPolicy = new \Qiniu_RS_PutPolicy( $this->bucket );
}
/*
* set expires time
* $expire second
*/
if( $expire != $this->putPolicy->Expires ) {
$this->putPolicy->Expires = $expire;
}
if( $callbackUrl != $this->putPolicy->CallbackUrl ) {
/*
* TODO 检查callbackUrl是否为其他站点
*/
$this->putPolicy->CallbackUrl = $callbackUrl;
}
if( $callbackBody != $this->putPolicy->CallbackBody ) {
$this->putPolicy->CallbackBody = $callbackBody;
}
return $this->putPolicy->Token(null);
}
/*
* upload a text to qiniu
*
* read: https://github.com/qiniu/php-sdk/tree/develop/docs#11%E4%B8%8A%E4%BC%A0%E6%B5%81%E7%A8%8B
*/
public function put( $content )
{
$key = md5($content);
$upToken = $this->getUpToken();
$i = 0;
do {
list($ret, $err) = Qiniu_Put( $upToken, $key, $content, null );
$i++;
/*
* 503 服务端不可用
* 504 服务端操作超时
* 599 服务端操作失败
*/
} while( $i < 3 AND $err !== null AND in_array( $err->Code, array( 503, 504, 599 ) ) );
if( $err !== null ) {
throw new QiniuPutException( $err->Err, $err->Code, $key );
} else {
return $ret['key'];
}
}
/*
* upload a file to qiniu
*
* read: https://github.com/qiniu/php-sdk/tree/develop/docs#11%E4%B8%8A%E4%BC%A0%E6%B5%81%E7%A8%8B
*/
public function putFile( $filePath )
{
if( !file_exists( $filePath ) ) {
throw new FileNotFoundException($filePath, 404);
}
$key = md5_file( $filePath );
$upToken = $this->getUpToken();
$putExtra = new \Qiniu_PutExtra();
$putExtra->Crc32 = 1;
$i = 0;
do {
list($ret, $err) = Qiniu_PutFile( $upToken, $key, $filePath, $putExtra );
$i++;
/*
* 503 服务端不可用
* 504 服务端操作超时
* 599 服务端操作失败
*/
} while( $i < 3 AND $err !== null AND in_array( $err->Code, array( 503, 504, 599 ) ) );
if( $err !== null ) {
throw new QiniuPutException( $err->Err, $err->Code, $key );
} else {
return $ret['key'];
}
}
/*
* upload a file to qiniu
* 获取上传文件的原始名字,不进行md5转换 by wpp
* read: https://github.com/qiniu/php-sdk/tree/develop/docs#11%E4%B8%8A%E4%BC%A0%E6%B5%81%E7%A8%8B
*/
public function putFileOrigin( $filePath )
{
if( !file_exists( $filePath ) ) {
throw new FileNotFoundException($filePath, 404);
}
// $key = md5_file( $filePath );
$key = preg_replace('/(.*)\/{1}([^\/]*)/i', '$2', $filePath);
$upToken = $this->getUpToken();
$putExtra = new \Qiniu_PutExtra();
$putExtra->Crc32 = 1;
$i = 0;
do {
list($ret, $err) = Qiniu_PutFile( $upToken, $key, $filePath, $putExtra );
$i++;
/*
* 503 服务端不可用
* 504 服务端操作超时
* 599 服务端操作失败
*/
} while( $i < 3 AND $err !== null AND in_array( $err->Code, array( 503, 504, 599 ) ) );
if( $err !== null ) {
throw new QiniuPutException( $err->Err, $err->Code, $key );
} else {
return $ret['key'];
}
}
/*
* delete a resource from qiniu
*/
public function delete( $key )
{
$err = Qiniu_RS_Delete( $this->client, $this->bucket, $key );
if( $err !== null ) {
throw new QiniuDeleteException( $err->Err, $err->Code, $key );
} else {
return true;
}
}
/*
* batch delete
*/
public function batchDelete()
{
$keys = func_get_args();
if( func_num_args() <= 0 ) {
return array();
}
foreach( $keys as $i => $key ) {
$keys[$i] = new \Qiniu_RS_EntryPath( $this->bucket, $key );
}
list( $ret, $err ) = Qiniu_RS_BatchDelete($client, $entries);
if( $err !== null ) {
$ret['code'] = $err->Code;
return $ret;
} else {
return $ret;
}
}
/*
* rename a resource
*/
public function move( $oldKey, $newKey, $newBucket = null )
{
if( $newBucket === null ) {
$newBucket = $this->bucket;
}
$err = Qiniu_RS_Move( $this->client, $this->bucket, $oldKey, $newBucket, $newKey );
if( $err !== null ) {
throw new QiniuMoveException( $err->Err, $err->Code, $key );
} else {
return true;
}
}
/*
* batch rename
*
* param $pair array( 'old' => 'old-key', 'new' => 'new-key' )
* param $pair2 array( 'old' => 'old-key', 'new' => 'new-key' )
* ...
*
*/
public function batchMove()
{
$keys = func_get_args();
if( func_num_args() <= 0 ) {
return array();
}
$entries = array();
foreach( $keys as $i => $key ) {
if( isset( $key['old'] ) AND !empty( $key['old'] ) AND isset( $key['new'] ) AND !empty( $key['new'] ) ) {
$key['old'] = new \Qiniu_RS_EntryPath( $this->bucket, $key['old'] );
$key['new'] = new \Qiniu_RS_EntryPath( $this->bucket, $key['new'] );
$entries[$i] = new \Qiniu_RS_EntryPathPair( $key['old'], $key['new'] );
} else {
$entries[$i] = new \Qiniu_RS_EntryPathPair(
new \Qiniu_RS_EntryPath( $this->bucket, 'empty' ),
new \Qiniu_RS_EntryPath( $this->bucket, 'empty' )
);
}
}
list( $ret, $err ) = Qiniu_RS_BatchDelete($client, $entries);
if( $err !== null ) {
$ret['code'] = $err->Code;
return $ret;
} else {
return $ret;
}
}
/*
* copy a resource
*/
public function copy( $oldKey, $newKey, $newBucket = null )
{
if( $newBucket === null ) {
$newBucket = $this->bucket;
}
$err = Qiniu_RS_Copy( $this->client, $this->bucket, $oldKey, $newBucket, $newKey );
if( $err !== null ) {
throw new QiniuCopyException( $err->Err, $err->Code, $key );
} else {
return true;
}
}
/*
* batch copy
* param $pair array( 'from' => 'from-key', 'to' => 'to-key' )
* param $pair2 array( 'from' => 'from-key', 'to' => 'to-key' )
* ...
*/
public function batchCopy( array $pairs )
{
$keys = func_get_args();
if( func_num_args() <= 0 ) {
return array();
}
$entries = array();
foreach( $keys as $i => $key ) {
if( isset( $key['from'] ) AND !empty( $key['from'] ) AND isset( $key['to'] ) AND !empty( $key['to'] ) ) {
$key['from'] = new \Qiniu_RS_EntryPath( $this->bucket, $key['from'] );
$key['to'] = new \Qiniu_RS_EntryPath( $this->bucket, $key['to'] );
$entries[$i] = new \Qiniu_RS_EntryPathPair( $key['from'], $key['to'] );
} else {
$entries[$i] = new \Qiniu_RS_EntryPathPair(
new \Qiniu_RS_EntryPath( $this->bucket, 'empty' ),
new \Qiniu_RS_EntryPath( $this->bucket, 'empty' )
);
}
}
list( $ret, $err ) = Qiniu_RS_BatchCopy($client, $entries);
if( $err !== null ) {
$ret['code'] = $err->Code;
return $ret;
} else {
return $ret;
}
}
/*
* get a resource attributes
*/
public function stat( $key )
{
list( $ret, $err ) = Qiniu_RS_Stat( $this->client, $this->bucket, $key );
if( $err !== null ) {
throw new QiniuStatException( $err->Err, $err->Code, $key );
} else {
return $ret;
}
}
/*
* batch get resources attributes
*/
public function batchStat()
{
$keys = func_get_args();
if( func_num_args() <= 0 ) {
return array();
}
foreach( $keys as $i => $key ) {
$keys[$i] = new \Qiniu_RS_EntryPath( $this->bucket, $key );
}
list( $ret, $err ) = Qiniu_RS_BatchStat( $this->client, $keys );
if( $err !== null ) {
$ret['code'] = $err->Code;
return $ret;
} else {
return $ret;
}
}
/*
* get image resource with custom size
*
* TODO this is a old qiniu api, don't use this
*
* read more: http://developer.qiniu.com/docs/v6/api/reference/obsolete/imageview.html
*/
public function imageView( $width, $height, $key, $mode = 1 )
{
return true;
}
public function getKey($url)
{
$key = trim(parse_url($url, PHP_URL_PATH), '/');
return $key;
}
public function getDomain()
{
return $this->domain;
}
}
<file_sep>/Exception/QiniuException.php
<?php
namespace DWD\QiniuSdkBundle\Exception;
class QiniuException extends \Exception
{
protected $key;
public function __construct( $message, $code = 0, $key = null )
{
$this->key = $key;
parent::__construct( $message, $code );
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: key:\"{$this->key}\" {$this->message}";
}
}
|
d1349d3f5ffde0e35ee6791d41aaa65949cdd83c
|
[
"Markdown",
"PHP"
] | 10 |
PHP
|
Doweidu/DWDQiniuSdkBundle
|
e93954cc083315d54e6647e4eb0d57636f1dce9b
|
c2e0b02fbd3b085d965454e8143c7eb9a04b22b9
|
refs/heads/master
|
<repo_name>wferreira/agencyrobot-arduino<file_sep>/agencyrobot-arduino.ino
int motor1_enablePin = 11; //pwm
int motor1_in1Pin = 13;
int motor1_in2Pin = 12;
int motor2_enablePin = 10; //pwm
int motor2_in1Pin = 8;
int motor2_in2Pin = 7;
void setup()
{
//on initialise les pins du moteur 1
pinMode(motor1_in1Pin, OUTPUT);
pinMode(motor1_in2Pin, OUTPUT);
pinMode(motor1_enablePin, OUTPUT);
//on initialise les pins du moteur 2
pinMode(motor2_in1Pin, OUTPUT);
pinMode(motor2_in2Pin, OUTPUT);
pinMode(motor2_enablePin, OUTPUT);
Serial.begin(9600);
delay(2000);
Serial.println("Robot car is ready !");
}
char command;
void loop()
{
if(Serial.available()){
char newCommand = Serial.read();
Serial.print("You typed: " );
Serial.println(command);
if (newCommand != command){
command = newCommand;
Stop();
delay(500);
}
}
switch (command) {
case 'F':
Forward(255);
break;
case 'B':
Backward(255);
break;
case 'R':
TurnRight(255);
break;
case 'L':
TurnLeft(255);
break;
case 'S':
Stop();
break;
}
}
void Stop(){
SetMotorsRight(0, true);
SetMotorsLeft(0, false);
}
void Forward(int speed){
SetMotorsRight(speed, true);
SetMotorsLeft(speed, false);
}
void Backward(int speed){
SetMotorsRight(speed, false);
SetMotorsLeft(speed, true);
}
void TurnRight(int speed){
SetMotorsRight(speed, false);
SetMotorsLeft(speed, false);
}
void TurnLeft(int speed){
SetMotorsRight(speed, true);
SetMotorsLeft(speed, true);
}
void SetMotorsRight(int speed, boolean reverse)
{
analogWrite(motor1_enablePin, speed);
digitalWrite(motor1_in1Pin, ! reverse);
digitalWrite(motor1_in2Pin, reverse);
}
void SetMotorsLeft(int speed, boolean reverse)
{
analogWrite(motor2_enablePin, speed);
digitalWrite(motor2_in1Pin, ! reverse);
digitalWrite(motor2_in2Pin, reverse);
}
|
a8273ddf1f4410c4d49f76fc30e46a6e5a040d4e
|
[
"C++"
] | 1 |
C++
|
wferreira/agencyrobot-arduino
|
163f53b4df1e668df8120b5cf713c5df3c22e8a1
|
42e95ff7bc69b65969ab2be3e3e8d807023b56ad
|
refs/heads/master
|
<repo_name>lostpapers/OpenGLStudies<file_sep>/QtOpenGLViewer/input.h
#pragma once
#include <Qt>
#include <QPoint>
class Input
{
public:
enum class State
{
Invalid,
Registered,
Unregistered,
Triggered,
Pressed,
Released
};
static State keyState( Qt::Key key);
static bool keyTriggered( Qt::Key key);
static bool keyPressed( Qt::Key key);
static bool keyReleased( Qt::Key key);
static State buttonState( Qt::MouseButton button );
static bool buttonTriggered( Qt::MouseButton button );
static bool buttonPressed( Qt::MouseButton button );
static bool buttonReleased( Qt::MouseButton button );
static QPoint mousePosition();
static QPoint mouseDelta();
private:
static void update();
static void registerKeyPress( int key );
static void registerKeyRelease( int key );
static void registerMousePress( Qt::MouseButton button );
static void registerMouseRelease( Qt::MouseButton button );
static void reset();
friend class MainWindow;
};
inline bool Input::keyTriggered(Qt::Key key)
{
return keyState(key) == State::Triggered;
}
inline bool Input::keyPressed(Qt::Key key)
{
return keyState(key) == State::Pressed;
}
inline bool Input::keyReleased(Qt::Key key)
{
return keyState(key) == State::Released;
}
inline bool Input::buttonTriggered(Qt::MouseButton button)
{
return buttonState(button) == State::Triggered;
}
inline bool Input::buttonPressed(Qt::MouseButton button)
{
return buttonState(button) == State::Pressed;
}
inline bool Input::buttonReleased(Qt::MouseButton button)
{
return buttonState(button) == State::Released;
}
<file_sep>/QtOpenGLViewer/transform3D.cpp
#include "transform3D.h"
void Transform3D::translate(const QVector3D& vec3)
{
m_dirty = true;
m_translation += vec3;
}
void Transform3D::rotate(const QQuaternion &quat)
{
m_dirty = true;
m_rotation = quat * m_rotation;
}
const QMatrix4x4& Transform3D::toMatrix()
{
if( m_dirty)
{
m_dirty = false;
m_matrix.setToIdentity();
m_matrix.translate(m_translation);
m_matrix.rotate(m_rotation);
m_matrix.scale(m_scale);
}
return m_matrix;
}
<file_sep>/Shadertoy/sphere_gears_reconstruction.c
#define AA
#define ZERO min(iFrame,0)
float smoothMax( in float a, in float b, in float k )
{
float h = max( k-abs(a-b),0.0);
return max(a,b) + (0.25/k)*h*h;
}
vec2 rot45( in vec2 pos )
{
return vec2( pos.x-pos.y, pos.x+pos.y) * 0.707107;
}
// SDF objects (Thanks to Inigo Quilez tutorials)
float sdBox( in vec3 pos, in vec3 sides )
{
return length( max(abs(pos)-sides, 0.0 ) );
}
float sdBox2DExtruted( in vec2 pos, in vec2 sides )
{
return length( max(abs(pos)-sides, 0.0 ) );
}
float sdSphere( in vec3 pos, in float r )
{
return length( pos )-r;
}
float sdCross( in vec3 pos, in vec3 r )
{
pos = abs(pos);
// Conditional move optimization?
pos.xz = (pos.z>pos.x)? pos.zx : pos.xz;
return sdBox( pos, r );
}
float sdStickV( in vec3 pos, in float l )
{
pos.y = max(pos.y-l, 0.0);
return length( pos );
}
vec4 sdGear( in vec3 pos, in float time, in float offset )
{
#define SECTOR_ANGLE (2.0*3.14159/12.0)
pos.y = abs(pos.y);
float angle = time + offset*SECTOR_ANGLE;
pos.xz = mat2( cos(angle), -sin(angle),
sin(angle), cos(angle)) * pos.xz;
// Gear teeth extrusion
//---------------------
// Only one box, with multiple instances through SDF duplication.
// We compute in which sector, on XZ plane, is pos (Y is vertical, so rotation is in XZ plane)
float sector = round( atan(pos.z,pos.x)/SECTOR_ANGLE );
vec3 rotated_pos = pos;
angle = sector*SECTOR_ANGLE;
rotated_pos.xz = mat2( cos(angle), -sin(angle), sin(angle), cos(angle))*rotated_pos.xz;
float dist = sdBox2DExtruted( rotated_pos.xz-vec2(0.17,0.0), vec2( 0.04, 0.018 ) ) - 0.01;
// Gear Ring extrusion
//--------------------
// Infinite ring
float dObject = abs(length(pos.xz)-0.155)-0.018;
dist = min( dist, dObject );
// Smooth Clipping plane for top and bottom
//-----------------------------------------
// (disabled to be replaced by sphere clipping below)
//dist = smoothMax( dist, abs(pos.y)-0.03, 0.005 );
// Cross shape
//------------
dObject = sdCross( pos-vec3(0.0,0.48,0.0), vec3(0.2,0.01,0.01) );
dist = min( dist, dObject );
// Smooth Clipping sphere
//-----------------------
float r = length( pos );
dist = smoothMax( dist, abs(r-0.5)-0.03, 0.003 );
// Vertical stick
dObject = sdStickV( pos, 0.5)-0.01;
dist = min( dist, dObject );
return vec4( dist, pos );;
}
// Definition of the scene through SDF. Returns the distance to the nearest surface
vec4 map( in vec3 pos, in float time )
{
// Central sphere
vec4 res = vec4( sdSphere(pos, 0.12), pos );
vec4 d;
// Mirroring gears through easy rotation by swapping axis
// as everything is nicely aligned to system coord axis
vec3 pa = abs(pos);
pa = ( pa.x>pa.y && pa.x>pa.z) ? pa = pos.yxz*vec3(pos.x>0.0?-1:1,1,1) :
( pa.z>pa.y ) ? pa = pos.xzy*vec3(pos.z>0.0?-1:1,1,1) :
pa = pos.xyz*vec3(pos.y<0.0?-1:1,1,1);
// Gear tilted in YZ plane, XZ plane and XY plane
vec3 px = vec3( rot45(pos.zy), pos.x*((pos.z>0.0)?1.0:-1.0) ); if( abs(px.x)>abs(px.y)) px = px.zxy;
vec3 py = vec3( rot45(pos.xz), pos.y*((pos.x>0.0)?1.0:-1.0) ); if( abs(py.x)>abs(py.y)) py = py.zxy;
vec3 pz = vec3( rot45(pos.yx), pos.z*((pos.y>0.0)?1.0:-1.0) ); if( abs(pz.x)>abs(pz.y)) pz = pz.zxy;
// Renderings
d = sdGear( pa, 3.0*time,0.0 ); if(d.x<res.x ) res = d;
d = sdGear( px, 3.0*time,0.5 ); if(d.x<res.x ) res = d;
d = sdGear( py, 3.0*time,0.5 ); if(d.x<res.x ) res = d;
d = sdGear( pz, 3.0*time,0.5 ); if(d.x<res.x ) res = d;
return res;
}
// Approximation de normale par dérivation
// Le gradient est équivalent à la normale de la surface
vec3 calcNormal(in vec3 pos, in float time )
{
vec2 e = vec2 (0.001,0.0);
return normalize(
vec3( map( pos+e.xyy, time ).x - map( pos-e.xyy, time ).x,
map( pos+e.yxy, time ).x - map( pos-e.yxy, time ).x,
map( pos+e.yyx, time ).x - map( pos-e.yyx, time ).x ) );
}
// Thanks to <NAME>
float calcAmbientOcclusion( in vec3 pos, in vec3 nor, in float time )
{
float occ = 0.0;
float sca = 1.0;
for( int i=ZERO; i<5; i++ )
{
float h = 0.01 + 0.12*float(i)/4.0;
float d = map( pos+h*nor, time ).x;
occ += (h-d)*sca;
sca *= 0.95;
}
return clamp( 1.0 - 3.0*occ, 0.0, 1.0 );
}
vec4 rayMarching( in vec3 ray_origin, vec3 ray_direct, in float time )
{
vec4 impact = vec4(0.0);
float t = 0.0;
for( int i=0; i<250; i++)
{
// pos = position du point d'échantillonage le long du rayon
vec3 pos = ray_origin + t*ray_direct;
// test d'impact de l'objet
impact = map( pos, time );
// on est à l'intérieur
if( impact.x<0.0001 )
break;
t += impact.x;
// Si on est trop loin, on n'a rien trouvé d'intéressant
// Equivalent du Far Clipping Plane
if( t>20.0)
break;
}
return vec4(t,impact.yzw);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
float time = iTime;
float animation = -10.0*(iMouse.x/iResolution.x-0.5);
// Recentrage des coordonnées, entre -1 et 1
vec2 p = (2.0*fragCoord-iResolution.xy)/iResolution.y;
// Camera reculée de 1 en Z, et on regarde vers l'origine
// X up, Z right, Z toward us
vec3 ray_origin = vec3(1.0*sin(animation),0.25,1.0*cos(animation)); // c'est la positon de la caméra
//vec3 ray_origin = vec3( 0,0.25,1);
vec3 ray_direct = normalize( vec3( p, -1.) );
// Camera
vec3 target = vec3 (0.0);
vec3 ww = normalize(target-ray_origin);
vec3 uu = normalize( cross(ww, vec3(0,1,0)));
vec3 vv = normalize( cross(uu,ww) );
// direction du rayon dans le monde, depuis le repère de la caméra
ray_direct = normalize( p.x*uu + p.y*vv + 1.5*ww );
// La couleur par défaut est celle du ciel, qui devient plus claire vers le bas
//vec3 col = vec3(0.4, 0.75, 1.0) - 0.7 * ray_direct.y;
// Effet atmosphérique vers l'horizon
//col = mix( col, vec3(0.7, 0.75, 0.8), exp(-10.0*ray_direct.y));
vec3 col = vec3(0.0);
//for( int m=0; m<AA; m++ )
{
// ray marching
vec4 impact = rayMarching( ray_origin, ray_direct, time );
// On a trouvé quelque chose
if( impact.x<=20.0 )
{
vec3 position = ray_origin + impact.x*ray_direct;
vec3 normal = calcNormal( position, time );
float occlusion = calcAmbientOcclusion( position + normal*0.001, normal, time);
// Box mapping
vec3 material = 0.5 * texture( iChannel0, impact.yz).xyz
+ 0.5 * texture( iChannel0, impact.yw).xyz;
material = material*material;
vec3 light = vec3(3.0)*(0.5 + 0.5* normal.y)*occlusion;
col = material * light;
// Color = f( normale )
//col = 0.5 + 0.5* normal;
// calcul d'éclairage diffus par lumière directionnelle (soleil)
// Produit scalaire de la normale avec la direction de la lumière
// qu'on limite entre 0 et 1 (ce qui est négatif est dans l'ombre)
//vec3 sun_direct = normalize(vec3 (1.0,0.50, 0.20));
//float sun_diffuse = clamp(dot(normal,sun_direct), 0.0, 1.0);
// on lance un nouveau rayon vers le soleil pour savoir si
// le point est éclairé ou non en fonction des objets qui sont
// entre le point et le soleil
// On décale le point de la surface pour éviter une intersection parasite
//float sun_shadow = rayMarching( position+normal*0.001, sun_direct, time ).x;
//if( sun_shadow<=20.0 )
// sun_shadow = 0.0;
//else
// sun_shadow = 1.0;
// Calcul de l'éclairage venant du ciel, avec un décalage pour ce qui vient du sol
//float sky_diffuse = clamp(0.5+0.5*dot(normale,vec3(0.0,1.0,0.0)), 0.0, 1.0);
// Calcul de reflet de lumière du sol
//
//float bounce_diffuse = clamp(0.5+0.5*dot(normale,vec3(0.0,-1.0,0.0)), 0.0, 1.0);
// Combinaison des couleurs
//col = material*vec3(7.0,4.5,3.0)*sun_diffuse*sun_shadow;
//col += material*vec3(0.5,0.8,0.9)*sky_diffuse;
//col += material*vec3(0.7,0.3,0.2)*bounce_diffuse;
}
// gamma correction, à mettre dès le début pour travailler dans un rendu d'éclairage correct
col = pow( col, vec3(0.4545) );
}
fragColor = vec4(col,1.0);
}
<file_sep>/Shadertoy/happy_jumping_reconstruction.c
// Personal version of Inigo Quilez tutorial "Happy Jumping Deconstruction"
// 13-Feb-2020
//
// Great thanks to Inigo for his more than thorough tutorial
//
// I've understood most of the concepts and mathematical fundations underlying the SDF rendering.
// The following themes are the ones I still have to study:
// - sdEllipsoid()
// - Better version of calcNormal()
// - calcAO()
// Min smoothing fonction
float smoothMin( in float a, in float b, in float k)
{
// h is positive when the distance between a and b values is less than k.
// Maximum is attained when a==b
float h = max( k-abs(a-b), 0.0 );
// To be sure that the returned value is smooth, a square fonction
// is used to ensure derivative continuity at 0.
return min( a, b )-h*h*0.25/k;
}
// Max smoothing fonction
float smoothMax( in float a, in float b, in float k)
{
// See smoothMin() comments
float h = max( k - abs(a-b), 0.0 );
return max( a, b )+h*h*0.25/k;
}
// SDF sphere
float sdSphere( in vec3 position, in float radius )
{
return length( position )-radius;
}
// SDF ellipsoid (Formula by <NAME>)
float sdEllipsoid(in vec3 position, in vec3 radius)
{
float k0 = length( position/radius );
float k1 = length( position/(radius*radius) );
return k0*(k0-1.0)/k1;
}
// SDF stick (Optimal algorithm by <NAME>)
vec2 sdStick( in vec3 p, in vec3 a, in vec3 b, in float ra, in float rb )
{
vec3 ba = b-a;
vec3 pa = p-a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
return vec2(length( pa-h*ba )-mix( ra, rb, h), h);
}
// Returns a Vec2 where x=distance, y=material
//
// List of materials
// - Body = 2.0
// - Eyes = 3.0
// Test si le point est à l'intérieur de la forme ou non
// et à quelle distance se trouve t il. 0 indique que
// l'on est sur la surface. On combine deux objets en retournant
// celui qui est le plus proche
// vec4 result = (distance, id, occlusion, ? )
vec4 map( in vec3 position, float time )
{
// Monster
// extract fract part of time = [0.0, 1.0[
float time1 = fract(time);
float time4 = abs(fract(time*0.5)-0.5)/0.5;
float parabolic = 4.0 * time1 * (1.0 - time1); // Parabolic jump movement
float parabolicDT = 4.0-8.0*time1; // Derivative
float x =-1.0+2.0*(time4);
vec3 center = vec3( 0.5*(x), // Left to Right movement
pow(parabolic,2.0-parabolic) + 0.1, // Smooth movement on ground rebound
floor(time)+pow(time1,0.7)-1.0 ); // Slight front impulse on rebound
// Body
vec2 uu = normalize(vec2( 1.0, -parabolicDT ));
vec2 vv = vec2(-uu.y, uu.x);
// Expand & Squash effect
float expandY = 0.5 + 0.5*parabolic;
expandY += (1.0-smoothstep( 0.0, 0.4, parabolic))*(1.0-expandY);
float expandZ = 1.0 / expandY;
vec3 posQ = position - center; // vec3 q = pos - cen;
float ro = x*0.3;
float cc = cos(ro);
float ss = sin(ro);
posQ.xy = mat2(cc,-ss,ss,cc)*posQ.xy;
vec3 posR = posQ; // vec3 r = q;
posQ.yz = vec2( dot(uu,posQ.yz), dot(vv,posQ.yz) );
vec4 result = vec4( sdEllipsoid( posQ, vec3(0.25,0.25*expandY,0.25*expandZ) ), 2.0, 1.0, 0.0); // 2.0 = body color
// Bounding volume around body of 2 units
if( result.x<1.0)
{
float t2 = fract(time+0.8);
float p2 = 0.5-0.5*cos(6.2831*t2);
// Head
// ----
vec3 h = posR; // head position
float headAnim = -1.0+2.0*smoothstep(-0.2,0.2,sin(time));
cc = cos(headAnim);
ss = sin(headAnim);
h.xz = mat2(cc,ss,-ss,cc) * h.xz; // Rotate head
vec3 headSymetric = vec3( abs(h.x),h.yz); // hq
float dPart = sdEllipsoid(h-vec3( 0.0, 0.20, 0.02 ), vec3( 0.08, 0.2, 0.15 ));
result.x = smoothMin( result.x, dPart, 0.1 );
dPart = sdEllipsoid(h-vec3( 0.0, 0.21,-0.1 ), vec3( 0.2, 0.2, 0.2 ));
result.x = smoothMin( result.x, dPart, 0.1 );
// Wrinkles
{
float yy = posR.y-0.02-2.5*posR.x*posR.x;
result.x += 0.001*sin(yy*120.0)*(1.0-smoothstep(0.0,0.1,abs(yy)));
}
// Arms
vec3 sq = vec3( abs(posR.x), posR.yz );
vec2 dArms = sdStick(
sq,
vec3(0.18-0.05*headAnim*sign(posR.x),0.2,-0.05),
vec3(0.3+0.1*p2,-0.2+0.3*p2,-0.15), 0.03, 0.06 );
result.x = smoothMin( result.x, dArms.x, 0.01+0.04*(1.0-dArms.y)*(1.0-dArms.y)*(1.0-dArms.y) );
// Legs
{
float t6 = cos(6.2831*(time*0.5+0.25));
float ccc = cos(1.57*t6*sign(posR.x));
float sss = sin(1.57*t6*sign(posR.x));
vec3 base = vec3(0.12,-0.07,-0.1); base.y -= 0.1*expandZ;
vec2 dLegs = sdStick( sq, base, base + vec3(0.2,-ccc,sss)*0.2, 0.04, 0.07 );
result.x = smoothMin( result.x, dLegs.x, 0.07 );
}
// Ears
vec2 dEars = sdStick( headSymetric, vec3(0.15,0.32,-0.05), vec3(0.2,0.2,-0.07), 0.01, 0.04 ) ;
result.x = smoothMin( result.x, dEars.x, 0.01 );
// Mouth - Extend sides by deforming with a parabola y=f(x)
// smoothMax + négative dist to carve
dPart = sdEllipsoid(h-vec3(0.0,0.15+3.0*headSymetric.x*headSymetric.x,0.2), vec3(0.1,0.04,0.2));
result.x = smoothMax( result.x, -dPart, 0.02 );
result.z = 1.0-smoothstep(-0.01,0.001,-dPart);
// Eyebrows
vec3 eyeLids = headSymetric - vec3(0.12,0.34,0.15);
eyeLids.xy = mat2(3,4,-4,3)/5.0*eyeLids.xy;// Rotation, données de matrice avec Pythagore, pas besoin de sin/cos
float dEyeLids = sdEllipsoid(eyeLids, vec3(0.06,0.03,0.05));
result.x = smoothMin( dEyeLids, result.x, 0.04);
// Eyes
// Duplication par particularité des SDF, avec utilisation de valeur
// absolue pour faire croire au point courant qu'il y a une deuxième sphère
float dEye = sdSphere( headSymetric-vec3(0.08,0.27,0.06), 0.065);
if( dEye<result.x )
{
result.xy = vec2(dEye, 3.0);
result.z = 1.0-smoothstep(0.0,0.017, dEye);
}
float dIris = sdSphere( headSymetric-vec3(0.075,0.28,0.102), 0.0395);
if( dIris<result.x ) { result.xyz = vec3(dIris, 4.0, 1.0); }
}
// Ground
// ------
float floorHeight = (-0.1 + 0.05*(sin(2.0*position.x)+sin(2.0*position.z)));
float l = length((position-center).xz);
float groundTime = fract(time);
floorHeight -= 0.1* // amplitude
sin(groundTime*10.0+l*3.0)* // sin wave
exp(-1.0*l)* // decay in distance
exp(-1.0*groundTime)* // decay in time
smoothstep(0.0,0.1,groundTime);
float dGround = 0.6*(position.y - floorHeight);
// Bubbles
// -------
vec3 posBubble = vec3(
mod(abs(position.x),3.0),
position.y,
mod(position.z+1.5,3.0)-1.5 );
// Unique id for bubble : Add randomness to give a more natural feeling
vec2 idBubble = vec2( floor(position.x/3.0), floor((position.z+1.5)/3.0) );
float fidBubble = idBubble.x*11.1 + idBubble.y*31.7; // id for unique deformat/offset
float fy = fract(fidBubble*1.312+time*0.1);
float siz = 4.0*fy*(1.0-fy); // Smoothly size to 0 to avoid pop disappearance
float y = 4.0*fy-1.0; // up movement
vec3 rad = vec3(0.7,1.0+0.5*sin(fidBubble),0.7);
rad -= 0.1*(sin(position.x*3.0)+sin(position.y*4.0+sin(position.z*5.0))); //Deformation surface
// Ellipsoid
float dBubble = sdEllipsoid(posBubble-vec3(2.0,y,0.0),siz*rad );
// Distance modification pattern identical to ground texture
// Problem: it creates differences in the distance field that can perturbs computation like shadows
dBubble -= 0.005*smoothstep(-0.3, 0.3, sin( 18.0*position.x)+sin(18.0*position.y)+sin(18.0*position.z));
// Locally increased ray marching precision to prevent artifacts
dBubble *= 0.4;
//dBubble = min (dBubble, 2.0);
dGround = smoothMin(dGround, dBubble,0.3);
if( dGround<result.x) result.xyz = vec3( dGround, 1.0, 1.0 );
// Candies
// -------
vec3 vp = vec3( mod(position.x+0.25,0.5)-0.25,
position.y,
mod(position.z+0.25,0.5)-0.25 );
vec2 id = floor((position.xz+0.25)*2.0 ) ;
// disruption of grid
vec2 dis = cos( vec2( id.x*72.2+id.y*13.7,
id.x*81.6+id.y*51.4));
float dCandy = sdSphere(vp-vec3(dis.x * 0.1,floorHeight,dis.y*0.1), 0.05 );
// fake candy occlusion from ground, without casting ray
float candy_occlusion = clamp(40.0*(position.y-floorHeight),0.0,1.0);
if( dCandy<result.x) result.xyz = vec3( dCandy, 5.0, candy_occlusion );
return result;
}
vec4 rayMarching( in vec3 ray_origin, vec3 ray_direct, float time )
{
#define NEAR_CLIP 0.5
#define FAR_CLIP 20.0
#define MAX_STEPS 250
vec4 result = vec4(NEAR_CLIP, 0.0, -1.0, -1.0);
float distance = NEAR_CLIP;
for( int i=0; i<MAX_STEPS && distance<FAR_CLIP; i++)
{
vec3 pos = ray_origin + distance*ray_direct;
if(pos.y>3.5)
break;
// Get nearest point from scene
vec4 impact = map(pos, time);
// Point is sufficiently near
if( impact.x<0.01 )
{
result = vec4( distance, impact.yzw );
break;
}
distance += impact.x;
}
return result;
}
// Compute normal with localized gradient
// cf. Inigo for better version
vec3 calcNormal(in vec3 pos, float time )
{
vec2 e = vec2 (0.001,0.0);
return normalize(
vec3( map(pos+e.xyy, time).x-map(pos-e.xyy, time).x,
map(pos+e.yxy, time).x-map(pos-e.yxy, time).x,
map(pos+e.yyx, time).x-map(pos-e.yyx, time).x ));
}
// Unrealistic cast shadows
float castShadow( in vec3 ray_origin, vec3 ray_direct, float time )
{
float res = 1.0;
float distance = 0.01;
for( int i=0; i<60 && distance<20.0; i++)
{
// pos = position du point d'échantillonage le long du rayon
vec3 pos = ray_origin + distance*ray_direct;
// test d'impact de l'objet
float impact = map(pos, time).x;
// Ombre fonction de proximité rayon/objet et proximité origin/objet
res = min(res,24.0*max(impact,0.0)/distance);
if( impact<0.0001 )
break;
distance += clamp(impact,0.001,0.1);
}
return res;
}
// Thanks to <NAME>
// ... to be studied
float calcOcclusion( in vec3 pos, in vec3 nor, float time )
{
float occ = 0.0;
float sca = 1.0;
// 5 request around the point to SDF, darkkening the position in relation of
// proximity of surfaces
for( int i=0; i<5; i++ )
{
float h = 0.01 + 0.11*float(i)/4.0;
vec3 opos = pos + h*nor;
float d = map( opos, time ).x;
occ += (h-d)*sca;
sca *= 0.95;
}
return clamp( 1.0 - 2.0*occ, 0.0, 1.0 );
}
vec3 RenderScene( vec3 ray_origin, vec3 ray_direct, float time )
{
// La couleur par défaut est celle du ciel, qui devient plus claire vers le bas
vec3 col = vec3(0.5, 0.8, 0.9) - max( ray_direct.y,0.0)*0.5;
// sky texture (like clouds)
vec2 uv = ray_direct.xz/ray_direct.y;
float cloud_shape = sin(uv.x)+sin(uv.y) + // Basic shape
(sin(2.0*uv.x)+sin(2.0*uv.y)*0.5); // Add octave to shape (double frequency) at half amplitude
col = mix( col, vec3(0.7,0.8,0.9),smoothstep(-0.1,0.1,-0.5+cloud_shape));
// Effet atmosphérique vers l'horizon
col = mix( col, vec3(0.7, 0.8, 0.9), exp(-10.0*ray_direct.y));
// ray marching: on récupère distance d'impact et matériau
vec4 impact = rayMarching( ray_origin, ray_direct, time );
// On a trouvé quelque chose: materiau est défini
if( impact.y>0.0 )
{
vec3 position = ray_origin + impact.x*ray_direct;
vec3 normale = calcNormal(position, time);
vec3 reflection = reflect(ray_direct, normale);
vec3 material = vec3(0.18);
if( impact.y==1.0)
{
// Ground
material = vec3(0.05,0.1,0.02);
float f = -0.2+0.4*smoothstep(-0.2, 0.2, sin( 18.0*position.x)+sin(18.0*position.y)+sin(18.0*position.z));
material += f*vec3( 0.06, 0.06, 0.02 );
}
else if( impact.y==2.0)
{
// Body
material = vec3(0.2,0.1,0.02);
}
else if( impact.y==3.0)
{
// Eye
material = vec3(0.4);
}
else if( impact.y==4.0)
{
// Iris
material = vec3(0.02);
}
else
{
// Candy
material = vec3( 0.14,0.048,0.0 );
vec2 id = floor((position.xz+0.25)*2.0);
float fid = id.x*11.1 + id.y*31.7;
// Shift RGB channels through Cosinus
material += 0.036*cos( 10.0*fid + vec3(0.0,1.0,2.0));
}
// Calcul d'éclairage diffus par lumière directionnelle (soleil)
// Produit scalaire de la normale avec la direction de la lumière
// qu'on limite entre 0 et 1 (ce qui est négatif est dans l'ombre)
vec3 sun_direct = normalize(vec3 (1.0,0.50, 0.20));
float sun_diffuse = clamp(dot(normale,sun_direct), 0.0, 1.0);
// Old school specular, sneak Fresnel, 0.04 based reflection
//float sun_specular =;
// On lance un nouveau rayon vers le soleil pour savoir si
// le point est éclairé ou non en fonction des objets qui sont
// entre le point et le soleil
// On décale le point de la surface pour éviter une intersection parasite
float sun_shadow = castShadow( position+normale*0.0001, sun_direct,time );
// Calcul de l'éclairage venant du ciel, avec un décalage pour ce qui vient du sol
float sky_diffuse = clamp(0.5+0.5*dot(normale,vec3(0.0,1.0,0.0)), 0.0, 1.0);
// Calcul de spécularité pour lumière du ciel. On prend la refrection du vecteur
// de vue et on regarde s'il part vers le ciel. Smoothstep permet de régler la
// rugosité du matériau, en donnant un aspect plus brut ou plus doux
float sky_reflect = smoothstep( 0.0, 0.2, reflection.y);
// Calcul de reflet de lumière du sol
float bounce_diffuse = clamp(0.5+0.5*dot(normale,vec3(0.0,-1.0,0.0)), 0.0, 1.0);
// Fake subsurface scattering through Fresnel effect
// Compute if normale is facing toward us
float fresnel = clamp(1.0+dot(ray_direct, normale), 0.0, 1.0 );
// Compute ambiant occlusion
// Modulated by procedural occlusion coming from the model construction
float ao = calcOcclusion( position, normale, time) * impact.z;
// Diffuse lighting, applied on material color
vec3 lighting = vec3(0.0);
lighting += vec3( 9.00, 6.00, 3.00 )*sun_diffuse*
vec3(sun_shadow,sun_shadow*sun_shadow,sun_shadow*sun_shadow); // trick to add red to transition (G and B are suared to decay faster)
lighting += vec3( 1.10, 1.54, 2.20 )*sky_diffuse*ao;
lighting += vec3( 0.40, 1.30, 0.40 )*bounce_diffuse*ao;
lighting += vec3( 8.00, 4.00, 3.20 )*fresnel*(0.1+0.9*sun_shadow)*(0.5+0.5*sun_diffuse*ao); // SSS: modulated by incoming lights
col = material*lighting;
// Specular lighting, does not take material color in account
col += sky_reflect*0.07*vec3( 0.7, 0.9, 1.0 )*sky_diffuse*ao;
//col = vec3(fresnel);
//col = vec3(ao*ao);
//col = vec3(impact.z*impact.z);
//col = vec3(sun_shadow*sun_shadow);
//col = vec3(lighting*0.2);
// White balance / Color curve
col = pow(col, vec3(0.7,0.9,1.0));
// fog
col = mix( col, vec3(0.5,0.7,0.9), 1.0-exp( -0.0001*impact.x*impact.x*impact.x ) );
}
return col;
}
#define AA 2
#define BLUR_FRAMERATE 24.0
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
fragColor = vec4(0.0,0.0,0.0,1.0);
// Super sampling
for( int m=0; m<AA; m++ )
{
for( int n=0; n<AA; n++ )
{
vec2 coord_offset = -1.0+(0.5+vec2( float(m), float(n) ))/float(AA);
// Screen normalization [-1.0, 1.0]
vec2 p = (2.0*(fragCoord+coord_offset)-iResolution.xy)/iResolution.y;
// Time control, for motion blur with dithering
float motion_blur = float(m*AA+n)/float(AA*AA);
float motion_dither = texelFetch(iChannel0, ivec2(fragCoord)&255, 0).x ;
motion_blur += (motion_dither-0.5)/float(AA*AA);
float time = iTime - motion_blur*0.5/BLUR_FRAMERATE;
// Camera: Y up, X right, Z toward us
float animation = 10.0*iMouse.x/iResolution.x;
vec3 ray_origin = vec3(2.0*sin(animation),0.5,time + 2.0*cos(animation));
// Camera shake (secondary movement induced by monster bounce)
float bounceTime = -1.0+2.0*abs(fract(time*0.5)-0.5)*2.0;
float bounce = smoothstep(0.8,1.0,abs(bounceTime));
ray_origin += 0.05*sin(time*15.0+vec3(0.0,2.0,4.0))*bounce;
vec3 target = vec3 (0,0.5,time);
vec3 ww = normalize(target-ray_origin);
vec3 uu = normalize( cross(ww, vec3(0,1,0)));
vec3 vv = normalize( cross(uu,ww) );
// direction du rayon dans le monde, depuis le repère de la caméra
// le facteur associé à ww permet de gérer la focale
vec3 ray_direct = normalize( p.x*uu + p.y*vv + 1.8*ww );
vec3 col = RenderScene( ray_origin, ray_direct, time );
// gamma correction, put as soon as project is started to work
// in a correct light rendering environment
col = pow( col, vec3(0.4545) );
// col is in HDR, we clap to LDR
col = clamp(col, 0.0,1.0);
// increase contrast
col = col*0.5+0.5*col*col*(3.0-2.0*col);
fragColor.xyz += col;
//fragColor.xyz = vec3(motion_dither);
}
}
fragColor.xyz /= float(AA*AA);
}
<file_sep>/QtOpenGLViewer/main.cpp
#include "mainwindow.h"
#include <QGuiApplication>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
// Set OpenGL Version information; must be set before show() is called
// This is not explicitly neded, but it's a good way to check functionalities
QSurfaceFormat format;
format.setRenderableType(QSurfaceFormat::OpenGL);
format.setProfile(QSurfaceFormat::CoreProfile);
format.setVersion(3,3);
// set window
MainWindow w;
w.setFormat(format);
w.resize(QSize(800,600));
w.show();
return app.exec();
}
<file_sep>/QtOpenGLViewer/transform3D.h
#pragma once
#include <QVector3D>
#include <QQuaternion>
#include <QMatrix4x4>
class Transform3D
{
public:
// Constructeur
Transform3D();
void translate( float x, float y, float z );
void translate( const QVector3D& vec3 );
void rotate( float angle, const QVector3D& vec3 );
void rotate( const QQuaternion& quat );
const QMatrix4x4& toMatrix();
private:
bool m_dirty; // Optimisation pour ne pas à avoir à recréer la matrice résultante à chaque fois
QVector3D m_translation;
QVector3D m_scale;
QQuaternion m_rotation;
QMatrix4x4 m_matrix;
};
inline Transform3D::Transform3D() :
m_dirty(true),
m_scale(1.0f,1.0f,1.0f)
{
}
inline void Transform3D::translate(float dx, float dy,float dz)
{
translate(QVector3D(dx, dy, dz));
}
inline void Transform3D::rotate(float aScalar, const QVector3D& aVector )
{
rotate(QQuaternion::fromAxisAndAngle(aVector, aScalar));
}
<file_sep>/QtOpenGLViewer/mainwindow.h
#pragma once
#include <QOpenGLWindow>
#include <QOpenGLFunctions>
#include <QOpenGLBuffer>
#include <QOpenGLVertexArrayObject>
#include "transform3D.h"
#include "camera3d.h"
class QOpenGLShaderProgram;
class MainWindow :
public QOpenGLWindow,
protected QOpenGLFunctions
{
Q_OBJECT
public:
MainWindow();
~MainWindow();
void initializeGL() override;
void resizeGL(int w, int h) override;
void paintGL() override;
void teardownGL(); //!< Separate function to perform cleanup
protected slots:
void update();
void keyPressEvent(QKeyEvent *event) override;
void keyReleaseEvent(QKeyEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
private:
// OpenGLState
QOpenGLBuffer m_vertex; // Vertex & color buffer. Type is QOpenGLBuffer::VertexBuffer by default
QOpenGLVertexArrayObject m_object;
QOpenGLShaderProgram *m_program;
// Informations shaders
int u_modelToWorld;
int u_worldToCamera;
int u_cameraToView;
QMatrix4x4 m_projection;
Transform3D m_transform;
Camera3D m_camera;
// Outils privés
void printContextInformations(); //!< print information about OpenGL context
};
<file_sep>/QtOpenGLViewer/mainwindow.cpp
#include <QDebug>
#include <QString>
#include <QOpenGLShaderProgram>
#include <QKeyEvent>
#include "vertex.h"
#include "input.h"
#include "mainwindow.h"
// Triangle coloré
static const Vertex sg_verticesTriangle[] =
{
Vertex( QVector3D( 0.00f, 0.75f, 1.0f), QVector3D( 1.0f, 0.0f, 0.0f) ),
Vertex( QVector3D( 0.75f, -0.75f, 1.0f), QVector3D( 0.0f, 1.0f, 0.0f) ),
Vertex( QVector3D( -0.75f, -0.75f, 1.0f), QVector3D( 0.0f, 0.0f, 1.0f) )
};
// Cube coloré
// Attention à l'ordre des vertices, car il faut que les sommets d'une face soit dans le sens antihoraire
// Front
#define VERTEX_FTR Vertex( QVector3D( 0.5f, 0.5f, 0.5f), QVector3D( 1.0f, 0.0f, 0.0f ) )
#define VERTEX_FTL Vertex( QVector3D(-0.5f, 0.5f, 0.5f), QVector3D( 0.0f, 1.0f, 0.0f ) )
#define VERTEX_FBL Vertex( QVector3D(-0.5f, -0.5f, 0.5f), QVector3D( 0.0f, 0.0f, 1.0f ) )
#define VERTEX_FBR Vertex( QVector3D( 0.5f, -0.5f, 0.5f), QVector3D( 0.0f, 0.0f, 0.0f ) )
// Back
#define VERTEX_BTR Vertex( QVector3D( 0.5f, 0.5f, -0.5f), QVector3D( 1.0f, 1.0f, 0.0f ) )
#define VERTEX_BTL Vertex( QVector3D(-0.5f, 0.5f, -0.5f), QVector3D( 0.0f, 1.0f, 1.0f ) )
#define VERTEX_BBL Vertex( QVector3D(-0.5f, -0.5f, -0.5f), QVector3D( 1.0f, 0.0f, 1.0f ) )
#define VERTEX_BBR Vertex( QVector3D( 0.5f, -0.5f, -0.5f), QVector3D( 1.0f, 1.0f, 1.0f ) )
static const Vertex sg_vertices[] =
{
// Face 1 (Front)
VERTEX_FTR, VERTEX_FTL, VERTEX_FBL,
VERTEX_FBL, VERTEX_FBR, VERTEX_FTR,
// Face 2 (Back)
VERTEX_BBR, VERTEX_BTL, VERTEX_BTR,
VERTEX_BTL, VERTEX_BBR, VERTEX_BBL,
// Face 3 (Top)
VERTEX_FTR, VERTEX_BTR, VERTEX_BTL,
VERTEX_BTL, VERTEX_FTL, VERTEX_FTR,
// Face 4 (Bottom)
VERTEX_FBR, VERTEX_FBL, VERTEX_BBL,
VERTEX_BBL, VERTEX_BBR, VERTEX_FBR,
// Face 5 (Left)
VERTEX_FBL, VERTEX_FTL, VERTEX_BTL,
VERTEX_FBL, VERTEX_BTL, VERTEX_BBL,
// Face 6 (Right)
VERTEX_FTR, VERTEX_FBR, VERTEX_BBR,
VERTEX_BBR, VERTEX_BTR, VERTEX_FTR
};
#undef VERTEX_BBR
#undef VERTEX_BBL
#undef VERTEX_BTL
#undef VERTEX_BTR
#undef VERTEX_FBR
#undef VERTEX_FBL
#undef VERTEX_FTL
#undef VERTEX_FTR
MainWindow::MainWindow()
{
m_transform.translate(0.0f,0.0f,-5.0f);// L'objet est reculé de 5 unités
}
MainWindow::~MainWindow()
{
makeCurrent();
teardownGL();
}
void MainWindow::initializeGL()
{
// Perform initialization with the current OpenGL context
initializeOpenGLFunctions();
// Connexion signal et slot pour être averti d'une changement de frame. Par defaut le VSync
// est activé dans Qt. Il est aussi possible de s'appuyer sur QTimer, mais en programmation
// de rendu moderne, il est d'usage de s'appuyer sur la synchro d'écran
connect(this, SIGNAL(frameSwapped()),this,SLOT(update()));
printContextInformations();
// Ne faire le rendu que des faces qui sont affichée en sens antihoraire
glEnable(GL_CULL_FACE);
// Simply set the clear color
glClearColor(0.0f,0.0f,0.0f,1.0f);
// Initialisation spécifique à l'application
{
//--- Création du shader (ne pas libérer tant que le VertexArrayObject n'est pas créé)
m_program = new QOpenGLShaderProgram(); // Seule partie créée par 'new' car passera de main en main. 'delete' de l'instance libérera le shader de la mémoire GPU
m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shaders/simple.vert"); // Le Vertex shader travaille avec notre type Vertex, le Fragment shader prendra la sortie du Vertex shader, la sortie du Fragment se fait vers vers l'écran
m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shaders/simple.frag");
m_program->link(); // 'link()' rassemble les shaders. Le retour devrait être testé (sera fait plus tard)
m_program->bind(); // 'bind()' pour que ce shader soit celui qui est actif
//--- Définition des Uniforms des shaders
u_modelToWorld = m_program->uniformLocation("modelToWorld");
u_worldToCamera = m_program->uniformLocation("worldToCamera");
u_cameraToView = m_program->uniformLocation("cameraToView");
//--- Création du buffer (ne pas libérer tant que le VertexArrayObject n'est pas créé)
m_vertex.create(); // Creation du buffer pour une allocation dynamique
m_vertex.bind(); // Marquer comme buffer courant
m_vertex.setUsagePattern(QOpenGLBuffer::StaticDraw); // Les données ne changeront pas, donc rendu statique
m_vertex.allocate(sg_vertices,sizeof(sg_vertices)); // Allocation dans la mémoire graphique
//--- Création du VertexArrayObject (VAO)
// Attribut 0 = position, Attribut 1 = couleur
// les ...Offets, ...TupleSize et stride simplifient l'écriture)
m_object.create();
m_object.bind();
m_program->enableAttributeArray("position"); // On peut utiliser un index ou un nom spécifique pour l'attribut
m_program->enableAttributeArray("color"); // Ces attributs sont lié au dernier buffer alloué par allocate
m_program->setAttributeBuffer("position", GL_FLOAT,Vertex::positionOffset(),Vertex::PositionTupleSize,Vertex::stride());
m_program->setAttributeBuffer("color", GL_FLOAT,Vertex::colorOffset(),Vertex::ColorTupleSize,Vertex::stride());
m_object.release(); // Libération (unbind all), dans le sens inverse de la création. 'release' (et non 'unbind') est l'opposé du 'bind'
m_vertex.release();
m_program->release();
}
}
void MainWindow::resizeGL(int w, int h)
{
m_projection.setToIdentity();
m_projection.perspective( 45.0f, w/float(h), 0.0f, 1000.0f );
}
void MainWindow::paintGL()
{
// Clear with set clear color
glClear(GL_COLOR_BUFFER_BIT);
// Rendu utilisant le shader. Très simple car s'appuie sur un VAO
m_program->bind();
m_program->setUniformValue( u_worldToCamera, m_camera.toMatrix() );
m_program->setUniformValue( u_cameraToView, m_projection );
{
m_object.bind();
m_program->setUniformValue( u_modelToWorld, m_transform.toMatrix() );
glDrawArrays( GL_TRIANGLES, 0, sizeof(sg_vertices)/sizeof(sg_vertices[0]) );
m_object.release();
}
m_program->release();
}
void MainWindow::update()
{
Input::update();
// Récupération des entrées
if(Input::buttonPressed(Qt::RightButton))
{
static const float transSpeed = 0.5f; // A modifier par une valeur dépendante du taux de rafraichissement
static const float rotSpeed = 0.5f;
m_camera.rotate( -rotSpeed * Input::mouseDelta().x(), Camera3D::LocalUp);
m_camera.rotate( -rotSpeed * Input::mouseDelta().y(), m_camera.right());
QVector3D translation;
if( Input::keyPressed(Qt::Key_Z))
{
translation += m_camera.forward();
}
if( Input::keyPressed(Qt::Key_S))
{
translation -= m_camera.forward();
}
if( Input::keyPressed(Qt::Key_D))
{
translation += m_camera.right();
}
if( Input::keyPressed(Qt::Key_Q))
{
translation -= m_camera.right();
}
if( Input::keyPressed(Qt::Key_E))
{
translation += m_camera.up();
}
if( Input::keyPressed(Qt::Key_A))
{
translation -= m_camera.up();
}
m_camera.translate( transSpeed*translation);
}
// Mise à jour de l'objet
m_transform.rotate( 1.0f, QVector3D( 0.4f, 0.3f, 0.3f ) );
// Demande de rafraichissement
QOpenGLWindow::update();
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if (event->isAutoRepeat())
{
event->ignore();
}
else
{
Input::registerKeyPress(event->key());
}
}
void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
if (event->isAutoRepeat())
{
event->ignore();
}
else
{
Input::registerKeyRelease(event->key());
}
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
Input::registerMousePress(event->button());
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
Input::registerMouseRelease(event->button());
}
void MainWindow::teardownGL()
{
// Destruction des informations OpenGL
m_object.destroy();
m_vertex.destroy();
delete m_program;
}
void MainWindow::printContextInformations()
{
QString glType;
QString glVersion;
QString glProfile;
glType = (context()->isOpenGLES())?"OpenGL ES":"OpenGL";
glVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));
#define CASE(c) case QSurfaceFormat::c: glProfile = #c; break
switch(format().profile())
{
CASE(NoProfile);
CASE(CoreProfile);
CASE(CompatibilityProfile);
}
#undef CASE
// qPrintable is used to avoid string surrounded by quotation marks
qDebug()<<qPrintable(glType)<<qPrintable(glVersion)<<"("<<qPrintable(glProfile)<<")";
}
<file_sep>/QtOpenGLViewer/camera3d.cpp
#include "camera3d.h"
const QVector3D Camera3D::LocalForward( 0.0f, 0.0f, -1.0f );
const QVector3D Camera3D::LocalRight( 1.0f, 0.0f, 0.0f );
const QVector3D Camera3D::LocalUp( 0.0f, 1.0f, 0.0f );
const QMatrix4x4& Camera3D::toMatrix()
{
if( m_dirty )
{
m_dirty = false;
m_matrix.setToIdentity();
m_matrix.rotate(m_rotation.conjugated());
m_matrix.translate(-m_position);
}
return m_matrix;
}
void Camera3D::rotate(const QQuaternion& quat)
{
m_dirty = true;
m_rotation = quat * m_rotation;
}
void Camera3D::translate(const QVector3D& translation)
{
m_dirty = true;
m_position += translation;
}
QVector3D Camera3D::forward()
{
return m_rotation.rotatedVector(LocalForward);
}
QVector3D Camera3D::right()
{
return m_rotation.rotatedVector(LocalRight);
}
QVector3D Camera3D::up()
{
return m_rotation.rotatedVector(LocalUp);
}
<file_sep>/README.md
# Présentation
En quelques mots, mon but est d'explorer le plus loin possible tout ce qui touche aux nouvelles techniques de rendu en rapport avec le "Physically Based Rendering" (PBR). C'est un vaste sujets sur lequel j'ai réalistiquement 20 ans de retard.
De fil en aiguille, j'ai (mal)heureusement redécouverts d'autres sujets connexes tels le Ray-marching, le Path-tracing, les shaders, l'IBL (Image based lighting). Cela fait énormément de sujets intéressants à étudier en programmation
Tenir un journal me semble être le moyen le plus simple pour garder le cap dans mon projet et suivre mes progrès.
J'y garde donc mes notes, mes motivations, mes objectifs, mes tâches en cours et tout ce qui pourra me servir à progresser.
Avoir tout cela inscrit noir sur blanc me permet de m'y référer et de me rappeler régulièrement d'où je pars.
Je pense que cela sera un beau voyage.
***Note:** Pour des facilités d'usage, les notes les plus récentes sont en tête de journal (un peu comme un blog)*
# Objectifs & Tâches
## Court terme
- Gestion de la refraction/reflection dans un "ray marcher SDF"
- Matériaux PBR
- Image Based Lighting
## Moyen terme
- Implémenter un rendu temps réel en OpenGL, avec déplacement de caméra et affichage d'objets utilisant des vertex shaders et des fragment shaders.
- Utiliser quelques fragment shaders venant de ShaderToy
- Lumières
- Skybox
- Matériaux PBR
- importer des objets au format Wavefront (.OBJ)
- Exporter au format .PBR et tester dans PBRt-v3
## Long terme
# Journal de développement
## 04/03/20 - Vulkan? Raytracing?
Comme prévu, il est tentant de se disperser et il est donc important que je garde mes objectifs en vue.
Petit revirement de stratégie qui semble bien plus alignée avec mes envies: Vulkan, au lieu d'OpenGL?
Vulkan a une approche plus orientée Computer Graphcs, plus proche du GPU qu'OpenGL. De plus, c'est une technologie moderne qui a de bons échos et qui est reconnue.
A priori, peu de connaissance OpenGL sont nécessaires (voir pas du tout) et divers tutoriaux sont disponibles:
https://vulkan-tutorial.com/
Quant au Ray Tracing, c'est toujours un objectif a long terme de travailler sur une implémentation personnelle. Je n'ai pas encore de recul suffisant sur la techno qui supporterait ce projet, mais les approches GPU-oriented sont très tentantes. Ce que j'ai vu aussi sur Shadertoy m'a déjà donné un aperçu des problématique.
Je pense toutefois que s'intéresser aux concepts fondamentaux est nécessaire, et suivre un guide comme "RT in one week end" serait énorme.
https://github.com/RayTracing/raytracing.github.io
https://raytracing.github.io/books/RayTracingInOneWeekend.html
https://raytracing.github.io/books/RayTracingTheNextWeek.html
https://raytracing.github.io/books/RayTracingTheRestOfYourLife.html
## 03/03/20 - Shadertoy
Je voudrais mettre en place réflections et réfractions dans un Ray Marcher, de manière généraliste, afin de ne pas à avoir à employer des techniques foncitons de la scène.
Ces exemples correspondent à ce que je veux faire et il est donc nécessaire que je les étudie pour saisir les techniques employées:
[Glass and metal hearts](https://www.shadertoy.com/view/MdfcRs) - Utilise des définitions de matériaux et fait bien progresser des rayons au sein du SDF
[Almost Physically based glass](https://www.shadertoy.com/view/MsXyz8) - Implémentation plus obscure à base de macros, mais rendu bluffant
[Physically-based SDF](https://www.shadertoy.com/view/XlKSDR) - Scène simple, mais algos de référence
[Old Watch (IBL)](https://www.shadertoy.com/view/lscBW4) et [Old Watch (RT)](https://www.shadertoy.com/view/MlyyzW) - Même scène rendue avec 2 moteurs différents
[Ice Primitives](https://www.shadertoy.com/view/MscXzn) - Bonne structuration du code et
## 24/02/20 - Shadertoy
J'ai suivi les 2 tutoriaux de Inigo Quilez sur ses engrenages et sur la créatures bondisantes de bout en bout. CEla a permi de comprendre en profondeur certaines implications liées à la technique du SDF.
## 12/02/20 - Shadertoy
Très bonne avancée sur le développement de shaders et surtout sur les techniques liées au ray_marching et au description de scènes en "Signed Distance Field" (SDF)
Je suis plusieurs tutoriaux et réplique les techniques que j'ai pu analyser et comprendre.
## 06/02/20 - Premiers obstacles
J'ai compris que Qt5 avait amené pas mal de nouveauté dans ce qu'on appelle "Modern OpenGL". Le résultat est que les tutoriaux de Developpez.com sont moins intéressants car ils s'appueint sur Qt4.
A mon grand regret, le blog de <NAME> n'apporte plus de conseils simples pour progresser, une fois mon cube coloré affiché.
il faudrait que je décortique ses code-sources pour progresser, ce qui risque d'être une solution fastideuse. Je me garde cette idée de côté au cas où je ne trouverai pas de tutoriaux aussi efficaces.
Sinon en parallèle, je regarde ce qui existe comme projets sur Shadertoy qui pourraient me servir de référence pour mieux comprendre les shaders. Mais attention, il est aisé de se disperser vu le nombre de domaines qui sont intéressant (ray marching, SDF, PBR, ...)
.../...
Finalement, j'ai pris le parti de continuer l'exploration des nouvelles technos par l'intermédiaire de Shadertoy. En effet, cela founit un accès facile à un moteur de rendu très performant, qui peret notamment de déjà explorer très facilement plusieurs technos.
Grace à <NAME> et sa vidéo de deconstruction de Shader, j'ai déjà pu jouer à créer une visualisation par lancer de rayon, utilisant le principe de "Ray Marching" combiné à du "Sign Distance Field". Le rendu est pour l'instant à base de couleur diffuse, d'illumination directionnelle et du calcul d'ombres projetées.
## 05/02/20 - Shadertoy
J'ai voulu utiliser un shader simple de ShaderToy pour l'appliquer en tant que fragment shader sur mon cube.
Cela m'a permis de comprendre qu'en fait ShaderToy fournissait ses propres Uniforms. Il était nécessaire de faire moi-même le passage d'un Uniform pour le temps écoulé car ce n'était pas disponible par défaut. De même il faudrait que je fasse cela pour la souris.
J'ai vu aussi que ce n'était pas si simple d'avancer sans documentation sur le langage GLSL, donc il faut que je trouve un document de référence sur Qt5/OpenGL/GLSL
Le résultat de ma migration du shader a mis en évidence que le rendu était bien en coordonnées écran. La couleur ne semble donc pas mappée sur l'objet. Il faudrait donc que je transfère des informations d'UV pour que cela me donne un rendu en perspective
## 04/02/20 - Premiers Tutoriels Qt-OpenGL
Au sein de tous les sites parcourus, trois sites m'ont particulièrement parus pertinents pour commencer l'étude d'OpenGL. Les deux premiers s'appuient sur Qt pour la gestion des entrées et des fenêtres:
- [Le blog de <NAME>](https://www.trentreed.net/topics/opengl/) et [ses sources](https://github.com/TReed0803/QtOpenGL/tree/tutorial-series)
- [Le blog de <NAME>](http://guillaume.belz.free.fr/doku.php?id=start#articles_opengl) et [ses sources](https://github.com/GuillaumeBelz/qt-opengl)
- [Le site opengl-tutorial.org](http://www.opengl-tutorial.org/) et [ses sources](https://github.com/opengl-tutorials/ogl)
C'est grâce aux tutos de Trent que j'ai pu commencer le développement, mais les autres tutoriaux sont très intéressants. Il est probable que j'ai d'abord à faire ces 3 tutoriaux avant de progresser dans ma quête.
### PBRt
En ce qui concerne PBRt, j'ai trouvé ce site qui montre étape par étape les résultats qu'à obtenu Jan Walter avec son[Implémentation de PBRt en RUST](https://www.janwalter.org/jekyll/rendering/pbrt/rust/2017/05/08/pbrt-rust-v0_1_0.html).
C'est une bonnne idée que de progresser ainsi par étapes et je suivrai certainement un processus similaire. Mais pour le moment je garde cela dans un coin pour référence.
## Janvier 2020: Motivations originelles
Début 2020, je suis tombé par hasard sur ce livre disponible en accès libre depuis fin 2018:
[Physically Based Rendering : From theory to implementation](http://www.pbr-book.org/3ed-2018/contents.html).
Déjà ravi de trouver une telle manne de connaisance, c'était sans compter qu'en plus, ses généreux créateurs
avaient mis à disposition [toutes les sources de leur "ray tracer"](https://github.com/mmp/pbrt-v3).
Bien évidemment, j'ai été totalement débordé par l'envie d'étudier le bousin et de profiter de cette manne pour
écrire mon propre RT. Comme d'hab', quoi! comme un gamin qui ouvre ses nouveaux jouets à Noël.
Mais c'est loin d'être simple, car en continuant à explorer le thème, j'ai découvert combien le PBR a influencé le
monde du rendu temps-réel, pas seulement celui du calcul en différé. Unreal ou d'autres moteurs de jeux comme "Star
Citizen" par exemples, s'appuient sur certains principes du PBR pour améliorer leur rendu.
J'ai aussi découvert que certains développeurs s'étaient même amusés a créer des shaders a base de ray-marching
pour faire des rendus similaires à PBRt-v3, ou utilisant les formules du PBR pour le rendu des textures ou des
surfaces ([Shadertoy - PBR](https://www.shadertoy.com/results?query=tag%3Dpbr)).
A ce point là, je me suis demandé quelle serait la meilleure méthode pour progresser: Partir vers un Ray tracer,
ou s'appuyer sur les shaders GLSL?
Mais en fait, pourquoi ne pas mixer les deux.
J'ai donc réalisé que ce qui me satisferait serait de pouvoir obtenir un rendu temps-réel d'une scène, utilisant
des matériaux PBR, que je pourrai ensuite utiliser dans un ray-tracer de mon cru.
OpenGL m'a paru être naturellement le meilleur candidat pour la partie temps réel, et faciliser l'utilisation
des shaders GLSL
Continuant sur ce chemin, je suis alors tombé sur quantité de tutoriaux parlant de PBR, d'OpenGL, de Qt... Jusqu'à
ce qu'un début de route se dessine, notamment grâce aux tutoriaux Qt/OpenGL de Trent Reed.
Voici donc les premières étapes que je me suis définies dans cette aventure:
- Mettre en place une base d'outil de rendu temps réel, où il est possible de se déplacer autour d'un objet 3D
- Supporter un format de données pour le chargement d'objets et de scène (par exemple: scènes .PBR, fichiers Wavefront .OBJ)
- Définir des matériaux basiques et des lumières
- Exporter une scène pour rendu ray-tracer, où la caméra sera positionnée comme dans l'outil
- Faire un premier rendu basique de ray-tracing ou ray-marchine (à voir)
J'ai notamment en tête deux images trouvées sur le net, que j'aimerai générer par moi même grâce à ces outils:
[Plusieurs exemples de rendus sur le site de Stanford](https://graphics.stanford.edu/~henrik/images/cbox.html)
<img src="https://graphics.stanford.edu/~henrik/images/imgs/cbox_pathtracing.jpg" width="300">
[Doc Unreal: Physically Bases Materials](https://docs.unrealengine.com/en-US/Engine/Rendering/Materials/PhysicallyBased/index.html)
<img src="https://docs.unrealengine.com/Images/Engine/Rendering/Materials/PhysicallyBased/measured_materials.png" width="300">
<file_sep>/QtOpenGLViewer/camera3d.h
#pragma once
#include <QVector3D>
#include <QQuaternion>
#include <QMatrix4x4>
class Camera3D
{
public:
static const QVector3D LocalForward;
static const QVector3D LocalUp;
static const QVector3D LocalRight;
Camera3D();
void rotate( float angle, const QVector3D& axis);
void rotate( const QQuaternion& quat);
void translate( const QVector3D& translation );
QVector3D forward();
QVector3D right();
QVector3D up();
const QMatrix4x4& toMatrix();
private:
bool m_dirty;
QQuaternion m_rotation;
QVector3D m_position;
QMatrix4x4 m_matrix;
};
inline Camera3D::Camera3D() :
m_dirty( true )
{}
inline void Camera3D::rotate(float angle, const QVector3D& axis)
{
rotate(QQuaternion::fromAxisAndAngle( axis, angle));
}
|
2c1e1cdd110df0e4e1ad5f5610d6673bfe7c8c10
|
[
"Markdown",
"C",
"C++"
] | 11 |
C++
|
lostpapers/OpenGLStudies
|
d09db53928649da3cbecc34959812b1dd916ec5d
|
de3c1548c58c896261840a5722e096650f4c3407
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 30 16:01:07 2019
@author: anant
"""
#import modules
from me_indicators_automation.case_form import CaseForm
## House data
def house_metrics(file, content_type):
#file = './Data/5. House Data Summary Report_upto Kartik.xlsx'
cols = ['chw_name','houseID','house_name','has_plate','last_modified_date','closed']
house = CaseForm(filepath=file, cols=cols, filetype = content_type)
house.strip_str('houseID')
house.filter_for_condition('closed', False) #Drop closed cases
house.remove_duplicates(sort_by=['houseID', 'house_name', 'last_modified_date'],dupl_subset=['houseID', 'house_name'])
house.count_by_chw('has_plate','houseID',['has_plate',['yes']])
house.count_by_chw('no_plate','houseID',['has_plate',['no']])
return house.results<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 14:22:07 2020
@author: anant
"""
from me_indicators_automation.case_form import CaseForm
def clean(form):
col_mapping = {"woman_ID":"person_id"}
form.rename_columns(col_mapping)
form.strip_str('person_id')
## Post Delivery Form
def pdf_metrics(file, dt1='2015-01-01', dt2='2050-01-01', content_type='text/csv'):
#file = './Data/post_delivery_form.csv'
#dt1 = '2020-01-01'
#dt2 = '2020-03-31'
cols = ['chw_name','woman_ID','last_visit','delivery_date_pdf','delivery_location',
'child_one.birth_outcome1','child_two.birth_outcome2','child_three.birth_outcome3',
'child_one.baby_weight1','child_two.baby_weight2','child_three.baby_weight3',
'pregnancy_outcome']
#woman_at_home does not exist
pdf = CaseForm(filepath=file, cols=cols, filetype=content_type)
clean(pdf)
pdf_ppw_visited = CaseForm() #pdf_ppw_vis is created only to calculate ppw_visited (post partum women visited based on last_visit in date range)
pdf_ppw_visited.df = pdf.df
pdf_ppw_visited.filter_by_date('last_visit', [dt1,dt2])
pdf_ppw_visited.remove_duplicates(sort_by=['person_id', 'last_visit'],dupl_subset=['person_id'])
pdf_ppw_visited.count_by_chw('ppw_visited','person_id')
#filter for data with delivery date in the given date range, all indicators after this are based on this filtered data
pdf.filter_by_date('delivery_date_pdf', [dt1,dt2])
pdf.remove_duplicates(sort_by=['person_id', 'last_visit'],dupl_subset=['person_id'])
pdf.count_by_chw('num_of_deliv','person_id')
pdf.count_by_chw('inst_deliv','person_id',['delivery_location',['private_clinic_hospital', 'primary_health_center',
'nyaya_health_hospital', 'district_hospital', 'health_post',
'non-nhn_health_facility', 'govt_facility_outside_nepal',
'private_clinic-hospital_outside_nepal']])
pdf.count_by_chw('live_births1','person_id',['child_one.birth_outcome1',['live_birth']])
pdf.count_by_chw('live_births2','person_id',['child_two.birth_outcome2',['live_birth']])
pdf.count_by_chw('live_births3','person_id',['child_three.birth_outcome3',['live_birth']])
pdf.add_columns('live_births',['live_births1', 'live_births2', 'live_births3'])
pdf.count_by_chw('still_births1','person_id',['child_one.birth_outcome1',['still_birth']])
pdf.count_by_chw('still_births2','person_id',['child_two.birth_outcome2',['still_birth']])
pdf.count_by_chw('still_births3','person_id',['child_three.birth_outcome3',['still_birth']])
pdf.add_columns('still_births',['still_births1', 'still_births2', 'still_births3'])
pdf.count_by_chw_num_condition('low_birth_wt1','person_id',['child_one.baby_weight1','<',2.5])
pdf.count_by_chw_num_condition('low_birth_wt2','person_id',['child_two.baby_weight2','<',2.5])
pdf.count_by_chw_num_condition('low_birth_wt3','person_id',['child_three.baby_weight3','<',2.5])
pdf.add_columns('low_birth_wt',['low_birth_wt1', 'low_birth_wt2', 'low_birth_wt3'])
pdf.filter_for_condition('pregnancy_outcome','intended_abortion')
pdf.count_by_chw('safe_abortions','person_id',['delivery_location',['primary_health_center',
'nyaya_health_hospital', 'district_hospital']])
return pdf.concat_dataframes([pdf.results, pdf_ppw_visited.results])<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 14:22:07 2020
@author: anant
"""
import pandas as pd
from me_indicators_automation.form import Form
import datetime as dt
def clean(form):
col_mapping = {"woman_ID":"person_id", "woman_at_home":"person_at_home"}
form.rename_columns(col_mapping)
form.strip_id()
form.only_at_home()
form.remove_duplicates()
## Pregnancy Screening
def pss_metrics(file):
#filename = './Data/pregnancy_screening.csv'
cols = ['chw_name','woman_at_home','woman_ID','last_visit','last_visit_nepali',
'agrees_for_service','urine_test','urine_test_positive',
'pregnancy_status','balanced_counseling.bcs_form.method_change',
'menopause','want_more_children', 'birth_gap', 'contraceptive_current',
'balanced_counseling.bcs_form.counseling.method_chosen1']
pss = Form(file, cols)
clean(pss)
pss.count_by_chw('elig_wm','person_id')
pss.count_by_chw('rcvd_pss','person_id',['agrees_for_service',['yes']])
pss.count_by_chw('upt_done','person_id',['urine_test',['positive','negative','indetermined','test_malfunctioning']])
pss.count_by_chw('upt_pos','person_id',['urine_test',['positive']])
pss.count_by_chw('new_preg','person_id',['pregnancy_status',['pregnant']])
pss.count_by_chw('bcs_agree','person_id',['balanced_counseling.bcs_form.method_change',['yes']])
pss.count_by_chw('menop','person_id',['menopause',['yes']])
pss.count_by_chw('more_child','person_id',['want_more_children',['yes']])
pss.count_by_chw('birth_gap','person_id',['birth_gap',['two_or_more_years']])
pss.count_by_chw('hystectomy','person_id',['contraceptive_current',['hystectomy']])
pss.count_by_chw('sterilization','person_id',['contraceptive_current',['male_sterilization','female_sterilization']])
pss.count_by_chw('pills','person_id',['contraceptive_current',['pills']])
pss.count_by_chw('dipo','person_id',['contraceptive_current',['Dipo']])
pss.count_by_chw('iud','person_id',['contraceptive_current',['iud']])
pss.count_by_chw('implants','person_id',['contraceptive_current',['implants']])
pss.count_by_chw('refer','person_id',['contraceptive_current',['implants']])
#pss.results.to_csv('./uploads/'+dt.datetime.today().strftime('%m-%d-%Y %H%M%S')+'.csv', index=True)
return pss.results
<file_sep>from setuptools import setup
setup(
name='me_indicators_automation',
packages=['me_indicators_automation'],
include_package_data=True,
install_requires=[
'flask>=1.1.1',
'pandas>=1.0.1',
'xlrd >= 1.0.0'
],
)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 10:52:54 2020
@author: anant
"""
import pandas as pd
class CaseForm:
def __init__(self, filepath=None, cols=None, filetype=None):
self.filepath = filepath
self.cols = cols
if self.filepath is not None:
if filetype == 'text/csv':
self.df = pd.read_csv(self.filepath, usecols=self.cols, na_values=['---'])
else:
self.df = pd.read_excel(self.filepath, usecols=self.cols, na_values=['---'], sheet_name=0)
else:
self.df = pd.DataFrame()
self.results = pd.DataFrame()
def rename_columns(self, col_mapping):
self.col_mapping = col_mapping
self.df.rename(columns=col_mapping, inplace = True)
def create_duplicate_df2(self):
self.df2 = self.df.copy(deep=True)
def strip_str(self, str):
self.df[str].str.replace(" ","")
def count_by_chw(self, agg_col_nm, count_col, condition=None):
if condition == None:
grouped = self.df.groupby(['chw_name']).agg({count_col:'count'})
else:
grouped = self.df[self.df[condition[0]].isin(condition[1])].groupby(['chw_name']).agg({count_col:'count'})
self.results = pd.concat([self.results, grouped], axis=1, sort=False)
self.results[count_col].fillna(0, inplace = True)
self.results.rename(columns={self.results.columns[-1]:agg_col_nm}, inplace = True)
def countifs_by_chw(self, agg_col_nm, conditions):
countifs_df = pd.DataFrame()
for condition in conditions:
countifs_df[condition[0]] = self.df[condition[0]].isin(condition[1])
self.df['countifs_sum'] = countifs_df.sum(axis=1)
self.df.loc[self.df['countifs_sum']>0, 'countifs_sum'] = 1
grouped = self.df[self.df['countifs_sum']>0].groupby(['chw_name']).agg({'countifs_sum':'count'})
self.results = pd.concat([self.results, grouped], axis=1, sort=False)
self.results['countifs_sum'].fillna(0, inplace = True)
self.results.rename(columns={self.results.columns[-1]:agg_col_nm}, inplace = True)
def sum_by_chw(self, agg_col_nm, sum_col, condition=None):
if condition == None:
grouped = self.df.groupby(['chw_name']).agg(sum_col=(sum_col,'sum'))
else:
grouped = self.df[self.df[condition[0]].isin(condition[1])].groupby(['chw_name']).agg(sum_col=(sum_col,'sum'))
self.results = pd.concat([self.results, grouped], axis=1, sort=False)
self.results.rename(columns={self.results.columns[-1]:agg_col_nm}, inplace = True)
def remove_duplicates(self, sort_by, dupl_subset):
self.df = self.df.sort_values(sort_by, ascending = True).drop_duplicates(
subset=dupl_subset, keep='last')
def convert_to_Int64(self, cols):
"""Takes a dataframe, and a list of its columns, then converts the columns
to numeric, then to dtype Int64 before returning the dataframe"""
for col in cols:
self.df[col] = pd.to_numeric(self.df[col], errors='coerce')
self.df = self.df.astype({col:'Int64'})
def add_columns(self, new_col, to_add_cols):
self.results[new_col] = 0
for col in to_add_cols:
self.results[new_col] = self.results[new_col] + self.results[col].fillna(0)
self.results.drop(to_add_cols, axis=1, inplace=True)
def filter_for_condition(self, filter_col, value):
self.df = self.df[self.df[filter_col]==value]
def filter_out_condition(self, filter_col, value):
self.df = self.df[self.df[filter_col]!=value]
def filter_by_date(self, filter_col, dates):
self.df = self.df[(self.df[filter_col]>=dates[0]) & (self.df[filter_col]<=dates[1])]
def count_by_chw_date_condition(self, agg_col_nm, count_col, condition=None):
grouped = self.df[(self.df[condition[0]]>=condition[1][0]) & (self.df[condition[0]]<=condition[1][1])].groupby(['chw_name']).agg(count_col=(count_col,'count'))
self.results = pd.concat([self.results, grouped], axis=1, sort=False)
self.results.rename(columns={self.results.columns[-1]:agg_col_nm}, inplace = True)
def count_by_chw_num_condition(self, agg_col_nm, count_col, condition=None):
if condition[1] == '<':
grouped = self.df[self.df[condition[0]]<condition[2]].groupby(['chw_name']).agg(count_col=(count_col,'count'))
elif condition[1] == '>':
grouped = self.df[self.df[condition[0]]>condition[2]].groupby(['chw_name']).agg(count_col=(count_col,'count'))
elif condition[1] == '<=':
grouped = self.df[self.df[condition[0]]<=condition[2]].groupby(['chw_name']).agg(count_col=(count_col,'count'))
elif condition[1] == '>=':
grouped = self.df[self.df[condition[0]]>=condition[2]].groupby(['chw_name']).agg(count_col=(count_col,'count'))
elif condition[1] == '==':
grouped = self.df[self.df[condition[0]]==condition[2]].groupby(['chw_name']).agg(count_col=(count_col,'count'))
self.results = pd.concat([self.results, grouped], axis=1, sort=False)
self.results.rename(columns={self.results.columns[-1]:agg_col_nm}, inplace = True)
def concat_dataframes(self, dataframes):
return pd.concat(dataframes, axis=1, sort=False)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 30 16:01:07 2019
@author: anant
"""
#import modules
from me_indicators_automation.case_form import CaseForm
## Family data
def family_metrics(file, content_type):
#file = './Data/3. Family Enrollment Monthly report_Bhadra 2076.xlsx'
cols = ['chw_name','familyID','family_head','last_modified_date','closed',
'enrollment_complete','family_female_non_residents',
'family_male_non_residents','family_female_residents','family_male_residents','residence_type']
family = CaseForm(filepath=file, cols=cols, filetype=content_type)
family.strip_str('familyID')
family.filter_for_condition('closed', False) #Drop closed cases
family.remove_duplicates(sort_by=['familyID', 'family_head', 'last_modified_date'],dupl_subset=['familyID', 'family_head'])
family.df['residence_type'] = family.df['residence_type'].map({1:1,2:2,
3:3,'single':1,'primary':2,'secondary':3})
family.convert_to_Int64(['residence_type','family_female_non_residents','family_male_non_residents','family_female_residents','family_male_residents'])
family.count_by_chw('enroll_cmplt','familyID',['enrollment_complete',['yes']])
family.count_by_chw('enroll_not_cmplt','familyID',['enrollment_complete',['no']])
family.count_by_chw('Single','familyID',['residence_type',[1]])
family.count_by_chw('Primary','familyID',['residence_type',[2]])
family.count_by_chw('Secondary','familyID',['residence_type',[3]])
family.count_by_chw('fam_regd','familyID')
family.sum_by_chw('male_res','family_male_residents')
family.sum_by_chw('fem_res','family_female_residents')
family.sum_by_chw('male_nonres','family_male_non_residents')
family.sum_by_chw('fem_nonres','family_female_non_residents')
family.add_columns('tot_male', ['male_res','male_nonres'])
family.add_columns('tot_fem', ['fem_res','fem_nonres'])
return family.results<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 19:56:07 2020
@author: anant
"""
from me_indicators_automation import app
from flask import Flask, render_template, request, make_response
from me_indicators_automation import pss, pdf, house, family, individual, anc
UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/', methods=['GET','POST'])
@app.route('/home')
def home():
return render_template('home.html')
@app.route('/pss', methods=['GET','POST'])
def pss_data():
if request.method == "POST":
f = request.files['pss_file']
if 'date_checkbox' in request.form:
data = pss.pss_metrics(f, dt1=request.form['from'], dt2=request.form['to'], content_type=f.headers["Content-Type"])
else:
data = pss.pss_metrics(f, content_type=f.headers["Content-Type"])
resp = make_response(data.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=pss_metrics.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
@app.route('/pdf', methods=['GET','POST'])
def pdf_data():
if request.method == "POST":
f = request.files['pdf_file']
if 'date_checkbox' in request.form:
data = pdf.pdf_metrics(f, dt1=request.form['from'], dt2=request.form['to'], content_type=f.headers["Content-Type"])
else:
data = pdf.pdf_metrics(f, content_type=f.headers["Content-Type"])
resp = make_response(data.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=pdf_metrics.csv"
resp.headers["Content-Type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
return resp
@app.route('/house', methods=['GET','POST'])
def house_data():
if request.method == "POST":
f = request.files['house_file']
data = house.house_metrics(f, f.headers["Content-Type"])
resp = make_response(data.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=house_metrics.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
@app.route('/family', methods=['GET','POST'])
def family_data():
if request.method == "POST":
f = request.files['family_file']
data = family.family_metrics(f, f.headers["Content-Type"])
resp = make_response(data.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=family_metrics.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
@app.route('/individual', methods=['GET','POST'])
def individual_data():
if request.method == "POST":
f = request.files['individual_file']
data = individual.individual_metrics(f, f.headers["Content-Type"])
resp = make_response(data.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=individual_metrics.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
@app.route('/anc', methods=['GET','POST'])
def anc_data():
if request.method == "POST":
f = request.files['anc_file']
if 'date_checkbox' in request.form:
data = anc.anc_metrics(f, dt1=request.form['from'], dt2=request.form['to'], content_type=f.headers["Content-Type"])
else:
data = anc.anc_metrics(f, content_type=f.headers["Content-Type"])
resp = make_response(data.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=" + "sheet.xlsx"
resp.headers["Content-Type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
return resp
if __name__ == '__main__':
#app.run()
app.run(debug=True)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 30 16:01:07 2019
@author: anant
"""
#import modules
from me_indicators_automation.case_form import CaseForm
## Individual data
def individual_metrics(file, content_type):
#file = './Data/4. Individual-Enrollment_Bhadra 2076.xlsx'
cols = ['chw_name','name_text','individualID','last_modified_date','closed','eligible_woman',
'anc','pdf_direct','pnc1','pnc2','child_under_2','post_delivery','imam_patient',
'cd_patient','surgery_patient','hypertension_screening','hypertension_screening_second_visit']
individual = CaseForm(filepath=file, cols=cols, filetype = content_type)
individual.strip_str('individualID')
individual.filter_for_condition('closed', False) #Drop closed cases
individual.remove_duplicates(sort_by=['individualID', 'name_text', 'last_modified_date'],dupl_subset=['individualID', 'name_text'])
individual.convert_to_Int64(['anc','pdf_direct','pnc1','pnc2','child_under_2'])
# Calculate number of individuals receiving service, and convert to Int64
individual.df['receiving_service'] = individual.df[['eligible_woman',
'anc','pdf_direct','pnc1','pnc2','child_under_2','post_delivery','imam_patient','cd_patient','surgery_patient','hypertension_screening','hypertension_screening_second_visit']].sum(axis=1)>0
individual.convert_to_Int64(['receiving_service'])
individual.count_by_chw('ind_regd','individualID')
individual.sum_by_chw('elig_women','eligible_woman')
individual.sum_by_chw('anc','anc')
individual.sum_by_chw('pdf_direct','pdf_direct')
individual.sum_by_chw('pnc1','pnc1')
individual.sum_by_chw('pnc2','pnc2')
individual.sum_by_chw('u2_child','child_under_2')
individual.sum_by_chw('post_deliv','post_delivery')
individual.sum_by_chw('imam','imam_patient')
individual.sum_by_chw('cd','cd_patient')
individual.sum_by_chw('surgery','surgery_patient')
individual.sum_by_chw('htn_scrn','hypertension_screening')
individual.sum_by_chw('htn_2nd_scrn','hypertension_screening_second_visit')
individual.sum_by_chw('recv_service','receiving_service')
return individual.results<file_sep>M&E Indicators Automation
======
This application takes a csv file of specific format, and generates metrics for download in another csv file.
Install
-------
# clone the repository
Create a virtualenv and activate it::
$ python3 -m venv venv
$ . venv/bin/activate
Install me_indicators_automation::
$ pip install -e .
Run
---
$ export FLASK_APP=me_indicators_automation
$ export FLASK_ENV=development
$ flask run
Open http://127.0.0.1:5000 in a browser.
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 14:22:07 2020
@author: anant
"""
from me_indicators_automation.case_form import CaseForm
def clean(form):
col_mapping = {"woman_ID":"person_id", "woman_at_home":"person_at_home"}
form.rename_columns(col_mapping)
form.strip_str('person_id')
## Pregnancy Screening
def anc_metrics(file, dt1='2015-01-01', dt2='2050-01-01', content_type='text/csv'):
#file = './Data/6. ANC_data_Magh_2076.xlsx'
#dt1 = '2020-01-01'
#dt2 = '2020-04-30'
cols = ['chw_name', 'woman_at_home', 'visit_type', 'woman_ID', 'followup.pregnancy_status',
'agrees_for_service', 'last_visit', 'labs_complete', 'record_usg_findings', 'usg_complete',
'high_risk_vdrl', 'high_risk.high_risk_urine_sugar', 'high_risk_hcv', 'high_risk.high_risk_hiv',
'high_risk_rh_negative', 'high_risk_hbsag', 'high_risk_anemia', 'high_risk_urine_protein',
'high_risk_placenta_previa', 'high_risk_fetal_presentation', 'high_risk_no_of_fetus',
'high_risk', 'anc_visit1_month', 'anc_visit2_month', 'anc_visit3_month', 'anc_visit4_month',
'anc_visit5_month', 'anc_visit6_month', 'anc_visit7_month', 'anc_visit8_month', 'anc_visit9_month',
'anc_visit10_month', 'lmp_group.weeks_pregnant', 'immun-meds.albendazole_taken',
'immun-meds.daily_iron', 'immun-meds.tt_actual_first_dose']
anc = CaseForm(filepath=file, cols=cols, filetype=content_type)
clean(anc)
anc.filter_by_date('last_visit', [dt1,dt2])
anc_home = CaseForm()
anc_home.df = anc.df.copy()
'''
CALCULATE FOR HOME VISITS
'''
anc_home.filter_for_condition('visit_type', 'home')
anc_home.filter_out_condition('followup.pregnancy_status', 'No')
anc_home.remove_duplicates(sort_by=['person_id', 'person_at_home', 'last_visit'],dupl_subset=['person_id'])
anc_home.count_by_chw('home_visit_yes','person_id', ['person_at_home',['yes']])
anc_home.count_by_chw('home_visit_no','person_id', ['person_at_home',['no']])
#anc_home.add_columns('home_visit',['home_visit_yes', 'home_visit_no'])
anc_home.count_by_chw('agrees_for_service_yes','person_id', ['agrees_for_service',['yes']])
anc_home.count_by_chw('agrees_for_service_no','person_id', ['agrees_for_service',['no']])
#anc_home.add_columns('agrees_for_service',['agrees_for_service_yes', 'agrees_for_service_no'])
anc_home.filter_for_condition('agrees_for_service', 'yes')
anc_home.count_by_chw('labs_complete','person_id', ['labs_complete',['yes']])
anc_home.count_by_chw('record_usg_findings','person_id', ['record_usg_findings',['yes']])
anc_home.count_by_chw('usg_complete','person_id', ['usg_complete',['yes']])
anc_home.countifs_by_chw('lab_high_risk', [['high_risk_vdrl',['yes']],
['high_risk.high_risk_urine_sugar',['yes']],
['high_risk_hcv',['yes']],
['high_risk.high_risk_hiv',['yes']],
['high_risk_rh_negative',['yes']],
['high_risk_hbsag',['yes']],
['high_risk_anemia',['yes']],
['high_risk_urine_protein',['yes']]])
anc_home.countifs_by_chw('USG_high_risk', [['high_risk_placenta_previa',['yes']],
['high_risk_fetal_presentation',['yes']],
['high_risk_no_of_fetus',['yes']]])
anc_home.count_by_chw('high_risk', 'person_id', ['high_risk',[1]])
'''
CALCULATE FOR GROUP ANC VISITS
'''
anc_group = CaseForm()
anc_group.df = anc.df.copy()
'''
GOVERNMENT PROTOCOL
'''
anc_proto = CaseForm()
anc_proto.df = anc.df.copy()
anc_proto.remove_duplicates(sort_by=['person_id', 'person_at_home', 'last_visit'],dupl_subset=['person_id'])
anc_proto.countifs_by_chw('4th_complete', [['anc_visit1_month',[4]],
['anc_visit2_month',[4]],
['anc_visit3_month',[4]],
['anc_visit4_month',[4]],
['anc_visit5_month',[4]],
['anc_visit6_month',[4]],
['anc_visit7_month',[4]],
['anc_visit8_month',[4]],
['anc_visit9_month',[4]],
['anc_visit10_month',[4]]])
anc_proto.countifs_by_chw('6th_complete', [['anc_visit1_month',[6]],
['anc_visit2_month',[6]],
['anc_visit3_month',[6]],
['anc_visit4_month',[6]],
['anc_visit5_month',[6]],
['anc_visit6_month',[6]],
['anc_visit7_month',[6]],
['anc_visit8_month',[6]],
['anc_visit9_month',[6]],
['anc_visit10_month',[6]]])
anc_proto.countifs_by_chw('8th_complete', [['anc_visit1_month',[8]],
['anc_visit2_month',[8]],
['anc_visit3_month',[8]],
['anc_visit4_month',[8]],
['anc_visit5_month',[8]],
['anc_visit6_month',[8]],
['anc_visit7_month',[8]],
['anc_visit8_month',[8]],
['anc_visit9_month',[8]],
['anc_visit10_month',[8]]])
anc_proto.countifs_by_chw('9th_complete', [['anc_visit1_month',[9]],
['anc_visit2_month',[9]],
['anc_visit3_month',[9]],
['anc_visit4_month',[9]],
['anc_visit5_month',[9]],
['anc_visit6_month',[9]],
['anc_visit7_month',[9]],
['anc_visit8_month',[9]],
['anc_visit9_month',[9]],
['anc_visit10_month',[9]]])
anc_proto.countifs_by_chw('Proto_vis_cmplt', [['anc_visit1_month',[4, 6, 8, 9]],
['anc_visit2_month',[4, 6, 8, 9]],
['anc_visit3_month',[4, 6, 8, 9]],
['anc_visit4_month',[4, 6, 8, 9]],
['anc_visit5_month',[4, 6, 8, 9]],
['anc_visit6_month',[4, 6, 8, 9]],
['anc_visit7_month',[4, 6, 8, 9]],
['anc_visit8_month',[4, 6, 8, 9]],
['anc_visit9_month',[4, 6, 8, 9]],
['anc_visit10_month',[4, 6, 8, 9]]])
anc_proto.count_by_chw('anc_edd_mnth', 'person_id', ['lmp_group.weeks_pregnant', [36]])
anc_proto.count_by_chw('albendazole', 'person_id', ['immun-meds.albendazole_taken', ['yes']])
anc_proto.count_by_chw('daily_iron', 'person_id', ['immun-meds.daily_iron', ['yes']])
anc_proto.count_by_chw('tt_first_dose', 'person_id', ['immun-meds.tt_actual_first_dose', ['yes']])
anc.results = anc.concat_dataframes([anc_home.results, anc_group.results, anc_proto.results])
print(dt1, " - ", dt2)
return anc.results<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 14:22:07 2020
@author: anant
"""
from me_indicators_automation.case_form import CaseForm
def clean(form):
col_mapping = {"woman_ID":"person_id", "woman_at_home":"person_at_home"}
form.rename_columns(col_mapping)
form.strip_str('person_id')
form.filter_for_condition('person_at_home', 'yes') #Filter for person_at_home == yes
## Pregnancy Screening
def pss_metrics(file, dt1='2015-01-01', dt2='2050-01-01', content_type='text/csv'):
#file = './Data/pregnancy_screening.excel'
#dt1 = '2020-01-01'
#dt2 = '2020-03-31'
cols = ['chw_name','woman_at_home','woman_ID','last_visit','last_visit_nepali',
'agrees_for_service','urine_test','urine_test_positive',
'pregnancy_status','balanced_counseling.bcs_form.method_change',
'menopause','want_more_children', 'birth_gap', 'contraceptive_current',
'balanced_counseling.bcs_form.counseling.method_chosen1']
pss = CaseForm(filepath=file, cols=cols, filetype = content_type)
clean(pss)
pss.filter_by_date('last_visit', [dt1,dt2])
pss.remove_duplicates(sort_by=['person_id', 'last_visit'],dupl_subset=['person_id'])
pss.count_by_chw('elig_wm','person_id')
pss.count_by_chw('rcvd_pss','person_id',['agrees_for_service',['yes']])
pss.count_by_chw('upt_done','person_id',['urine_test',['positive','negative','indetermined','test_malfunctioning']])
pss.count_by_chw('upt_pos','person_id',['urine_test',['positive']])
pss.count_by_chw('new_preg','person_id',['pregnancy_status',['pregnant']])
pss.count_by_chw('bcs_agree','person_id',['balanced_counseling.bcs_form.method_change',['yes']])
pss.count_by_chw('menop','person_id',['menopause',['yes']])
pss.count_by_chw('more_child','person_id',['want_more_children',['yes']])
pss.count_by_chw('birth_gap','person_id',['birth_gap',['two_or_more_years']])
pss.count_by_chw('hystectomy','person_id',['contraceptive_current',['hystectomy']])
pss.count_by_chw('sterilization','person_id',['contraceptive_current',['male_sterilization','female_sterilization']])
pss.count_by_chw('pills','person_id',['contraceptive_current',['pills']])
pss.count_by_chw('dipo','person_id',['contraceptive_current',['Dipo']])
pss.count_by_chw('iud','person_id',['contraceptive_current',['iud']])
pss.count_by_chw('implants','person_id',['contraceptive_current',['implants']])
#FIX BELOW
#pss.count_by_chw('refer','person_id',['contraceptive_current',['implants']])
return pss.results
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 30 16:01:07 2019
@author: anant
"""
#Set up logger
import logging
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO)
logger = logging.getLogger()
#import modules
import requests
import datetime as dt
from requests.auth import HTTPBasicAuth
from pandas.io.json import json_normalize
import pandas as pd
import numpy as np
from multiprocessing.pool import ThreadPool
###############################################################################
# FUNCTIONS
###############################################################################
def get_json(feed_url):
"""Takes a odata feed url, and returns feed data as json dictionary"""
username = '<EMAIL>'
api = '<KEY>'
response = requests.get(
feed_url,
auth=HTTPBasicAuth(username, api))
return response.json()
def load_data_helper(args):
"""A helper function for passing multiple args to load_data()"""
return load_data(*args)
def load_data(name, feed_url):
"""Takes the name and url of odata feed, and returns a dataframe"""
logger.info('Start downloading %s data', name)
res_json = get_json(feed_url)
df = json_normalize(res_json, 'value')
while '@odata.nextLink' in res_json:
logger.debug('%d rows of %s data downloaded...', len(df.index), name)
nextLink = res_json['@odata.nextLink']
res_json = get_json(nextLink)
df = pd.concat([df, json_normalize(res_json, 'value')])
logger.info('Finished downloading %s data (%d rows)', name, len(df.index))
df = df.replace({'---':np.NaN,'':np.NaN})
return df
def drop_closed_and_duplicates(df,unique_id,name,date):
"""Takes a dataframe, uniuqe id and date by which to sort data, then drops
closed cases and any duplicates keeping the latest record based on date"""
df = df[df['closed']==False]
df = df.sort_values(
[unique_id,name,date], ascending = True).drop_duplicates(
subset=[unique_id,name], keep='last')
return df
def remove_spaces(string):
"""Takes a string, and returns the string without spaces"""
return string.str.replace(" ","")
def convert_to_Int64(df, cols):
"""Takes a dataframe, and a list of its columns, then converts the columns
to numeric, then to dtype Int64 before returning the dataframe"""
for col in cols:
df[col] = pd.to_numeric(df[col], errors='coerce')
df = df.astype({col:'Int64'})
return df
# USE COMMENTED COD BLOCK BELOW FOR LOADING DATA FROM EXCEL FILES
#=============================================================================
#############################################################################
# GET DATA FROM CSV
#############################################################################
def read_xls_file(filename,*cols):
df = pd.read_excel(filename, sheet_name=0, index_col=None, usecols=cols,
na_values=['---'])
return df
house_data = read_xls_file('./Data/5. House Data Summary Report_upto Kartik.xlsx','chw_name','houseID','house_name',
'has_plate','last_modified_date','closed')
family_data=read_xls_file('./Data/3. Family Enrollment Monthly report_Bhadra 2076.xlsx',
'chw_name','familyID','family_head','last_modified_date','closed',
'enrollment_complete','family_female_non_residents','family_male_non_residents','family_female_residents','family_male_residents','residence_type')
individual_data = read_xls_file('./Data/4. Individual-Enrollment_Bhadra 2076.xlsx',
'chw_name','name_text','individualID','last_modified_date',
'closed','eligible_woman','anc','pdf_direct',
'pnc1','pnc2','child_under_2','post_delivery','imam_patient','cd_patient','surgery_patient','hypertension_screening','hypertension_screening_second_visit')
# =============================================================================
################################################################################
## GET DATA FROM FEED
################################################################################
#
## Define odata feed urls, and
#house_feed = ('https://www.commcarehq.org/a/possible-communityhealth/api'
# '/v0.5/odata/cases/80c2235dad967acac68ecf44936fd7b9/feed')
#family_feed = ('https://www.commcarehq.org/a/possible-communityhealth/api'
# '/v0.5/odata/cases/37ccd8b2ef546d4668a6c1bc6349e827/feed')
#individual_feed = ('https://www.commcarehq.org/a/possible-communityhealth/api'
# '/v0.5/odata/cases/80c2235dad967acac68ecf4493746164/feed')
#
## Create lists of names and feeds to pass into load_data()
#names = ['house','family','individual']
#feeds = [house_feed, family_feed, individual_feed]
#
## Use multiprocessing to download the feeds simultaneously
#results = ThreadPool(3).map(load_data_helper, zip(names,feeds))
#house_data = results[0]
#family_data = results[1]
#individual_data = results[2]
###############################################################################
# CLEAN DATA
###############################################################################
# Trim ID of spaces
house_data['houseID']= remove_spaces(house_data['houseID'])
family_data['familyID']= remove_spaces(family_data['familyID'])
individual_data['individualID']= remove_spaces(individual_data['individualID'])
logger.info("Spaces in ID's trimmed")
# Sort by last_modified_date and delete duplicate houseIDs,
## keeping the row with latest last_modified_date
house_data = drop_closed_and_duplicates(house_data,'houseID','house_name',
'last_modified_date')
family_data = drop_closed_and_duplicates(family_data,'familyID','family_head',
'last_modified_date')
individual_data = drop_closed_and_duplicates(individual_data,'individualID','name_text',
'last_modified_date')
logger.info("Closed cases and duplicate cases removed")
# Clean residence_type to same type of value
family_data['residence_type'] = family_data['residence_type'].map({1:1,2:2,
3:3,'single':1,'primary':2,'secondary':3})
# Convert numeric columns to Int64
family_data = convert_to_Int64(
family_data, ['residence_type','family_female_non_residents','family_male_non_residents','family_female_residents','family_male_residents'])
individual_data = convert_to_Int64(
individual_data,['eligible_woman','anc','pdf_direct','pnc1','pnc2',
'child_under_2'])
logger.info("Data cleaned")
###############################################################################
# CALCULATE
###############################################################################
# Calculate number of individuals receiving service, and convert to Int64
individual_data['receiving_service'] = individual_data[['eligible_woman',
'anc','pdf_direct','pnc1','pnc2','child_under_2','post_delivery','imam_patient','cd_patient','surgery_patient','hypertension_screening','hypertension_screening_second_visit']].sum(axis=1)>0
individual_data = convert_to_Int64(individual_data, ['receiving_service'])
# Get indicators for house data
house_indicators = pd.crosstab(
house_data['chw_name'], house_data['has_plate']).join(
house_data.groupby('chw_name').agg(
houses_registered=('houseID','count'))).reset_index()
house_indicators.rename(
columns = {'no':'no_plate', 'yes':'has_plate'}, inplace = True)
logger.info("Indicators for house case data calculated")
# Get indicators for family data
family_indicators = pd.crosstab(family_data['chw_name'],
family_data['enrollment_complete']).join(
pd.crosstab(family_data['chw_name'],
family_data['residence_type'])).join(
family_data.groupby(['chw_name']).agg(
families_registered=('familyID', 'count'),
tot_res_male=('family_male_residents', 'sum'),
tot_res_fem=('family_female_residents', 'sum'),
tot_non_res_male=('family_male_non_residents', 'sum'),
tot_non_res_fem=('family_female_non_residents', 'sum')
)).reset_index()
family_indicators.rename(
columns = {'no':'enroll_not_complete', 'yes':'enroll_complete',
1: 'Single', 2: 'Primary', 3: 'Secondary'}, inplace = True)
family_indicators['tot_female_members'] = family_indicators['tot_res_fem'] + family_indicators['tot_non_res_fem']
family_indicators['tot_male_members'] = family_indicators['tot_res_male'] + family_indicators['tot_non_res_male']
logger.info("Indicators for family case data calculated")
# Get indicators for individual data
individual_indicators = individual_data.groupby(['chw_name']
).agg(individuals_registered=('individualID','count'),
eligible_women=('eligible_woman','sum'),
anc=('anc','sum'),
pdf_direct=('pdf_direct','sum'),
pnc1=('pnc1','sum'),
pnc2=('pnc2','sum'),
child_under_2=('child_under_2','sum'),
post_delivery=('post_delivery','sum'),
imam_patient=('imam_patient','sum'),
cd_patient=('cd_patient','sum'),
surgery_patient=('surgery_patient','sum'),
hypertension_screening=('hypertension_screening','sum'),
hypertension_screening_second_visit=('hypertension_screening_second_visit','sum'),
receiving_service=('receiving_service','sum')
).reset_index()
logger.info("Indicators for individual case data calculated")
###############################################################################
# OUTPUT
###############################################################################
# Create dataframe merging house, family, and individual indicators
me_indicators = house_indicators.merge(
family_indicators,on='chw_name',how='left').merge(
individual_indicators,on='chw_name', how='left')
# Reorder columns
me_indicators = me_indicators[[
'chw_name', 'houses_registered', 'has_plate', 'no_plate',
'families_registered', 'enroll_complete', 'enroll_not_complete',
'Single', 'Primary', 'Secondary','tot_res_fem', 'tot_res_male','tot_female_members','tot_male_members',
'individuals_registered', 'receiving_service', 'eligible_women', 'anc',
'pdf_direct', 'pnc1', 'pnc2', 'child_under_2','post_delivery','imam_patient','cd_patient','surgery_patient','hypertension_screening','hypertension_screening_second_visit']]
#Output to a csv file
#=============================================================================
me_indicators.to_csv('./Output/'+dt.datetime.today().strftime('%m-%d-%Y %H%M%S')+'.csv', index=False)
logger.info("csv file generated")
# =============================================================================
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 19:56:07 2020
@author: anant
"""
from flask import Flask
app = Flask(__name__)
import me_indicators_automation.views
if __name__ == '__main__':
#app.run()
app.run(debug=True)
|
8283f09616db765a48ca057783933db0c706df58
|
[
"Markdown",
"Python"
] | 13 |
Python
|
anantraut/me_indicators_automation
|
2c26459286f391aa9e1ae12b0e84d11e1811a7a0
|
842b076ee3f81cc651cc627411a9ebcc78b0acc2
|
refs/heads/master
|
<file_sep>const fs = require("fs");
const readline = require("readline");
const google = require("googleapis");
const googleAuth = require("google-auth-library");
const axios = require("axios");
const moment = require("moment");
const calendar = google.calendar("v3");
let rateLimitTimeout = 333; // in milliseconds
let rateExceededDelay = 2; // in minutes
const updateInterval = 30; // in minutes
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-nodejs-quickstart.json
const SCOPES = ["https://www.googleapis.com/auth/calendar"];
const TOKEN_DIR =
(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) +
"/.credentials/";
const TOKEN_PATH = TOKEN_DIR + "calendar-nodejs-quickstart.json";
// Load client secrets from a local file.
fs.readFile("client_secret.json", function processClientSecrets(err, content) {
if (err) {
console.info("Error loading client secret file: " + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Google Calendar API.
authorize(JSON.parse(content), refreshInterval);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
authorize = (credentials, callback) => {
const clientSecret = credentials.installed.client_secret;
const clientId = credentials.installed.client_id;
const redirectUrl = credentials.installed.redirect_uris[0];
const auth = new googleAuth();
let oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
};
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
getNewToken = (oauth2Client, callback) => {
const authUrl = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: SCOPES
});
console.info("Authorize this app by visiting this url: ", authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Enter the code from that page here: ", function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.info("Error while trying to retrieve access token", err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
};
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
storeToken = token => {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != "EEXIST") {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.info("Token stored to " + TOKEN_PATH);
};
// This function is used to refresh the events on a given interval
refreshInterval = oauth2Client => {
console.info("");
console.info("===============================");
console.info("Calendar syncing tool started");
console.info("===============================");
// This makes a call to sunmountain center to get the list of reservations
// It then creates an array of the room names that are currently on the reservations list
// Most of the code is to remove the duplicate room names
axios
.get(
`https://sunmountaincenter.secure.retreat.guru/api/v1/registrations?token=${process.env.RETREAT_GURU_TOKEN}limit=0&min_stay=${moment()
.subtract(3, "days")
.format("YYYY-MM-DD")}&max_stay=${moment()
.add(6, "months")
.format("YYYY-MM-DD")}`
)
.then(res => {
const registrations = res.data;
console.info(
"Number of registration from retreat guru: %s",
registrations.length
);
let seenRoom = {};
const roomList = res.data
.filter(registration => {
if (seenRoom[registration.room] !== true) {
seenRoom[registration.room] = true;
return registration.room;
}
})
.map(registration => {
return registration.room;
});
calendar.calendarList.list(
{
auth: oauth2Client,
maxResults: 50
},
(err, response) => {
if (err) {
console.info("Error while retrieving calendar list: %s", err);
return;
}
const calendarList = response.items;
const primary = calendarList.filter(
calendar => {
if (
calendar.primary
) {
return calendar;
}
}
);
const primaryCalendar = primary[0];
// Once we get the room names we map over the list to refresh the events for each room
// refreshMaster is a function that places all of the reservations into a single calendar
// regreshMaster is commented out because it wasn't necessary and we kept hitting Google's Rate limit
// refreshEvents is a function that places all of the reseravtions into calendars organized by room name.
// For example a if we got a room names "Room #2" from Retreat Guru then it would have it's own calendar with all events under that name placed there
// refreshMaster(oauth2Client, registrations, primaryCalendar, () => {
refreshEvents(oauth2Client, calendarList, registrations, roomList, 0);
// });
}
);
});
};
refreshMaster = (oauth2Client, registrations, primaryCalendar, callback) => {
let calendarId = primaryCalendar.id;
let calendarName = primaryCalendar.summary;
listEvents(oauth2Client, calendarId, "primary", (events, skipTwo) => {
if (skipTwo) {
// second reason to skip creating a calendar is if it already exists
skip = skipTwo;
}
deleteEvents(oauth2Client, events, calendarId, quotaExceeded => {
createEvents(
oauth2Client,
registrations,
calendarId,
calendarName,
true,
quotaExceeded => {
callback();
}
);
});
});
};
refreshEvents = (
oauth2Client,
calendarList,
registrations,
roomList,
index
) => {
const roomName = roomList[index];
let calendarId = "";
let calendarName = "";
calendarList.map(calendar => {
if (calendar.summary === roomName) {
calendarId = calendar.id;
calendarName = calendar.summary;
}
});
let skip = false;
if (calendarName && calendarId) {
skip = true; // if these values exist then skip creating a calendar because it already exists
}
listEvents(oauth2Client, calendarId, roomName, (events, skipTwo) => {
if (skipTwo) {
// second reason to skip creating a calendar is if it already exists
skip = skipTwo;
}
createCalendar(
oauth2Client,
roomName,
skip,
(newCalendarId, quotaExceeded) => {
if (newCalendarId) {
calendarId = newCalendarId;
}
deleteEvents(oauth2Client, events, calendarId, quotaExceeded => {
createEvents(
oauth2Client,
registrations,
calendarId,
calendarName,
false,
quotaExceeded => {
if (index < roomList.length - 1) {
setTimeout(() => {
refreshEvents(
oauth2Client,
calendarList,
registrations,
roomList,
index + 1
);
}, rateLimitTimeout);
} else {
console.info("===============================");
console.info("Next update in %s minutes", updateInterval);
console.info("===============================");
setTimeout(() => {
console.info("");
refreshInterval(oauth2Client);
}, 1000 * 60 * updateInterval);
}
}
);
});
}
);
});
};
/**
* Lists up to 200 events on the user's primary calendar.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
listEvents = (auth, calendarId, roomName, callback) => {
calendar.events.list(
{
auth: auth,
calendarId: calendarId,
maxResults: 200,
singleEvents: true,
orderBy: "startTime"
},
function(err, response) {
setTimeout(() => {
//set timeout for every new call to google to stay under rate limit
if (err) {
console.info("Error while retrieving event list: " + err);
callback(null, false);
return;
}
const events = response.items;
if (events.length == 0) {
console.info(
`Number of events found in Google Calendar for ${roomName}: ${
events.length
}`
);
callback(null, true);
} else {
console.info(
`Number of events found in Google Calendar for ${roomName}: ${
events.length
}`
);
callback(events, true);
}
}, rateLimitTimeout);
}
);
};
createCalendar = (auth, roomName, skip, callback) => {
if (skip) {
callback();
} else {
calendar.calendars.insert(
{
auth: auth,
resource: {
summary: roomName
}
},
function(err, response) {
setTimeout(() => {
//set timeout for every new call to google to stay under rate limit
if (err) {
console.info("Error while creating a calendar: " + err);
if (err.errors[0].reason === "quotaExceeded") {
callback(null, true);
}
return;
}
console.info("Calendar created for: " + response.summary);
callback(response.id);
}, rateLimitTimeout);
}
);
}
};
deleteEvents = (auth, events, calendarId, callback) => {
if (events) {
deleteEvent(auth, events, calendarId, callback, 0);
} else {
console.info("Skip deleting events for the given room name");
callback();
}
};
deleteEvent = (auth, events, calendarId, callback, index) => {
if (events.length > 0) {
calendar.events.delete(
{
auth: auth,
calendarId: calendarId,
eventId: events[index].id
},
(err, response) => {
setTimeout(() => {
//set timeout for every new call to google to stay under rate limit
if (err) {
if (err.code === 403) {
rateExceededDelay = rateExceededDelay * 2;
console.info(
"* Next event delayed for: %s minutes",
rateExceededDelay
);
setTimeout(() => {
deleteEvent(auth, events, calendarId, callback, index);
}, 1000 * 60 * rateExceededDelay);
}
} else if (index < events.length - 1) {
if (rateExceededDelay > 2) {
rateExceededDelay = rateExceededDelay / 2;
}
deleteEvent(auth, events, calendarId, callback, index + 1);
} else {
console.info("- Deleted all events");
if (rateExceededDelay > 2) {
rateExceededDelay = rateExceededDelay / 2;
}
callback();
}
}, rateLimitTimeout);
}
);
} else {
callback();
}
};
createEvents = (
auth,
registrations,
calendarId,
calendarName,
calendarPrimary,
callback
) => {
// create a list of reservations for the given room
const shortList = registrations.filter(registration => {
if (registration.room === calendarName || calendarPrimary) {
if (registration.room_id !== 0) {
return true;
}
}
return false;
});
if (shortList.length > 0) {
process.stdout.write("- Number of events created: 0");
createEvent(shortList, auth, calendarId, calendarName, 0, callback);
} else {
callback();
}
};
arrivalTimeframe = registration => {
if (registration.questions.arrival_timeframe.startsWith("200")) {
return moment(`${registration.start_date} 13:00:00.000`).format();
} else if (registration.questions.arrival_timeframe.startsWith("230")) {
return moment(`${registration.start_date} 13:30:00.000`).format();
} else if (registration.questions.arrival_timeframe.startsWith("300")) {
return moment(`${registration.start_date} 14:00:00.000`).format();
} else if (registration.questions.arrival_timeframe.startsWith("330")) {
return moment(`${registration.start_date} 14:30:00.000`).format();
} else {
return moment(`${registration.start_date} 13:00:00.000`).format();
}
};
createEvent = (
registrations,
auth,
calendarId,
calendarName,
index,
callback
) => {
const event = {
summary:
registrations[index].program === "Personal Booking"
? `${registrations[index].room} - ${registrations[index].first_name} ${
registrations[index].last_name
} for B&B`
: `${registrations[index].room} - ${registrations[index].program} - ${
registrations[index].first_name
} ${registrations[index].last_name} for retreats`,
location: `328 El Paso Blvd`,
description: description(registrations[index]),
start: {
dateTime: arrivalTimeframe(registrations[index]),
timeZone: "America/Denver"
},
end: {
dateTime: moment(`${registrations[index].end_date} 23:00:00.000`)
.subtract(1, "days")
.format(),
timeZone: "America/Denver"
},
recurrence: []
};
calendar.events.insert(
{
auth: auth,
calendarId: calendarId,
resource: event
},
(err, event) => {
setTimeout(() => {
//set timeout for every new call to google to stay under rate limit
if (err) {
process.stdout.write("\n");
console.info(
"There was an error contacting the Calendar service: " + err
);
if (err.code === 403) {
rateExceededDelay = rateExceededDelay * 2;
console.info(
"* Next event delayed for: %s minutes",
rateExceededDelay
);
setTimeout(() => {
createEvent(
registrations,
auth,
calendarId,
calendarName,
index,
callback
);
}, 1000 * 60 * rateExceededDelay);
}
} else if (index < registrations.length - 1) {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
process.stdout.write("- Number of events created: " + (index + 1));
if (rateExceededDelay > 2) {
rateExceededDelay = rateExceededDelay / 2;
}
createEvent(
registrations,
auth,
calendarId,
calendarName,
index + 1,
callback
);
} else {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
process.stdout.write("- Number of events created: " + (index + 1));
process.stdout.write("\n");
console.info("- Created all events");
if (rateExceededDelay > 2) {
rateExceededDelay = rateExceededDelay / 2;
}
callback();
}
}, rateLimitTimeout);
}
);
};
description = registration => {
let description = "";
description += `${registration.nights} Night${isPlural(registration.nights)}`;
Object.keys(registration.questions).map(key => {
if (
registration.questions[key] !== "" &&
typeof registration.questions[key] !== "object"
) {
description += `\n${formatKey(key)}: ${registration.questions[key]}`;
}
});
return description;
};
formatKey = key => {
let newKey = key.replace("_", " ");
newKey = toTitleCase(newKey);
return newKey;
};
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
isPlural = numOfNights => {
if (numOfNights > 1) {
return "s";
} else {
return "";
}
};
<file_sep># sunmountain
This project allows users to sync Retreat Guru with Google Calendar.
## Start the App
Add a retreat guru token to your environment variables
Type the following inside the project root directory
`node app.js`
This will start Google's OAuth authenticatio process allowing you to communicate with Google Calendar
You may also want to check out this link https://developers.google.com/calendar/quickstart/nodejs
|
3963e154004268ef103a489a73e343f026c46b0c
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
Flux-Teck/calendar-syncing-tool
|
00050ae6e0f3da5ee83a455cef71d8519d1ad217
|
21d5b060d455f6cc0a99a7e5fcb34046f2719599
|
refs/heads/master
|
<repo_name>rhoden23/Yelp<file_sep>/Yelp/BusinessDetailViewController.swift
//
// BusinessDetailViewController.swift
// Yelp
//
// Created by <NAME> on 10/21/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import MapKit
class BusinessDetailViewController: UIViewController {
@IBOutlet weak var businessImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ratingImageView: UIImageView!
@IBOutlet weak var categoriesLabel: UILabel!
@IBOutlet weak var closedLabel: UILabel!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var reviewCountLabel: UILabel!
@IBOutlet weak var isClosedLabel: UILabel!
var business:Business!
override func viewDidLoad() {
super.viewDidLoad()
businessImageView.setImageWith(business.imageURL!)
nameLabel.text = business.name
ratingImageView.image = business.ratingImage
categoriesLabel.text = business.categories
reviewCountLabel.text = "\(business.reviewCount!) Reviews"
addAnnotationAtAddress(address: business.address!, title: business.name!)
if let isClosed = business.isClosed {
if isClosed {
isClosedLabel.text = "Opens Today"
isClosedLabel.textColor = UIColor.green
}
}
}
func goTo(location:CLLocation) {
let span = MKCoordinateSpan(latitudeDelta: 0.001, longitudeDelta: 0.001)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: false)
}
func addAnnotationAtAddress(address: String, title: String) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
if let placemarks = placemarks {
if placemarks.count != 0 {
let coordinate = placemarks.first!.location!
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate.coordinate
annotation.title = title
self.goTo(location: coordinate)
self.mapView.addAnnotation(annotation)
}
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/Yelp/MapViewController.swift
//
// MapViewController.swift
// Yelp
//
// Created by <NAME> on 10/21/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController {
var businesses:[Business]!
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let locationCenter = CLLocation(latitude: 37.7833, longitude: -122.4167)
goTo(location: locationCenter)
for business in businesses{
if let address = business.address, let name = business.name {
addAnnotationAtAddress(address: address, title: name)
}
}
}
func goTo(location:CLLocation) {
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: false)
}
func addAnnotationAtAddress(address: String, title: String) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
if let placemarks = placemarks {
if placemarks.count != 0 {
let coordinate = placemarks.first!.location!
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate.coordinate
annotation.title = title
self.mapView.addAnnotation(annotation)
}
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/Yelp/BusinessesViewController.swift
//
// BusinessesViewController.swift
// Yelp
//
// Created by <NAME> on 4/23/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class BusinessesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UIScrollViewDelegate {
var isMoreDataLoading = false
var currentOffset = 0
var businesses: [Business]!
var selectedBusiness: Business?
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 120
}
}
override func viewDidLoad() {
super.viewDidLoad()
Business.searchWithTerm(term: "boba", completion: { (businesses, error) -> Void in
self.businesses = businesses
if let businesses = businesses {
for business in businesses {
self.tableView.reloadData()
print(business.name!)
print(business.address!)
}
}
}
)
createSearchBar()
/* Example of Yelp search with more search options specified
Business.searchWithTerm(term: "Restaurants", sort: .distance, categories: ["asianfusion", "burgers"]) { (businesses, error) in
self.businesses = businesses
for business in self.businesses {
print(business.name!)
print(business.address!)
}
}
*/
}
func createSearchBar() {
let searchBar = UISearchBar()
searchBar.delegate = self
searchBar.placeholder = "Yelp Search"
self.navigationItem.titleView = searchBar
}
// MARK: - UITableView datasource and delegate methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return businesses?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BusinessCell") as! BusinessCellTableViewCell
cell.business = businesses[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedBusiness = businesses[indexPath.row]
performSegue(withIdentifier: "ShowBusinessDetail", sender: self)
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - UIScrollView Delegate methods
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (!isMoreDataLoading) {
// Calculate the position of one screen length before the bottom of the results
let scrollViewContentHeight = tableView.contentSize.height
let scrollOffsetThreshold = scrollViewContentHeight - tableView.bounds.size.height
// When the user has scrolled past the threshold, start requesting
if (scrollView.contentOffset.y > scrollOffsetThreshold && tableView.isDragging) {
isMoreDataLoading = true
// Load more results
loadMoreData()
}
}
}
func loadMoreData() {
currentOffset+=20
Business.searchWithTerm(term: "boba",offset:currentOffset,completion: { (businesses, error) -> Void in
self.isMoreDataLoading = false
self.businesses.append(contentsOf:businesses!)
if let businesses = businesses {
for business in businesses {
self.tableView.reloadData()
print(business.name!)
print(business.address!)
}
}
}
)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
switch(identifier) {
case "ShowMap":
if let dvc = segue.destination as? MapViewController {
dvc.businesses = self.businesses
}
case "ShowBusinessDetail":
if let dvc = segue.destination as? BusinessDetailViewController {
dvc.business = selectedBusiness
}
default:
break
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
2a01bcf7323749351fbcfb2ebee411417bf0e36b
|
[
"Swift"
] | 3 |
Swift
|
rhoden23/Yelp
|
8b094c32928d1f4cce447d8697fba9ac022f885e
|
577060ec5d35390dfc5b86d1021f4d56d03d5526
|
refs/heads/master
|
<repo_name>douglasjordan2/Javascript-Document-Creator<file_sep>/html:css creator/js/index.js
// creates html elements
const create = name => {
return document.createElement(name);
}
// an object to hold the basic html doc
const doc = {
html: document.querySelector('html'),
head: create('head'),
title: create('title'),
stylesheet: create('style'),
body: create('body')
}
// function to append elements to parent element
const append = (parent, child) => {
return parent.appendChild(child);
}
const html = doc.html;
const head = doc.head;
const stylesheet = doc.stylesheet;
const title = doc.title;
const body = doc.body;
append(html, head);
append(head, title);
append(html, body);
// creates a stylesheet
const sheet = (function() {
const style = stylesheet;
append(style, document.createTextNode(""));
append(head, style);
return style.sheet;
})();
// object to hold styles
const styles = {
'*': {
name: '*',
rules: 'box-sizing: border-box;'
},
'body': {
name: 'body',
rules: 'background-color: black;'
}
};
// adds an id to an html element
const addId = (element, idname) => {
return element.id = idname;
}
// get an element by its id
const getId = id => {
return document.getElementById(id);
}
// adds a class
const addClass = (element, cssclass) => {
return element.classList.add(cssclass)
}
// get an array of elements by class name
const getClassArr = cssclass => {
return document.getElementsByClassName(cssclass);
}
// updates the html content
const addHtml = (element, content) => {
return element.innerHTML = `${content}`;
}
// example of creating an html element adding id, class, and content
doc.square = create('div');
const square = doc.square;
append(body, square);
addId(square, 'square');
addClass(square, 'square');
addHtml(square, "<h1>I am a red square</h1>")
// css specificity still applies, uncomment to see
/*
styles['square-id'] = {
name: '#square',
rules: 'background-color: blue; margin: 0 auto;'
}
*/
// updating html, uncomment
/*
addHtml(square, "<h1>I am now blue</h1>");
*/
// adding style rules
styles['square-class'] = {
name: '.square',
rules: 'height: 700px; width: 700px; background-color: red;'
}
// updating the body color, even though the rule was already declared. uncomment.
/*
styles['body'].rules += "background-color: green;"
*/
// keep at bottom of page so rules are already added and updated//
// function that inserts styling rules
const applyStyles = obj => {
sheet.insertRule(`${obj.name} {${obj.rules}}`);
}
// runs the function to apply all style rules
for(let i = 0; i < Object.values(styles).length; i++) {
applyStyles(Object.values(styles)[i]);
}<file_sep>/README.md
# Javascript-Document-Creator
|
520c23764018acdc55b856524feda2818a67ccc6
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
douglasjordan2/Javascript-Document-Creator
|
4cc20c274925304478c8afd33ecc0aafb1680cd8
|
1a2906d21743a0f4cbe491b6b58335d070345216
|
refs/heads/master
|
<repo_name>nbkr/nbkr-company-manager-payments<file_sep>/resources/post.php
<?php
$app->post('/', function() use ($app, $col) {
$vals = array();
$vals['deleted'] = false;
foreach($app->request->post() as $key => $value) {
if (! in_array($key, array('_id', 'deleted'))) {
$vals[$key] = $value;
}
}
// Checking if an internalcustomerid was given.
foreach (array('date', 'amount', 'account', 'description') as $i) {
if (! array_key_exists($i, $vals)) {
$app->response()->status(400);
$ret = array('message' => '"' . $i . '" was not given.',
'code' => 400);
echo json_encode($ret);
return;
}
}
// Checking if a payment with this data already exists.
$where = array();
foreach (array('date', 'amount', 'account', 'description') as $key) {
$where[$key] = $vals[$key];
}
$or = array();
array_push($or, array('deleted' => False));
array_push($or, array('deleted' => array('$exists' => False)));
$where['$or'] = $or;
if ($col->count($where) > 0) {
$app->response()->status(409);
$ret = array('message' => "That payment already exists.",
'code' => 409);
echo json_encode($ret);
return;
}
try {
$r = $col->insert($vals);
} catch(MongoCursorException $e) {
$app->response()->status(500);
$ret = array('message' => 'Insert failed.',
'code' => 500);
echo json_encode($ret);
}
$app->response()->status(200);
$ret = array('message' => 'Paymentrecord created.',
'code' => 200);
echo json_encode($ret);
});
?>
|
db002a46e81a29e9d448cf116daa7268800be6e0
|
[
"PHP"
] | 1 |
PHP
|
nbkr/nbkr-company-manager-payments
|
07aca9d86bcfee54be4cffcf8ca0ae39f97b2733
|
3b0f2aa121b38dd1889f0c277157f6a2f96e225c
|
refs/heads/master
|
<file_sep>using Business.Abstract;
using Business.Constants;
using Business.ValidationRules.FluentValidation;
using Core.Aspects.Autofac.Validation;
using Core.CrossCuttingConcerns.Validation;
using Core.Utilities.Results;
using DataAccess.Abstract;
using DataAccess.Concrete.InMemory;
using Entities.Concrete;
using Entities.DTOs;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Text;
namespace Business.Concrete //Eğer Manager görürseniz bu iş katmanının somut sınıfı
{
public class ProductManager:IProductService //Bir iş sınıfı başka sınıfları newlemez.
{ //Constructor Injection yapıyoruz.
IProductDal _productDal; //IProductDal ı buraya constaructor yapısı olarak getirdik çünkü IProductDal DataAccess'in soyut nesnesidir.Ve Inmemory ,EntityFramework ile referansı vardır.
//Yani bu işlemi yaparak IProductDal ın içindeki metotları kullanabilir hale geldik.
public ProductManager(IProductDal productDal)
{
_productDal = productDal;
}
[ValidationAspect(typeof(ProductValidator))] //Add metodunu doğrula ProductValidator daki kuralları kullanarak.
public IResult Add(Product product)
{
//Business codes
//validation //eklenmesini istediğiniz nesne nin yapısı ile ilgili doğrulamayı yapan kodlar validation kodlarıdır.
//if (product.ProductName.Length<2)
//{
// //magic strings
// return new ErrorResult(Messages.ProductNameInvalid);
//}
//Business codes
_productDal.Add(product); //Add in başına void i silip IResult yazdığımız için artık bir şey dönmek zorundayız.Ancak _productDal.Add(product); buradaki Add kendisi bir void olduğu için başına return yazamıyoruz.
return new SuccessResult(Messages.ProductAdded); //Bu yüzden buraya return yazdık ve Result ın içindekileri döndürüyor.
}
public IDataResult<List<Product>>GetAll()
{
//iş kodları
//Yetkisi var mı? gibi soruları ve kuralları geçerse aşağıdaki kodları çalıştırır yani ürünleri şartı sağlarsa verir
if (DateTime.Now.Hour==1) //DateTime.Now.Hour bizim sistemimizin anlık saatini gösterir.//Bu kodda 22.00 dan 22.59 a kadar
{
return new ErrorDataResult<List<Product>>(Messages.MaintenanceTime); //Data döndürmüyoruz sadece mesaj verdik Prdo
}
return new SuccessDataResult<List<Product>>(_productDal.GetAll(),Messages.ProductsListed);
}
public IDataResult<List<Product>> GetAllByCategoryId(int id)
{
return new SuccessDataResult<List<Product>>(_productDal.GetAll(p => p.CategoryId == id));
}
public IDataResult<Product> GetById(int productId)
{
return new SuccessDataResult<Product>(_productDal.Get(p => p.ProductId == productId)); //SuccessDataResult içinde Product var.Onun da ctor una _productDal.Get(p => p.ProductId == productId) gönderiryorsun.
}
public IDataResult<List<Product>> GetByUnitPrice(decimal min, decimal max)
{
return new SuccessDataResult<List<Product>>(_productDal.GetAll(p => p.UnitPrice <= min && p.UnitPrice <= max));
}
public IDataResult<List<ProductDetailDto>> GetProductDetails()
{
return new SuccessDataResult<List<ProductDetailDto>>(_productDal.GetProductDetails());
}
}
}
<file_sep>using Business.Abstract;
using DataAccess.Abstract;
using Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Text;
namespace Business.Concrete
{
public class CategoryManager : ICategoryService
{
ICategoryDal _categoryDal; //İleride teknolojiyi değiştirirsek diye burada constructor injection yaptık.Bu şekilde bağımlılık oluşturduk
//Şu demek oluyor "Ben categoryManager olarak veri erişim katmanına bağlıyım ama biraz zayıf bağımlılığım var.
//Çünkü İnterface üzerinden referans üzerinden bağımlılığım var.DataAccess de istediğin kadar dolaş ama benim burdaki kurallarıma uy"
public CategoryManager(ICategoryDal categoryDal)
{
_categoryDal = categoryDal;
}
public List<Category> GetAll()
{
//İş Kodları
return _categoryDal.GetAll();
}
//Select * from Categories where CategoryId=3
public Category GetById(int categoryId)
{
return _categoryDal.Get(c => c.CategoryId == categoryId);
}
}
}
<file_sep>using Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Text;
namespace Business.Constants //Temel mesajlarımızı bu class içersine koyacağız.Bu class Nortwind projemize ait bu sebepten Core a yazmadık.Core a evrensel kodlar yazılır.
{
public static class Messages //Başında static vermemizin sebebi bu bir sabit ve sürekli new lenmesini istemiyoruz.Başında static olunca direk Messages. diyeceğiz ve uygulama hayatı boyunca tek (intıns)ı oluyor
{
public static string ProductAdded = "Ürün eklendi"; //Bu 2 satuırdaki değişkenleri pascal case yazdık çünkü başında public var.
public static string ProductNameInvalid = "Ürün ismi geçersiz";
public static string MaintenanceTime= "Sistem Bakımda";
public static string ProductsListed= "Ürünler Listelendi";
}
}
<file_sep>using Castle.DynamicProxy;
using Core.CrossCuttingConcerns.Validation;
using Core.Utilities.Interceptors;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Core.Aspects.Autofac.Validation
{
public class ValidationAspect : MethodInterception
{
private Type _validatorType;
public ValidationAspect(Type validatorType) //Attribute lara tipleri böyle atarız.
{
if (!typeof(IValidator).IsAssignableFrom(validatorType)) //Eğer kullanıcının verdiği validatorType bir IValidator degilse ona bu uyarıyı ver.
{
throw new System.Exception("Bu bir doğrulama sınıfı değil");
}
_validatorType = validatorType;
}
protected override void OnBefore(IInvocation invocation)
{
var validator = (IValidator)Activator.CreateInstance(_validatorType); //Activator.CreateInstance(_validatorType) burada Reflexion'dır (_validatorType ın bir İnstance sını oluşturur.).(Burada _validatorType örneğin bizim ProductValidator)
var entityType = _validatorType.BaseType.GetGenericArguments()[0]; //ProductValidatorun çalışma tipini bul. //ProductValidatorun BaseType 'ı gidip bakıldığında ( AbstractValidator<Product> ) ve bunun generic argümanlarında ilk ini bul.
var entities = invocation.Arguments.Where(t => t.GetType() == entityType); //Ve onun parametrelerini bul // ( invocation ) metot demek //Validatorun tipine eşit olan parametreleri bul.(ProductValidator un ki product dır) entityType bu sebepten var.//Çünkü Bir metotda birden fazla parametre olabilir,Birden fazla Validational da olabilir.
foreach (var entity in entities) //Herbir parametre yi tek tek gez (çünkü birden fazla parametre olabilir)
{
ValidationTool.Validate(validator, entity); //ValidationTool u kullanarak Validate et
}
}
}
}
|
879ce1526a89ab6754377635992875b0d78c0387
|
[
"C#"
] | 4 |
C#
|
djomolungma/MyFinalProject
|
9255f5b9daf6b9623756dda84c4ce1d0d27e63e2
|
e5f0c0c3f36728d5f4aa42303abfea867e3acab2
|
refs/heads/master
|
<file_sep>package com.dk.customservice.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SampleApiController {
@RequestMapping("/hello")
public @ResponseBody String hello(@RequestParam String user) {
return "Hello "+ user;
}
}
<file_sep># eureka-client-service app
## Build with maven
mvn clean install
## Docker command
docker build -t eureka-client-service:v1 .
## Run with Docker
docker run eureka-client-service:v1
## Run with Kubernetes using google cloud and use your porject.
## If you want run and validate
kubectl run eureka-client-service --image=eureka-client-service:v1
## Deploy spring boot using Kubernetes deployment file
kubectl create -f eureka-client-service-config.yaml
## Update deployment with v2 version
kubectl set image deployment/eureka-client-service eureka-client-service=eureka-client-service:v2
## Create multiple instances ( Replicas ) , below will create 3 instances of zuul proxy
kubectl scale deployment eureka-client-service --replicas=2
<file_sep>FROM openjdk:8
ENV APP_HOME=/app/springboot/
ADD ./target/eureka-client-service-1.0.0.jar ${APP_HOME}/app.jar
RUN chmod -R u+x ${APP_HOME} && \
chgrp -R 0 ${APP_HOME} && \
chmod -R g=u ${APP_HOME} /etc/passwd
USER 10001
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app/springboot/app.jar"]
EXPOSE 8765
|
fea1888a581dd12599b87d319ebebdc44f42e814
|
[
"Markdown",
"Java",
"Dockerfile"
] | 3 |
Java
|
dkudale/eureka-client-service
|
4d909db67232b2cce9532ec7594b83dee9640c4c
|
067c182dffc04b7ac88ef066f5bbc0b855256559
|
refs/heads/master
|
<repo_name>joker9357/Naive-Bayes-and-logistical-regression<file_sep>/main.py
# -*- coding: utf-8 -*-
from ParseFile import parse, test_vector
from Naive_Bayes import accuracy
from Logistical_Regression import preprocess, logic_accuracy
from ParseStopWord import cut_the_stop_word, adjust_vector
def main():
print("main function")
spam_word, spam_word_set, spam_count, ham_word, ham_word_set, ham_count, attribute, input_vector, total_set, \
spam_row, ham_row = parse('./train/spam', './train/ham')
print("finish parse")
naive_bayes_accuracy = accuracy(spam_count, spam_word, spam_word_set, ham_count, ham_word, ham_word_set, total_set)
print("finish Naive_Bayes")
weight_matrix = [0]*len(attribute)
preprocess(input_vector, weight_matrix, 0.1, 4)
test_matrix = test_vector(attribute, './test/spam', './test/ham')
logistic_accuracy = logic_accuracy(weight_matrix, test_matrix)
print(naive_bayes_accuracy, logistic_accuracy)
stop_index, spam_cut, ham_cut = cut_the_stop_word(spam_word_set, ham_word_set, total_set, attribute)
input_vector, test_matrix = adjust_vector(input_vector, test_matrix, stop_index)
naive_bayes_without_stop_word=accuracy(spam_count, spam_word, spam_word_set, ham_count, ham_word, ham_word_set, total_set, spam_cut, ham_cut)
weight_matrix = [0] * len(attribute)
preprocess(input_vector, weight_matrix, 0.1, 4)
logistic_without_stop_word_accuracy = logic_accuracy(weight_matrix, test_matrix)
print("finish main")
print(naive_bayes_without_stop_word, logistic_without_stop_word_accuracy)
if __name__ == "__main__": main()<file_sep>/Logistical_Regression.py
import math
def preprocess(input_vector, weight_matrix, learning_rate, lambda_input):
for iterator in range(2):
gradient = []
w0 = 0
for vector in input_vector:
sum_of_product = 0
for i in range(1, len(vector)):
sum_of_product=sum_of_product+weight_matrix[i-1]*vector[i]
try:
exp = math.exp(1.0*w0+sum_of_product)
gradient.append(vector[0]-(exp/(1+exp)))
except:
gradient.append(vector[0] - 1)
for j in range(len(weight_matrix)):
sum_all = 0
for i in range(len(input_vector)):
sum_all = sum_all + input_vector[i][j+1]*gradient[i]
weight_matrix[j] = weight_matrix[j]+(learning_rate*sum_all)-(learning_rate*lambda_input*weight_matrix[j])
print("finish preprocess")
return weight_matrix
def logic_accuracy(weight_matrix, test_matrix):
success = 0
count = 0
for vector in test_matrix:
count += 1
sum_of_result = 0
for i in range(1, len(vector)):
sum_of_result += weight_matrix[i-1]*vector[i]
if sum_of_result > 0 and vector[0] == 1:
success += 1
if sum_of_result < 0 and vector[0] == 0:
success += 1
return 1.0*success/count
print("finish logic_accuracy")
<file_sep>/ParseFile.py
import os
import collections
def parse(spam_path,ham_path):
print("parse function")
spam_lists, spam_count = getfile(spam_path)
ham_lists, ham_count = getfile(ham_path)
spam_data = get_data(spam_lists)
ham_data = get_data(ham_lists)
spam_word, spam_word_set, spam_row = calculate_the_number_of_word_in_this_set(spam_data)
ham_word, ham_word_set, ham_row = calculate_the_number_of_word_in_this_set(ham_data)
total_set = spam_word_set + ham_word_set
attribute, input_vector = inputvector(spam_word, spam_row, ham_word, ham_row,total_set)
return spam_word, spam_word_set, spam_count, ham_word, ham_word_set, ham_count, attribute, input_vector, total_set, \
spam_row, ham_row
def test_parse(path):
print("test parse")
lists, count = getfile(path)
data = get_data(lists)
return data
def getfile(path):
count = 0
lists = []
for filename in os.listdir(path):
filename_path = os.path.join(path, filename)
if not filename.startswith('.') and os.path.isfile(filename_path):
lists.append(filename_path)
count += 1
return lists, count
def get_data(lists):
data = []
for file in lists:
with open(file, 'r', encoding='utf-8', errors='ignore') as file_read:
d = file_read.read()
data.append(d)
return data
def calculate_the_number_of_word_in_this_set(data):
row=[]
word_in_this_fold = []
for text in data:
row.append(len(word_in_this_fold))
words_in_text = text.split()
for word in words_in_text:
if len(word) <= 1 or word == 'Subject:':
continue
word_in_this_fold.append(word)
word_set = collections.Counter(word_in_this_fold)
return word_in_this_fold, word_set, row
def inputvector(spam_word, spam_row, ham_word, ham_row, total_set):
attribute = list(total_set.keys())
length = len(attribute)
inputmatrix = []
for i in range(len(spam_row)):
if i+1 <= len(spam_row)-1:
text = spam_word[spam_row[i]:spam_row[i+1]]
else:
text = spam_word[spam_row[i]:]
text_counter = collections.Counter(text)
vector = [0]*length
for j in text_counter:
if j not in attribute:
continue
attribute_index = attribute.index(j)
vector[attribute_index] = text_counter[j]
vector.insert(0, 0)
inputmatrix.append(vector)
for i in range(len(ham_row)):
if i+1 <= len(ham_row)-1:
text = ham_word[ham_row[i]:ham_row[i+1]]
else:
text = ham_word[ham_row[i]:]
text_counter = collections.Counter(text)
vector = [0]*length
for j in text_counter:
attribute_index = attribute.index(j)
vector[attribute_index] = text_counter[j]
vector.insert(0, 1)
inputmatrix.append(vector)
return attribute, inputmatrix
def test_vector(attribute, spam_path, ham_path):
spam_lists, spam_count = getfile(spam_path)
ham_lists, ham_count = getfile(ham_path)
spam_data = get_data(spam_lists)
ham_data = get_data(ham_lists)
spam_word, spam_word_set, spam_row = calculate_the_number_of_word_in_this_set(spam_data)
ham_word, ham_word_set, ham_row = calculate_the_number_of_word_in_this_set(ham_data)
length = len(attribute)
test_matrix = []
for i in range(len(spam_row)):
if i+1 <= len(spam_row)-1:
text = spam_word[spam_row[i]:spam_row[i+1]]
else:
text = spam_word[spam_row[i]:]
text_counter = collections.Counter(text)
vector = [0]*length
for j in text_counter:
if j not in attribute:
continue
attribute_index = attribute.index(j)
vector[attribute_index] = text_counter[j]
vector.insert(0, 0)
test_matrix.append(vector)
for i in range(len(ham_row)):
if i+1 <= len(ham_row)-1:
text = ham_word[ham_row[i]:ham_row[i+1]]
else:
text = ham_word[ham_row[i]:]
text_counter = collections.Counter(text)
vector = [0]*length
for j in text_counter:
if j not in attribute:
continue
attribute_index = attribute.index(j)
vector[attribute_index] = text_counter[j]
vector.insert(0, 1)
test_matrix.append(vector)
return test_matrix
<file_sep>/Naive_Bayes.py
import math
from ParseFile import test_parse
def training(spam_count, spam_word, spam_word_set, ham_count, ham_word, ham_word_set, total_set, spam_cut=0, ham_cut=0):
spam_prior = math.log(1.0*spam_count/(spam_count+ham_count), 2)
ham_prior = math.log(1.0*ham_count/(spam_count+ham_count), 2)
spam_length = len(spam_word)-spam_cut
ham_length = len(ham_word)-ham_cut
total_length = len(total_set)
spam_dict = {}
ham_dict = {}
for i in spam_word_set:
num = spam_word_set[i]
p = 1.0*(num+1)/(spam_length+total_length)
spam_dict[i] = math.log(p, 2)
for i in ham_word_set:
num = ham_word_set[i]
p = 1.0*(num+1)/(ham_length+total_length)
ham_dict[i] = math.log(p, 2)
return spam_prior, ham_prior, spam_dict, ham_dict,total_length
def accuracy(spam_count, spam_word, spam_word_set, ham_count, ham_word, ham_word_set, total_set, spam_cut=0, ham_cut=0):
success = 0#number of right file
count = 0 #number of test file
spam_prior, ham_prior, spam_dict, ham_dict, total_length = training(spam_count, spam_word, spam_word_set, ham_count, ham_word, ham_word_set, total_set, spam_cut, ham_cut)
print("finish training")
spam_data = test_parse('./test/spam')
ham_data = test_parse('./test/ham')
for i in spam_data:
count+=1
p_s = spam_prior
p_h = ham_prior
word = calculate_the_number_of_word(i)
for j in range(len(word)):
if word[j] in spam_dict:
p_s += spam_dict[word[j]]
else:
p_s += 1.0*(math.log(1/(spam_count+total_length), 2))
if word[j] in ham_dict:
p_h += ham_dict[word[j]]
else:
p_h += 1.0*(math.log(1/(ham_count+total_length), 2))
if p_s > p_h:
success += 1
for i in ham_data:
count+=1
p_s = spam_prior
p_h = ham_prior
word = calculate_the_number_of_word(i)
for j in range(len(word)):
if word[j] in spam_dict:
p_s += spam_dict[word[j]]
else:
p_s += 1.0 * (math.log(1 / (spam_count + total_length), 2))
if word[j] in ham_dict:
p_h += ham_dict[word[j]]
else:
p_h += 1.0 * (math.log(1 / (ham_count + total_length), 2))
if p_s < p_h:
success += 1
print("finish Navie Bayes")
return 1.0*success/count
def calculate_the_number_of_word(data):
word_in_this_fold = []
words_in_text = data.split()
for word in words_in_text:
if len(word) <= 1 or word == 'Subject:':
continue
word_in_this_fold.append(word)
return word_in_this_fold
<file_sep>/ParseStopWord.py
import collections
def parse_stop_word():
path = './STOP_WORDS.txt'
with open(path, 'r', encoding='utf-8', errors='ignore') as file_read:
d = file_read.read()
data = d.split()
return data
print("finish parse stop word")
def cut_the_stop_word(spam_word_set, ham_word_set, total_set, attribute):
data = parse_stop_word()
# data = ['ello2', 'hello3']
spam_cut = 0
ham_cut = 0
stop_index = []
for word in data:
if word in spam_word_set:
spam_cut += spam_word_set[word]
del spam_word_set[word]
if word in ham_word_set:
ham_cut += ham_word_set[word]
del ham_word_set[word]
if word in total_set:
del total_set[word]
index = attribute.index(word)
stop_index += [index]
del attribute[index]
return stop_index, spam_cut, ham_cut
print("finish cut")
def adjust_vector(input_matrix, test_matrix, stop_index):
for input_vector in input_matrix:
for index in stop_index:
del input_vector[index+1]
for test_vector in test_matrix:
for index in stop_index:
del test_vector[index+1]
return input_matrix, test_matrix
|
4346d705453826b0d5a7efd3ba022b2501b2782f
|
[
"Python"
] | 5 |
Python
|
joker9357/Naive-Bayes-and-logistical-regression
|
d44e2e21f09376cef8519a97d35893a54fe5b3f6
|
d82d35ea4eb9b8336d0badce52b6eff4919022b9
|
refs/heads/master
|
<file_sep>using System;
using System.IO;
using Microsoft.Win32;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using QuickGraph;
using GraphSharp.Controls;
namespace GKS
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void InsertValuesFromFile(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "All files (*.*)|*.*";
if (ofd.ShowDialog() == true)
{
TextRange doc = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
using (FileStream fs = new FileStream(ofd.FileName, FileMode.Open))
{
if (System.IO.Path.GetExtension(ofd.FileName).ToLower() == ".txt")
doc.Load(fs, DataFormats.Text);
}
}
}
public void Calc(object sender, RoutedEventArgs e)
{
string rtbText = new TextRange(rtb.Document.ContentStart,
rtb.Document.ContentEnd).Text;
List<string> listOfOperaions = rtbText.Split(new[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries).ToList();
int cntFields = listOfOperaions.Count();
/*
if (cntFields > 5)
this.Width = this.Width + (cntFields - 5) * 75;
else
this.Width = 520;
*/
List<string>[] details = new List<string>[cntFields];
for (int i = 0; i < cntFields; i++)
details[i] = new List<string>();
List<string> listOfUnequeOperations = new List<string>();
int iter = 0;
foreach (string strOfOperation in listOfOperaions)
{
details[iter] = strOfOperation.Split(new char[] { ' ' }).ToList();
foreach (string s in details[iter])
if (listOfUnequeOperations.FindIndex(x => x == s) == -1)
listOfUnequeOperations.Add(s);
iter++;
}
#region OutInTextBlock
tbOut.Text = "Count of unique elements: " + listOfUnequeOperations.Count().ToString() + "\n";
//tbOut.Text += "Max element of help matrix: " + details.Max() + "\n";
/*
for (int i = 0; i < cntFields; i++)
{
foreach (int value in details[i])
{
tbOut.Text += value + " ";
}
tbOut.Text += "\n";
}
*/
#endregion
#region CreateHelpMatrix
int[,] helpMatrix = new int[cntFields, cntFields];
for (int i = 1; i < cntFields; i++)
{
for (int j = 0; j < i; j++)
{
int cntDifElements = 0;
foreach (string item in details[j])
{
if (details[i].FindIndex(x => x == item) == -1)
{
cntDifElements++;
}
}
foreach (string item in details[i])
{
if (details[j].FindIndex(x => x == item) == -1)
{
cntDifElements++;
}
}
helpMatrix[i, j] = listOfUnequeOperations.Count() - cntDifElements;
}
}
#endregion
/*
int[,] helpMatrix = new int[,] { {0,0,0,0,0 },
{3,0,0,0,0 },
{2,5,0,0,0 },
{4,5,3,0,0 },
{3,4,4,5,0 } };
*/
PrintHelpMatrix(helpMatrix, cntFields);
#region CreateGroup
List<int>[] groups = new List<int>[1];
//find group
int iterator = 0;
while (SumOfAllElements(helpMatrix, cntFields) != 0)
{
groups[iterator] = new List<int>();
int maxValue = 0;
List<int> maxI = new List<int>();
List<int> maxJ = new List<int>();
//fing max values
for (int i = 0; i < cntFields; i++)
{
for (int j = 0; j < i; j++)
{
if (helpMatrix[i, j] > maxValue)
{
maxI.Clear();
maxJ.Clear();
maxValue = helpMatrix[i, j];
maxI.Add(i);
maxJ.Add(j);
}
if ((helpMatrix[i, j] == maxValue) &&
(
(maxI.FindIndex(x => x == i) != -1) ||
(maxJ.FindIndex(x => x == j) != -1)
|| (maxI.FindIndex(x => x == j) != -1) ||
(maxJ.FindIndex(x => x == i) != -1)
))
{
maxI.Add(i);
maxJ.Add(j);
}
}
}
//clear help matrix
for (int i = 1; i < cntFields; i++)
{
for (int j = 0; j < i; j++)
{
if (
(maxI.FindIndex(x => x == i) != -1) ||
(maxJ.FindIndex(x => x == j) != -1)
)
{
helpMatrix[i, j] = 0;
}
}
}
foreach (var item in maxI)
if (groups[iterator].FindIndex(x => x == item) == -1
&& !FindElement(groups, iterator, item)
)
groups[iterator].Add(item);
foreach (var item in maxJ)
if (groups[iterator].FindIndex(x => x == item) == -1
&& !FindElement(groups, iterator, item)
)
groups[iterator].Add(item);
Array.Resize(ref groups, groups.Length + 1);
iterator++;
}
while (groups[iterator] == null || groups[iterator].Count() == 0)
{
Array.Resize(ref groups, groups.Length - 1);
iterator--;
}
#endregion
tbOut.Text += "\n Groups:";
PrintGroups(groups);
#region ClaryfingTheContentOfGroups
List<int> blockDetails = new List<int>();
for (int j = 0; j < groups.Length - 1; j++)
{
#region Sort Group
int maxLenght = 0;
int maxRow = 0;
int cntMaxGroup = 0;
List<int> indexMaxGroup = new List<int>();
for (int i = j; i < groups.Length; i++)
{
List<string> temp = new List<string>();
temp = FindUniqueOperationInGroup(groups[i], details);
if (maxLenght < temp.Count())
{
maxLenght = temp.Count();
maxRow = i;
cntMaxGroup = 0;
indexMaxGroup.Clear();
}
else if (maxLenght == temp.Count())
{
cntMaxGroup++;
indexMaxGroup.Add(i);
}
}
#region sorting groups with the same number of elements
if (cntMaxGroup > 1)
{
int maxDetail = 0;
for (int i = j; i < groups.Length; i++)
{
if (indexMaxGroup.FindIndex(x => x == i) != -1)
{
int cntDetail = 0;
for (int q = 0; q < details.Length; q++)
{
if (groups[i].FindIndex(x => x == q) == -1
&&
blockDetails.FindIndex(x => x == q) == -1)
{
int cntSameOperations = 0;
foreach (var operation in details[i])
if (FindUniqueOperationInGroup(groups[i], details).FindIndex(x => x == operation) != -1)
cntSameOperations++;
if (details[i].Count == cntSameOperations)
cntDetail++;
}
}
if (maxDetail < cntDetail)
{
maxDetail = cntDetail;
maxRow = i;
}
}
}
}
#endregion
//sort groups;
List<int> tmp = groups[maxRow];
groups[maxRow] = groups[j];
groups[j] = tmp;
#endregion
for (int i = 0; i < details.Length; i++)
{
if (groups[j].FindIndex(x => x == i) == -1
&&
blockDetails.FindIndex(x => x == i) == -1)
{
int cntSameOperations = 0;
foreach (var operation in details[i])
if (FindUniqueOperationInGroup(groups[j], details).FindIndex(x => x == operation) != -1)
cntSameOperations++;
if (details[i].Count == cntSameOperations)
{
foreach (var item in groups)
if (item.FindIndex(x => x == i) != -1)
item.Remove(i);
groups[j].Add(i);
}
}
}
foreach (var item in groups[j])
blockDetails.Add(item);
}
#endregion
#region Create Update Group
List<int>[] updateGroups = new List<int>[1];
int indexNewGroup = 0;
foreach (var group in groups)
{
if (group.Count() != 0)
{
updateGroups[indexNewGroup] = group;
Array.Resize(ref updateGroups, updateGroups.Length + 1);
indexNewGroup++;
}
}
Array.Resize(ref updateGroups, updateGroups.Length - 1);
#endregion
tbOut.Text += "\n\nNewGroup:";
PrintGroups(updateGroups);
#region Creating Adjacency Matrix
List<int[,]> listOfAdjacencyMatrix = new List<int[,]>();
tbOut.Text += "\n\nMatrix for groups:\n\n";
foreach (var group in updateGroups)
{
List<string> uniqueOperationForGroup = FindUniqueOperationInGroup(group, details);
int cntUniqueOperations = uniqueOperationForGroup.Count;
int[,] adjacencyMatrix = new int[cntUniqueOperations, cntUniqueOperations];
foreach (var detailId in group)
{
string[] operation = details[detailId].ToArray();
int cntOperationInDetail = operation.Length;
for (int i = 1; i < cntOperationInDetail; i++)
{
int trackIndex = uniqueOperationForGroup.FindIndex(x => x == operation[i]);
int prevIndex = uniqueOperationForGroup.FindIndex(x => x == operation[i - 1]);
adjacencyMatrix[prevIndex, trackIndex] = 1;
}
}
listOfAdjacencyMatrix.Add(adjacencyMatrix);
#region Print Matrix
tbOut.Text += "\n\t";
for (int i = 0; i < cntUniqueOperations; i++)
{
string[] operation = uniqueOperationForGroup.ToArray();
tbOut.Text += operation[i] + " ";
}
tbOut.Text += "\n";
for (int i = 0; i < cntUniqueOperations; i++)
{
string[] operation = uniqueOperationForGroup.ToArray();
tbOut.Text += operation[i] + "\t";
for (int j = 0; j < cntUniqueOperations; j++)
tbOut.Text += adjacencyMatrix[i, j] + " ";
tbOut.Text += "\n";
}
#endregion
}
#endregion
#region Create Graph
tabControl.Items.Clear();
for (int i = 0; i < updateGroups.Count(); i++)
{
var g = new BidirectionalGraph<object, IEdge<object>>();
List<string> uniqueOperationForGroup = FindUniqueOperationInGroup(updateGroups[i], details);
int cntUniqueOperations = uniqueOperationForGroup.Count;
foreach (var operation in uniqueOperationForGroup)
g.AddVertex(operation);
foreach (var detailId in updateGroups[i])
{
string[] operations = details[detailId].ToArray();
int cntOperationInDetail = operations.Length;
for (int j = 1; j < cntOperationInDetail; j++)
g.AddEdge(new Edge<object>(operations[j - 1], operations[j]));
}
GraphLayout gl = new GraphLayout();
gl.LayoutAlgorithmType = "KK";
gl.OverlapRemovalAlgorithmType = "FSA";
gl.Graph = g;
TabItem ti = new TabItem();
ti.Header = "Group" + (i + 1);
ti.Content = gl;
tabControl.Items.Add(ti);
}
#endregion
#region Create Models
List<List<string>>[] arrayOfGroupModels = new List<List<string>>[updateGroups.Length];
for (int i = 0; i < updateGroups.Length; i++)
{
List<string> uniqueOpeationInGroup = FindUniqueOperationInGroup(updateGroups[i], details);
List<List<string>> listOfModels = new List<List<string>>();
for (int j = 0; j < uniqueOpeationInGroup.Count; j++)
{
List<string> model = new List<string>();
model.Add(uniqueOpeationInGroup[j]);
listOfModels.Add(model);
}
arrayOfGroupModels[i] = listOfModels;
}
PrintModel(arrayOfGroupModels);
#endregion
#region group merger
PrintModel(arrayOfGroupModels);
#region circuit check
bool checkCircuit = false;
for (int i = 0; i < updateGroups.Length; i++)
{
int[,] currentAndjancencyMatrix = CreateAdjacencyMatrixToModel(arrayOfGroupModels[i], listOfAdjacencyMatrix[i], FindUniqueOperationInGroup(updateGroups[i], details));
for (int r = 0; r < currentAndjancencyMatrix.GetLength(0) && !checkCircuit; r++)
for (int c = 0; c < currentAndjancencyMatrix.GetLength(0) && !checkCircuit; c++)
{
if (currentAndjancencyMatrix[r, c] == 1)
{
List<int> usedIndex = new List<int>();
usedIndex.Add(c);
checkCircuit = CheckCircuit(ref arrayOfGroupModels[i], currentAndjancencyMatrix, usedIndex, r);
if (checkCircuit)
{
MergeModel(ref arrayOfGroupModels[i], r, c);
arrayOfGroupModels[i].RemoveAll(x => x.Count == 0);
}
}
}
if (checkCircuit)
{
checkCircuit = false;
i = -1;
}
}
#endregion
PrintModel(arrayOfGroupModels);
#region check on closed cirle
bool circleCheck = false;
for (int i = 0; i < updateGroups.Length; i++)
{
int[,] currentAndjancencyMatrix = CreateAdjacencyMatrixToModel(arrayOfGroupModels[i], listOfAdjacencyMatrix[i], FindUniqueOperationInGroup(updateGroups[i], details));
for (int r = 0; r < currentAndjancencyMatrix.GetLength(0) && !circleCheck; r++)
for (int c = 0; c < currentAndjancencyMatrix.GetLength(0) && !circleCheck; c++)
{
if (currentAndjancencyMatrix[r, c] == 1)
{
List<int> usedIndex = new List<int>();
usedIndex.Add(c);
circleCheck = CheckCirlce(ref arrayOfGroupModels[i], currentAndjancencyMatrix, usedIndex, r);
if (circleCheck)
{
MergeModel(ref arrayOfGroupModels[i], r, c);
arrayOfGroupModels[i].RemoveAll(x => x.Count == 0);
}
}
}
if (circleCheck)
{
circleCheck = false;
i = -1;
}
}
#endregion
PrintModel(arrayOfGroupModels);
#endregion
}
public int SumOfAllElements(int[,] array, int size)
{
int sum = 0;
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
sum += array[i, j];
return sum;
}
public int SumOfAllElementsInRow(int[,] ajdencecyMatrix, int row)
{
int sum = 0;
for (int i = 0; i < ajdencecyMatrix.GetLength(1); i++)
sum += ajdencecyMatrix[row, i];
return sum;
}
public bool FindElement(List<int>[] array, int size, int findValue)
{
for (int i = 0; i < size; i++)
if (array[i].FindIndex(x => x == findValue) != -1)
return true;
return false;
}
public void PrintHelpMatrix(int[,] helpMatrix, int cntFields)
{
tbOut.Text += "Help matrix:\n";
for (int i = 0; i < cntFields; i++)
{
for (int j = 0; j < cntFields; j++)
tbOut.Text += helpMatrix[i, j] + " ";
tbOut.Text += "\n";
}
}
public void PrintGroups(List<int>[] groups)
{
for (int i = 0; i < groups.Length; i++)
{
tbOut.Text += "\n " + (i + 1) + " - { ";
foreach (var item in groups[i])
tbOut.Text += (item + 1) + " ";
tbOut.Text += "}";
}
}
public void PrintModel(List<List<string>>[] arrayOfGroupModels)
{
for (int i = 0; i < arrayOfGroupModels.Length; i++)
{
tbOut.Text += "\nModels of " + (i + 1) + " group\n";
for (int p = 0; p < arrayOfGroupModels[i].Count; p++)
{
tbOut.Text += "Model " + (p + 1) + ": { ";
foreach (var operation in arrayOfGroupModels[i][p])
tbOut.Text += operation + " ";
tbOut.Text += "}\n";
}
}
}
public List<string> FindUniqueOperationInGroup(List<int> detailsInGroup, List<string>[] details)
{
List<string> uniqueOperationList = new List<string>();
foreach (var detailId in detailsInGroup)
foreach (var operation in details[detailId])
if (uniqueOperationList.FindIndex(x => x == operation) == -1)
uniqueOperationList.Add(operation);
return uniqueOperationList;
}
public int[,] CreateAdjacencyMatrixToModel(List<List<string>> listOfModels, int[,] adjacencyMatrix, List<string> uniqueOperationInGroup)
{
int[,] adjacencyMatrixToModel = new int[listOfModels.Count, listOfModels.Count];
//выбор модели
for (int i = 0; i < listOfModels.Count; i++)
//выбор операции
for (int j = 0; j < listOfModels[i].Count; j++)
{
int indexInAdjacencyMatrix = uniqueOperationInGroup.FindIndex(x => x == listOfModels[i][j]);
for (int iam = 0; iam < adjacencyMatrix.GetLength(0); iam++)
{
var currentUniqueValue = uniqueOperationInGroup[iam];
if (adjacencyMatrix[indexInAdjacencyMatrix, iam] == 1
&& listOfModels[i].FindIndex(x => x == currentUniqueValue) == -1)
{
int indexModel = -1;
foreach (var model in listOfModels)
if (model.FindIndex(x => x == currentUniqueValue) != -1)
indexModel = listOfModels.FindIndex(x => x == model);
adjacencyMatrixToModel[i, indexModel] = 1;
}
}
}
return adjacencyMatrixToModel;
}
public void MergeModel(ref List<List<string>> listOfModel, int indexToWrite, int indexToRemove)
{
while (listOfModel[indexToRemove].Count > 0)
{
listOfModel[indexToWrite].Add(listOfModel[indexToRemove].First());
listOfModel[indexToRemove].Remove(listOfModel[indexToRemove].First());
}
}
public bool CheckCircuit(ref List<List<string>> listOfModel, int[,] currentAndjancencyMatrix, List<int> usedIndexList, int mainIndex)
{
int indexOfParent = usedIndexList.Last();
if (SumOfAllElementsInRow(currentAndjancencyMatrix, indexOfParent) > 1) return false;
for (int i = 0; i < currentAndjancencyMatrix.GetLength(0); i++)
{
if (currentAndjancencyMatrix[indexOfParent, i] == 1)
{
if (currentAndjancencyMatrix[mainIndex, i] == 1)
{
MergeModel(ref listOfModel, indexOfParent, i);
return true;
}
else if (usedIndexList.FindIndex(x => x == i) == -1)
{
usedIndexList.Add(i);
if(CheckCircuit(ref listOfModel, currentAndjancencyMatrix, usedIndexList, mainIndex))
{
MergeModel(ref listOfModel, indexOfParent, i);
return true;
}
}
}
}
return false;
}
public bool CheckCirlce(ref List<List<string>> listOfModel, int[,] currentAndjancencyMatrix, List<int> usedIndexList, int mainIndex)
{
int indexOfParent = usedIndexList.Last();
for (int i = 0; i < currentAndjancencyMatrix.GetLength(0); i++)
{
if (currentAndjancencyMatrix[indexOfParent, i] == 1)
{
if (currentAndjancencyMatrix[i, mainIndex] == 1)
{
MergeModel(ref listOfModel, indexOfParent, i);
return true;
}
else if (usedIndexList.FindIndex(x => x == i) == -1)
{
usedIndexList.Add(i);
if(CheckCirlce(ref listOfModel, currentAndjancencyMatrix, usedIndexList, mainIndex))
{
MergeModel(ref listOfModel, indexOfParent, i);
return true;
}
}
}
}
return false;
}
}
}
|
df05dfe4ddd298496f3e2e6dcca9f26df5b044f7
|
[
"C#"
] | 1 |
C#
|
xtiche/GKS
|
a975d462e78ef0352815f141ddde972c437a320b
|
dfd23d751ddeeb0c583df631510930e9f2092553
|
refs/heads/main
|
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class RemoveLegacyFields extends Migration
{
/**
* Helper function to migrate old fields to new format
*/
private function updateToNewFormat(stdClass $user, Array $current_properties, String $old_value, String $new_value){
if (isset($user->$old_value) && strlen($user->$old_value) > 0 && !isset($current_properties[$new_value])) DB::table('user_properties')->insert(['user_id' => $user->id, 'field_id' => $new_value, 'value' => $user->$old_value]);
}
/**
* Helper function to remove fields
*/
private function removeFields(Array $fields){
foreach($fields as $field) DB::table('fields')->where('id', $field)->delete();
}
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Rename unused 'category' on 'fields'
Schema::table('fields', function (Blueprint $table) {
$table->renameColumn('category', 'icon');
});
Schema::table('fields', function (Blueprint $table) {
$table->string('icon')->nullable(false)->default('bs.gear')->change();
});
// Add items to 'fields' table
$fields = DB::table('fields');
$fields->insert(['id' => 'accounts.moonton.mobile_legends', 'name' => 'Mobile Legends: Bang Bang User ID', 'editable' => true]);
$fields->insert(['id' => 'accounts.riot.valorant', 'name' => 'Valorant User ID', 'editable' => true]);
$fields->insert(['id' => 'accounts.tencent.pubg_mobile', 'name' => 'PUBG Mobile User ID', 'editable' => true]);
$fields->insert(['id' => 'accounts.valve.dota2', 'name' => 'DOTA 2 User ID', 'editable' => true]);
try {
$fields->insert(['id' => 'binusian.community_service_hours', 'name' => 'Current BINUSIAN Community Service Hours', 'editable' => false]);
$fields->insert(['id' => 'binusian.regional', 'name' => 'BINUSIAN Regional / Campus Location', 'editable' => false]);
$fields->insert(['id' => 'binusian.sat', 'name' => 'Current BINUSIAN SAT points', 'editable' => false]);
$fields->insert(['id' => 'binusian.scu', 'name' => 'Current BINUSIAN SCU/IPK', 'editable' => false]);
$fields->insert(['id' => 'binusian.sdc.training.basic.om', 'name' => 'LKMM PRIME/"Optimizing Me" training date', 'editable' => false]);
$fields->insert(['id' => 'binusian.sdc.training.basic.taoc', 'name' => 'LKMM COMMET/"The Art of Communication" training date', 'editable' => false]);
$fields->insert(['id' => 'binusian.sdc.training.intermediate', 'name' => 'LKMM Intermediate" training date', 'editable' => false]);
$fields->insert(['id' => 'binusian.sdc.training.advanced', 'name' => 'LKMM Advanced" training date', 'editable' => false]);
$fields->insert(['id' => 'binusian.year', 'name' => 'BINUSIAN Year', 'editable' => false]);
} catch (Illuminate\Database\QueryException $e){
printf("BINUSIAN-related fields already exists!\n");
}
$fields->insert(['id' => 'contacts.phone', 'name' => 'Phone Number', 'editable' => true]);
$fields->insert(['id' => 'contacts.instagram', 'name' => 'Instagram registered username', 'editable' => true]);
$fields->insert(['id' => 'contacts.line', 'name' => 'LINE registered phone number or ID', 'editable' => true]);
$fields->insert(['id' => 'contacts.telegram', 'name' => 'Telegram registered phone number or username', 'editable' => true]);
$fields->insert(['id' => 'contacts.twitter', 'name' => 'Twitter registered username', 'editable' => true]);
$fields->insert(['id' => 'contacts.whatsapp', 'name' => 'WhatsApp registered phone number', 'editable' => true]);
$fields->insert(['id' => 'university.nim', 'name' => 'Student ID / NIM', 'editable' => false]);
$fields->insert(['id' => 'university.major', 'name' => 'Major / Study Program', 'editable' => false]);
// Update the Laravel's 'users' table
$query = DB::table('users')->select(['id', 'binusian', 'nim', 'phone', 'line', 'whatsapp', 'id_mobile_legends', 'id_pubg_mobile', 'id_valorant', 'major'])->get();
foreach ($query as $user){
// Get current user properties and map them into a new array
$query2 = DB::table('user_properties')->where('user_id', $user->id)->get();
$current_properties = [];
for ($i = 0; $i < count($query2); $i++){
$current_properties[$query2[$i]->field_id] = $query2[$i]->value;
}
// Automatically update new fields which was not set before
if (isset($user->binusian) && $user->binusian == true && !isset($current_properties['binusian.year'])) DB::table('user_properties')->insert(['user_id' => $user->id, 'field_id' => 'binusian.year', 'value' => '20' . substr($user['nim'], 0, 2)]);
$this->updateToNewFormat($user, $current_properties, 'major', 'university.major');
$this->updateToNewFormat($user, $current_properties, 'nim', 'university.nim');
$this->updateToNewFormat($user, $current_properties, 'phone', 'contacts.phone');
$this->updateToNewFormat($user, $current_properties, 'line', 'contacts.line');
$this->updateToNewFormat($user, $current_properties, 'whatsapp', 'contacts.whatsapp');
$this->updateToNewFormat($user, $current_properties, 'id_mobile_legends', 'accounts.moonton.mobile_legends');
$this->updateToNewFormat($user, $current_properties, 'id_pubg_mobile', 'accounts.tencent.pubg_mobile');
$this->updateToNewFormat($user, $current_properties, 'id_valorant', 'accounts.riot.valorant');
}
// Drop columns
Schema::dropColumns('users', ['binusian', 'nim', 'phone', 'line', 'whatsapp', 'id_mobile_legends', 'id_pubg_mobile', 'id_valorant', 'major']);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Update the Laravel's 'users' table
if (Schema::hasTable('users')) Schema::table('users', function (Blueprint $table) {
$table->boolean('binusian')->default(false);
$table->bigInteger('nim')->nullable();
$table->text('phone')->nullable();
$table->text('line')->nullable();
$table->text('whatsapp')->nullable();
$table->text('id_mobile_legends')->nullable();
$table->text('id_pubg_mobile')->nullable();
$table->text('id_valorant')->nullable();
$table->text('major')->nullable();
});
// Update the 'user_properties table
$user_properties = DB::table('user_properties');
$query = $user_properties->get();
foreach ($query as $property){
$user = DB::table('users')->where('id', $property->user_id);
switch ($property->field_id){
case 'university.major':
$user->update(['major' => $property->value]);
break;
case 'university.nim':
$user->update(['nim' => $property->value]);
break;
case 'contacts.phone':
$user->update(['phone' => $property->value]);
break;
case 'contacts.line':
$user->update(['line' => $property->value]);
break;
case 'contacts.whatsapp':
$user->update(['whatsapp' => $property->value]);
break;
case 'accounts.moonton.mobile_legends':
$user->update(['id_mobile_legends' => $property->value]);
break;
case 'accounts.riot.valorant':
$user->update(['id_valorant' => $property->value]);
break;
case 'accounts.tencent.pubg_mobile':
$user->update(['id_pubg_mobile' => $property->value]);
break;
default: continue 2;
}
}
$user_properties->where('field_id', 'university.major')
->orWhere('field_id', 'university.nim')
->orWhere('field_id', 'contacts.phone')
->orWhere('field_id', 'contacts.line')
->orWhere('field_id', 'contacts.whatsapp')
->orWhere('field_id', 'accounts.moonton.mobile_legends')
->orWhere('field_id', 'accounts.riot.valorant')
->orWhere('field_id', 'accounts.tencent.pubg_mobile')
->delete();
// Query all users to check their BINUSIAN status
$query = DB::table('users')->get();
foreach ($query as $user){
if ($user->university_id > 1 && $user->university_id <= 4) DB::table('users')->where('id', $user->id)->update(['binusian' => true]);
}
// Remove field definitions
// Add items to 'fields' table
$this->removeFields([
'accounts.moonton.mobile_legends', 'accounts.riot.valorant', 'accounts.tencent.pubg_mobile', 'accounts.valve.dota2',
'contacts.phone', 'contacts.instagram', 'contacts.line', 'contacts.telegram', 'contacts.twitter', 'contacts.whatsapp',
'university.nim', 'university.major'
]);
// Re-add 'category' to 'fields'
Schema::table('fields', function (Blueprint $table) {
$table->renameColumn('icon', 'category');
});
}
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class CreateDatabaseV2 extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Create 'universities' table
if (!Schema::hasTable('universities')) Schema::create('universities', function (Blueprint $table) {
$table->increments('id');
$table->text('name');
});
// Add "Uncategorized
DB::table('universities')->insert(['name' => 'None / Uncategorized']);
// Update the Laravel's 'users' table
if (Schema::hasTable('users')) Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('university_id')->default(1);
$table->foreign('university_id')->references('id')->on('universities');
$table->boolean('binusian')->default(false);
$table->bigInteger('nim')->nullable();
$table->text('phone')->nullable();
$table->text('line')->nullable();
$table->text('whatsapp')->nullable();
$table->text('id_mobile_legends')->nullable();
$table->text('id_pubg_mobile')->nullable();
$table->text('id_valorant')->nullable();
$table->text('major')->nullable();
});
// Create 'tickets' table
// if (!Schema::hasTable('tickets')) Schema::create('tickets', function (Blueprint $table) {
// $table->increments('id');
// $table->text('email')->unique();
// $table->text('password');
// $table->text('name');
// $table->unsignedInteger('university_id');
// $table->foreign('university_id')->references('id')->on('universities');
// $table->boolean('binusian')->default(false);
// $table->bigInteger('nim');
// $table->text('phone');
// $table->text('line')->nullable();
// $table->text('whatsapp')->nullable();
// });
// Create 'events' table
if (!Schema::hasTable('events')) Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->text('name');
$table->text('location')->nullable();
$table->dateTime('date', 0);
$table->unsignedInteger('price')->default(0);
$table->boolean('opened')->default(false);
$table->boolean('attendance_opened')->default(false);
$table->boolean('attendance_is_exit')->default(false);
$table->text('url_link')->nullable();
$table->text('totp_key');
$table->unsignedInteger('seats')->default(0);
$table->unsignedInteger('slots')->default(1);
$table->unsignedInteger('team_members')->default(0);
$table->unsignedInteger('team_members_reserve')->default(0);
$table->integer('files')->default(0);
});
// Create 'teams' table
if (!Schema::hasTable('teams')) Schema::create('teams', function (Blueprint $table) {
$table->increments('id');
$table->text('name');
$table->unsignedInteger('event_id');
$table->foreign('event_id')->references('id')->on('events');
$table->integer('score')->default(0);
$table->text('remarks')->nullable();
});
// Create 'registration' table
if (!Schema::hasTable('registration')) Schema::create('registration', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('ticket_id');
$table->foreign('ticket_id')->references('id')->on('users');
$table->unsignedInteger('event_id');
$table->foreign('event_id')->references('id')->on('events');
$table->unsignedInteger('team_id')->nullable();
$table->foreign('team_id')->references('id')->on('teams');
$table->integer('status');
$table->text('remarks')->nullable();
$table->text('payment_code')->nullable();
});
// Create 'attendance' table
if (!Schema::hasTable('attendance')) Schema::create('attendance', function (Blueprint $table) {
$table->increments('id');
$table->dateTime('entry_timestamp')->nullable();
$table->dateTime('exit_timestamp')->nullable();
$table->unsignedInteger('registration_id');
$table->foreign('registration_id')->references('id')->on('registration');
$table->text('remarks');
});
// Add ADMIN and Committee
DB::table('universities')->insert(['name' => 'COMPUTERUN 2020 System Administrator']);
DB::table('universities')->insert(['name' => 'COMPUTERUN 2020 Official Committee']);
// Add BINUS
DB::table('universities')->insert(['name' => 'BINUS University - Universitas Bina Nusantara']);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('attendance');
Schema::dropIfExists('registration');
Schema::dropIfExists('teams');
// Schema::dropIfExists('tickets');
if (Schema::hasTable('users')){
Schema::table('users', function (Blueprint $table) {
$table->dropForeign(['university_id']);
});
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['university_id', 'binusian', 'nim', 'phone', 'line', 'whatsapp', 'id_mobile_legends', 'id_pubg_mobile', 'id_valorant']);
});
}
Schema::dropIfExists('events');
Schema::dropIfExists('universities');
}
}
<file_sep>Hola!
.
My name is (...) and I will be participating in the COMPUTERUN 2.0 [INSERT WEBINAR TITLE]!
.
Can’t wait to EXECUTE! Because by participating in this event I will get a chance to gain valuable insights, knowledge, tips & tricks from industry-experienced speakers that will help me in the future! Looking forward to experiencing creativity through technology! 🔥🛠️
.
Hold up a sec! Before scrolling to another post, make sure to check out their page @computerun or through their website at http://www.computerun.id<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class MoveOnFromComputerun2020 extends Migration
{
/**
* Helper function to remove fields
*/
private function removeFields(Array $fields){
foreach($fields as $field) DB::table('fields')->where('id', $field)->delete();
}
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Add new fields to 'events'
if (Schema::hasTable('events')) Schema::table('events', function (Blueprint $table) {
$table->boolean('private')->default(true);
$table->mediumText('cover_image')->nullable();
$table->string('kicker')->nullable();
$table->longText('description_public')->nullable();
$table->longText('description_pending')->nullable();
$table->longText('description_private')->nullable();
$table->string('theme_color_foreground')->nullable();
$table->string('theme_color_background')->nullable();
});
// Add new table
if (!Schema::hasTable('event_permissions')) Schema::create('event_permissions', function (Blueprint $table) {
$table->integer('event_id')->unsigned();
$table->foreign('event_id')->references('id')->on('events');
$table->string('field_id');
$table->foreign('field_id')->references('id')->on('fields');
$table->boolean('required');
$table->string('validation_rule')->nullable();
$table->mediumText('validation_description')->nullable();
$table->primary(['event_id', 'field_id']);
});
// Change how admins are stored
// Current admins will be promoted as global admins
// Current committees will be promoted as global committee
$fields = DB::table('fields');
$fields->insert(['id' => 'role.administrator', 'name' => 'System Administrator', 'editable' => false]);
$fields->insert(['id' => 'role.committee', 'name' => 'System-Wide Committee', 'editable' => false]);
$users = DB::table('users')->where('university_id', 2)->orWhere('university_id', 3)->get();
foreach ($users as $user){
DB::table('user_properties')->insert(['user_id' => $user->id, 'field_id' => ($user->university_id == 2 ? 'role.administrator' : 'role.committee'), 'value' => 1]);
}
// Create new table for event-specific admins and committees
if (!Schema::hasTable('event_roles')) Schema::create('event_roles', function (Blueprint $table) {
$table->integer('event_id')->unsigned();
$table->foreign('event_id')->references('id')->on('events');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('role')->nullable();
$table->string('system_role');
$table->foreign('system_role')->references('id')->on('fields');
$table->primary(['event_id', 'user_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('event_roles');
Schema::dropIfExists('event_permissions');
if (Schema::hasTable('events')){
Schema::table('events', function (Blueprint $table) {
$table->dropColumn('private');
$table->dropColumn('cover_image');
$table->dropColumn('kicker');
$table->dropColumn('description_public');
$table->dropColumn('description_pending');
$table->dropColumn('description_private');
$table->dropColumn('theme_color_foreground');
$table->dropColumn('theme_color_background');
});
}
$users = DB::table('user_properties')->where('field_id', 'role.administrator')->orWhere('field_id', 'role.committee')->get();
foreach ($users as $user){
if ($user->field_id == 'role.administrator') DB::table('users')->where('user_id', $user->user_id)->update([
'university_id' => 2
]);
else DB::table('users')->where('user_id', $user->user_id)->update([
'university_id' => 3
]);
}
$this->removeFields(['role.administrator', 'role.committee']);
}
}
<file_sep>1. Participants must **deactivate their microphone throughout the whole event** and can only activate when they are allowed to talk by the MC.
2. **Participants from [BINUS University](https://binus.ac.id) must rename their display name to “<NAME>”.**
3. Participants are **prohibited to talk using inappropriate language or containing racial, religious, and ethnicity discrimination**.
4. Participants are **prohibited from smoking/vaping and sleeping** during the seminar.
5. Participants must fill **both entry and exit tickets** in order to receive an E-Certificate (all participants) as well as [SAT points](https://student.binus.ac.id/sat/) (BINUSIAN only).
6. Participants are only allowed to ask from the Question Form provided in [Slido](https://sli.do).
<file_sep>1. Participants are required to fill in **both entry and exit tickets** at the specified time for attendance recording purposes & door prize requirement.
2. Participants are required to **turn on their camera and apply the virtual background** provided by the committee.
3. Participants are required to **turn off their microphone** and only activated when requested by the committee.
4. Participants are **prohibited to talk using inappropriate language or containing racial, religious, and ethnicity discrimination**.
5. Participants are **not allowed to smoke, vape or sleep** during the session.
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddReferralCode extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::hasTable('referral_codes')) Schema::create('referral_codes', function (Blueprint $table) {
$table->string('id', 8)->primary();
$table->text('name');
$table->boolean('opened');
$table->timestamps();
});
if (Schema::hasTable('registration')) Schema::table('registration', function (Blueprint $table){
$table->string('referral_code', 8)->nullable();
$table->foreign('referral_code')->references('id')->on('referral_codes');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if (Schema::hasTable('registration')){
Schema::table('registration', function (Blueprint $table){
$table->dropForeign(['referral_code']);
});
Schema::table('registration', function (Blueprint $table){
$table->dropColumn(['referral_code']);
});
};
Schema::drop('referral_codes');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller{
/*
Validate the data entered into the form
*/
public function formSubmit(Request $request){
$request->validate([
// regex:/^([a-zA-Z]+)(\s[a-zA-Z]+)*$/
'Name' => "required|regex:/^([a-zA-Z]+)(\s[a-zA-Z]+)*$/",
'University' => "required|string",
'Email' => "required|email|",
// 'Email' => "required|email|unique:users", --> haven't had the database
'LineID' => "required|string",
'PhoneNumber' =>"required|min:10|max:13",
'Event' => "required",
'Confirm' => "required",
],[
'Name.required' => 'Name cannot be empty',
'Name.regex' => 'Name must be alphabetical',
'University.required' => 'University cannot be empty',
'Email.required' => 'Email cannot be empty',
'LineID.required' => 'Line ID cannot be empty',
'PhoneNumber.required' => 'Phone Number cannot be empty',
'PhoneNumber.min' => 'Phone Number must at least 10 digit',
'PhoneNumber.max' => 'Phone Number cannot be more than 13 digit',
'Event.required'=> 'Event cannot be empty',
'Confirm.required' => 'Please check the box to confirm'
]);
// print_r($message->input());
}
// public function store(Request $request){
// $validatedData = $request->validate([
// 'Name' => "required|regex:/^([a-zA-Z]+)(\s[a-zA-Z]+)*$/",
// 'University' => "required|string",
// 'Email' => "required|email",
// 'LineID' => "required|string",
// 'PhoneNumber' =>"required|min:10|max:13",
// 'Event' => "required",
// 'Confirm' => "required",
// ]);
// print_r($request->input());
// }
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
class Computerun2AdditionalFields extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$fields = DB::table('fields');
$fields->insert(['id' => 'promo.business_it_case', 'name' => 'Promo Code for Business-IT Case Competition', 'editable' => true]);
$fields->insert(['id' => 'promo.business_it_case_bundle', 'name' => 'Promo Code for Business-IT Case Competition (Bundle)', 'editable' => true]);
$fields->insert(['id' => 'promo.sprint', 'name' => 'Promo Code for SPRINT', 'editable' => true]);
$fields->insert(['id' => 'promo.web_design', 'name' => 'Promo Code for Web Design Competition', 'editable' => true]);
$fields->insert(['id' => 'promo.web_design_bundle', 'name' => 'Promo Code for Web Design Competition (Bundle)', 'editable' => true]);
$fields->insert(['id' => 'promo.workshop', 'name' => 'Promo Code for Workshop', 'editable' => true]);
$fields->insert(['id' => 'location.country', 'name' => 'Country of Origin', 'editable' => true]);
$fields->insert(['id' => 'location.home_address', 'name' => 'Home Address', 'editable' => true]);
$fields->insert(['id' => 'location.indonesia.province', 'name' => 'Domicile Province', 'editable' => true]);
$fields->insert(['id' => 'location.postal_code', 'name' => 'Postal Code', 'editable' => true]);
$fields->insert(['id' => 'merchandise.tshirt.size', 'name' => 'T-Shirt Merchandise Size', 'editable' => true]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
$user_properties = DB::table('user_properties');
$user_properties->where('field_id', 'promo.business_it_case')
->orWhere('field_id', 'promo.business_it_case_bundle')
->orWhere('field_id', 'promo.sprint')
->orWhere('field_id', 'promo.web_design')
->orWhere('field_id', 'promo.web_design_bundle')
->orWhere('field_id', 'promo.workshop')
->orWhere('field_id', 'location.country')
->orWhere('field_id', 'location.home_address')
->orWhere('field_id', 'location.indonesia.province')
->orWhere('field_id', 'location.postal_code')
->orWhere('field_id', 'merchandise.tshirt.size')
->delete();
}
}
<file_sep><p class="h2 text-center fw-bold">Rp 4.000.000,-</p>
1. **Logo ukuran M** pada:
+ Setiap publikasi (termasuk *trailer* dan *aftermovie*) pada [akun-akun sosial media resmi **COMPUTERUN 2.0**]
+ Bagian *footer* pada website resmi **COMPUTERUN 2.0**
+ Sertifikat/*e-certificate* pemenang sub-acara
+ Setiap *merchandise* yang diberikan kepada para peserta maupun pembicara
+ *Welcoming page* yang digunakan oleh panitia untuk melakukan presentasi acara **COMPUTERUN 2.0** kepada peserta
2. ***Ad Libs*** nama produk atau perusahaan selama acara berlangsung
[akun-akun sosial media resmi **COMPUTERUN 2.0**]: https://linktr.ee/computerun
<file_sep>Hola!👋🏻
.
My name is (Name), will be participating in the COMPUTERUN 2.0 Business-IT Case Competition alongside my team, (INSERT TEAM NAME HERE), (TAG OTHER MEMBER INSTAGRAM ACCOUNT).👨🏻💻
.
I am ready to EXECUTE! Because by participating in this event will help me hone and enhance my problem solving, critical reasoning, analytical thinking, and teamwork skills by applying my knowledge in solving real-life industry cases. But other than that, along with other development skills, I will also be gaining valuable moreover unforgettable experience as well as knowledge that will surely help me tackle business and technology problems in the future! Looking forward to experiencing creativity through technology!🔥🛠️
.
Hold up a sec! Before scrolling to another post, make sure to check out their page @computerun or through their website at http://www.computerun.id<file_sep>Hola!
.
My name is (YOUR NAME), and will be participating in the COMPUTERUN 2.0 UI/UX Design Workshop!🪄
.
I am ready to EXECUTE! Because by participating in this event, I will be able to learn the foundation and principles of UI/UX design, user analysis, and also design my own prototype! But other than that, along with other development skills, I will also be gaining valuable moreover unforgettable experience as well as knowledge that will surely help me in the UI/UX field. Looking forward to experiencing creativity through technology! 🔥🛠️
.
Hold up a sec! Before scrolling to another post, make sure to check out their page @computerun or through their website at http://www.computerun.id<file_sep>## General Competition Rules
1. Each participant must be an **active S1/D4/D3 (bachelor) student** of a public or private university, with proof of scanned **student identification card (KTM)**.
2. Each group must consist of **two (2) members and one (1) leader**.
3. Each group member may belong from the same or different colleges or institutions.
4. Each participant is **not allowed** to indicate the origin of their institution or college.
5. Each registered group **cannot change the group name or group members for any reason**.
6. Each participant **must upload a twibbon** on each group member's Instagram account.
## Proposal Submission Guidelines
+ The maximum number of proposal pages consists of **15 pages**. Attachments, cover, and references are **not** included in the count.
+ Participants are **allowed to provide ideas in their content** such as company profile, supporting data/statistics, problems and situational analysis, etc.
+ Proposal **must** be written in English.
+ The journal references must be no more than 10 years.
+ Proposal format:
- **Title:** Times New Roman 16pt, Bold
- **Body:** Times New Roman 12pt
- **Layout:** Justified
- **Paper size:** A4
- **Line spacing:** 1.5 Lines
- **Margin:** Normal (top and bottom 2.5 cm, left 2 cm, right 1.5 cm)
- **File format:** .pdf
- **File name:** GROUP NAME_3 FIRST WORDS OF PAPER TITLE
- **Header:** PAPER TITLE – COMPUTERUN 2.0
- **Footer:** Page Number at bottom right of the page (starting from the first page after the cover)
Users of operating systems where **Times New Roman** is not generally available are allowed to substitute the font with **[Liberation Serif](https://github.com/liberationfonts/liberation-fonts)** (default in Apache OpenOffice.org and LibreOffice), **[Tinos](https://fonts.google.com/specimen/Tinos)** (default in Chrome OS), **[(GNU) FreeSerif](http://www.gnu.org/software/freefont/)**, **Nimbus Roman**, **Nimbus Roman No9 L**, or **[TeX Gyre Termes](http://www.gust.org.pl/projects/e-foundry/tex-gyre)** in the generated PDF files.
## Additional Rules and Guidelines
Full details of the COMPUTERUN 2.0 Web Design Competition guidelines are available on [this Guidebook (PDF)](https://drive.google.com/drive/folders/1POK9vsjJk08WX1VD6ajv5E5vPNc6nKXb).
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class AddQueueMigration extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Create "Clients" table, consisting of list of valid clients
if (!Schema::hasTable('attendance_clients')) Schema::create('attendance_clients', function (Blueprint $table) {
$table->string('id');
$table->text('name');
$table->boolean('enabled')->default(false);
$table->primary('id');
});
// Create "Emails" queue
if (!Schema::hasTable('email_queue')) Schema::create('email_queue', function (Blueprint $table) {
$table->increments('id');
$table->text('email');
$table->text('subject');
$table->longText('message');
$table->text('status')->default('PENDING');
$table->dateTime('created_at');
$table->dateTime('updated_at')->nullable();
});
// Create "Attendance" queue
if (!Schema::hasTable('attendance_queue')) Schema::create('attendance_queue', function (Blueprint $table) {
$table->increments('id');
$table->string('attendance_client_id');
$table->text('email');
$table->text('totp_key');
$table->text('status')->default('PENDING');
$table->dateTime('created_at');
$table->dateTime('updated_at')->nullable();
$table->foreign('attendance_client_id')->references('id')->on('attendance_clients');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('attendance_queue');
Schema::dropIfExists('email_queue');
Schema::dropIfExists('attendance_clients');
}
}
<file_sep># Computerun 2020 Official Website
## Building
In order to build the website, make sure that you have generated the `.env` environment variable. To create a new one, go to the `/scripts` folder, and execute `python3 generate_env.py`.
> This script requires (preferably latest version of) Python 3 with external libraries. If you are unsure which library is required, run `pip install pillow pyotp qrcode uuid` before executing the script
> This script will generate a temporary image file, `temp.png`, to display the QR code for Administration Panel authentication. While this file has been exempted from Git through `.gitignore` files, it is still recommended to run the script inside the `/scripts` folder (i.e. `cd scripts && python3 generate_env.py` rather than `python3 scripts/generate_env.py`) for security reasons.
Additionally, you might want to [download and install Composer](https://getcomposer.org/download) and run `composer install` to install all dependencies
<file_sep><?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'phone' => ['required', 'string'],
'line' => ['nullable', 'string'],
'whatsapp' => ['nullable', 'string'],
'university_id' => ['required', 'numeric'],
'nim' => ['nullable', 'string'],
'binus_regional' => ['nullable', 'string'],
'major_name' => ['nullable', 'string'],
'new_university' => ['nullable', 'string'],
'student_id_card' => ['nullable', 'image']
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\Models\User
*/
protected function create(array $data)
{
if ($data['new_university'] != ""){
$data['university_id'] = DB::table('universities')->insertGetId(['name' => $data['new_university']]);
}
if ($data['university_id'] == 2 || $data['university_id'] == 3) $data['university_id'] = 1;
$new_user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => <PASSWORD>($data['password']),
'university_id' => $data['university_id'],
]);
$user_properties = DB::table('user_properties');
// Save phone, LINE, WhatsApp information
$user_properties->insert(['user_id' => $new_user->id, 'field_id' => 'contacts.phone', 'value' => $data['phone']]);
if ($data['line']) $user_properties->insert(['user_id' => $new_user->id, 'field_id' => 'contacts.line', 'value' => $data['line']]);
if ($data['whatsapp']) $user_properties->insert(['user_id' => $new_user->id, 'field_id' => 'contacts.whatsapp', 'value' => $data['whatsapp']]);
// Save BINUSIAN status
if ($data['university_id'] == 4){
$user_properties->insert(['user_id' => $new_user->id, 'field_id' => 'binusian.regional', 'value' => $data['binus_regional']]);
$user_properties->insert(['user_id' => $new_user->id, 'field_id' => 'binusian.year', 'value' => '20' . substr($data['nim'], 0, 2)]);
}
// Save major / study program
if ($data['nim']) $user_properties->insert(['user_id' => $new_user->id, 'field_id' => 'university.nim', 'value' => $data['nim']]);
if ($data['major']) $user_properties->insert(['user_id' => $new_user->id, 'field_id' => 'university.major', 'value' => $data['major']]);
// Save Student ID Card
if (request()->hasFile('student_id_card')){
// Copy and register new upload
$path = request()->file('student_id_card')->store('verification');
$fileId = DB::table('files')->insertGetId([
"name" => $path
]);
DB::table('kyc')->insert([
'ticket_id' => $new_user->id,
'file_id' => $fileId,
'created_at' => now()
]);
}
return $new_user;
}
}
<file_sep>Hola!👋🏻
.
My name is (YOUR NAME), will be participating in the COMPUTERUN 2.0 Website Design Competition alongside my team, (INSERT TEAM NAME HERE), (TAG OTHER MEMBER IG ACCOUNT).👨🏻💻
.
I am ready to EXECUTE! Participating in this event will help me test my coding skills through software applications to design and construct a website using both creative and technical skills in solving real-life industry cases. This will hone my programming, creativity, and IT skills. But other than that, along with other development skills, I will also be gaining valuable moreover unforgettable experience as well as knowledge that will surely help me tackle business and technology problems in the future. Looking forward to experiencing creativity through technology!🔥🛠️
.
Hold up a sec! Before scrolling to another post, make sure to check out their page @computerun or through their website at http://www.computerun.id<file_sep><?php
/*
* This file is part of the overtrue/phplint
*
* (c) overtrue <<EMAIL>>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Overtrue\PHPLint\Command;
use DateTime;
use Exception;
use JakubOnderka\PhpConsoleColor\ConsoleColor;
use JakubOnderka\PhpConsoleHighlighter\Highlighter;
use N98\JUnitXml\Document;
use Overtrue\PHPLint\Cache;
use Overtrue\PHPLint\Linter;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Terminal;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
/**
* Class LintCommand.
*/
class LintCommand extends Command
{
/**
* @var array
*/
protected $defaults = [
'jobs' => 5,
'path' => '.',
'exclude' => [],
'extensions' => ['php'],
'warning' => false
];
/**
* @var \Symfony\Component\Console\Input\InputInterface
*/
protected $input;
/**
* @var \Symfony\Component\Console\Output\OutputInterface
*/
protected $output;
/**
* Configures the current command.
*/
protected function configure()
{
$this
->setName('phplint')
->setDescription('Lint something')
->addArgument(
'path',
InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
'Path to file or directory to lint.'
)
->addOption(
'exclude',
null,
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
'Path to file or directory to exclude from linting'
)
->addOption(
'extensions',
null,
InputOption::VALUE_REQUIRED,
'Check only files with selected extensions (default: php)'
)
->addOption(
'jobs',
'j',
InputOption::VALUE_REQUIRED,
'Number of parraled jobs to run (default: 5)'
)
->addOption(
'configuration',
'c',
InputOption::VALUE_REQUIRED,
'Read configuration from config file (default: ./.phplint.yml).'
)
->addOption(
'no-configuration',
null,
InputOption::VALUE_NONE,
'Ignore default configuration file (default: ./.phplint.yml).'
)
->addOption(
'no-cache',
null,
InputOption::VALUE_NONE,
'Ignore cached data.'
)
->addOption(
'cache',
null,
InputOption::VALUE_REQUIRED,
'Path to the cache file.'
)
->addOption(
'no-progress',
null,
InputOption::VALUE_NONE,
'Hide the progress output.'
)
->addOption(
'json',
null,
InputOption::VALUE_OPTIONAL,
'Path to store JSON results.'
)
->addOption(
'xml',
null,
InputOption::VALUE_OPTIONAL,
'Path to store JUnit XML results.'
)
->addOption(
'warning',
'w',
InputOption::VALUE_NONE,
'Also show warnings.'
)
->addOption(
'quiet',
'q',
InputOption::VALUE_NONE,
'Allow to silenty fail.'
);
}
/**
* Initializes the command just after the input has been validated.
*
* This is mainly useful when a lot of commands extends one main command
* where some things need to be initialized based on the input arguments and options.
*
* @param InputInterface $input An InputInterface instance
* @param OutputInterface $output An OutputInterface instance
*/
public function initialize(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
}
/**
* Executes the current command.
*
* This method is not abstract because you can use this class
* as a concrete class. In this case, instead of defining the
* execute() method, you set the code to execute by passing
* a Closure to the setCode() method.
*
* @param InputInterface $input An InputInterface instance
* @param OutputInterface $output An OutputInterface instance
*
* @throws \LogicException When this abstract method is not implemented
*
* @return null|int null or 0 if everything went fine, or an error code
*
* @see setCode()
*
* @throws \JakubOnderka\PhpConsoleColor\InvalidStyleException
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$startTime = microtime(true);
$startMemUsage = memory_get_usage(true);
$output->writeln($this->getApplication()->getLongVersion() . " by overtrue and contributors.\n");
$options = $this->mergeOptions();
$verbosity = $output->getVerbosity();
if ($verbosity >= OutputInterface::VERBOSITY_DEBUG) {
$output->writeln('Options: ' . json_encode($options) . "\n");
}
$linter = new Linter($options['path'], $options['exclude'], $options['extensions'], $options['warning']);
$linter->setProcessLimit($options['jobs']);
if (!empty($options['cache'])) {
Cache::setFilename($options['cache']);
}
$usingCache = 'No';
if (!$input->getOption('no-cache') && Cache::isCached()) {
$usingCache = 'Yes';
$linter->setCache(Cache::get());
}
$fileCount = count($linter->getFiles());
if ($fileCount <= 0) {
$output->writeln('<info>Could not find files to lint</info>');
return 0;
}
$errors = $this->executeLint($linter, $input, $output, $fileCount);
$timeUsage = Helper::formatTime(microtime(true) - $startTime);
$memUsage = Helper::formatMemory(memory_get_usage(true) - $startMemUsage);
$code = 0;
$errCount = count($errors);
$output->writeln(sprintf(
"\n\nTime: <info>%s</info>\tMemory: <info>%s</info>\tCache: <info>%s</info>\n",
$timeUsage,
$memUsage,
$usingCache
));
if ($errCount > 0) {
$output->writeln('<error>FAILURES!</error>');
$output->writeln("<error>Files: {$fileCount}, Failures: {$errCount}</error>");
$this->showErrors($errors);
if (empty($options['quiet'])) {
$code = 1;
}
} else {
$output->writeln("<info>OK! (Files: {$fileCount}, Success: {$fileCount})</info>");
}
$context = [
'time_usage' => $timeUsage,
'memory_usage' => $memUsage,
'using_cache' => 'Yes' == $usingCache,
'files_count' => $fileCount,
];
if (!empty($options['json'])) {
$this->dumpJsonResult((string) $options['json'], $errors, $options, $context);
}
if (!empty($options['xml'])) {
$this->dumpXmlResult((string) $options['xml'], $errors, $options, $context);
}
return $code;
}
/**
* @param string $path
* @param array $errors
* @param array $options
* @param array $context
*/
protected function dumpJsonResult($path, array $errors, array $options, array $context = [])
{
$result = [
'status' => 'success',
'options' => $options,
'errors' => $errors,
];
\file_put_contents($path, \json_encode(\array_merge($result, $context)));
}
/**
* @param string $path
* @param array $errors
* @param array $options
* @param array $context
*
* @throws Exception
*/
protected function dumpXmlResult($path, array $errors, array $options, array $context = [])
{
$document = new Document();
$suite = $document->addTestSuite();
$suite->setName('PHP Linter');
$suite->setTimestamp(new DateTime());
$suite->setTime($context['time_usage']);
$testCase = $suite->addTestCase();
foreach ($errors as $errorName => $value) {
$testCase->addError($errorName, 'Error', $value['error']);
}
$document->save($path);
}
/**
* Execute lint and return errors.
*
* @param Linter $linter
* @param InputInterface $input
* @param OutputInterface $output
* @param int $fileCount
*
* @return array
*/
protected function executeLint($linter, $input, $output, $fileCount)
{
$cache = !$input->getOption('no-cache');
$maxColumns = floor((new Terminal())->getWidth() / 2);
$verbosity = $output->getVerbosity();
$displayProgress = !$input->getOption('no-progress');
$displayProgress && $linter->setProcessCallback(function ($status, SplFileInfo $file) use ($output, $verbosity, $fileCount, $maxColumns) {
static $i = 1;
$percent = floor(($i / $fileCount) * 100);
$process = str_pad(" {$i} / {$fileCount} ({$percent}%)", 18, ' ', STR_PAD_LEFT);
if ($verbosity >= OutputInterface::VERBOSITY_VERBOSE) {
$filename = str_pad(" {$i}: " . $file->getRelativePathname(), $maxColumns - 10, ' ', \STR_PAD_RIGHT);
if ($status === 'ok') {
$status = '<info>OK</info>';
} elseif ($status === 'error') {
$status = '<error>Error</error>';
} else {
$status = '<error>Warning</error>';
}
$status = \str_pad($status, 20, ' ', \STR_PAD_RIGHT);
$output->writeln(\sprintf("%s\t%s\t%s", $filename, $status, $process));
} else {
if ($i && 0 === $i % $maxColumns) {
$output->writeln($process);
}
if ($status === 'ok') {
$status = '<info>.</info>';
} elseif ($status === 'error') {
$status = '<error>E</error>';
} else {
$status = '<error>W</error>';
}
$output->write($status);
}
++$i;
});
$displayProgress || $output->write('<info>Checking...</info>');
return $linter->lint([], $cache);
}
/**
* Show errors detail.
*
* @param array $errors
*
* @throws \JakubOnderka\PhpConsoleColor\InvalidStyleException
*/
protected function showErrors($errors)
{
$i = 0;
$this->output->writeln("\nThere was " . count($errors) . ' errors:');
foreach ($errors as $filename => $error) {
$this->output->writeln('<comment>' . ++$i . ". {$filename}:{$error['line']}" . '</comment>');
$this->output->write($this->getHighlightedCodeSnippet($filename, $error['line']));
$this->output->writeln("<error> {$error['error']}</error>");
}
}
/**
* @param string $filePath
* @param int $lineNumber
* @param int $linesBefore
* @param int $linesAfter
*
* @return string
*/
protected function getCodeSnippet($filePath, $lineNumber, $linesBefore = 3, $linesAfter = 3)
{
$lines = file($filePath);
$offset = $lineNumber - $linesBefore - 1;
$offset = max($offset, 0);
$length = $linesAfter + $linesBefore + 1;
$lines = array_slice($lines, $offset, $length, $preserveKeys = true);
end($lines);
$lineStrlen = strlen(key($lines) + 1);
$snippet = '';
foreach ($lines as $i => $line) {
$snippet .= (abs($lineNumber) === $i + 1 ? ' > ' : ' ');
$snippet .= str_pad($i + 1, $lineStrlen, ' ', STR_PAD_LEFT) . '| ' . rtrim($line) . PHP_EOL;
}
return $snippet;
}
/**
* @param string $filePath
* @param int $lineNumber
* @param int $linesBefore
* @param int $linesAfter
*
* @return string
*
* @throws \JakubOnderka\PhpConsoleColor\InvalidStyleException
*/
public function getHighlightedCodeSnippet($filePath, $lineNumber, $linesBefore = 3, $linesAfter = 3)
{
if (
!class_exists('\JakubOnderka\PhpConsoleHighlighter\Highlighter') ||
!class_exists('\JakubOnderka\PhpConsoleColor\ConsoleColor')
) {
return $this->getCodeSnippet($filePath, $lineNumber, $linesBefore, $linesAfter);
}
$colors = new ConsoleColor();
$highlighter = new Highlighter($colors);
$fileContent = file_get_contents($filePath);
return $highlighter->getCodeSnippet($fileContent, $lineNumber, $linesBefore, $linesAfter);
}
/**
* Merge options.
*
* @return array
*/
protected function mergeOptions()
{
$options = $this->input->getOptions();
$options['path'] = $this->input->getArgument('path');
$options['cache'] = $this->input->getOption('cache');
if ($options['warning'] === false) {
unset($options['warning']);
}
$config = [];
if (!$this->input->getOption('no-configuration')) {
$filename = $this->getConfigFile();
if (empty($options['configuration']) && $filename) {
$options['configuration'] = $filename;
}
if (!empty($options['configuration'])) {
$this->output->writeln("<comment>Loaded config from \"{$options['configuration']}\"</comment>\n");
$config = $this->loadConfiguration($options['configuration']);
} else {
$this->output->writeln("<comment>No config file loaded.</comment>\n");
}
} else {
$this->output->writeln("<comment>No config file loaded.</comment>\n");
}
$options = array_merge($this->defaults, array_filter($config), array_filter($options));
is_array($options['extensions']) || $options['extensions'] = explode(',', $options['extensions']);
return $options;
}
/**
* Get configuration file.
*
* @return string|null
*/
protected function getConfigFile()
{
$inputPath = $this->input->getArgument('path');
$dir = './';
if (1 == count($inputPath) && $first = reset($inputPath)) {
$dir = is_dir($first) ? $first : dirname($first);
}
$filename = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '.phplint.yml';
return realpath($filename);
}
/**
* Load configuration from yaml.
*
* @param string $path
*
* @return array
*/
protected function loadConfiguration($path)
{
try {
$configuration = Yaml::parse(file_get_contents($path));
if (!is_array($configuration)) {
throw new ParseException('Invalid content.', 1);
}
return $configuration;
} catch (ParseException $e) {
$this->output->writeln(sprintf('<error>Unable to parse the YAML string: %s</error>', $e->getMessage()));
return [];
}
}
}
<file_sep><?php
/*
* This file is part of the overtrue/phplint
*
* (c) overtrue <<EMAIL>>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Overtrue\PHPLint\Process;
use Symfony\Component\Process\Process;
/**
* Class Lint.
*/
class Lint extends Process
{
/**
* @return bool
*/
public function hasSyntaxError()
{
$output = trim($this->getOutput());
if (defined('HHVM_VERSION') && empty($output)) {
return false;
}
return false === strpos($output, 'No syntax errors detected');
}
/**
* @return bool|array
*/
public function getSyntaxError()
{
if ($this->hasSyntaxError()) {
$out = explode("\n", trim($this->getOutput()));
return $this->parseError(array_shift($out));
}
return false;
}
/**
* Parse error message.
*
* @param string $message
*
* @return array
*/
public function parseError($message)
{
$pattern = '/^(PHP\s+)?(Parse|Fatal) error:\s*(?:\w+ error,\s*)?(?<error>.+?)\s+in\s+.+?\s*line\s+(?<line>\d+)/';
$matched = preg_match($pattern, $message, $match);
if (empty($message)) {
$message = 'Unknown';
}
return [
'error' => $matched ? "{$match['error']} in line {$match['line']}" : $message,
'line' => $matched ? abs($match['line']) : 0,
];
}
/**
* @return bool
*/
public function hasSyntaxIssue()
{
$output = trim($this->getOutput());
if (defined('HHVM_VERSION') && empty($output)) {
return false;
}
return (bool)preg_match('/(Warning:|Deprecated:|Notice:)/', $output);
}
/**
* @return bool|array
*/
public function getSyntaxIssue()
{
if ($this->hasSyntaxIssue()) {
$out = explode("\n", trim($this->getOutput()));
return $this->parseIssue(array_shift($out));
}
return false;
}
/**
* Parse error message.
*
* @param string $message
*
* @return array
*/
private function parseIssue($message)
{
$pattern = '/^(PHP\s+)?(Warning|Deprecated|Notice):\s*?(?<error>.+?)\s+in\s+.+?\s*line\s+(?<line>\d+)/';
$matched = preg_match($pattern, $message, $match);
if (empty($message)) {
$message = 'Unknown';
}
return [
'error' => $matched ? "{$match['error']} in line {$match['line']}" : $message,
'line' => $matched ? abs($match['line']) : 0,
];
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
class TicketStatusController extends Controller
{
/**
* Converts Event IDs to names
*/
private function resolveEventId($id){
try {
return DB::table('events')->where('id', $id)->get()[0]->name;
} catch (Exception $e){
return null;
}
}
/**
* Get the event details
*/
private function resolveEventDetails($id){
try {
return DB::table('events')->where('id', $id)->get()[0];
} catch (Exception $e){
return null;
}
}
/**
* Converts Status IDs to names
*/
private $status = array("Pending", "Rejected", "Approved", "Cancelled", "Attending", "Attended");
private function resolveStatusId($id){
if ($id >= 0 && $id < count($this->status)) return $this->status[$id];
}
private function getTicketNumber(Request $request){
if (Session::get('ticket_number') != null && Session::get('ticket_number') != '') return Session::get('ticket_number');
else return $request->input('ticketnumber');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$request = new Request;
$ticketnumber = Session::get('ticket_number', null);
$nim = Session::get('nim', null);
if ($ticketnumber != null && $ticketnumber != '' && $nim != null && $nim != '') return $this->store($request);
else return view("dashboard.login", ['error' => null, 'action' => '/login', 'message' => "Check your registration status and e-ticket"]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view("dashboard.login", ['error' => null, 'action' => '/login', 'message' => "Check your registration status and e-ticket"]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request1)
{
$ticketnumber = $this->getTicketNumber($request1);
$nim = Session::get('nim', $request1->input('nim'));
$request = DB::table("tickets")->where('id', $ticketnumber)->get();
if (count($request) == 0 || $request[0]->nim != $nim){
return view("dashboard.login", ['error' => 'Wrong Ticket Number or NIM', 'action' => '/login', 'message' => "Check your registration status and e-ticket"]);
};
foreach($request1->all() as $key => $value) {
switch ($key){
case "action-change-email":
if ($value != '') DB::table('tickets')->where('id', $ticketnumber)->update(['email' => $value]);
break;
case "action-change-phone":
if ($value != '') DB::table('tickets')->where('id', $ticketnumber)->update(['phone' => $value]);
break;
case "action-change-line":
if ($value != '') DB::table('tickets')->where('id', $ticketnumber)->update(['line' => $value]);
break;
case "action-change-whatsapp":
if ($value != '') DB::table('tickets')->where('id', $ticketnumber)->update(['whatsapp' => $value]);
break;
}
};
$events = DB::table('registration')->where('ticket_id', $ticketnumber)->get();
$name = $request[0]->name;
$account_details = [
"name" => $name,
"nim" => $nim,
"ticketnumber" => $ticketnumber,
"binusian" => ($request[0]->binusian == 1) ? true : false,
"contact" => [
"email" => $request[0]->email,
"phone" => $request[0]->phone,
"line" => $request[0]->line,
"whatsapp" => $request[0]->whatsapp
]
];
for ($i = 0; $i < count($events); $i++){
$event_details = $this->resolveEventDetails($events[$i]->event_id);
$events[$i]->event_id = $event_details->id;
$events[$i]->event_name = $event_details->name;
$events[$i]->attendance_opened = ($event_details->attendance_opened == 1) ? true : false;
$events[$i]->attendance_is_exit = ($event_details->attendance_is_exit == 1) ? true : false;
$events[$i]->status_code = $events[$i]->status;
$events[$i]->status = $this->resolveStatusId($events[$i]->status);
$events[$i]->url_link = $event_details->url_link;
$events[$i]->totp_key = $event_details->totp_key;
};
// Set Session Cookie
Session::put('name', $name);
Session::put('nim', $nim);
Session::put('ticket_number', $ticketnumber);
return view("dashboard.tickets", ['error' => null, 'account_details' => $account_details, 'events' => $events]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
public function logout(Request $request)
{
Session::flush();
Auth::logout();
return redirect('/login');
}
}
<file_sep><?php // phpcs:ignoreFile
/**
* This contains the information needed to convert the function signatures for php 8.1 to php 8.0 (and vice versa)
*
* This file has three sections.
* The 'added' section contains function/method names from FunctionSignatureMap (And alternates, if applicable) that do not exist in php 8.0
* The 'removed' section contains the signatures that were removed in php 8.1
* The 'changed' section contains functions for which the signature has changed for php 8.1.
* Each function in the 'changed' section has an 'old' and a 'new' section,
* representing the function as it was in PHP 8.0 and in PHP 8.1, respectively
*
* @see CallMap.php
*
* @phan-file-suppress PhanPluginMixedKeyNoKey (read by Phan when analyzing this file)
*/
return [
'added' => [
'array_is_list' => ['bool', 'array' => 'array'],
],
'changed' => [
'ftp_connect' => [
'old' => ['resource|false', 'hostname' => 'string', 'port=' => 'int', 'timeout=' => 'int'],
'new' => ['FTP\Connection|false', 'hostname' => 'string', 'port=' => 'int', 'timeout=' => 'int'],
],
'ftp_ssl_connect' => [
'old' => ['resource|false', 'hostname' => 'string', 'port=' => 'int', 'timeout=' => 'int'],
'new' => ['FTP\Connection|false', 'hostname' => 'string', 'port=' => 'int', 'timeout=' => 'int'],
],
'ftp_login' => [
'old' => ['bool', 'ftp' => 'resource', 'username' => 'string', 'password' => '<PASSWORD>'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'username' => 'string', 'password' => '<PASSWORD>'],
],
'ftp_pwd' => [
'old' => ['string|false', 'ftp' => 'resource'],
'new' => ['string|false', 'ftp' => 'FTP\Connection'],
],
'ftp_cdup' => [
'old' => ['bool', 'ftp' => 'resource'],
'new' => ['bool', 'ftp' => 'FTP\Connection'],
],
'ftp_chdir' => [
'old' => ['bool', 'ftp' => 'resource', 'directory' => 'string'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'directory' => 'string'],
],
'ftp_exec' => [
'old' => ['bool', 'ftp' => 'resource', 'command' => 'string'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'command' => 'string'],
],
'ftp_raw' => [
'old' => ['array', 'ftp' => 'resource', 'command' => 'string'],
'new' => ['array', 'ftp' => 'FTP\Connection', 'command' => 'string'],
],
'ftp_mkdir' => [
'old' => ['string|false', 'ftp' => 'resource', 'directory' => 'string'],
'new' => ['string|false', 'ftp' => 'FTP\Connection', 'directory' => 'string'],
],
'ftp_rmdir' => [
'old' => ['bool', 'ftp' => 'resource', 'directory' => 'string'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'directory' => 'string'],
],
'ftp_chmod' => [
'old' => ['int|false', 'ftp' => 'resource', 'permissions' => 'int', 'filename' => 'string'],
'new' => ['int|false', 'ftp' => 'FTP\Connection', 'permissions' => 'int', 'filename' => 'string'],
],
'ftp_alloc' => [
'old' => ['bool', 'ftp' => 'resource', 'size' => 'int', '&w_response=' => 'string'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'size' => 'int', '&w_response=' => 'string'],
],
'ftp_nlist' => [
'old' => ['array|false', 'ftp' => 'resource', 'directory' => 'string'],
'new' => ['array|false', 'ftp' => 'FTP\Connection', 'directory' => 'string'],
],
'ftp_rawlist' => [
'old' => ['array|false', 'ftp' => 'resource', 'directory' => 'string', 'recursive=' => 'bool'],
'new' => ['array|false', 'ftp' => 'FTP\Connection', 'directory' => 'string', 'recursive=' => 'bool'],
],
'ftp_mlsd' => [
'old' => ['array|false', 'ftp' => 'resource', 'directory' => 'string'],
'new' => ['array|false', 'ftp' => 'FTP\Connection', 'directory' => 'string'],
],
'ftp_systype' => [
'old' => ['string|false', 'ftp' => 'resource'],
'new' => ['string|false', 'ftp' => 'FTP\Connection'],
],
'ftp_fget' => [
'old' => ['bool', 'ftp' => 'resource', 'stream' => 'resource', 'remote_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'stream' => 'FTP\Connection', 'remote_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
],
'ftp_nb_fget' => [
'old' => ['int', 'ftp' => 'resource', 'stream' => 'resource', 'remote_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
'new' => ['int', 'ftp' => 'FTP\Connection', 'stream' => 'FTP\Connection', 'remote_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
],
'ftp_pasv' => [
'old' => ['bool', 'ftp' => 'resource', 'enable' => 'bool'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'enable' => 'bool'],
],
'ftp_get' => [
'old' => ['bool', 'ftp' => 'resource', 'local_filename' => 'string', 'remote_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'local_filename' => 'string', 'remote_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
],
'ftp_nb_get' => [
'old' => ['int', 'ftp' => 'resource', 'local_filename' => 'string', 'remote_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
'new' => ['int', 'ftp' => 'FTP\Connection', 'local_filename' => 'string', 'remote_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
],
'ftp_nb_continue' => [
'old' => ['int', 'ftp' => 'resource'],
'new' => ['int', 'ftp' => 'FTP\Connection'],
],
'ftp_fput' => [
'old' => ['bool', 'ftp' => 'resource', 'remote_filename' => 'string', 'stream' => 'resource', 'mode=' => 'int', 'offset=' => 'int'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'remote_filename' => 'string', 'stream' => 'FTP\Connection', 'mode=' => 'int', 'offset=' => 'int'],
],
'ftp_nb_fput' => [
'old' => ['int', 'ftp' => 'resource', 'remote_filename' => 'string', 'stream' => 'resource', 'mode=' => 'int', 'offset=' => 'int'],
'new' => ['int', 'ftp' => 'FTP\Connection', 'remote_filename' => 'string', 'stream' => 'FTP\Connection', 'mode=' => 'int', 'offset=' => 'int'],
],
'ftp_put' => [
'old' => ['bool', 'ftp' => 'resource', 'remote_filename' => 'string', 'local_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'remote_filename' => 'string', 'local_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
],
'ftp_append' => [
'old' => ['bool', 'ftp' => 'resource', 'remote_filename' => 'string', 'local_filename' => 'string', 'mode=' => 'int'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'remote_filename' => 'string', 'local_filename' => 'string', 'mode=' => 'int'],
],
'ftp_nb_put' => [
'old' => ['int', 'ftp' => 'resource', 'remote_filename' => 'string', 'local_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
'new' => ['int', 'ftp' => 'FTP\Connection', 'remote_filename' => 'string', 'local_filename' => 'string', 'mode=' => 'int', 'offset=' => 'int'],
],
'ftp_size' => [
'old' => ['int', 'ftp' => 'resource', 'filename' => 'string'],
'new' => ['int', 'ftp' => 'FTP\Connection', 'filename' => 'string'],
],
'ftp_mdtm' => [
'old' => ['int', 'ftp' => 'resource', 'filename' => 'string'],
'new' => ['int', 'ftp' => 'FTP\Connection', 'filename' => 'string'],
],
'ftp_rename' => [
'old' => ['bool', 'ftp' => 'resource', 'from' => 'string', 'to' => 'string'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'from' => 'string', 'to' => 'string'],
],
'ftp_delete' => [
'old' => ['bool', 'ftp' => 'resource', 'filename' => 'string'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'filename' => 'string'],
],
'ftp_site' => [
'old' => ['bool', 'ftp' => 'resource', 'command' => 'string'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'command' => 'string'],
],
'ftp_close' => [
'old' => ['bool', 'ftp' => 'resource'],
'new' => ['bool', 'ftp' => 'FTP\Connection'],
],
'ftp_quit' => [
'old' => ['bool', 'ftp' => 'resource'],
'new' => ['bool', 'ftp' => 'FTP\Connection'],
],
'ftp_set_option' => [
'old' => ['bool', 'ftp' => 'resource', 'option' => 'int', 'value' => 'mixed'],
'new' => ['bool', 'ftp' => 'FTP\Connection', 'option' => 'int', 'value' => 'mixed'],
],
'ftp_get_option' => [
'old' => ['mixed|false', 'ftp' => 'resource', 'option' => 'int'],
'new' => ['mixed|false', 'ftp' => 'FTP\Connection', 'option' => 'int'],
],
],
'removed' => [],
];
<file_sep><p class="h5">Acara <b>COMPUTERUN 2.0</b> ini akan mengadakan kegiatan-kegiatan berupa:</p>
1. ***Opening Ceremony*** dengan kompetisi ***Virtual Run***<br><b class="teal-text">Target Peserta:</b> 300 orang
2. **2 × *Webinar*** yang mengangkat tema:
1. ***“Creativity in Building and Managing Business during Pandemic”***<br><b class="teal-text">Target Peserta:</b> 300 orang
2. ***“Implementation of *UI/UX* in Building A Digital Business”***<br><b class="teal-text">Target Peserta:</b> 300 orang
3. Sebuah ***Workshop*** yang bertema ***“Increasing User
Satisfaction based on User Habits”***<br><b class="teal-text">Target Peserta:</b> 40 orang
4. **2 jenis perlombaan** yang menguji para peserta internasional dalam **merancang situs web** (*Web Design Competition*) serta **menyelesaikan kasus *Business-*IT** (*Business-*IT *Case Competition*)<br><b class="teal-text">Target Peserta:</b> 20 tim (masing-masing kompetisi) dengan 3 orang / tim
5. ***Closing Ceremony*** untuk mengumumkan pemenang dan mengakhiri rangkaian kegiatan acara COMPUTERUN 2.0<br><b class="teal-text">Target Peserta:</b> 150 peserta **(Khusus undangan)**
<p class="h5">Seluruh rangkaian kegiatan ini akan menggunakan <b>Bahasa Inggris</b> sebagai bahasa pengantar, mengingat bahwa kegiatan-kegiatan tersebut akan <b>dilaksanakan secara internasional</b>. Perlu diketahui bahwa kegiatan-kegiatan tersebut akan dilaksanakan secara <b>daring (<i>online</i>)</b> mengingat situasi pandemi saat ini.</p>
<file_sep><p class="h2 text-center fw-bold">Rp 8.000.000,-</p>
1. **Logo ukuran XL** pada:
+ *Virtual background* pembicara dan pembawa acara
+ Setiap publikasi (termasuk *trailer* dan *aftermovie*) pada [akun-akun sosial media resmi **COMPUTERUN 2.0**]
+ Bagian *footer* pada website resmi **COMPUTERUN 2.0**
+ Sertifikat/*e-certificate* pemenang sub-acara
+ Setiap *merchandise* yang diberikan kepada para peserta maupun pembicara
+ *Welcoming page* yang digunakan oleh panitia untuk melakukan presentasi acara **COMPUTERUN 2.0** kepada peserta
2. Kesempatan untuk melakukan:
+ **Unggahan gambar/video promosi** di [akun-akun sosial media resmi **COMPUTERUN 2.0**]
+ **Penayangan video promosi** maks. 1,5 menit sepanjang acara berlangsung
+ ***Company Presentation*** maks. 10 menit sepanjang acara berlangsung
3. ***Ad Libs*** nama produk atau perusahaan selama acara berlangsung
4. Pihak panitia akan memastikan **tidak adanya pihak sponsor sejenis** yang ikut berpartisipasi dalam acara **COMPUTERUN 2.0**.
[akun-akun sosial media resmi **COMPUTERUN 2.0**]: https://linktr.ee/computerun
<file_sep><?php
namespace App\Http\Controllers;
use App\Mail\SendZoomReminder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\{Auth, Cache, DB, Mail, Session};
use Illuminate\Support\Str;
use DateTime;
class AdminController extends Controller
{
// Utility function to get all participant details of an event
private function util_getParticipantsByEventId($event_id){
return DB::table('registration')
->where('event_id', $event_id)
->join('users', 'users.id', '=', 'registration.ticket_id')
->join('universities', 'universities.id', '=', 'users.university_id')
->select('registration.*', 'users.name', 'users.nim', 'users.email', 'users.phone', 'users.line', 'users.whatsapp', DB::raw('universities.name AS university_name'))
->orderBy('status', 'desc')
->where('users.university_id', '!=', 2)
->where('users.university_id', '!=', 3)
->get();
}
// Utility function to get all attending committee details of an event
private function util_getCommitteesByEventId($event_id){
return DB::table('registration')
->where('event_id', $event_id)
->join('users', 'users.id', '=', 'registration.ticket_id')
->join('universities', 'universities.id', '=', 'users.university_id')
->select('registration.*', 'users.name', 'users.nim', 'users.email')
->orderBy('status', 'desc')
->where('users.university_id', 2)
->orWhere('users.university_id', 3)
->get();
}
public function index($path){
// Make sure that it's an Admin
if (!Auth::check() || (Auth::user()->university_id < 2 || Auth::user()->university_id > 3)){
Session::put('error', 'Admin: Not Authorized');
return redirect('login');
}
// Switch Case
switch ($path){
case "events":
return view('admin.events');
break;
}
}
public function getAllUsers(){
// Make sure that it's an Admin
if (!Auth::check() || (Auth::user()->university_id < 2 || Auth::user()->university_id > 3)){
Session::put('error', 'Admin: Not Authorized');
return redirect('login');
}
$users = DB::table('users')
->select('users.id', 'users.name', 'users.university_id', DB::raw('universities.name AS university_name'), 'users.email', 'users.verified')
->join('universities', 'university_id', 'universities.id')
->get();
$universities = DB::table('universities')->get();
return view('admin.users', ['users' => $users, 'universities' => $universities]);
}
public function postAllUsers(Request $request){
// Make sure that it's an Admin (Higher Level)
if (!Auth::check() || (Auth::user()->university_id != 2)){
Session::put('error', 'Admin: Not Authorized');
return redirect('login');
}
foreach($request->all() as $key => $value) {
if (Str::startsWith($key, "status-") && $value >= 0){
$key = substr($key, 7);
if ($value >= 0 && $value != '' && $key != Auth::user()->id) DB::table('users')->where('id', $key)->update(['university_id' => $value]);
}
}
return redirect('/admin/users');
}
public function getEventsList(){
// Make sure that it's an Admin
if (!Auth::check() || (Auth::user()->university_id < 2 || Auth::user()->university_id > 3)){
Session::put('error', 'Admin: Not Authorized');
return redirect('login');
}
return view('admin.events');
}
public function getEventParticipants($event_id){
// Make sure that it's an Admin
if (!Auth::check() || (Auth::user()->university_id < 2 || Auth::user()->university_id > 3)){
Session::put('error', 'Admin: Not Authorized');
return redirect('login');
}
$check = parent::checkAdminOrCommittee(Auth::id(), $event_id);
// Check whether the event exists
$event = DB::table('events')->where('id', $event_id)->first();
if (!$event){
Request::put('error', 'This event does not exist.');
return redirect('home');
}
// Gather the data
$data = DB::table('registration')->select('registration.*', 'users.name', 'users.email', 'users.verified', 'users.email_verified_at', 'users.university_id', 'users.created_at', 'users.updated_at')->join('users', 'users.id', 'registration.ticket_id')->where('event_id', $event_id)->get();
$event->current_seats = count($data);
$event->attending = 0;
$event->attended = 0;
foreach ($data as $registration){
if ($registration->status == 1) $event->current_seats--;
if ($registration->status == 4) $event->attending++;
if ($registration->status == 5) $event->attended++;
}
// Return view
return view('admin.event-manager', ['event' => $event, 'registrations' => $data, 'role' => $check]);
}
public function postEventParticipants(Request $request, $event_id){
// Make sure that it's an Admin (Higher Level)
if (!Auth::check() || (Auth::user()->university_id != 2)){
Session::put('error', 'Admin: Not Authorized');
return redirect('login');
}
foreach($request->all() as $key => $value) {
if (Str::startsWith($key, "status-") && strlen($value) > 0 && $value >= 0){
$key = substr($key, 7);
DB::table('registration')->where('id', $key)->update(['status' => $value]);
} else if (Str::startsWith($key, "sprint-") && strlen($value) > 0){
$key = substr($key, 7);
$user_id = DB::table('registration')->where('id', $key)->select('ticket_id')->first()->ticket_id;
DB::table('user_properties')->where('field_id', 'sprint.type')->whereRaw('user_id = ' . $user_id)->updateOrInsert([
'field_id' => 'sprint.type',
'user_id' => $user_id
], ['value' => $value]);
} else if (Str::startsWith($key, "workshop-") && strlen($value) > 0){
$key = substr($key, 9);
$user_id = DB::table('registration')->where('id', $key)->select('ticket_id')->first()->ticket_id;
DB::table('user_properties')->where('field_id', 'workshop.date')->whereRaw('user_id = ' . $user_id)->updateOrInsert([
'field_id' => 'workshop.date',
'user_id' => $user_id
], ['value' => $value]);
} else if (Str::startsWith($key, "action-")) switch ($key){
case "action-update-kicker":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['kicker' => $value]);
break;
case "action-update-name":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['name' => $value]);
break;
case "action-update-date":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['date' => new DateTime($value)]);
break;
case "action-update-location":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['location' => $value]);
break;
case "action-update-price":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['price' => $value]);
break;
case "action-update-cover_image":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['cover_image' => $value]);
break;
case "action-update-theme_color_foreground":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['theme_color_foreground' => $value]);
break;
case "action-update-theme_color_background":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['theme_color_background' => $value]);
break;
case "action-update-description_public":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['description_public' => $value]);
break;
case "action-update-description_pending":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['description_pending' => $value]);
break;
case "action-update-description_private":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['description_private' => $value]);
break;
case "action-registration-status":
if ($value == "enabled") DB::table('events')->where('id', $event_id)->update(['opened' => 1]);
else if ($value == "disabled") DB::table('events')->where('id', $event_id)->update(['opened' => 0]);
break;
case "action-registration-private":
if ($value == "private") DB::table('events')->where('id', $event_id)->update(['private' => 1]);
else if ($value == "public") DB::table('events')->where('id', $event_id)->update(['private' => 0]);
break;
case "action-registration-auto_accept":
if ($value == "enabled") DB::table('events')->where('id', $event_id)->update(['auto_accept' => 1]);
else if ($value == "disabled") DB::table('events')->where('id', $event_id)->update(['auto_accept' => 0]);
break;
case "action-update-seats":
if ($value > 0) DB::table('events')->where('id', $event_id)->update(['seats' => $value]);
break;
case "action-update-slots":
if ($value > 0) DB::table('events')->where('id', $event_id)->update(['slots' => $value]);
break;
case "action-update-team_members":
if ($value > 0) DB::table('events')->where('id', $event_id)->update(['team_members' => $value]);
break;
case "action-update-team_members_reserve":
if ($value > 0) DB::table('events')->where('id', $event_id)->update(['team_members_reserve' => $value]);
break;
case "action-update-payment_link":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['payment_link' => $value]);
break;
case "action-attendance-status":
if ($value == "enabled") DB::table('events')->where('id', $event_id)->update(['attendance_opened' => 1]);
else if ($value == "disabled") DB::table('events')->where('id', $event_id)->update(['attendance_opened' => 0]);
break;
case "action-attendance-type":
if ($value == "entrance") DB::table('events')->where('id', $event_id)->update(['attendance_is_exit' => 0]);
else if ($value == "exit") DB::table('events')->where('id', $event_id)->update(['attendance_is_exit' => 1]);
break;
case "action-update-url_link":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['url_link' => $value]);
break;
case "action-update-totp_key":
if ($value != '') DB::table('events')->where('id', $event_id)->update(['totp_key' => $value]);
break;
}
// Clear cache
Cache::forget('availableEvents');
$availableEvents = DB::table('events')->where('private', false)->where('opened', true)->get();
Cache::put('availableEvents', $availableEvents, 300);
}
return redirect("/admin/event/" . $event_id);
}
public function downloadEventParticipants($event_id){
// Make sure that it's an Admin
if (!Auth::check() || (Auth::user()->university_id < 2 || Auth::user()->university_id > 3)){
Session::put('error', 'Admin: Not Authorized');
return redirect('login');
}
$registration = $this->util_getParticipantsByEventId($event_id);
// TODO: Save from database to CSV
}
// Module to download from File ID
public function downloadFromFileId($type, $file_id){
// Make sure that it's an Admin
if(!Auth::check()){
Session::put('error', 'User: Please Login First');
return redirect('login');
}
if (Auth::user()->university_id < 2 || Auth::user()->university_id > 3){
Session::put('error', 'Admin: Not Authorized');
return redirect('login');
}
$file = DB::table('files')->where('id', $file_id)->first();
if ($file == null){
Session::put('error', 'Admin: File ID not found');
return redirect('home');
}
if($type == 1){
try {
return response()->download(storage_path("app/" . $file->name));
} catch (\Exception $e){
Session::put('error', 'Admin: Internal Server Error');
return redirect('home');
}
}else if($type == 2){
try {
return response()->download(storage_path("app/" . $file->answer_path));
} catch (\Exception $e){
Session::put('error', 'Admin: Internal Server Error');
return redirect('home');
}
}
}
// Module to send email to participants
public function sendZoomEmail($registration_id) {
if(!Auth::check() || Auth::user()->university_id != 2) return redirect('login')->with('error','Admin: Not Authorized');
$data = DB::table('registration')
->join('events','registration.event_id','=','events.id')
->join('users','registration.ticket_id','=','users.id')
->where('registration.id',$registration_id)
->first();
$data->id = $registration_id;
$data->event_name = DB::table('registration')
->join('events','registration.event_id','=','events.id')
->where('registration.id',$registration_id)
->first()->name;
if($data->remarks == 'SENT MAIL!') return back()->with('error','Admin: already send the email');
Mail::to($data->email)->send(new SendZoomReminder([
"event_name"=>$data->event_name,
"user_name"=>$data->name,
"event_date"=>date('Y-m-d', strtotime($data->date)),
"event_time"=>date('H:i', strtotime($data->date))
]));
DB::table('registration')
->where('id',$registration_id)
->update([
'remarks'=>'EMAIL SENT!'
]);
return back()->with('status','success sent the email');
}
// public function sendZoomEmail(Request $request){
// // Make sure that it's an Admin (Higher Level)
// if (!Auth::check() || (Auth::user()->university_id != 2)){
// Session::put('error', 'Admin: Not Authorized');
// return redirect('login');
// }
//
// // Do a SELECT query across multiple tables
// // $main_query = DB::table('registration')
// // ->selectRaw('registration.id AS \'registration_id\', registration.ticket_id, registration.event_id, events.name AS \'event_name\', DATE(events.date) AS \'event_date\', TIME(events.date) AS \'event_time\', users.name AS \'user_name\', users.email AS \'email\', registration.remarks AS \'remarks\'')
// // ->join('users','users.id','=','registration.ticket_id')
// // ->join('events','events.id','=','registration.event_id')
// // ->whereRaw('registration.event_id >= 8 AND registration.event_id <= 10 AND registration.status != 1 AND registration.remarks != \'EMAIL SENT!\'')
// // ->orderBy('event_date', 'ASC')
// // ->get();
// $main_query = DB::select("SELECT registration.id AS 'registration_id', registration.ticket_id, registration.event_id, events.name AS 'event_name', DATE(events.date) AS 'event_date', TIME(events.date) AS 'event_time', users.name AS 'user_name', users.email AS 'email', registration.remarks AS 'remarks' FROM registration JOIN users ON users.id = registration.ticket_id JOIN events ON events.id = registration.event_id WHERE registration.event_id >= 8 AND registration.event_id <= 10 AND registration.status != 1 ORDER BY event_date ASC");
//
// // Make sure that the query non-empty results
// if (count($main_query) == 0){
// Session::put('error', 'Admin: No more emails to send');
// return redirect('login');
// }
//
// // Send emails to first 10 emails
// $email_list = "";
// $registration_id_list = "";
// $j = 0; // Correction
// for ($i = 0; ($i - $j) < 10 && $i < count($main_query); $i++){
// // Send Email
// if ($main_query[$i]->remarks == "EMAIL SENT!"){
// $j++;
// continue;
// }
// Mail::to($main_query[$i]->email)->send(new SendZoomReminder(json_decode(json_encode($main_query[$i]), true)));
// $email_list .= " " . $main_query[$i]->email;
// DB::table('registration')->where("id", $main_query[$i]->id)->update(["remarks" => "EMAIL SENT!"]);
//
// $registration_id_list .= $main_query[$i]->registration_id;
// if ($i + 1 < 10 && $i + 1 < count($main_query)) $registration_id_list .= ", ";
// }
//
// // Make sure that the query non-empty results, again
// if ($registration_id_list == ''){
// Session::put('error', 'Admin: No more emails to send');
// return redirect('login');
// }
//
// // DB::table('registration')->whereRaw("id IN (" . $registration_id_list . ")")->update(["remarks" => "EMAIL SENT!"]);
//
// Session::put('status', 'Sent email to ' . ($i - $j) . ' participants:' . $email_list);
// return redirect('login');
// }
}
<file_sep>+ Setiap sponsor yang ingin berpartisipasi harus menyatakan kesediaannya dengan **menandatangani Surat Perjanjian Kerjasama** yang disediakan.
+ Setiap sponsor membayar **50% dana sponsorship** yang dilakukan **paling lambat 2 hari** setelah Surat Perjanjian Kerjasama yang disediakan.
+ Pelunasan dana sponsor **selambat-lambatnya** dilakukan pada hari acara Webinar yaitu hari **Sabtu, 27 November 2021**.
+ **Materi publikasi serta media** yang akan disampaikan oleh pihak sponsor berupa logo sponsor, iklan, dan lainnya selambat–lambatnya telah kami terima **1 (satu) bulan sebelum acara berlangsung**.
<file_sep>Pihak media partner mendukung kesuksesan acara dengan memberikan kontribusi antara lain:
+ **Membantu publikasi acara COMPUTERUN 2.0** melalui media (cetak dan elektronik).
+ **Mendukung, memenuhi, memberikan fasilitas, sarana, dan segala kebutuhan yang diperlukan** selama acara COMPUTERUN 2.0 berlangsung.
<file_sep>Pihak panitia COMPUTERUN 2.0 memberikan kontraprestasi dalam bentuk:
+ **Poster**<br>Logo atau nama media partner dicantumkan pada poster dengan ukuran S.
+ ***Adlibs* oleh MC**<br>MC menyebutkan nama-nama media partner sebanyak 1 (satu) kali pada saat acara workshop webinar berlangsung.
+ **Publikasi Sosial Media**<br>Logo atau nama media partner dicantumkan sebanyak **1 (satu) kali** melalui akun Instagram, Twitter, dan YouTube resmi COMPUTERUN 2.0.
+ **Website**<br>Logo atau nama media partner dicantumkan pada website COMPUTERUN 2.0.
<file_sep>1. Participants must **attend the workshop on time**.
2. Participants are required to **turn on their camera and apply the virtual background** provided by the committee.
3. Participants are recommended to wear casual or formal attire.
4. Participants must rename their ZOOM name with the format **“Full Name - University Name”**
5. Participants are required to **turn off their microphone** and only activated when requested by the committee.
6. Participants are allowed only to ask questions by raising their hand, or write their questions in the chat box.
7. Participants are **prohibited to talk using inappropriate language or containing racial, religious, and ethnicity discrimination**.
8. Participants are **not allowed to smoke, vape or sleep** during the session.
9. Participants are **required to use [Figma](https://figma.com)** during the workshop session, both web app & desktop app are allowed.
<file_sep>+ Meningkatkan eksistensi universitas, serta organisasi **HIMSISFO** dan **HIMTI** yang berjalan dalam bidang teknologi informasi baik dalam lingkup nasional hingga internasional.
+ Memahami hal-hal mengenai **kreativitas** dalam menciptakan sebuah **inovasi**, serta **menciptakan peluang bisnis** yang berbasis **teknologi**.
+ **Menghasilkan perubahan positif dan pemimpin yang unggul** baik dalam individu maupun organisasi yang dapat diterima secara global.
+ Mempersiapkan mahasiswa **BINUS University** dan **seluruh peserta** dalam dunia pekerjaan.
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddEventGroupMigration extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Create "Event Group" table
if (!Schema::hasTable('event_groups')) Schema::create('event_groups', function (Blueprint $table) {
$table->increments('id');
$table->text('name');
$table->longText('description')->nullable();
$table->text('url')->nullable();
$table->mediumText('cover_image')->nullable();
});
// Alter "Events" table
if (Schema::hasTable('events')) Schema::table('events', function (Blueprint $table) {
$table->unsignedInteger('event_group_id')->nullable();
$table->foreign('event_group_id')->references('id')->on('event_groups');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Alter "Events" table
if (Schema::hasTable('events')) Schema::table('events', function (Blueprint $table) {
$table->dropColumn('event_group_id');
});
// Drop "Event Group" table
Schema::dropIfExists('event_group');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Symfony\Component\Yaml\Yaml;
class PagesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return redirect('/');
}
/**
* Utility function to fetch the YAML file
*
* @param int $id
* @return array
*/
public static function parseYamlFromPage($id)
{
$index_path = public_path() . '/docs/2021/pages/' . $id . '/index.yml';
if (!file_exists($index_path)){
return false;
}
return Yaml::parse(file_get_contents($index_path));
}
/**
* Utility function to get excerpt from a valid document
*
* @param int $id
* @return array
*/
public static $fullPlaintextProperties = ['kicker', 'title'];
public static $plaintextProperties = ['description', 'text'];
public static function getExcerptFromWidget($widget, $recursive, $limit)
{
$result = '';
if (isset($widget['type']) && $widget['type'] === 'markdown'){
if (isset($widget['file']) && !isset($widget['text']) && file_exists(public_path() . $widget['file'])){
$widget['text'] = strip_tags(new \Parsedown())->text(file_get_contents(public_path() . $widget['file']));
} else $widget['text'] = strip_tags((new \Parsedown())->text($widget['text']));
}
foreach(PagesController::$plaintextProperties as $property) if (isset($widget[$property])){
$result .= $widget[$property] . ' ';
$limit -= strlen($widget[$property]) + 1;
}
if ($recursive == true) foreach(PagesController::$fullPlaintextProperties as $property) if (isset($widget[$property])){
$result .= $widget[$property] . ' ';
$limit -= strlen($widget[$property]) + 1;
}
// Remove last space
if (strlen($result) > 0){
$result = substr($result, 0, -1);
$limit++;
}
if ($limit < 0) $result = substr($result, 0, $limit - 1) . '…';
else if (($recursive === true || is_int($recursive)) && isset($widget['children'])){
foreach ($widget['children'] as $c){
$extracted = PagesController::getExcerptFromWidget($c, $recursive, $limit);
if (strlen($extracted) > 0 && strlen($result) > 0) $extracted = ' ' . $extracted;
$result .= $extracted;
$limit -= strlen($extracted);
if ($limit < 0){
$result = substr($result, ($recursive === true) ? true : ($recursive - 1), $limit - 1) . '…';
break;
}
}
}
return $result;
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// Check whether the YAML file is valid
$index_data = $this->parseYamlFromPage($id);
if ($index_data === false || !isset($index_data['@manifest'])){
abort(404);
return;
}
// Return view with unparsed data (parsing is done on view)
return view('components.page', $index_data);
}
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class EmailQueueV2 extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Adds new features into the existing email queue database
if (Schema::hasTable('email_queue')) Schema::table('email_queue', function (Blueprint $table) {
$table->text('message_type')->default('PLAINTEXT');
$table->text('sender_name')->default('Registration System');
$table->integer('priority')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if (Schema::hasTable('email_queue')) Schema::table('email_queue', function (Blueprint $table) {
$table->dropColumn('message_type');
$table->dropColumn('sender_name');
$table->dropColumn('priority');
});
}
}
<file_sep>1. Participants must reach the minimum distance of **5 KM (approx. 3.11 mi)**, which can be accumulated during the race period.
2. Participants are **prohibited to use any vehicle** (bicycle, motorcycle, car, or any other transportation mode) in tracking their running miles.
3. Participants are **not allowed to use the treadmill**.
4. Participants must use **[STRAVA](https://www.strava.com)** to record their run and **only run records from [STRAVA](https://www.strava.com) are accepted as valid**.
5. Participants must join the **COMPUTERUN 2.0 STRAVA club** or else any run records submitted are considered invalid.
6. Participants submit their running records (distance and screenshot) through **our form available on COMPUTERUN 2.0 website**.
7. Participants are **allowed** to submit their running records **multiple times**.
8. The **Finisher Pack (medal, t-shirt, and string bag)** will only be given to those who have reached the target distance of 5 km.
## Additional Rules and Guidelines
Full details of the COMPUTERUN 2.0 SPRINT Virtual Run Competition guidelines are available on [this Guidebook (PDF)](https://drive.google.com/drive/folders/1POK9vsjJk08WX1VD6ajv5E5vPNc6nKXb).<file_sep><?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Exception;
class NewAttendanceController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
// Utility function to check whether the registration has been opened
private function isEventExists($eventId){
try {
// Check the database whether the event is opened
$event = DB::table('events')->where('id', $eventId)->get();
if (!isset($event) || count($event) == 0 || $event[0]->attendance_opened == 0) return false;
return $event[0]->name;
} catch (Exception $e){
return false;
}
}
// private function validateEvent($eventId, $eventtoken){
// try {
// // Check the database whether the event is opened
// $event = DB::table('events')->where('id', $eventId)->get();
// if (!isset($event) || count($event) == 0 || $event[0]->attendance_opened == 0) return false;
// if ($event[0]->totp_key != $eventtoken) return false;
// return $event[0]->name;
// } catch (Exception $e){
// return false;
// }
// }
//
// private function handleAttendance($eventId, $user){
//// dd(Carbon::now());
// $eventSearch = DB::table('events')->where('id', $eventId)->get()[0];
//
// try {
// // buat ngecek apakah peserta telah mengikuti atau sedang mengikuti
// $isExit = true;
// if ($eventSearch->attendance_is_exit == 0) $isExit = false;
//
// // Search on ticket
// $registrationSearch = DB::table('registration')->where('ticket_id', $user->id)->where('event_id', $eventId)->get();
// if (count($registrationSearch) == 0) throw new Exception();
//
// $i = 0;
// while ($i < count($registrationSearch) && $registrationSearch[$i]->status < 2) $i++;
// if ($i == count($registrationSearch)) throw new Exception();
//
// // Add to Attendance
// $attendancePayload = [
//// 'registration_id' => $registrationSearch[$i]->id,
//// 'type' => "EVENT_#" . $eventId . "_" . (($isExit) ? "EXIT" : "ENTRANCE"),
//// 'timestamp' => now()
// ];
//// DB::table("attendance")->insertGetId($attendancePayload);
// $attendanceId = "";
//
// // Update the registration table
// if (
// (!$isExit && $registrationSearch[$i]->status == 2) ||
// ($isExit && $registrationSearch[$i]->status == 4)
// ) DB::table("registration")->where('id', $registrationSearch[$i]->id)->update(['status' => (!$isExit) ? 4 : 5]);
//
// $viewPayload = [
//// 'attendance_id' => $attendanceId,
//// 'registration_id' => $registrationSearch[$i]->id,
//// 'event_id' => $eventId,
//// 'account_id' => $user->id,
//// 'account_name' => $user->name,
//// 'attendance_type' => $attendancePayload['type'],
//// 'attendance_timestamp' => date_format($attendancePayload['timestamp'],"Y-m-d H:i:s"),
//// 'event_name' => $eventSearch->name,
//// 'url_link' => $eventSearch->url_link
// ];
//
// return ($isExit) ? view("static.webinar-end", $viewPayload) : view("static.webinar-start", $viewPayload);
// } catch (Exception $e){
// Session::put('error', 'Attendance: No valid tickets found for this event.');
// return redirect('home');
// }
// }
//
// // Login Page
// public function index($eventId){
// $validated = $this->isEventExists($eventId);
// if (!$validated){
// Session::put('error', 'Attendance: This event is not open for attendance or does not exist.');
// }
//
// // Directly check the ticket if the user has logged in
// //if (Session::has('nim') && Session::has('ticket_number')) return $this->handleAttendance($eventId, Session::get('nim'), Session::get('ticket_number'));
//
// return redirect('login');
// }
//
// // Handle submissions
// public function store(Request $request, $eventId){
// if (!Auth::check()) return response()->json(['error' => 'You are not authenticated']);
//
// $eventtoken = $request->input('event-token');
// $validated = $this->validateEvent($eventId, $eventtoken);
// if (!$validated){
// Session::put('error', 'Attendance: Incorrect Attendance Token. Please try again.');
// return redirect('home');
// }
//
// return $this->handleAttendance($eventId, Auth::user());
// }
public function index($event_id, $id) {
if(!$this->isEventExists($event_id)) return redirect('home')->with('error', 'Attendance: This event is not open for attendance or does not exist.');
$data = DB::table('registration')
->join('events','registration.event_id','=','events.id')
->where('registration.event_id',$event_id)
->where('registration.id',$id)
->first();
$data->id = $id;
$attendance = DB::table('attendance')
->join('registration','attendance.registration_id','=','registration.id')
->where('registration.event_id', $event_id)
->where('registration.id',$id)
->first();
return view('static.webinar-start',[
'data'=>$data,
'attendance'=>$attendance
]);
}
public function store(Request $request, $event_id, $id){
if($request->type == 1) {
DB::table('users')->where('id',Auth::user()->id)->update([
'nim'=>$request->nim,
'major'=>$request->major
]);
return back()->with('status','Success update profile data');
}elseif ($request->type == 2) {
$attendance = DB::table('attendance')
->join('registration','attendance.registration_id','=','registration.id')
->where('registration.event_id', $event_id)
->where('registration.id',$id)
->first();
if($attendance != null) return back()->with('error','You have been record your entry attendance at '. $attendance->entry_timestamp);
DB::table('attendance')->insert([
'entry_timestamp'=>Carbon::now(),
'registration_id'=>$request->registration_id,
'remarks'=>'Attending'
]);
DB::table('registration')
->where('registration.event_id',$event_id)
->where('registration.id',$id)
->update([
'status'=>4
]);
}elseif ($request->type == 3) {
$attendance = DB::table('attendance')
->where('registration_id', $request->registration_id)
->first();
if($attendance == null) return back()->with('error','You have not record your entry attendance');
if($attendance->exit_timestamp != null) return back()->with('error','You have been record your exit attendance at '. $attendance->exit_timestamp);
$event = DB::table('events')
->where('id',$event_id)
->first();
if($request->event_token == null || $request->event_token != $event->totp_key) return back()->with('error','You have input the wrong token key');
DB::table('attendance')
->where('registration_id',$request->registration_id)
->update([
'exit_timestamp'=>Carbon::now(),
'remarks'=>'Attended'
]);
DB::table('registration')
->where('registration.event_id',$event_id)
->where('registration.id',$id)
->update([
'status'=>5
]);
}
return back()->with('status','Success record attendance to system');
}
}
<file_sep>from tkinter import *
import base64
import datetime
import os
import webbrowser
# The following dependencies must be installed separately
from PIL import Image
import pyotp
import qrcode
import uuid
class App(Frame):
prepend_template = '''
APP_NAME="Computerun 2020"
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=<PASSWORD>
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${{APP_NAME}}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${{PUSHER_APP_KEY}}"
MIX_PUSHER_APP_CLUSTER="${{PUSHER_APP_CLUSTER}}"
'''
env_APP_KEY = ""
env_DB_CONNECTION = "mysql"
env_DB_HOST = "127.0.0.1"
env_DB_PORT = "3306"
env_DB_DATABASE = "laravel"
env_DB_USERNAME = "root"
env_DB_PASSWORD = ""
env_ADMIN_2FA_KEY = str(uuid.uuid4())
is_custom_APP_KEY = False
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
menu = Menu(self.master)
self.master.config(menu=menu)
# "About" menu
aboutMenu = Menu(menu)
aboutMenu.add_command(label="Website (for event promotion)", command=self.websiteLink)
aboutMenu.add_command(label="GitHub Repository", command=self.githubLink)
aboutMenu.add_command(label="Sponsor Our Event")
menu.add_cascade(label="About", menu=aboutMenu)
# Form fields
Label(master, text="Step 1: Fill Optional Details", font="sans-serif 18 bold").grid(row=0, column=0, columnspan=2)
Label(master, text="App Key").grid(row=1, column=0)
Label(master, text="DB Server Connection").grid(row=2, column=0)
Label(master, text="DB Server Host (IP Address)").grid(row=3, column=0)
Label(master, text="DB Server Port").grid(row=4, column=0)
Label(master, text="Database Name").grid(row=5, column=0)
Label(master, text="DB Server Username").grid(row=6, column=0)
Label(master, text="DB Server Password").grid(row=7, column=0)
Label(master, text="Admin 2FA Key").grid(row=8, column=0)
input_APP_KEY = Entry(master)
input_DB_CONNECTION = Entry(master)
input_DB_HOST = Entry(master)
input_DB_PORT = Entry(master)
input_DB_DATABASE = Entry(master)
input_DB_USERNAME = Entry(master)
input_DB_PASSWORD = Entry(master)
input_ADMIN_2FA_KEY = Entry(master)
input_APP_KEY.grid(row=1, column=1)
input_DB_CONNECTION.grid(row=2, column=1)
input_DB_HOST.grid(row=3, column=1)
input_DB_PORT.grid(row=4, column=1)
input_DB_DATABASE.grid(row=5, column=1)
input_DB_USERNAME.grid(row=6, column=1)
input_DB_PASSWORD.grid(row=7, column=1)
input_ADMIN_2FA_KEY.grid(row=8, column=1)
def clicked():
if input_APP_KEY.get() != "":
self.env_APP_KEY = input_APP_KEY.get()
if input_DB_CONNECTION.get() != "":
self.env_DB_CONNECTION = input_DB_CONNECTION.get()
if input_DB_HOST.get() != "":
self.env_DB_HOST = input_DB_HOST.get()
if input_DB_PORT.get() != "":
self.env_DB_PORT = input_DB_PORT.get()
if input_DB_DATABASE.get() != "":
self.env_DB_DATABASE = input_DB_DATABASE.get()
if input_DB_USERNAME.get() != "":
self.env_DB_USERNAME = input_DB_USERNAME.get()
if input_DB_PASSWORD.get() != "":
self.env_DB_PASSWORD = input_DB_PASSWORD.get()
if input_ADMIN_2FA_KEY.get() != "":
self.env_ADMIN_2FA_KEY = input_ADMIN_2FA_KEY.get()
self.is_custom_APP_KEY = True
self.generateTotpChallenge()
Button(master, text="Generate", command=clicked).grid(row=9,column=0, columnspan=2)
def generateEnvFile(self):
print("Generating .env file...")
envFile = open("../.env", "w")
envFile.write(self.prepend_template)
envFile.write("\n\n# Generated from /scripts/generate_env.py at " + datetime.datetime.now().isoformat() + "\n")
envFile.write("APP_KEY=" + self.env_APP_KEY + "\n")
envFile.write("DB_CONNECTION=" + self.env_DB_CONNECTION + "\n")
envFile.write("DB_HOST=" + self.env_DB_HOST + "\n")
envFile.write("DB_PORT=" + self.env_DB_PORT + "\n")
envFile.write("DB_DATABASE=" + self.env_DB_DATABASE + "\n")
envFile.write("DB_USERNAME=" + self.env_DB_USERNAME + "\n")
envFile.write("DB_PASSWORD=" + self.env_DB_PASSWORD + "\n")
envFile.write("ADMIN_2FA_KEY=" + self.env_ADMIN_2FA_KEY + "\n")
envFile.close()
Label(self.master, text="Done!", font="sans-serif 18 bold").grid(row=0, column=0, columnspan=2)
Label(self.master, text="Your .env file has been created.").grid(row=1, column=0)
Label(self.master, text="If you are new to this repository, please execute\n'php artisan key:generate' on the root directory\nto create a new APP_KEY.", fg="red").grid(row=2, column=0)
def generateTotpChallenge(self):
self.destroyAllWidgets()
Label(self.master, text="Step 2: TOTP Verification", font="sans-serif 18 bold").grid(row=0, column=0, columnspan=2)
# Create the QR code
base32Encoded = base64.b32encode(str.encode(self.env_ADMIN_2FA_KEY)).decode()
totp = pyotp.totp.TOTP(base32Encoded)
qrPayload = totp.provisioning_uri(name="Admin", issuer_name="Computerun 2020")
qrcode.make(qrPayload).save("temp.png")
# Resize so it fits the canvas
img = Image.open("temp.png")
img = img.resize((300, 300), Image.ANTIALIAS)
img.save("temp.png")
# Load inside the canvas
qrCanvas = Canvas(self.master, width = 300, height = 300)
qrCanvas.grid(row=1, column=0)
qrCanvas.imgBuffer = PhotoImage(file="temp.png")
qrCanvas.imgBuffer.subsample(2)
qrCanvas.create_image(0, 0, anchor = NW, image = qrCanvas.imgBuffer)
def openInDesktop():
webbrowser.open(qrPayload)
Button(self.master, text="Open in desktop app", command=openInDesktop).grid(row=2, column=0)
Label(self.master, text="Instruction", font="sans-serif 16 bold").grid(row=3, column=0)
Label(self.master, text="Scan this QR code into your Authenticator app\n(Google/Microsoft Authenticator, Authy, FreeOTP, etc.)\nand enter the code below").grid(row=4, column=0)
input_TOTP = Entry(self.master)
input_TOTP.grid(row=5, column=0)
errorMessage = Label(self.master, text="", fg="red")
errorMessage.grid(row=7, column=0)
def verifyTotp():
if totp.verify(otp=input_TOTP.get()):
self.destroyAllWidgets()
self.generateEnvFile()
else:
errorMessage["text"] = "Invalid OTP\nIf this issue persists, check your\ndate/time settings."
Button(self.master, text="Verify", command=verifyTotp).grid(row=6, column=0)
def destroyAllWidgets(self):
for widget in self.master.winfo_children():
widget.destroy()
def exitProgram(self):
if os.path.exists("temp.png"):
os.remove("temp.png")
exit()
def openLink(self, url):
webbrowser.open(url)
def githubLink(self):
webbrowser.open("https://www.github.com/reinhart1010/computerun-2020")
def websiteLink(self):
webbrowser.open("http://computerun.id")
root = Tk()
app = App(root)
root.wm_title("Computerun 2020")
root.geometry("400x600")
root.mainloop()
<file_sep><?php
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return (new App\Http\Controllers\PagesController())->show('home');
// return view('static.index');
});
Route::get('/email/verify', function () {
return view('auth.verify');
})->middleware('auth')->name('verification.notice');
Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
$request->fulfill();
return redirect('/home');
})->middleware(['auth', 'signed'])->name('verification.verify');
// Route::get('/uses', function () {
// return view('static.uses');
// });
Route::get('/sponsor-us', function () {
return (new App\Http\Controllers\PagesController())->show('sponsor-us');
});
Route::get('/media-partner-proposal', function () {
return (new App\Http\Controllers\PagesController())->show('media-partner-proposal');
});
Route::get('/event-template', function () {
return view('static.event-template');
});
Route::get('/contact', function () {
return (new App\Http\Controllers\PagesController())->show('contact');
});
Route::get('/twibbon', function () {
return redirect('/info/twibbon-guidelines');
});
Route::resource('info', 'PagesController');
Route::view('userview', "registration");
Route::post('postcontroller', 'PostController@formSubmit');
// Login / User Dashboard
// Route::resource('/login', 'TicketStatusController');
Route::get('/logout', 'TicketStatusController@logout');
Auth::routes(['verify' => false]);
// Auth::routes(['verify' => true]);
Route::post('/changeaccountdetails', 'UserSettingsController@updateContacts');
// Get user details (for registration)
Route::post('/getuserdetails', 'UserSettingsController@getUserDetails');
// Handle registration
Route::get('/register/{id}', 'UserSettingsController@registrationRedirectHandler');
Route::post('/registerevent', 'UserSettingsController@registerToEvent');
// Handle payments
Route::get('/pay/{paymentcode}', 'UserSettingsController@paymentIndex');
Route::post('/pay/{paymentcode}', 'UserSettingsController@paymentHandler');
// Handle User download file
Route::get('/user/downloadFile/cp/{teamid}', 'UserSettingsController@downloadFileCompetition');
Route::get('/user/downloadFile/{type}/{paymentcode}/{fileid}', 'UserSettingsController@downloadFileUser');
// Handle competition
Route::get('/cp/{teamid}', 'UserSettingsController@competitionIndex');
Route::post('/cp/{teamid}', 'UserSettingsController@competitionHandler');
// Handle attendance
Route::get('/attendance/{eventId}/{id}', 'NewAttendanceController@index');
Route::post('/attendance/{eventId}/{id}', 'NewAttendanceController@store');
// Handle attendance
//Route::get('/attendance/{eventId}', ['uses' =>'NewAttendanceController@index']);
//Route::post('/attendance/{eventId}', ['uses' =>'NewAttendanceController@store']);
// Route::get('/webinarTest', function () {
// $payload = [
// 'attendance_id' => "1",
// 'registration_id' => "2",
// 'event_id' => "3",
// 'account_id' => "4",
// 'account_name' => "5",
// 'attendance_type' => "6",
// 'attendance_timestamp' => "7",
// 'event_name' => "Lorem Ipsum",
// 'url_link' => "https://gojek.com"
// ];
// return view('static.webinar-end', $payload);
// });
// User Dashboard
Route::get('/profile', function () {
return redirect('/home');
});
Route::get('/home', 'HomeController@index')->name('dashboard.home');
// Administration Panel
Route::get('/admin', function () {
return redirect('/home');
});
// Route::get('/admin/{path}', 'AdminController@index');
Route::get('/admin/downloadFile/{type}/{file_id}', 'AdminController@downloadFromFileId');
Route::get('/admin/events', 'AdminController@getEventsList');
Route::get('/admin/event/{event_id}', 'AdminController@getEventParticipants');
Route::post('/admin/event/{event_id}', 'AdminController@postEventParticipants');
Route::get('/admin/users', 'AdminController@getAllUsers');
Route::post('/admin/users', 'AdminController@postAllUsers');
Route::get('/admin/sendemail/{registration_id}', 'AdminController@sendZoomEmail');
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class MergeRegistrationAndAttendance extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Update "registration" database
Schema::table('registration', function (Blueprint $table) {
$table->dateTime('check_in_timestamp')->nullable();
$table->dateTime('check_out_timestamp')->nullable();
});
// Merge all "attendance" to "registration"
$attendances = DB::table('attendance')->get();
foreach ($attendances as $attendance){
$registration = DB::table('registration')->where('id', $attendance->registration_id)->first();
if ($registration->check_in_timestamp == null || strtotime($attendance->entry_timestamp) < strtotime($registration->check_in_timestamp)){
DB::table('registration')->where('id', $attendance->registration_id)->update(['check_in_timestamp' => $attendance->entry_timestamp]);
}
if ($registration->check_out_timestamp == null || strtotime($attendance->exit_timestamp) < strtotime($registration->check_out_timestamp)){
DB::table('registration')->where('id', $attendance->registration_id)->update(['check_out_timestamp' => $attendance->exit_timestamp]);
}
if (strlen($registration->remarks) == 0 || $registration->remarks == 'Late'){
DB::table('registration')->where('id', $attendance->registration_id)->update(['check_out_timestamp', $attendance->remarks]);
}
}
// Delete columns
Schema::dropIfExists('attendance');
$registrations = DB::table('registration')->get();
foreach ($registrations as $registration){
$check_in_length = strlen($registration->check_in_timestamp);
$check_out_length = strlen($registration->check_out_timestamp);
if ($check_in_length + $check_out_length == 0) continue;
$status = 4;
$remarks = 'On Time';
if ($check_in_length == 0 && $check_out_length > 0) $remarks = 'Late';
if ($check_in_length > 0 && $check_out_length > 0 && $registration->remarks != 'Late') $status = 5;
DB::table('registration')->where('id', $registration->id)->update(['status' => $status, 'remarks' => $remarks]);
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Recreate 'attendance' table
if (!Schema::hasTable('attendance')) Schema::create('attendance', function (Blueprint $table) {
$table->increments('id');
$table->dateTime('entry_timestamp')->nullable();
$table->dateTime('exit_timestamp')->nullable();
$table->unsignedInteger('registration_id');
$table->foreign('registration_id')->references('id')->on('registration');
$table->text('remarks');
});
// Put all 'registration' timestamp inside 'attendance'
$registrations = DB::table('registration')->orderBy('check_in_timestamp', 'asc')->get();
foreach($registrations as $registration){
$check_in_length = strlen($registration->check_in_timestamp);
$check_out_length = strlen($registration->check_out_timestamp);
if ($check_in_length + $check_out_length == 0) continue;
DB::table('attendance')->insert(['registration_id' => $registration->id, 'entry_timestamp' => $registration->check_in_timestamp, 'exit_timestamp' => $registration->check_out_timestamp, 'remarks' => $registration->remarks]);
}
Schema::table('registration', function (Blueprint $table) {
$table->dropColumn('check_in_timestamp');
$table->dropColumn('check_out_timestamp');
});
}
}
<file_sep>var majorList = [
{
name: "Accounting",
regex: /^( )*((Akuntan(si){0,1})|(Acc(ount(ing|ant)){0,1}))( )*$/gi
},
{
name: "Computer Science",
regex: /^( )*((T(eknik){0,1}( )*I(nformatika){0,1})|(IT)|(Comp(uter){0,1}( )*Sci(ence){0,1}))( )*$/gi
},
{
name: "Computer Science, Global Class",
regex: /^( )*((T(eknik){0,1}( )*I(nformatika){0,1})|(IT)|(C(omp(uter){0,1}){0,1}( )*S(ci(ence){0,1}){0,1}))[ (,-:]+(G(lobal){0,1}( )*C(lass){0,1})\){0,1}( )*$/gi
},
{
name: "Computer Science, Master Track",
regex: /^( )*((T(eknik){0,1}( )*I(nformatika){0,1})|(IT)|(C(omp(uter){0,1}){0,1}( )*S(ci(ence){0,1}){0,1}))[ (,-:]+(M(aster){0,1}( )*T(rack){0,1})\){0,1}( )*$/gi
},
{
name: "Cyber Security",
regex: /^( )*C(y(ber){0,1}){0,1}( )*S(ec(urity){0,1}){0,1}( )*$/gi
},
{
name: "Game Application and Technology",
regex: /^( )*G(ame){0,1}( )*A(pp(lication){0,1}(s){0,1}){0,1}( )*((and)|&){0,1}( )*T(ech(nology){0,1}){0,1}( )*$/gi
},
{
name: "DKV Animation",
regex: /^( )*D(esain){0,1}( )*K(omunikasi){0,1}( )*V(isual){0,1}[ (,-:]+A(nim((asi)|(ation)){0,1}){0,1}\){0,1}( )*$/gi
},
{
name: "DKV Creative Advertising",
regex: /^( )*D(esain){0,1}( )*K(omunikasi){0,1}( )*V(isual){0,1}[ (,-:]+C(reative){0,1}( )*A(d(vert(ising){0,1}){0,1}){0,1}\){0,1}( )*$/gi
},
{
name: "DKV New Media",
regex: /^( )*D(esain){0,1}( )*K(omunikasi){0,1}( )*V(isual){0,1}[ (,-:]+N(ew){0,1}( )*M(edia){0,1}\){0,1}( )*$/gi
},
{
name: "Food Technology",
regex: /^( )*Food( )*Tech(nology){0,1}( )*$/gi
},
{
name: "Information Systems",
regex: /^( )*((I(nfo(rmation){0,1}){0,1}( )*S(ys(tem(s){0,1}){0,1}){0,1})|(S(is(tem){0,1}){0,1})( )*((I(nfo(rmasi){0,1}){0,1})|(fo)))( )*$/gi
},
{
name: "Magister Computer Science",
regex: /^( )*((Magister)|(S2))( )*((T(eknik){0,1}( )*I(nformatika){0,1})|(IT)|(C(omp(uter){0,1}){0,1}( )*S(ci(ence){0,1}){0,1}))( )*$/gi
},
{
name: "Marketing Communication",
regex: /^( )*Mar(ket(ing){0,1}){0,1}( )*Com(m(unication(s){0,1}){0,1}){0,1}( )*$/gi
},
{
name: "Mass Communication",
regex: /^( )*Mas(s){0,1}( )*Com(m(unication(s){0,1}){0,1}){0,1}( )*$/gi
},
{
name: "Mobile Application and Technology",
regex: /^( )*M(obile){0,1}( )*A(pp(lication){0,1}(s){0,1}){0,1}( )*((and)|&){0,1}( )*T(ech(nology){0,1}){0,1}( )*$/gi
}
]
function phoneNumberAutofill(id){
document.getElementById(id).value = (document.getElementById("action-change-phone").value == "") ? document.getElementById("action-change-phone").placeholder : document.getElementById("action-change-phone").value;
}
function updateCart(){
var total = 0, res = "";
var query = document.querySelectorAll(".eventitem:checked");
query.forEach(function (data){
if(data.attributes["data-price"]) total += parseInt(data.attributes["data-price"].nodeValue);
});
if (query.length > 0){
res += "<h4>TOTAL PRICE</h4>";
res += "<h1>Rp " + total + "</h1>";
if (total > 0){
res += '<label for="evidence">Payment Receipt: </label><input type="file" id="evidence" name="evidence" accept="image/*" required>';
}
res += '<input type="hidden" name="total" value="' + total + '">';
res += '<button type="submit" class="btn btn-primary">Submit</button>';
document.getElementById("confirmation").innerHTML = res;
} else {
document.getElementById("confirmation").innerHTML = "Please select one of the events before submitting.";
}
}
function autofillMajor(id){
// Autofill major nicknames and alternative nicknames
// Database based on https://gist.github.com/reinhart1010/43e9544172c501055f5a5067ed317843
var init = document.getElementById(id).value;
var initial = init.toLowerCase().charCodeAt(0);
var i;
// Optimization to reduce algorithmic complexity to be closer to O(n/2)
if (initial - "a".charCodeAt(0) < "z".charCodeAt(0) - initial) for (i = 0; i < majorList.length; i++){
if (init.match(majorList[i].regex)){
init = majorList[i].name;
break;
}
} else for (i = majorList.length - 1; i >= 0; i--){
if (init.match(majorList[i].regex)){
init = majorList[i].name;
break;
}
};
document.getElementById(id).value = init;
}
function binusianToggle(enabled){
var query = document.querySelectorAll(".binusian-only");
query.forEach(function (data){
data.required = enabled;
data.style.display = (enabled) ? "block" : "none";
});
}
<file_sep><?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class SendNewTeamNotification extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($data)
{
$this->data = $data;
$this->subject('You have been added to a team in COMPUTERUN 2020 (' . $data["team_name"] . ')');
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->markdown('emails.newteamnotification');
}
}
<file_sep><p class="h2 text-center fw-bold">Rp 2.000.000,-</p>
**Logo ukuran S** pada:
+ Setiap publikasi (termasuk *trailer* dan *aftermovie*) pada [akun-akun sosial media resmi **COMPUTERUN 2.0**]
+ Bagian *footer* pada website resmi **COMPUTERUN 2.0**
+ Setiap *merchandise* yang diberikan kepada para peserta maupun pembicara
+ *Welcoming page* yang digunakan oleh panitia untuk melakukan presentasi acara **COMPUTERUN 2.0** kepada peserta
[akun-akun sosial media resmi **COMPUTERUN 2.0**]: https://linktr.ee/computerun
<file_sep>## General Competition Rules
1. Each participant must be an **active S1/D4/D3 (bachelor) student** of a public or private university, with proof of scanned **student identification card (KTM)**.
2. Each group must consist of **two (2) members and one (1) leader**.
3. Each group member may belong from the same or different colleges or institutions.
4. Each participant is **not allowed** to indicate the origin of their institution or college.
5. Each registered group **cannot change the group name or group members for any reason**.
6. Each participant **must upload a twibbon** on each group member's Instagram account.
## Website Development Guidelines
+ The use of frameworks or templates from other people or third-party are **not allowed**.
+ The final website must be **originally created** and is not the result of plagiarism.
+ Components included in the final website such as the use of elements or materials (logos, photoworks, graphicworks, trademarks, etc) must be free from copyright.
+ The website created in this competition has never been included in previous or any competition before.
+ Elements such as ethnicity, religion, race, inter-group relations and pornographic elements are strictly prohibited in the website.
+ Every reference used in making of the website must be submitted in a separate file with the format of “.docx” or “txt”
+ Judges and the committees possess the right to cancel or disqualify participants that are proven cheating, fraud indicated in plagiarism or any copyright infringement.
## Additional Rules and Guidelines
Full details of the COMPUTERUN 2.0 Web Design Competition guidelines are available on [this Guidebook (PDF)](https://drive.google.com/drive/folders/1POK9vsjJk08WX1VD6ajv5E5vPNc6nKXb).
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected function checkAdminOrCommittee($userId, $eventId){
$admin = false;
$committee = false;
// Check whether the user is an admin or comittee
$select = DB::table('user_properties')->where('user_id', $userId);
$query = $select->where('field_id', 'role.administrator')->first();
if ($query && $query->value == '1'){
$admin = true;
$committee = true;
}
$select = DB::table('user_properties')->where('user_id', $userId);
$query = $select->where('field_id', 'role.committee')->first();
if ($query && $query->value == '1'){
$committee = true;
}
if (!$admin && !$committee && $eventId > 0){
// Check whether Event ID exists
$select = DB::table('events')->where('id', $eventId)->first();
if ($select){
$select = DB::table('event_roles')->where('event_id', $eventId);
$query = $select->where('user_id', $userId)->where('system_role', 'role.administrator')->first();
if ($query){
$admin = true;
$committee = true;
}
$select = DB::table('event_roles')->where('event_id', $eventId);
$query = $select->where('user_id', $userId)->where('system_role', 'role.committee')->first();
if ($query){
$committee = true;
}
}
}
return (object) [
'admin' => $admin,
'committee' => $committee
];
}
/**
* Utility function to ensure that the user has been authenticated
*/
protected function requiresLogin(string $path, int $eventId, bool $for_admin, bool $for_committee){
if (!Auth::check()){
Session::put('error', 'Please log in before continuing to this page');
Session::put('loginTo', $path);
return false;
}
$check = $this->checkAdminOrCommittee(Auth::id(), $eventId);
if (($check->admin && $for_admin) || ($check->committee && $for_committee) == true) return true;
Session::put('error', 'You are not authorized to access this page');
return false;
}
public function validateFields($event_permissions, $user_properties)
{
$eligible_to_register = true;
for ($i = 0, $j = 0; $i < count($event_permissions) && $j < count($user_properties); $i++, $j++){
$diff = strcmp($event_permissions[$i]->field_id, $user_properties[$j]->field_id);
// If equal
if ($diff == 0){
$event_permissions[$i]->current_value = $user_properties[$j]->value;
// Validate with regex
if (strlen($event_permissions[$i]->validation_rule) == 0 || preg_match($event_permissions[$i]->validation_rule, $user_properties[$j]->value)){
$event_permissions[$i]->satisfied = true;
} else {
$eligible_to_register = false;
}
}
// If $user_properties[$j]'s ASCII difference is less than $event_permissions[$i]
else if ($diff > 0){
// Try to repeat the loop
// Increment $j but not $i
$i--;
}
// Else if the field is not found
else {
// Is the field required or optional?
if ($event_permissions[$i]->required){
$eligible_to_register = false;
}
// Increment $i but not $j
$j--;
}
}
// If the last required permissions is not satisfied
if ($i > 0 && !isset($event_permissions[$i - 1]->satisfied) && $event_permissions[$i - 1]->required){
$eligible_to_register = false;
}
// Check whether there are validations which have not been checked
if ($i < count($event_permissions)) for (; $i < count($event_permissions); $i++){
if ($event_permissions[$i]->required){
$eligible_to_register = false;
}
}
// Return a new stdClass
return (object) [
'eligible_to_register' => $eligible_to_register,
'event_permissions' => $event_permissions
];
}
}
<file_sep><?php
declare(strict_types=1);
namespace VarRepresentation\Node;
use VarRepresentation\Node;
/**
* Represents an array literal
*/
class Array_ extends Node
{
/** @var list<ArrayEntry> the list of nodes (keys and optional values) in the array */
public $entries;
/** @param list<ArrayEntry> $entries the list of nodes (keys and optional values) in the array */
public function __construct(array $entries)
{
$this->entries = $entries;
}
/**
* If this is a list, returns only the nodes for values.
* If this is not a list, returns the entries with keys and values.
*
* @return list<ArrayEntry>|list<Node>
*/
public function getValuesOrEntries(): array
{
$values = [];
foreach ($this->entries as $i => $entry) {
if ($entry->key->__toString() !== (string)$i) {
// not a list
return $this->entries;
}
$values[] = $entry->value;
}
return $values;
}
public function __toString(): string
{
// TODO check if list
$inner = \implode(', ', $this->getValuesOrEntries());
return '[' . $inner . ']';
}
public function toIndentedString(int $depth): string
{
$parts = $this->getValuesOrEntries();
if (\count($parts) === 0) {
return '[]';
}
$representation = "[\n";
foreach ($parts as $part) {
$representation .= \str_repeat(' ', $depth + 1) . $part->toIndentedString($depth + 1) . ",\n";
}
return $representation . \str_repeat(' ', $depth) . "]";
}
}
<file_sep>## Registration Fees
The ticket price for SPRINT is Rp55.000 (Medal-only) or Rp170.000 (for full set of Finisher Pack). However, you can invite another friend or foe into SPRINT and get a special price of Rp300.000 (2 pax, full set).
## Shipping/Delivery Fees
The above registration fee does **not** include additional fees for shipment or delivery of the **Finisher Pack**. We will send the Finisher Pack directly from Central Jakarta, and the following prices apply depending on your domicile.
| Location | Price |
|---|---|---|
| **Java, Bali, and Nusa Tenggara Barat** | Rp20.000 |
| **Nusa Tenggara Timur** | Rp 35.000 |
| **Sumatra and nearby islands**<br>(e.g. Riau islands and Belitung) | Rp 20.000 |
| **Kalimantan** | Rp50.000 |
| **Sulawesi and nearby islands** | Rp70.000 |
| **Maluku and North Maluku islands** | Rp95.000 |
| **Papua islands** | Rp150.000 |<file_sep><?php
namespace App\Http\Controllers;
use App\Mail\SendInvoice;
use App\Mail\SendNewTeamNotification;
use Illuminate\Contracts\Session\Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\{Auth, DB, Mail, Session as facadeSession};
class UserSettingsController extends Controller
{
public function attendEvent($eventId, $eventToken){
}
// Module to get user details
public function getUserDetails(Request $request){
// Ensure that the user has logged in
if (!Auth::check()) return response()->json(['error' => 'You are not authenticated']);
// Ensure that the user has complete payload
if (!$request->has('email') || !$request->has('eventId')) return response()->json(['error' => 'Incomplete Request']);
if ($request->input('email') == Auth::user()->email){
if ($request->input('allowSelf') == false) return response()->json(['error' => 'You should not add yourself as a member']);
$user_data = Auth::user();
} else {
// Search on database
$user_data = DB::table('users')->where('email', $request->input('email'))->first();
if (!$user_data) return response()->json(['error' => 'User not found']);
}
if (!DB::table('events')->where('id', $request->input('eventId'))->first()) return response()->json(['error' => 'Event not found']);
// Check user_properties
$event_permissions = DB::table('event_permissions')->join('fields', 'event_permissions.field_id', 'fields.id')->where('event_id', $request->input('eventId'))->get();
$incomplete = []; $invalid = [];
$response = [
"name" => $user_data->name,
"incomplete" => $incomplete,
"invalid" => $invalid
];
if (!Auth::guest() && (Auth::user()->university_id == 2 || Auth::user()->university_id == 3)) $response['eventPermissions'] = [];
foreach ($event_permissions as $permission){
$user_properties = DB::table('user_properties')->where('user_id', $user_data->id)->where('field_id', $permission->field_id)->first();
if (!$user_properties){
array_push($incomplete, $permission->name . ' (' . $permission->validation_description . ')');
continue;
}
if (!Auth::guest() && (Auth::user()->university_id == 2 || Auth::user()->university_id == 3)) $response['eventPermissions'][] = [
'name' => $permission->name,
'current_value' => $user_properties->value
];
if (strlen($permission->validation_rule) > 0 && !preg_match($permission->validation_rule, $user_properties->value)) array_push($invalid, $permission->name . ' (' . $permission->validation_description . ')');
}
return response()->json($response);
}
// Module to generate competition page
public function competitionIndex(Request $request, $teamid) {
if(!Auth::check()){
$request->session()->put('error','You will need to log in first');
return redirect("/home");
}
$requests = DB::table("registration")
->join("events", "events.id", "=", "registration.event_id")
->join("users", "users.id", "=", "registration.ticket_id")
->join("teams","teams.id", "=", "registration.team_id")
->join("files","files.id", "=", "registration.file_id")
->where("team_id", $teamid)
->where("attendance_opened",1)
->select("registration.*", "files.*", DB::raw('events.name AS event_name'), DB::raw('users.name AS user_name'), DB::raw('teams.name AS team_name'), DB::raw('events.attendance_opened AS event_opened'))
->get();
// dd($requests);
if (count($requests) == 0){
$request->session()->put('error', 'Team ID not found');
return redirect("/home");
}
// dd($requests);
// dd(count($requests));
$currentId = Auth::user()->id;
// dd($request[]);
$isAuthorized = false;
for ($i = 0; $i < count($requests); $i++){
if ($requests[$i]->ticket_id == $currentId && $requests[$i]->status >= 2){
$isAuthorized = true;
break;
}
}
if (!$isAuthorized){
$request->session()->put('error', 'Only the approved team can access');
return redirect("/home");
}
return view("account.competition", ["requests" => $requests, "teamid" => $teamid]);
}
// Module to handle competition page
public function competitionHandler(Request $request, $teamid) {
if(!Auth::check()){
$request->session()->put('error','You will need to log in first');
return redirect("/home");
}
// Ensure that the payment code exists
$requests = DB::table("registration")
->where("team_id", $teamid)
->first();
// dd($requests);
if ($requests == null){
$request->session()->put('error', 'TeamID not found');
return redirect("/home");
}
// Validate the inputs
$request->validate([
'file' => 'mimes:jpeg,png,pdf,zip'
]);
// Save to storage and add to Database
$path = $request->file('file')->store('competitions/answer');
DB::table('files')->where('id',$requests->file_id)->update([
"answer_path" => $path
]);
$team = DB::table('teams')->where('id', $requests->team_id)->first();
$event = DB::table('events')->where('id', $requests->event_id)->first();
$admins = DB::table('users')->select(['name', 'email'])->where('university_id', 2)->get();
foreach ($admins as $admin){
DB::table('email_queue')->insert([
'subject' => "$team->name has just submitted case answer for $event->name. Would you mind checking it out?",
'sender_name' => 'Shift (COMPUTERUN 2.0)',
'email' => $admin->email,
'created_at' => now(),
'message_type' => 'MARKDOWN',
'message' => "Hey admins,<br><br>**$team->name** has just submitted the case answer for the **$event->name**. Just look on https://computerun.id/admin/event/$event->id and download the file from https://computerun.id/admin/downloadFile/2/$requests->file_id.<br><br>Oh, and make sure you're logged in as an admin before viewing it. Thanks and have a nice day!"
]);
}
$request->session()->put('status', 'Your files have been uploaded');
return redirect('/home');
}
// Module to generate payment page
public function paymentIndex(Request $request, $paymentcode){
if (!Auth::check()){
$request->session()->put('error', 'You will need to log in first');
return redirect("/home");
}
// Ensure that the payment code exists
$requests = DB::table("registration")
->where("payment_code", $paymentcode)
->join("events", "events.id", "=", "registration.event_id")
->join("users", "users.id", "=", "registration.ticket_id")
->select("registration.*", "events.price", DB::raw('events.name AS event_name'), DB::raw('users.name AS user_name'),"status","ticket_id")
->get();
if (count($requests) == 0){
$request->session()->put('error', 'Payment code not found');
return redirect("/home");
}
// Check whether the user is one of the participants
$currentId = Auth::user()->id;
$isAuthorized = false;
for ($i = 0; $i < count($requests); $i++){
if ($requests[$i]->ticket_id == $currentId){
$isAuthorized = true;
break;
}
}
if (!$isAuthorized){
$request->session()->put('error', 'Only the ticket holder can upload the registration document');
return redirect("/home");
}
return view("account.payment", ["requests" => $requests, "paymentcode" => $paymentcode]);
}
// Module to upload payment receipts
public function paymentHandler(Request $request, $paymentcode){
if (!Auth::check()){
$request->session()->put('error', 'You will need to log in first');
return redirect("/home");
}
// Ensure that the payment code exists
$requests = DB::table("registration")
->where("payment_code", $paymentcode)
->join("events", "events.id", "=", "registration.event_id")
->join("users", "users.id", "=", "registration.ticket_id")
->select("registration.*", "events.price", DB::raw('events.name AS event_name'), DB::raw('users.name AS user_name'))
->get();
if (count($requests) == 0){
$request->session()->put('error', 'Payment code not found');
return redirect("/home");
}
// Check whether the user is one of the participants
$currentId = Auth::user()->id;
$isAuthorized = false;
for ($i = 0; $i < count($requests); $i++){
if ($requests[$i]->ticket_id == $currentId){
$isAuthorized = true;
break;
}
}
if (!$isAuthorized){
$request->session()->put('error', 'Invalid Payment Code');
return redirect("/home");
}
// Validate the inputs
$request->validate([
'file' => 'mimes:jpeg,png,pdf,zip'
]);
// Save to storage and add to Database
$path = $request->file('file')->store('uploads');
$fileId = DB::table('files')->insertGetId([
"name" => $path
]);
DB::table("registration")
->where("payment_code", $paymentcode)
->where("status", '<=',2)
->update(["file_id" => $fileId]);
$user = Auth::user();
$event = $requests[0];
$admins = DB::table('users')->select(['name', 'email'])->where('university_id', 2)->get();
foreach ($admins as $admin){
DB::table('email_queue')->insert([
'subject' => "$user->name has just paid for our $event->event_name. Would you mind checking it out?",
'sender_name' => 'Shift (COMPUTERUN 2.0)',
'email' => $admin->email,
'created_at' => now(),
'message_type' => 'MARKDOWN',
'message' => "Hey admins,<br><br>**$user->name** has just submitted payment receipts for **$event->event_name**. Just look for **Payment Code #$paymentcode** on https://computerun.id/admin/event/$event->event_id and download the file from https://computerun.id/admin/downloadFile/1/$fileId.<br><br>Oh, and make sure you're logged in as an admin before viewing it. Thanks and have a nice day!"
]);
}
$request->session()->put('status', 'Your files have been uploaded');
return redirect('/home');
}
// Module to register to certain events
public function registerToEvent(Request $request){
if (!Auth::check()) return redirect("/home");
$redirect_to = '/home';
if ($request->has('redirect_to')) $redirect_to = $request->input('redirect_to');
// Get event ID
$event_id = $request->input("event_id");
$team_required = false;
// Get the slot number
$slots = ($request->has("slots") && $request->input("slots") > 1) ? $request->input("slots") : 1;
// Set the referral code
$referral_code = null;
if ($request->has("referral_code") && strlen($request->input("referral_code")) > 0) $referral_code = $request->input("referral_code");
// Set the Payment Code
$payment_code = null;
// Check on database whether the event exists
$event = DB::table("events")->where("id", $event_id)->first();
$currentTickets = DB::table('registration')->selectRaw('count(*) as total')->where('event_id', $event->id)->where('status', '!=', 1)->first();
if (!$event){
$request->session()->put('error', "Event not found.");
return redirect($redirect_to);
} else if ($currentTickets->total >= $event->seats) {
$request->session()->put('error', "Unable to register to " . $event->name . " due to full capacity.");
return redirect($redirect_to);
} else if ($event->opened == 0) {
$request->session()->put('error', "The registration period for " . $event->name . " has been closed.");
return redirect($redirect_to);
} else if ($event->team_members + $event->team_members_reserve > 0) $team_required = true;
if ($event->price > 0) $payment_code = uniqid();
// Create an array of users to be validated
$leader = Auth::user();
$members = [];
$reserve = [];
// Create an email draft
$event_title = (strlen($event->kicker) > 0 ? ($event->kicker . ': ') : '') . $event->name;
$email_template = [
'message_type' => 'MARKDOWN',
'sender_name' => 'COMPUTERUN 2.0 - ' . (strlen($event->kicker) > 0 ? $event->kicker : $event->name),
'created_at' => date("Y-m-d H:i:s")
];
// Get whether teams are needed
if ($team_required == true){
if (!$request->has("create_team") || !$request->has("team_name") || $request->input("team_name") == ""){
$request->session()->put('error', "You will need to create a team for " . $event->name . ".");
return redirect($redirect_to);
}
// Team members
for ($i = 1; $i <= $event->team_members; $i++){
if (!$request->has('team_member_' . $i)){
$request->session()->put('error', "Incomplete team members");
return redirect($redirect_to);
}
$members[] = DB::table('users')->where('email', $request->input('team_member_' . $i))->first();
}
// Reserve members
for ($i = 1; $i <= $event->team_members_reserve; $i++){
if ($request->has('team_member_reserve_' . $i)){
$reserve[] = DB::table('users')->where('email', $request->input('team_member_reserve_' . $i))->first();
}
}
}
// Validate users
$queue = [$leader];
$queue = array_merge($queue, $members, $reserve);
$event_permissions = DB::table('event_permissions')->where('event_id', $event->id)->get();
$validation_failed = 0;
foreach ($queue as $user){
$user_properties = DB::table('user_properties')->where('user_id', $user->id)->get();
$registrations = DB::table('registration')->where('event_id', $event->id)->where('ticket_id', $user->id)->where('status', '!=', 1)->get();
$validation = parent::validateFields($event_permissions, $user_properties);
if ($event->slots - count($registrations) <= 0) $validation->eligible_to_register = false;
if (!$validation->eligible_to_register){
$validation_failed++;
}
}
if ($validation_failed > 0){
$request->session()->put('error', "You or your team members are not eligible to register to this event.");
return redirect($redirect_to);
}
// Validate referral code
if ($referral_code !== null){
$referral_check = DB::table('referral_codes')->where('opened', true)->where('id', $referral_code)->first();
if (!$referral_check){
$request->session()->put('error', "Invalid referral code.");
return redirect($redirect_to);
}
}
if ($team_required == true){
// Create a new team
$team_id = DB::table("teams")->insertGetId(["name" => $request->input("team_name"), "event_id" => $event_id]);
// Assign the database template
$query = [];
$draft = ["event_id" => $event_id, "status" => (($event->auto_accept == true) ? 2 : 0), "referral_code" => $referral_code, "payment_code" => $payment_code, "team_id" => $team_id, "ticket_id" => null, "remarks" => null];
// Assign the User ID of the team leader
$tempdetails = Auth::user();
for ($j = 0; $j < $slots; $j++){
$temp = $draft;
$temp["ticket_id"] = $tempdetails->id;
$temp["remarks"] = "Team Leader";
if ($slots > 1) $temp["remarks"] = $temp["remarks"] . ", Slot " . ($j + 1);
array_push($query, $temp);
}
// Find the User ID of team members
for ($i = 1; $i <= $event->team_members; $i++){
$tempdetails = DB::table("users")->where("email", $request->input("team_member_" . $i))->first();
for ($j = 0; $j < $slots; $j++){
$temp = $draft;
echo(print_r($tempdetails));
$temp["ticket_id"] = $tempdetails->id;
$temp["remarks"] = "Team Member";
if ($slots > 1) $temp["remarks"] = $temp["remarks"] . ", Slot " . ($j + 1);
array_push($query, $temp);
}
// Send Email
// Mail::to($request->input("team_member_" . ($i + 1)))->send(new SendNewTeamNotification(["name" => $tempdetails["name"], "team_name" => $request->input("team_name"), "team_id" => $team_id, "team_leader_name" => Auth::user()->name, "team_leader_email" => Auth::user()->email, "role" => "Main Player/Member " . ($i + 1), "event_name" => $event->name, "event_kicker" => $event->kicker]));
$email_draft = $email_template;
$email_draft['subject'] = 'You have been invited to join ' . $event_title . ' by ' . $leader->name;
$email_draft['message'] = 'You have been invited by ' . $leader->name . ' (' . $leader->email . ') to join as a member of "' . $request->input("team_name") . '" to join ' . $event_title . PHP_EOL . PHP_EOL . 'Your team and ticket details can be found on [https://computerun.id/profile/](https://computerun.id/profile/).' . PHP_EOL . PHP_EOL . 'If you are being added by mistake, please contact the respective event committees.';
if ($event->price == 0 && $event->auto_accept == true && strlen($event->description_private) > 0) $email_template['message'] .= PHP_EOL . PHP_EOL . '## Important Information for Event/Attendance' . PHP_EOL . PHP_EOL . $event->description_private;
else if (strlen($event->description_pending) > 0) $email_template['message'] .= PHP_EOL . PHP_EOL . '## Important Information for Event/Attendance' . PHP_EOL . PHP_EOL . $event->description_pending;
$email_draft['email'] = $tempdetails->email;
DB::table('email_queue')->insert($email_draft);
}
// Find the User ID of reseve team members
for ($i = 1; $i <= $event->team_members_reserve; $i++){
if (!$request->has("team_member_reserve_" . $i) || $request->input("team_member_reserve_" . $i) == "") continue;
$tempdetails = DB::table("users")->where("email", $request->input("team_member_reserve_" . $i))->first();
for ($j = 0; $j < $slots; $j++){
$temp = $draft;
echo(print_r($tempdetails));
$temp["ticket_id"] = $tempdetails->id;
$temp["remarks"] = "Reserve Team Member";
if ($slots > 1) $temp["remarks"] = $temp["remarks"] . ", Slot " . ($j + 1);
array_push($query, $temp);
}
// Send Email
// Mail::to($request->input("team_member_reserve_" . ($i + 1)))->send(new SendNewTeamNotification(["name" => $tempdetails->name, "team_name" => $request->input("team_name"), "team_id" => $team_id, "team_leader_name" => Auth::user()->name, "team_leader_email" => Auth::user()->email, "role" => "Reserve Player/Member " . ($i + 1), "event_name" => $event->name, "event_kicker" => $event->kicker]));
$email_draft = $email_template;
$email_draft['subject'] = 'You have been invited to join ' . $event_title . ' by ' . $leader->name;
$email_draft['message'] = 'You have been invited by ' . $leader->name . ' (' . $leader->email . ') to join as a reserve member of "' . $request->input("team_name") . '" to join ' . $event_title . PHP_EOL . PHP_EOL . 'Your team and ticket details can be found on [https://computerun.id/profile/](https://computerun.id/profile/).' . PHP_EOL . PHP_EOL . 'If you are being added by mistake, please contact the respective event committees.';
if ($event->price == 0 && $event->auto_accept == true && strlen($event->description_private) > 0) $email_template['message'] .= PHP_EOL . PHP_EOL . '## Important Information for Event/Attendance' . PHP_EOL . PHP_EOL . $event->description_private;
else if (strlen($event->description_pending) > 0) $email_template['message'] .= PHP_EOL . PHP_EOL . '## Important Information for Event/Attendance' . PHP_EOL . PHP_EOL . $event->description_pending;
$email_draft['email'] = $tempdetails->email;
DB::table('email_queue')->insert($email_draft);
}
var_dump($query);
// Insert into the database
DB::table("registration")->insert($query);
} else {
// Assign the participant
DB::table("registration")->insert(["ticket_id" => Auth::user()->id, "event_id" => $event_id, "status" => (($event->auto_accept == true) ? 2 : 0), "payment_code" => $payment_code]);
}
// Send Email for Payment
// if($event->price > 0) Mail::to(Auth::user()->email)->send(SendInvoice::createEmail((object) ["name" => Auth::user()->name, "event_id" => $event->id, "user_id" => Auth::user()->id, "event_name" => $event->name, "payment_code" => $payment_code, "total_price" => $event->price * $slots]));
// Send Email for Payment
$email_template['subject'] = 'Welcome to ' . $event_title . '!';
$email_template['message'] = 'Thank you for registering to ' . $event_title . '.';
$email_template['email'] = $leader->email;
if ($event->price == 0 && $event->auto_accept == true){
$email_template['message'] .= ' Your registration has been approved by our team.' . PHP_EOL . PHP_EOL . 'Your ticket and team (if any) details can be found on https://computerun.id/profile/.' . PHP_EOL . PHP_EOL . 'If you are being registered by mistake, please contact the respective event committees.';
if (strlen($event->description_private) > 0) $email_template['message'] .= PHP_EOL . PHP_EOL . '## Important Information for Event/Attendance' . PHP_EOL . PHP_EOL . $event->description_private;
} else {
$email_template['message'] .= ' Please finish your payment (if any) and wait while our team verifies and approves your registration.' . PHP_EOL . PHP_EOL . 'You may check your ticket status regularly on https://computerun.id/profile/.' . PHP_EOL . PHP_EOL . 'If you are being registered by mistake, please contact the respective event committees.';
if (strlen($event->description_pending) > 0) $email_template['message'] .= PHP_EOL . PHP_EOL . '## Important Information for Event/Attendance' . PHP_EOL . PHP_EOL . $event->description_pending;
}
DB::table('email_queue')->insert($email_template);
// Return Response
if ($event->price > 0){
if (strlen($event->payment_link) > 0) return redirect($this->getPaymentLink($event, (object) ['payment_code' => $payment_code]));
else return redirect('/pay/' . $payment_code);
}
return redirect($redirect_to);
}
// Module to register to certain events
public function registerEvent(Request $request){
if (!Auth::check()) return redirect("/home");
$redirect_to = '/home';
if ($request->has('redirect_to')) $redirect_to = $request->input('redirect_to');
// Get event ID
$event_id = $request->input("event_id");
$team_required = false;
// Get the slot number
$slots = ($request->has("slots") && $request->input("slots") > 1) ? $request->input("slots") : 1;
// Set the Payment Code
$payment_code = uniqid();
// Check on database whether the event exists
$event = DB::table("events")->where("id", $event_id)->first();
if (!$event){
$request->session()->put('error', "Event not found.");
return redirect($redirect_to);
} else if ($event->opened == 0) {
$request->session()->put('error', "The registration period for " . $event->name . " has been closed.");
return redirect($redirect_to);
} else if ($event->team_members + $event->team_members_reserve > 0) $team_required = true;
// Get whether teams are needed
if ($team_required == true){
if (!$request->has("create_team") || !$request->has("team_name") || $request->input("team_name") == ""){
$request->session()->put('error', "You will need to create a team for " . $event->name . ".");
return redirect($redirect_to);
}
// Create a new team
$team_id = DB::table("teams")->insertGetId(["name" => $request->input("team_name"), "event_id" => $event_id]);
$requires_account = null;
// Detect game-specific Account ID
if (preg_match("/Mobile Legends/i", $event->name) == 1){
$requires_account = "mobile_legends";
} else if (preg_match("/PUBG Mobile/i", $event->name) == 1){
$requires_account = "pubg_mobile";
} else if (preg_match("/Valorant/i", $event->name) == 1){
$requires_account = "valorant";
}
// Assign the database template
$query = [];
$draft = ["event_id" => $event_id, "status" => 0, "payment_code" => $payment_code, "team_id" => $team_id, "ticket_id" => null, "remarks" => null];
// Assign the User ID of the team leader
$tempdetails = json_decode(json_encode(Auth::user()), true);
for ($j = 0; $j < $slots; $j++){
$temp = $draft;
$temp["ticket_id"] = $tempdetails->id;
$temp["remarks"] = "Team Leader";
if ($slots > 1) $temp["remarks"] = $temp["remarks"] . ", Slot " . ($j + 1);
array_push($query, $temp);
}
// Find the User ID of team members
for ($i = 0; $i < $event->team_members; $i++){
$tempdetails = json_decode(json_encode(DB::table("users")->where("email", $request->input("team_member_" . ($i + 1)))->first()), true);
for ($j = 0; $j < $slots; $j++){
$temp = $draft;
echo(print_r($tempdetails));
$temp["ticket_id"] = $tempdetails["id"];
if ($requires_account != null){
$temp["remarks"] = "Team Member, ID: " . $tempdetails["id_" . $requires_account];
} else {
$temp["remarks"] = "Team Member";
}
if ($slots > 1) $temp["remarks"] = $temp["remarks"] . ", Slot " . ($j + 1);
array_push($query, $temp);
}
// Send Email
Mail::to($request->input("team_member_" . ($i + 1)))->send(new SendNewTeamNotification(["name" => $tempdetails["name"], "team_name" => $request->input("team_name"), "team_id" => $team_id, "team_leader_name" => Auth::user()->name, "team_leader_email" => Auth::user()->email, "role" => "Main Player " . ($i + 1), "event_name" => $event->name]));
}
// Find the User ID of reseve team members
for ($i = 0; $i < $event->team_members_reserve; $i++){
if (!$request->has("team_member_reserve_" . ($i + 1)) || $request->input("team_member_reserve_" . ($i + 1)) == "") continue;
$tempdetails = json_decode(json_encode(DB::table("users")->where("email", $request->input("team_member_reserve_" .($i + 1)))->first()), true);
for ($j = 0; $j < $slots; $j++){
if ($request->has("team_member_reserve_" . ($i + 1))){
$temp = $draft;
$temp["ticket_id"] = $tempdetails["id"];
if ($requires_account != null){
$temp["remarks"] = "Team Member (Reserve), ID: " . $tempdetails["id_" . $requires_account];
} else {
$temp["remarks"] = "Team Member (Reserve)";
}
}
if ($slots > 1) $temp["remarks"] = $temp["remarks"] . ", Slot " . ($j + 1);
array_push($query, $temp);
}
// Send Email
Mail::to($request->input("team_member_reserve_" . ($i + 1)))->send(new SendNewTeamNotification(["name" => $tempdetails["name"], "team_name" => $request->input("team_name"), "team_id" => $team_id, "team_leader_name" => Auth::user()->name, "team_leader_email" => Auth::user()->email, "role" => "Reserve Player " . ($i + 1), "event_name" => $event->name]));
}
// Insert into the database
DB::table("registration")->insert($query);
} else {
// Assign the participant
DB::table("registration")->insert(["ticket_id" => Auth::user()->id, "event_id" => $event_id, "status" => 0, "payment_code" => $payment_code]);
}
// Send Email for Payment
if($event->price > 0) Mail::to(Auth::user()->email)->send(new SendInvoice(["name" => Auth::user()->name, "event_name" => $event->name, "payment_code" => $payment_code, "total_price" => $event->price * $slots]));
// Return Response
$request->session()->put('status', "Your registration request has been sent. Please check your email for payment instructions.");
return redirect($redirect_to);
}
// Module to Unified Registration Flow
public function registrationRedirectHandler(Request $request, $id){
// Unregisterd Users -> Go to Login Page
// Registered Users -> Go to Profile and trigger modal
if($id > 0) $request->session()->put('register', $id);
return redirect("/home");
}
// Module to update contacts
public function updateContacts(Request $request){
// Ensure that the user has logged in
if (!Auth::check()) return redirect("/home");
$redirect_to = '/home';
if ($request->has('redirect_to')) $redirect_to = $request->input('redirect_to');
// Set the User ID
$userid = Auth::user()->id;
// Create Draft
$draft = [];
foreach($request->all() as $key => $value) {
if (str_starts_with($key, 'action-change-')){
$field_id = substr($key, 14);
$res = DB::table('fields')->select('id', DB::raw('replace(id, \'.\', \'_\') as id_mod'))->where('editable', true)->having('id_mod', $field_id)->first();
if ($res !== null && strlen($value) > 0) DB::table('user_properties')->upsert(['user_id' => Auth::user()->id, 'field_id' => $res->id, 'value' => $value], ['user_id', 'field_id']);
}
};
// Save "updated_at"
$draft["updated_at"] = now();
DB::table('users')->where('id', $userid)->update($draft);
$request->session()->put('status', "Your Account Settings has been updated.");
return redirect($redirect_to);
}
public function downloadFileCompetition($teamid){
if(!Auth::check()){
facadeSession::put('error', 'User: Please Login First');
return redirect('login');
}
$check = DB::table("registration")
->join("events", "events.id", "=", "registration.event_id")
->where("team_id", $teamid)
->where("attendance_opened",1)
->first();
if($check == null){
facadeSession::put('error', 'User: Not Authorized or File not found');
return redirect('home');
}
try {
if ($check->attendance_opened !== 1) return redirect('home');
switch ($check->event_id){
case 3: return response()->download(storage_path("app/competitions/bitcase-e.pdf"));
case 4: return response()->download(storage_path("app/competitions/webdes-e.pdf"));
case 5: return response()->download(storage_path("app/competitions/bitcase-f.pdf"));
case 6: return response()->download(storage_path("app/competitions/webdes-f.pdf"));
default: return redirect('home');
}
} catch (\Exception $e){
facadeSession::put('error', 'Alert: Internal Server Error');
return redirect('home');
}
}
public function downloadFileUser($type ,$paymentcode ,$fileid){
if(!Auth::check()){
facadeSession::put('error', 'User: Please Login First');
return redirect('login');
}
if($type == 0) $check = DB::table("registration")
->where("file_id", $fileid)
->where("ticket_id", Auth::user()->id)
->where("payment_code", $paymentcode)
->join("files","files.id","=","registration.file_id")
->first();
elseif($type == 1) $check = DB::table("registration")
->where("file_id", $fileid)
->where("ticket_id", Auth::user()->id)
->where("team_id", $paymentcode)
->join("files","files.id","=","registration.file_id")
->first();
if($check == null){
facadeSession::put('error', 'User: Not Authorized or File ID not found');
return redirect('home');
}
if ($type == 0) {
try {
return response()->download(storage_path("app/" . $check->name));
} catch (\Exception $e){
facadeSession::put('error', 'Alert: Internal Server Error');
return redirect('home');
}
}else if ($type == 1){
try {
return response()->download(storage_path("app/" . $check->answer_path));
} catch (\Exception $e){
facadeSession::put('error', 'Alert: Internal Server Error');
return redirect('home');
}
}
}
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\{DB, Schema};
class AddEventData extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Add Expected List of Target Universities, as shown on the Sponsorship Proposal
// 1-10
DB::table('universities')->insert(['name' => 'UI - Universitas Indonesia']);
DB::table('universities')->insert(['name' => 'UNJ - Universitas Negeri Jakarta']);
DB::table('universities')->insert(['name' => 'UNTAR - Universitas Tarumanegara']);
DB::table('universities')->insert(['name' => 'USAKTI - Universitas Trisakti']);
DB::table('universities')->insert(['name' => 'UPH - Universitas Pelita Harapan']);
DB::table('universities')->insert(['name' => 'UMN - Universitas Multimedia Nusantara']);
DB::table('universities')->insert(['name' => 'UEU - Universitas Esa Unggul']);
DB::table('universities')->insert(['name' => 'UNIKA Atma Jaya']);
DB::table('universities')->insert(['name' => 'UBM - Universitas Bunda Mulia']);
DB::table('universities')->insert(['name' => 'ITB - Institut Teknologi Bandung']);
// 11-20
DB::table('universities')->insert(['name' => 'UNPAD - Universitas Padjajaran']);
DB::table('universities')->insert(['name' => 'UNIKOM - Universitas Komputer Indonesia']);
DB::table('universities')->insert(['name' => 'UNPAR - Universitas Katolik Parahyangan']);
DB::table('universities')->insert(['name' => 'UG - Universitas Gunadarma']);
DB::table('universities')->insert(['name' => 'President University - Universitas Presiden']);
DB::table('universities')->insert(['name' => 'BSI - Universitas Bina Sarana Informatika']);
DB::table('universities')->insert(['name' => 'UMB - Universitas Mercu Buana']);
DB::table('universities')->insert(['name' => 'Universitas Pancasila']);
DB::table('universities')->insert(['name' => 'Universitas Pertamina']);
DB::table('universities')->insert(['name' => 'UNDIP - Universitas Diponegoro']);
// 21-30
DB::table('universities')->insert(['name' => 'IPB - Institut Pertanian Bogor']);
DB::table('universities')->insert(['name' => 'UNHAS - Universitas Hasanuddin']);
DB::table('universities')->insert(['name' => 'ITERA - Institut Teknologi Sumatera']);
DB::table('universities')->insert(['name' => 'UNBRAW - Institut Brawijaya']);
DB::table('universities')->insert(['name' => 'ITS - Institut Teknologi Sepuluh November']);
// #26 - UPN: Divide into 3 regions
DB::table('universities')->insert(['name' => 'UPN "Veteran" - DKI Jakarta']);
DB::table('universities')->insert(['name' => 'UPN "Veteran" - DI Yogyakarta']);
DB::table('universities')->insert(['name' => 'UPN "Veteran" - Jawa Timur']);
DB::table('universities')->insert(['name' => 'YARSI - Universitas Yarsi']);
DB::table('universities')->insert(['name' => 'UIN Syarif Hidayatullah']);
DB::table('universities')->insert(['name' => 'UNS - Universitas Sebelas Maret']);
DB::table('universities')->insert(['name' => 'UGM - Universitas Gadjah Mada']);
// 31-40
DB::table('universities')->insert(['name' => 'UII - Universitas Islam Indonesia']);
DB::table('universities')->insert(['name' => 'UBAYA - Universitas Surabaya']);
DB::table('universities')->insert(['name' => 'Telkom University - Universitas Telkom']);
DB::table('universities')->insert(['name' => 'UNNES - Universitas Negeri Semarang']);
DB::table('universities')->insert(['name' => 'UNP - Universitas Negeri Padang']);
DB::table('universities')->insert(['name' => 'UNUD - Universitas Udayana']);
DB::table('universities')->insert(['name' => 'UNAIR - Universitas Airlangga']);
DB::table('universities')->insert(['name' => 'UNSRI - Universitas Sriwijaya']);
DB::table('universities')->insert(['name' => 'UBD - Universitas Bina Darma']);
DB::table('universities')->insert(['name' => 'UK Petra - Universitas Kristen Petra']);
// Add Event List
DB::table('events')->insert(['name' => 'Business-IT Case Competition', 'price' => 300000, 'opened' => 1, 'date' => '2020-12-02 23:59:59', 'team_members' => 2, 'totp_key' => rand(100000, 999999)]);
DB::table('events')->insert(['name' => 'Mobile Application Development Competition', 'price' => 300000, 'opened' => 1, 'date' => '2020-12-02 23:59:59', 'team_members' => 2, 'totp_key' => rand(100000, 999999)]);
DB::table('events')->insert(['name' => 'Mini E-Sport: Mobile Legends', 'price' => 50000, 'opened' => 0, 'date' => '2020-10-03 00:00:00', 'team_members' => 5, 'team_members_reserve' => 1, 'slots' => 2, 'totp_key' => rand(100000, 999999)]);
DB::table('events')->insert(['name' => 'Mini E-Sport: PUBG Mobile', 'price' => 20000, 'opened' => 0, 'date' => '2020-10-03 00:00:00', 'team_members' => 5, 'team_members_reserve' => 1, 'slots' => 2, 'totp_key' => rand(100000, 999999)]);
DB::table('events')->insert(['name' => 'Mini E-Sport: Valorant', 'price' => 35000, 'opened' => 0, 'date' => '2020-10-03 00:00:00', 'team_members' => 5, 'team_members_reserve' => 1, 'slots' => 2, 'totp_key' => rand(100000, 999999)]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Remove all universities except the four former ones
DB::table('universities')->where('id', '>', '4')->delete();
DB::raw('ALTER TABLE `universities` (AUTO_INCREMENT = 5);');
// Remove all events
DB::table('events')->where('id', '>', '0')->delete();
DB::raw('ALTER TABLE `events` (AUTO_INCREMENT = 1);');
}
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\{DB, Schema};
class CreateFilesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Create the "files" table
if (!Schema::hasTable('files')) Schema::create('files', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->text('name');
});
// Create the "payments" table (Pembayaran)
if (!Schema::hasTable('payments')) Schema::create('payments', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->text('payee');
$table->text('payment_method');
$table->text('payment_account');
$table->unsignedBigInteger('file_id')->nullable();
$table->foreign('file_id')->references('id')->on('files');
$table->integer('status')->default(0);
});
// Update the "registration" table to include files
Schema::table('registration', function (Blueprint $table) {
$table->unsignedBigInteger('file_id')->nullable();
$table->foreign('file_id')->references('id')->on('files');
$table->unsignedBigInteger('payment_id')->nullable();
$table->foreign('payment_id')->references('id')->on('payments');
});
// Create the "kyc" table (Know Your Customer - Verifikasi KTM)
if (!Schema::hasTable('kyc')) Schema::create('kyc', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->unsignedBigInteger('ticket_id')->nullable();
$table->foreign('ticket_id')->references('id')->on('users');
$table->unsignedBigInteger('file_id')->nullable();
$table->foreign('file_id')->references('id')->on('files');
$table->integer('status')->default(0);
});
// Update the "users" table to include NIMs from other universities
Schema::table("users", function (Blueprint $table){
// Change NIM to support texts and longer integers
$table->text('nim')->nullable()->change();
// Add isVerified
$table->integer('verified')->default(0);
});
// Add Certificates
if (!Schema::hasTable('certificates')) Schema::create('certificates', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->unsignedBigInteger('ticket_id')->nullable();
$table->foreign('ticket_id')->references('id')->on('users');
$table->unsignedInteger('event_id')->nullable();
$table->foreign('event_id')->references('id')->on('events');
$table->unsignedBigInteger('file_id')->nullable();
$table->foreign('file_id')->references('id')->on('files');
$table->integer('status')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('certificates');
if (Schema::hasTable('users')) Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['verified']);
$table->bigInteger('nim')->nullable()->change();
});
Schema::dropIfExists('kyc');
if (Schema::hasTable('registration')){
Schema::table('registration', function (Blueprint $table) {
$table->dropForeign(['file_id']);
$table->dropForeign(['payment_id']);
});
Schema::table('registration', function (Blueprint $table) {
$table->dropColumn(['file_id', 'payment_id']);
});
}
Schema::dropIfExists('payments');
Schema::dropIfExists('files');
}
}
<file_sep>ARG VERSION=7.4
FROM composer:1.10 AS build
RUN composer global require overtrue/phplint:^2.0
FROM php:${VERSION}-cli-alpine
COPY --from=build /tmp/vendor /root/.composer/vendor
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
RUN cp /usr/local/etc/php/php.ini-development /usr/local/etc/php/php.ini
ENTRYPOINT ["/entrypoint.sh"]
<file_sep>Hola!
.
My name is (....) and I will be participating in the COMPUTERUN 2.0 Virtual Run Competition! 🏃
.
Life is better in running shoes, so I guess It’s time to move my legs as I am ready to SPRINT! With the aim to help me develop and maintain a healthier lifestyle through running during this pandemic. Remember, it doesn’t matter the distance as long as you do it, it will count! 👣
.
Hold up a sec! Before scrolling to another post, make sure to check out their page @computerun or through their website at http://www.computerun.id
|
e2ee5c43a621852db671bf048d7fdc1ebdb5238e
|
[
"Markdown",
"JavaScript",
"Python",
"PHP",
"Dockerfile"
] | 49 |
PHP
|
reinhart1010/computerun-2020
|
b8ffdfdbf1f84ccb6c5466542d08a92a9913f280
|
c941ef20ee79d835a6a56877578d6bb38ae8e75e
|
refs/heads/main
|
<file_sep>// program to write to console
// passing number
console.log(8);
// passing string
console.log('hello');
// passing variable
const x = 'hello';
console.log(x);
// passing function
function sayName() {
return 'Hello Pranitha';
}
console.log(sayName());
// passing string and a variable
const name = 'Pranitha';
console.log('Hello ' + name);
// passing object
let obj = {
name: 'Pranitha',
age: 20
}
console.log(obj);<file_sep>console.log("Hello Welcome World");<file_sep>// program to create JavaScript object using object literal
const person = {
name: 'Pranitha',
age: 20,
hobbies: ['reading', 'Keyboard', 'Singing', 'coding'],
greet: function() {
console.log('Hey You?.');
},
score: {
maths: 99,
science: 85
}
};
console.log(typeof person); // object
// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.greet();
console.log(person.score.maths);<file_sep>function greet() {
const string = `My name is ${this.firstName} ${this.secondName}. I am ${this.age} years old.`;
console.log(string);
}
const human = {
firstName: "Pranitha",
lastName: "Ravi",
age: 20,
};
greet.call(human); // My name is Judah undefined. I am 26 years old.<file_sep>// program to create JavaScript object using instance of an object
function Person() {
this.name = 'pranitha',
this.age = 18,
this.hobbies = ['reading', 'games', 'coding'],
this.greet = function() {
console.log('Hello to my fantasy.');
},
this.score = {
maths: 90,
science: 80
}
}
const person = new Person();
console.log(typeof person); // object
// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.greet();
console.log(person.score.maths);
|
e7b725214f8d7de06294ded4aa9efca659787cb6
|
[
"JavaScript"
] | 5 |
JavaScript
|
pranithacse/nodejspranitha
|
ba359fbe0adbc44b775360f0a52cb7ac18643f63
|
a949ab33d99f520d7af9c069656c1eef8e926de6
|
refs/heads/master
|
<file_sep>// <NAME>
// Multi-threading Application Project: Stimulating multi-threading with producer and consumer
#include <windows.h>
#include <stdlib.h>
#include <iostream>
#include <ctime>
#define MAX_THREADS 2
using namespace std;
int counterLimit = 0;
int counter = 0;
int bufferSize;
int *buffer;
int in = 0;
int out = 0;
DWORD WINAPI producerThread(LPVOID);
DWORD WINAPI consumerThread(LPVOID);
HANDLE hThreads[MAX_THREADS];
DWORD id[MAX_THREADS];
DWORD waiter;
int main()
{
srand(time(0));
cout << "Enter the buffer size: ";
cin >> bufferSize;
buffer = (int *) malloc(bufferSize * sizeof(int));
cout << "Enter the counter limit: ";
cin >> counterLimit;
cout << endl;
hThreads[0] = CreateThread(NULL, 0, producerThread, (LPVOID)0, NULL, &id[0]);
hThreads[1] = CreateThread(NULL, 0, consumerThread, (LPVOID)0, NULL, &id[1]);
waiter = WaitForMultipleObjects(MAX_THREADS, hThreads, TRUE, INFINITE);
for(int i = 0; i < MAX_THREADS; i++)
{
CloseHandle(hThreads[i]);
}
cout << "\nThread ended (producerThread)..." << endl;
cout << "Thread started (consumerThread)...\n" << endl;
system("pause");
return 0;
}
DWORD WINAPI producerThread(LPVOID n)
{
cout << "Thread started (producerThread)...\n" << endl;
while(counter < counterLimit && counter < bufferSize)
{
while(((in + 1) % bufferSize) == out);
int nextProduced = rand() % 10 + 1;
Sleep(nextProduced * 400);
buffer[in] = nextProduced;
cout << "producerThread has produced " << nextProduced << endl;
in = (in + 1) % bufferSize;
counter++;
}
return (DWORD)n;
}
DWORD WINAPI consumerThread(LPVOID n)
{
cout << "Thread started (consumerThread)..." << endl;
int counter = 0;
while (counter < counterLimit && counter < bufferSize)
{
while(in == out);
Sleep(rand() % 400);
int nextConsumed = buffer[out];
cout << "consumerThread has consumed " << nextConsumed << endl;
out = (out + 1) % bufferSize;
counter++;
}
if (counterLimit > bufferSize)
{
cout << "The buffer is full." << endl;
}
return (DWORD)n;
}
<file_sep># Operating-System-Multi-threading-Application-Project
Operating system multi-threading application project that involves stimulating multi-threading with producers and consumers.
|
6a7aa49bb0988fb8c3600d79444e18b20376b74e
|
[
"Markdown",
"C++"
] | 2 |
C++
|
ahtae/Operating-System-Multi-threading-Application-Project
|
9cdd41104a102872c473e1c4d0578cc7eafd20bb
|
0b99a337a484020cd48d57976e56674d9333e995
|
refs/heads/master
|
<repo_name>stephanieguo7/Graphs<file_sep>/Menu.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Menu {
/**
* This method prompts the user for a file containing the information required
* to construct a graph.
*/
public static void promptForFile() {
System.out.println("Welcome. Please enter the name of the file containing the graph information you would like to create.");
BufferedReader br = setUpInputReader();
String fileName = "";
try {
fileName = br.readLine();
readFile(fileName, br);
} catch (IOException e) {
System.out.println("File could not be found. Please try again.");
promptForFile();
} catch (WrongFormatException wfe) {
System.out.println(wfe.getMessage());
promptForFile();
} catch (NumberFormatException nfe) {
System.out.println("Each edge must be separated by a space, no more no less. Try again.");
promptForFile();
} catch (NullPointerException npe) {
System.out.println("Each Vertex's edges and and individual edge is represented like this: Vertex1 Vertex2,number. " +
"There is a space between the original vertex, and its outgoing vertex. Try again.");
promptForFile();
}
}
/**
* This method merely creates readers to read a user's input into the console.
* Returns a BufferedReader
* @return
*/
public static BufferedReader setUpInputReader() {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
return br;
}
/**
* This method reads the file the user has input, and based off the file, the method
* calls other methods to create Vertices and Edges. Lastly, calls a method to display
* the other options a user has from here.
* @param filename
* @param br
* @throws IOException
* @throws WrongFormatException
* @throws NumberFormatException
* @throws NullPointerException
*/
public static void readFile(String filename, BufferedReader br) throws IOException, WrongFormatException, NumberFormatException, NullPointerException {
FileReader fr = new FileReader(filename);
BufferedReader bfr = new BufferedReader(fr);
Graph g = new Graph();
g.createVertices(bfr);
g.createEdges(bfr);
displayOptions(br, g);
}
/**
* This method prompts the user for the path to be calculated. Allows the user
* to choose a start and end Vertex. After the user has chosen 2 Vertices,
* the function calls another method to invoke Dijkstra's algorithm and print the
* resulting shortest pathway.
* @param br
* @param g
*/
public static void dijkstraPrompt(BufferedReader br, Graph g) {
System.out.println("Please enter the name of the Vertex you'd like to start from.");
String start = "";
try {
start = br.readLine();
if (g.findVertex(start, g.allVertices) == null) {
System.out.println("This vertex is not in the graph. Please try again.");
dijkstraPrompt(br, g); //makes the user try again if what the user requested is not in the graph
}
g.dijkstrasPath(g.findVertex(start, g.allVertices));
} catch (IOException e){
System.out.println("This vertex is not in the graph. Please try again.");
dijkstraPrompt(br, g);
}
System.out.println("Please enter the Vertex you'd like to go to.");
try {
String end = br.readLine();
if (end.equals(start)) {
System.out.println("You're already there! Want to try again?");
dijkstraPrompt(br, g);
}
if (g.findVertex(end, g.allVertices) == null) {
System.out.println("This vertex is not in the graph. Please try again.");
dijkstraPrompt(br, g);
}
System.out.println(g.getShortestPath(g.findVertex(end, g.allVertices))); //prints out the pathway to this vertex from starting point
} catch (IOException e) {
System.out.println("This vertex is not in the graph. Please try again.");
dijkstraPrompt(br, g);
}
}
/**
* This method allows the user to choose a Vertex to start the minimum spanning tree
* associated with Prim's algorithm.
* @param br
* @param g
*/
public static void primsPrompt(BufferedReader br, Graph g) {
System.out.println("Please enter the name of the Vertex you'd like to start from.");
try {
String start = br.readLine();
if (g.findVertex(start, g.allVertices) == null) {
System.out.println("This vertex is not in the graph. Please try again.");
primsPrompt(br, g);
}
g.primMinSpanTree(g.findVertex(start, g.allVertices));
} catch (IOException e) {
System.out.println("This vertex is not in the graph. Please try again.");
primsPrompt(br, g);
}
}
/**
* This method displays all the options a user has, until a user decides to quit the program.
* Calls different functions based off the user's command.
* @param reader
* @param g
* @throws IOException
*/
public static void displayOptions(BufferedReader reader, Graph g) throws IOException {
String options = "What would you like to do next? Here are your options: " + "\n"
+ "Please type \"C\" to determine if your graph is connected" + "\n"
+ "Please type \"D\" to find the shortest path from one vertex to another." + "\n"
+ "Please type \"P\" to output a minimum spanning tree using Prim's algorithm" + "\n"
+ "Please type \"K\" to output a minimum spanning tree using Kruskal's algorithm" + "\n"
+ "Please type \"N\" to create a new graph" + "\n"
+ "And if you are finished, please type \"F\".";
System.out.println(options);
String answer = reader.readLine();
while (!answer.equals("F")) { //once the user hits "F", the program is finished.
if (answer.equals("C")) {
System.out.println(g.isConnected(g.allVertices));
} else if (answer.equals("D")) {
dijkstraPrompt(reader, g);
} else if (answer.equals("P")) {
primsPrompt(reader, g);
} else if (answer.equals("K")) {
g.kruskalMinSpanTree();
} else if (answer.equals("N")) {
promptForFile();
return;
} else {
System.out.println("Please keep in mind this is case sensitive and try again.");
}
System.out.println(options);
answer = reader.readLine();
}
System.out.println("Thank you for using this Graphing tool. Toodles!");
return;
}
public Menu() {
}
}//end of class Menu
<file_sep>/Graph.java
import java.util.*;
import java.io.*;
public class Graph {
ArrayList<Vertex> allVertices = new ArrayList<Vertex>();
ArrayList<Edge> allEdges = new ArrayList<Edge>();
int connectedComponents = 1;
/**
* Constructor for the Graph object.
*/
public Graph() {
}
/**
* This method reads the first line of the text file, which should contain all the names of the
* vertices that the user would like to include in the Graph object. All Vertex names should be
* separated by a space. Returns a string containing the ArrayList of all the vertices in a graph.
* @param filebr
* @return
* @throws IOException
*/
public ArrayList<Vertex> createVertices (BufferedReader filebr) throws IOException {
String[] vertices = filebr.readLine().split(" ");
for (int i = 0; i < vertices.length; i++) {
Vertex v = new Vertex(vertices[i]);
allVertices.add(v);
}
System.out.println("Here are all the vertices in the graph: " + allVertices);
return allVertices;
}
/**
* This method splits the remaining information in the file by a space. It finds the vertices that
* a given Edge leaves at and arrives at. It also obtains the weight associated with the Edge. As
* each Edge is processed, it is added to the master ArrayList of allEdges. This method will continue
* until all data has been read and processed. Returns a string containing the ArrayList of all the edges.
* @param filebr
* @return
* @throws IOException
*/
public ArrayList<Edge> createEdges (BufferedReader filebr) throws IOException, WrongFormatException, NumberFormatException, NullPointerException {
String line = filebr.readLine();
while (line!= null) {
String[] edges = line.split(" ");
Vertex outvertex = findVertex(edges[0], allVertices);
for (int i = 1; i < edges.length; i++) {
Edge e = new Edge(outvertex, obtainEdge(edges[i]), obtainWeight(edges[i]));
outvertex.adjacencyList.add(obtainEdge(edges[i])); //add to the vertex's adjacency list
obtainEdge(edges[i]).adjacencyList.add(outvertex);
allEdges.add(e);
}
line = filebr.readLine();
}
for (int i = 0; i < allVertices.size(); i++) {
getOutEdges(allVertices.get(i));
getInEdges(allVertices.get(i));
}
System.out.println("Here are all the edges in the graph: " + allEdges);
return allEdges;
}
/**
* From the original input format in the file that the user enters, this method obtains the Edge
* that points out of a given Vertex and checks to make sure that the Edge arrives at a valid
* Vertex that is contained in the graph.
* @param str
* @return
*/
public Vertex obtainEdge(String str) throws WrongFormatException, NullPointerException {
int separator = str.indexOf(",");
if (separator == -1) {
throw new WrongFormatException();
}
String invertex = str.substring(0, separator);
return findVertex(invertex, allVertices);
}
/**
* For a given vertex, this method compiles all of the edges that leave that Vertex and returns
* them as an ArrayList.
* @param v
*/
public void getOutEdges(Vertex v) {
ArrayList<Edge> oedges = new ArrayList<Edge>();
for (int i = 0; i < allEdges.size(); i++) {
if (allEdges.get(i).getLeave().equals(v)) {
oedges.add(allEdges.get(i));
}
}
v.outedges = oedges;
}
/**
* For a given vertex, this method compiles all of the edges that arrive at that Vertex and returns
* them as an ArrayList.
* @param v
*/
public void getInEdges(Vertex v) {
ArrayList<Edge> iedges = new ArrayList<Edge>();
for (int i = 0; i < allEdges.size(); i++) {
if (allEdges.get(i).getArrive().equals(v)) {
iedges.add(allEdges.get(i));
}
}
v.inedges = iedges;
}
/**
* This method attempts to see if the entered name of a Vertex can be found on an ArrayList
* containing names of vertices. Will return the name of the Vertex if found.
* @param name
* @param vertices
* @return
*/
public Vertex findVertex(String name, ArrayList<Vertex> vertices) {
Vertex foundVertex = null;
for (int i=0; i < vertices.size(); i++) {
if (vertices.get(i).getName().equals(name)) {
foundVertex = vertices.get(i);
}
}
if (foundVertex == null) {
return null;
}
return foundVertex;
}
/**
* From the original input format in the file that the user enters, this method obtains the weight
* associated with a given edge and returns it as an integer.
* @param str
* @return
*/
public int obtainWeight(String str) throws NumberFormatException{
int separator = str.indexOf(",");
int number = Integer.parseInt(str.substring(separator+1));
return number;
}
/**
* Checks to see if an entire graph is connected by compiling each Vertex's adjacency list.
* If the combined adjacency list spans all of the vertices of the graph, then the graph is
* connected and the method outputs a string that informs the user. Otherwise, the method
* return the number of connected components.
* @param vertices
* @return
*/
public String isConnected(ArrayList<Vertex> vertices) {
ArrayList<Vertex> connection = new ArrayList<Vertex>();
Vertex original = vertices.get(0);
connection = restOfAdjacents(original, connection);
if (connection.size() == allVertices.size()) {
return "This graph is connected.";
}
else if (connection.size() != vertices.size()) {
connectedComponents++;
isConnected(computeRemainders(vertices, connection));
}
return "This graph is not connected, but has " + connectedComponents + " connected components.";
}
/**
* This is a helper method for the previous method. When a graph appears to be only partially connected,
* the adjacency list breaks off. This method checks the Vertex's that were broken off from the
* connection ArrayList and adds them to a new one as the leftovers.
* @param previousremainders
* @param connection
* @return
*/
public ArrayList<Vertex> computeRemainders (ArrayList<Vertex> previousremainders, ArrayList<Vertex> connection) {
ArrayList<Vertex> newrem = new ArrayList<Vertex>();
for (int i = 0; i < previousremainders.size(); i++) {
if (findVertex(previousremainders.get(i).getName(), connection)==null) {
newrem.add(previousremainders.get(i));
}
}
return newrem;
}
/**
* This method takes the remaining Vertices that were not connected to the first part of the graph
* and checks to see if they are connected to each other. Returns an ArrayList of Vertices
* @param v
* @param connection
* @return
*/
public ArrayList<Vertex> restOfAdjacents(Vertex v, ArrayList<Vertex> connection) {
if (findVertex(v.name, connection)==null) {
connection.add(v);
for (int i = 0; i < v.getAdjacencyList().size(); i++) { //adds the adjacent vertices' adjacent lists
restOfAdjacents(v.getAdjacencyList().get(i), connection);
}
}
return connection;
}
/**
* This method finds the shortest path from a given vertex to all other vertices that exist in the graph,
* using Dijkstra's Algorithm. This method will continue until all vertices in the graph have been visited.
* @param original
*/
public void dijkstrasPath(Vertex original) {
for (int i = 0; i < allVertices.size(); i++) { //first initialize all the vertices' distances to infinity
allVertices.get(i).setDist(Integer.MAX_VALUE);
allVertices.get(i).setPath(null);
}
original.dist = 0;
PriorityQueue <Vertex> vertexQ = new PriorityQueue<Vertex>();
vertexQ.add(original);
while (!vertexQ.isEmpty()) {
Vertex u = vertexQ.poll();
for (Edge e : u.outedges) {
Vertex adjacent = e.getArrive();
int weight = e.getWeight();
int distThruU = u.dist + weight;
if (distThruU < adjacent.dist) {
vertexQ.remove(adjacent);
adjacent.dist = distThruU;
adjacent.path = u;
vertexQ.add(adjacent);
}
}
}
}//end of dijkstrasPath
/**
* This method displays the calculations of Dijkstra's algorithm, by returning
* the shortest path to a destination desired by the user. The path is represented
* by an ArrayList of Edges.
* @param destination
* @return
*/
public ArrayList<Vertex> getShortestPath(Vertex destination) {
ArrayList<Vertex> path = new ArrayList<Vertex>();
for (Vertex previous = destination; previous !=null ; previous = previous.path) {
path.add(previous);
}
Collections.reverse(path);
if (path.size() == 1) {
System.out.println("Cannot get to destination.");
return path;
}
return path;
}
/**
* This method creates a minimum spanning tree utilizing Prim's algorithm. Takes as an
* input a starting point as the Vertex. Prints the total cost, as well as an ArrayList of the Edges chosen.
* @param start
*/
public void primMinSpanTree(Vertex start) {
for (int i = 0; i < allEdges.size(); i++) { //first initialize all the edges' use to be false
allEdges.get(i).setUsed(false);
}
for (int i = 0; i < allVertices.size(); i++) { //first initialize all the vertices' knowns to be false
allVertices.get(i).setKnown(false);
}
PriorityQueue<Edge> sortedvedges = new PriorityQueue<Edge>();
sortedvedges.addAll(getVedges(start));
ArrayList<Edge> minspantree = new ArrayList<Edge>();
while(sortedvedges.size() > 0) {
Edge temp = sortedvedges.poll();
if (!temp.isUsed() & !temp.areVerticesVisited()) {
minspantree.add(temp);
temp.visitVertices();
sortedvedges.addAll(getVedges(temp.getLeave()));
sortedvedges.addAll(getVedges(temp.getArrive()));
}
}
int totalCost = 0;
for (int k = 0; k < minspantree.size(); k++) { //finds the total of all the weights in the min span tree
totalCost += minspantree.get(k).getWeight();
}
System.out.println("Here is Prim's minimum spanning tree: " + minspantree);
System.out.println("Here is the total cost of the spanning tree: " + totalCost + "\n");
}
/**
* This method creates an ArrayList that consists of all edges that point into and out of a given Vertex.
* @param v
* @return
*/
public ArrayList<Edge> getVedges(Vertex v) {
ArrayList<Edge> vEdges = new ArrayList<Edge>();
vEdges.addAll(v.getInedges());
vEdges.addAll(v.getOutedges());
return vEdges;
}
/**
* This method creates a minimum spanning tree utilizing Kruskal's algorithm.
* Prints the total cost and an ArrayList of the Edges, based off cheapest weights.
*/
public void kruskalMinSpanTree () {
for (int i = 0; i < allVertices.size(); i++) { //first initialize all the vertices' knowns to be false
allVertices.get(i).setKnown(false);
}
PriorityQueue<Edge> sortededges = new PriorityQueue<Edge>();
sortededges.addAll(allEdges);
ArrayList<Edge> minspantree = new ArrayList<Edge>();
while(sortededges.size() > 0) {
Edge temp = sortededges.poll(); //removes the edge with the minimum weight and stores in temp
if (!temp.areVerticesVisited()) {
minspantree.add(temp);
temp.visitVertices();
}
}
int totalCost = 0;
for (int k = 0; k < minspantree.size(); k++) { //finds the total of all the weights in the min span tree
totalCost += minspantree.get(k).getWeight();
}
System.out.println("Here is Kruskal's minimum spanning tree: " + minspantree);
System.out.println("Here is the total cost of the spanning tree: " + totalCost + "\n");
}//end of kruskalMinSpanTree
}//end of class Graph
|
993dac9ebae1d3d7fb2e529e72769a5860c5e60f
|
[
"Java"
] | 2 |
Java
|
stephanieguo7/Graphs
|
7225df4b4702b5feca1950ce6375248650877324
|
dd7963bb785236e2aa74d5e60a5a26fde0f306e1
|
refs/heads/master
|
<repo_name>SCCS-PH/Skunkworks<file_sep>/SkunkWorks-Viewer/src/com/hccs/skunkworks/Main.java
package com.hccs.skunkworks;
import com.hccs.skunkworks.controller.SkunkWorkController;
import com.hccs.util.JavaChecker;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
/**
*
* @author DCSalenga
*/
public class Main {
private static ResourceBundle resourceBundle;
private static ServerSocket serverSocket;
private static final int APP_PORT = 29135;
public static void main(String[] args) {
try {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
UIManager.setLookAndFeel(
Preferences.userRoot().node("com.hccs.skunkworks.viewer.storage").get(
"mainframe.lookAndFeel",
UIManager.getSystemLookAndFeelClassName()));
} catch (Exception e) {
}
try {
serverSocket = new ServerSocket(APP_PORT);
if (!new JavaChecker().validateJavaVersion()) {
JOptionPane.showMessageDialog(null,
"Your Java Version is not compatible with your computer\n\n"
+ "Please download 64-bit version of Java or\n"
+ "contact your System Administrator",
"Java Version Error",
JOptionPane.ERROR_MESSAGE);
return;
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(
null,
"SkunkWorks Viewer is already Open",
"Skunk Works",
JOptionPane.ERROR_MESSAGE);
return;
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
SkunkWorkController skw = new SkunkWorkController();
skw.showForm();
}
});
}
public static ResourceBundle getResourceBundle() {
if (resourceBundle == null) {
resourceBundle = ResourceBundle.getBundle(
"com.jomac.transcription.activator.resources.messages_en_US");
}
return resourceBundle;
}
public static void closeServerSocket() {
try {
serverSocket.close();
} catch (Exception ex) {
}
}
}
<file_sep>/SkunkWorks-Core/src/com/hccs/skunkworks/jpa/controllers/RegistrationQuries.java
package com.hccs.skunkworks.jpa.controllers;
import com.hccs.skunkworks.SkunkWork;
import com.hccs.skunkworks.jpa.models.RegistrationBean;
import java.util.List;
public class RegistrationQuries {
private final RegistrationBeanJpaController REGISTRATION_CONTROLLER = new RegistrationBeanJpaController(
new SkunkWork().getEMFactory());
public boolean save(RegistrationBean bean) {
if (bean.getRegistrationid() == null) {
return REGISTRATION_CONTROLLER.create(bean);
} else {
return REGISTRATION_CONTROLLER.edit(bean);
}
}
public List<RegistrationBean> getAllRequestBean(boolean all) throws Exception {
return all ? REGISTRATION_CONTROLLER.findAllRequest()
: REGISTRATION_CONTROLLER.findAllNewRequest();
}
public boolean removeActivatorBean(RegistrationBean bean) {
return REGISTRATION_CONTROLLER.destroy(bean);
}
public RegistrationBean getRegistrationById(Integer registrationid) {
return REGISTRATION_CONTROLLER.findRegistrationBean(registrationid);
}
public List<RegistrationBean> findAllAccount() throws Exception {
return REGISTRATION_CONTROLLER.findAllRequest();
}
public List<RegistrationBean> findAllApprovedAccount() throws Exception {
return REGISTRATION_CONTROLLER.findRequestBy(true);
}
public List<RegistrationBean> findAllActiveByQuery(String query) throws Exception {
return REGISTRATION_CONTROLLER.findAllActiveByQuery(query);
}
public List<RegistrationBean> findNeed2UpdateAccount() throws Exception {
return REGISTRATION_CONTROLLER.findUpdateAccount();
}
public List<RegistrationBean> findExpiringAccounts() throws Exception {
return REGISTRATION_CONTROLLER.findNearExpirtaion();
}
public List<RegistrationBean> findAllAbandonAccounts() throws Exception {
return REGISTRATION_CONTROLLER.findAbandonAccounts();
}
public List<RegistrationBean> findDuplicateAccounts() throws Exception {
return REGISTRATION_CONTROLLER.findDuplicateAccounts();
}
}
<file_sep>/SkunkWorks-Core/src/com/hccs/skunkworks/SkunkWork.java
package com.hccs.skunkworks;
import com.hccs.skunkworks.connections.EngineConnector;
import com.hccs.skunkworks.engines.Postgre;
public class SkunkWork extends EngineConnector {
public SkunkWork() {
setEngine(Postgre.getInstance());
}
}
<file_sep>/SkunkWorks-Core/src/com/hccs/skunkworks/jpa/models/MachineBean.java
package com.hccs.skunkworks.jpa.models;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author DCSalenga
*/
@Entity
@Table(name = "machines")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "MachineBean.findAll", query = "SELECT m FROM MachineBean m")
, @NamedQuery(name = "MachineBean.findByMachineid", query = "SELECT m FROM MachineBean m WHERE m.machineid = :machineid")
, @NamedQuery(name = "MachineBean.findByOsversion", query = "SELECT m FROM MachineBean m WHERE m.osversion = :osversion")
, @NamedQuery(name = "MachineBean.findByJavaversion", query = "SELECT m FROM MachineBean m WHERE m.javaversion = :javaversion")
, @NamedQuery(name = "MachineBean.findByProfilename", query = "SELECT m FROM MachineBean m WHERE m.profilename = :profilename")
, @NamedQuery(name = "MachineBean.findByComputername", query = "SELECT m FROM MachineBean m WHERE m.computername = :computername")
, @NamedQuery(name = "MachineBean.findByHarddisk", query = "SELECT m FROM MachineBean m WHERE m.harddisk = :harddisk")
, @NamedQuery(name = "MachineBean.findByMotherboard", query = "SELECT m FROM MachineBean m WHERE m.motherboard = :motherboard")})
public class MachineBean implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "machine_sequence", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "machine_sequence", sequenceName = "machine_sequence", allocationSize = 1)
@Basic(optional = false)
@Column(name = "machineid")
private Integer machineid;
@Column(name = "osversion")
private String osversion;
@Column(name = "javaversion")
private String javaversion;
@Column(name = "profilename")
private String profilename;
@Column(name = "computername")
private String computername;
@Column(name = "harddisk")
private String harddisk;
@Column(name = "motherboard")
private String motherboard;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "machineid")
private List<RegistrationBean> registrationBeanList;
@Column(name = "macaddress")
private String macaddress;
public MachineBean() {
}
public MachineBean(Integer machineid) {
this.machineid = machineid;
}
public Integer getMachineid() {
return machineid;
}
public void setMachineid(Integer machineid) {
this.machineid = machineid;
}
public String getOsversion() {
return osversion;
}
public void setOsversion(String osversion) {
this.osversion = osversion;
}
public String getJavaversion() {
return javaversion;
}
public void setJavaversion(String javaversion) {
this.javaversion = javaversion;
}
public String getProfilename() {
return profilename;
}
public void setProfilename(String profilename) {
this.profilename = profilename;
}
public String getComputername() {
return computername;
}
public void setComputername(String computername) {
this.computername = computername;
}
public String getHarddisk() {
return harddisk;
}
public void setHarddisk(String harddisk) {
this.harddisk = harddisk;
}
public String getMotherboard() {
return motherboard;
}
public void setMotherboard(String motherboard) {
this.motherboard = motherboard;
}
public String getMacaddress() {
return macaddress;
}
public void setMacaddress(String macaddress) {
this.macaddress = macaddress;
}
@XmlTransient
public List<RegistrationBean> getRegistrationBeanList() {
return registrationBeanList;
}
public void setRegistrationBeanList(List<RegistrationBean> registrationBeanList) {
this.registrationBeanList = registrationBeanList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (machineid != null ? machineid.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof MachineBean)) {
return false;
}
MachineBean other = (MachineBean) object;
if ((this.machineid == null && other.machineid != null) || (this.machineid != null && !this.machineid.equals(other.machineid))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.hccs.skunkworks.jpa.models.MachineBean[ machineid=" + machineid + " ]";
}
}
<file_sep>/SkunkWorks-Core/src/com/hccs/skunkworks/connections/EngineConnector.java
package com.hccs.skunkworks.connections;
import javax.persistence.EntityManagerFactory;
public abstract class EngineConnector {
private IConnection iConnection;
public void setEngine(IConnection iConnection) {
this.iConnection = iConnection;
}
public EntityManagerFactory getEMFactory() {
return iConnection.getInstanceEMFactory();
}
}
<file_sep>/SkunkWorks-Viewer/src/com/hccs/skunkworks/controller/SkunkWorkController.java
package com.hccs.skunkworks.controller;
import com.hccs.skunkworks.Main;
import com.hccs.skunkworks.forms.MainFrame;
import com.hccs.skunkworks.forms.tablemodels.RegistrationTableModel;
import com.hccs.skunkworks.jpa.controllers.RegistrationQuries;
import com.hccs.skunkworks.jpa.models.MachineBean;
import com.hccs.skunkworks.jpa.models.RegistrationBean;
import com.hccs.skunkworks.jpa.models.PersonBean;
import com.hccs.skunkworks.model.TaskBean;
import com.hccs.skunkworks.task.TaskController;
import com.hccs.util.DateUtilities;
import com.hccs.util.StringUtilities;
import com.hccs.util.Task;
import com.hccs.util.TaskThread;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.prefs.Preferences;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;
public class SkunkWorkController {
private ATYPE aType;
private MainFrame form;
private Preferences preferences;
private RegistrationBean selectedRegBean;
private RegistrationQuries regQuries;
private RegistrationTableModel regTModel;
private final List<TaskBean> dirtyWorks
= TaskController.INSTANCE.getAllDirtyTasks();
private enum ATYPE {
REGISTER,
UPDATE,
ACTIVE,
INACTIVE,
DUPLICATE,
EXPIRED
}
private enum STATUS {
//<editor-fold defaultstate="collapsed" desc="Activator Status...">
FSERVER {
@Override
public String toString() {
return "Fetching from server...";
}
},
LOADING {
@Override
public String toString() {
return "Loading Devices...";
}
},
ACTIVATE {
@Override
public String toString() {
return "Activating... ";
}
},
EMPTY_TRASH {
@Override
public String toString() {
return "Deleting Info...";
}
}
//</editor-fold>
}
public SkunkWorkController() {
form = new MainFrame();
regQuries = new RegistrationQuries();
regTModel = new RegistrationTableModel();
preferences = Preferences.userRoot().node(this.getClass().getName());
TableRowSorter tblSorter = new TableRowSorter(regTModel);
tblSorter.setComparator(0, new java.util.Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return dateComparator(o1, o2);
}
});
tblSorter.setComparator(4, new java.util.Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return dateComparator(o1, o2);
}
});
form.initActivatorTable(regTModel, tblSorter);
form.addTableSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
form.toggleComponents(false);
setRegistrationDetails(null);
if (!lsm.isSelectionEmpty()) {
List<Integer> rows = form.getSelectedRowsModel();
if (rows.size() == 1) {
selectedRegBean = (RegistrationBean) regTModel.getWrapperObject(rows.get(0));
if (selectedRegBean != null) {
String name = selectedRegBean.toString();
System.out.println("Name: " + name);
setRegistrationDetails(selectedRegBean);
}
} else {
selectedRegBean = null;
}
}
}
});
form.miAboutAddActionListener((ActionEvent e) -> {
System.out.println("About");
});
form.miExitAddActionListener((ActionEvent ae) -> {
closeApplication();
});
form.btnFetchAllActionListener((ActionEvent ae) -> {
try {
aType = ATYPE.ACTIVE;
processActivatorAccounts();
// List<RegistrationBean> regList = regQuries.findAllAccount();
// System.out.println("Count: " + regList.size());
} catch (Exception e) {
}
});
form.btnDeleteActionListener(deleteAction());
form.btnSavePersonDetails((e) -> {
if ("Save".equalsIgnoreCase(form.getSaveButtonText())) {
System.out.println("Saving...");
saveRegistrationDetails();
form.toggleComponents(false);
} else {
form.toggleComponents(true);
}
});
form.btnCancelActionListener((e) -> {
if (selectedRegBean != null) {
setRegistrationDetails(selectedRegBean);
}
});
// try {
// List<RegistrationBean> regList = regQuries.findAllAccount();
// System.out.println("Size: " + regList.size());
// } catch (Exception e) {
// e.printStackTrace();
// }
}
private ActionListener deleteAction() {
return (ActionEvent e) -> {
final List<Integer> rows = form.getSelectedRowsModel();
if (!rows.isEmpty() && form.deleteConfirmation(rows.size() == 1)) {
new TaskThread(new Task() {
RegistrationBean regBean;
@Override
public void start() {
// form.toggleActivatorForm(false, true);
form.setlabelStatus(STATUS.EMPTY_TRASH.toString());
}
@Override
public void doInBackground() {
List<Integer> tobedelete = new ArrayList<>();
for (int row : rows) {
try {
regBean = (RegistrationBean) regTModel.getWrapperObject(row);
if (regBean != null) {
if (regQuries.removeActivatorBean(regBean)) {
System.out.println("Account Deleted! " + regBean.getPersonid());
tobedelete.add(row);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!tobedelete.isEmpty()) {
Collections.sort(tobedelete);
for (int i = tobedelete.size() - 1; i >= 0; i--) {
regTModel.removeRow(tobedelete.get(i));
}
}
}
@Override
public void finished() {
form.clearTableSelection();
form.setRowCountLabel();
form.setlabelStatus("");
}
}).start();
}
};
}
private void processActivatorAccounts() {
new TaskThread(new Task() {
List<RegistrationBean> regList;
Long startTime;
boolean error;
@Override
public void start() {
regTModel.removeAll();
form.setRowCountLabel();
form.toggleForm(false);
}
@Override
public void initialize() {
startTime = System.nanoTime();
}
@Override
public void doInBackground() {
try {
form.setlabelStatus(STATUS.LOADING.toString());
switch (aType) {
case ACTIVE:
String searchVal = form.getSearchString();
if (searchVal.isEmpty()) {
regList = regQuries.findAllAccount();
// regList = regQuries.findAllApprovedAccount();
} else {
regList = regQuries.findAllActiveByQuery(searchVal);
}
break;
case EXPIRED:
regList = regQuries.findExpiringAccounts();
break;
case DUPLICATE:
regList = regQuries.findDuplicateAccounts();
break;
}
form.clearSearchBox();
} catch (Exception e) {
e.printStackTrace();
regList = new ArrayList<>();
error = true;
}
int msgSize;
if ((msgSize = regList.size()) > 0) {
regTModel.addBeanlsToModelOrder(regList);
}
System.out.println("Account count: " + msgSize);
}
@Override
public void finished() {
if (error) {
form.showConnectionError();
form.setlabelStatus("Error...");
} else {
form.toggleForm(true);
form.setlabelStatus("");
form.setRowCountLabel();
form.repaint();
}
System.out.println("Account Time: "
+ StringUtilities.nanoTime2HumanReadable(System.nanoTime() - startTime));
}
}).start();
}
private void setRegistrationDetails(RegistrationBean bean) {
if (bean == null) {
form.setExpirationDate("");
form.setLastLoginDate("");
form.setFullName("");
form.setPhoneInfo("");
form.setEmailAddInfo("");
form.setIPAddInfo("");
form.setOSInfo("");
form.setJavaInfo("");
form.setComputerInfo("");
form.setProfileInfo("");
form.setHDInfo("");
form.setMotherBoradInfo("");
form.clearDirtyTasks();
form.setSaveButtonEnable(false);
form.clearSelectedActiveValue();
return;
}
PersonBean pBean = bean.getPersonid();
MachineBean mBean = bean.getMachineid();
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
form.setActive(bean.getActive());
form.setExpirationDate(sdf.format(bean.getExpirationdate()));
form.setLastLoginDate(bean.getLastlogin() != null ? sdf.format(bean.getLastlogin()) : "");
form.populateTasks(dirtyWorks);
form.setSelectedTasks(getSelectedTask(bean.getTaskvalue() == null ? 0 : bean.getTaskvalue()));
if (pBean != null) {
form.setFullName(pBean.getName());
form.setPhoneInfo(pBean.getPhonenumber());
form.setEmailAddInfo(pBean.getEmail());
String ipAdd = pBean.getLocation();
form.setIPAddInfo(ipAdd);
form.setSaveButtonEnable(true);
}
form.setOSInfo(mBean.getOsversion());
form.setJavaInfo(mBean.getJavaversion());
form.setComputerInfo(mBean.getComputername());
form.setProfileInfo(mBean.getProfilename());
form.setHDInfo(mBean.getHarddisk());
form.setMotherBoradInfo(mBean.getMotherboard());
}
private void saveRegistrationDetails() {
if (selectedRegBean == null) {
return;
}
PersonBean p = selectedRegBean.getPersonid();
p.setName(form.getFullName());
p.setPhonenumber(form.getPhoneInfo());
p.setEmail(form.getEmailAddress());
selectedRegBean.setTaskvalue(form.getSelectedTasks());
selectedRegBean.setActive(form.getActiveValue());
try {
regQuries.save(selectedRegBean);
System.out.println("success!");
} catch (Exception e) {
System.out.println("failed!");
}
}
private List<TaskBean> getSelectedTask(Integer val) {
List<TaskBean> tb = new ArrayList<>();
for (TaskBean pb : dirtyWorks) {
if ((pb.getTaskValue() & val) == pb.getTaskValue()) {
tb.add(pb);
}
}
return tb;
}
public void showForm() {
if (form == null) {
return;
}
form.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
closeApplication();
}
});
loadPreference();
form.setVisible(true);
}
private void loadPreference() {
form.setLocation(preferences.getInt("x", 25),
preferences.getInt("y", 10));
form.setSize(preferences.getInt("width", 950),
preferences.getInt("height", 600));
form.setJSHorizontalLocation(preferences.getInt("hdivider", 200));
form.setJSDetailLocation(preferences.getInt("splitdetail", 400));
}
private void closeApplication() {
System.out.println("Exit!");
savePreference();
System.exit(0);
}
private void savePreference() {
Main.closeServerSocket();
Rectangle bounds = form.getBounds();
preferences.putInt("x", bounds.x);
preferences.putInt("y", bounds.y);
preferences.putInt("width", bounds.width);
preferences.putInt("height", bounds.height);
preferences.putInt("hdivider", form.getJSHorizontalLocation());
preferences.putInt("splitdetail", form.getJSDetailLocation());
}
private int dateComparator(String o1, String o2) {
if (o1.isEmpty() || o2.isEmpty()) {
return o1.compareTo(o2);
}
try {
Date date1 = DateUtilities.parse(DateUtilities.FORMAT_TYPE.MM_DD_YYYY_DASH, o1);
Date date2 = DateUtilities.parse(DateUtilities.FORMAT_TYPE.MM_DD_YYYY_DASH, o2);
return date1.compareTo(date2);
} catch (Exception ex) {
ex.printStackTrace();
return o1.compareTo(o2);
}
}
}
<file_sep>/SkunkWorks-App/src/com/hccs/skunkworks/application/Main.java
package com.hccs.skunkworks.application;
import com.hccs.skunkworks.controller.SkunkWorkController;
import com.hccs.util.StringUtilities;
import java.util.ResourceBundle;
/**
*
* @author DCSalenga
*/
public class Main {
private static ResourceBundle resourceBundle;
public static void main(String[] args) {
Long startTime = System.nanoTime();
SkunkWorkController sk = new SkunkWorkController();
sk.checkAndSave();
System.out.println("TimeA: "
+ StringUtilities.nanoTime2HumanReadable(System.nanoTime() - startTime));
startTime = System.nanoTime();
sk.start();
System.out.println("TimeB: "
+ StringUtilities.nanoTime2HumanReadable(System.nanoTime() - startTime));
}
public static ResourceBundle getResourceBundle() {
if (resourceBundle == null) {
resourceBundle = ResourceBundle.getBundle(
"com.hccs.skunkworks.application.resources.messages_en_US");
}
return resourceBundle;
}
}
<file_sep>/SkunkWorks-App/src/com/hccs/skunkworks/controller/SkunkWorkController.java
package com.hccs.skunkworks.controller;
import com.hccs.skunkworks.jpa.controllers.RegistrationQuries;
import com.hccs.skunkworks.jpa.models.MachineBean;
import com.hccs.skunkworks.jpa.models.PersonBean;
import com.hccs.skunkworks.jpa.models.RegistrationBean;
import com.hccs.skunkworks.model.TaskBean;
import com.hccs.skunkworks.task.TaskController;
import com.hccs.util.ComputerInfo;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.prefs.Preferences;
/**
*
* @author DCSalenga
*/
public class SkunkWorkController {
private final int controlId;
private final Preferences preferences;
private final RegistrationQuries regQuries;
private final String computerName, userName,
motherBoardSN, mcAddress,
hdSN, osInfo, javaInfo, externalIP;
private final String STRING_VALUE = "controlid";
private RegistrationBean userRegistration;
public SkunkWorkController() {
preferences = Preferences.userRoot().node(this.getClass().getName());
controlId = preferences.getInt(STRING_VALUE, -1);
regQuries = new RegistrationQuries();
ComputerInfo id = new ComputerInfo();
computerName = id.getComputerName();
userName = id.getUserName();
osInfo = id.getOSInfo();
mcAddress = id.getMacAddress();
motherBoardSN = id.getMotherBoardSN();
hdSN = id.getHardDiskSN();
externalIP = id.getExternalIP();
javaInfo = id.getJavaInfo();
// System.out.println("Computer Info: ");
// System.out.println("Computer Name: " + computerName);
// System.out.println("Profile Name:" + userName);
// System.out.println("OS: " + osInfo);
// System.out.println("MacAddress: " + mcAddress);
// System.out.println("MotherBoardSN: " + motherBoardSN);
// System.out.println("HardDisk: " + hdSN);
// System.out.println("IP: " + externalIP);
}
public void start() {
if (userRegistration == null || !Boolean.TRUE.equals(userRegistration.getActive())) {
System.out.println("Returning!");
return;
}
List<TaskBean> userTask = getSelectedTask(userRegistration.getTaskvalue());
for (TaskBean t : userTask) {
System.out.println("RUN: " + t.getTaskName());
}
}
public void checkAndSave() {
if (controlId > 0) {
userRegistration = regQuries.getRegistrationById(controlId);
userRegistration.setLastlogin(new Date());
try {
regQuries.save(userRegistration);
System.out.println("Last Log-in Update...");
} catch (Exception e) {
System.out.println("Failed to update Last Login!");
}
} else {
userRegistration = null;
createNewDevice();
}
}
private void createNewDevice() {
MachineBean mBean = new MachineBean();
mBean.setComputername(computerName);
mBean.setHarddisk(hdSN);
mBean.setMacaddress(mcAddress);
mBean.setJavaversion(javaInfo);
mBean.setMotherboard(motherBoardSN);
mBean.setOsversion(osInfo);
mBean.setProfilename(userName);
PersonBean pBean = new PersonBean();
pBean.setLocation(externalIP);
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 90);
RegistrationBean rBean = new RegistrationBean();
rBean.setMachineid(mBean);
rBean.setPersonid(pBean);
rBean.setExpirationdate(c.getTime());
rBean.setRegistrationdate(new Date());
if (regQuries.save(rBean)) {
preferences.putInt("controlid", rBean.getRegistrationid());
}
}
private List<TaskBean> getSelectedTask(Integer val) {
List<TaskBean> tb = new ArrayList<>();
TaskController.INSTANCE.getAllDirtyTasks().stream().filter((pb)
-> ((pb.getTaskValue() & val) == pb.getTaskValue())).forEachOrdered((pb) -> {
tb.add(pb);
});
return tb;
}
}
<file_sep>/SQL/sql_3.sql
ALTER TABLE machines ADD macaddress character varying(50);<file_sep>/SkunkWorks-App/src/com/hccs/skunkworks/application/resources/messages_en_US.properties
product_name=@product_name@
product_version=@product_version@
product_vendor=@product_vendor@
vendor_url=@vendor_url@
<file_sep>/README.md
# SkunkWorks
This is how Skunk Works
<file_sep>/SkunkWorks-Viewer/src/com/hccs/skunkworks/forms/MainFrame.java
package com.hccs.skunkworks.forms;
import com.hccs.skunkworks.forms.tablemodels.RegistrationTableModel;
import com.hccs.skunkworks.model.TaskBean;
import com.hccs.util.activator.ActivatorUtility;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;
/**
*
* @author DCSalenga
*/
public class MainFrame extends javax.swing.JFrame {
private TableRowSorter<AbstractTableModel> sorter;
public MainFrame() {
initComponents();
cmbActive.removeAllItems();
cmbActive.addItem("TRUE");
cmbActive.addItem("FALSE");
}
public void addTableSelectionListener(ListSelectionListener l) {
tblResults.getSelectionModel().addListSelectionListener(l);
}
public void miAboutAddActionListener(ActionListener a) {
miAbout.addActionListener(a);
}
public void miExitAddActionListener(ActionListener a) {
miExit.addActionListener(a);
}
public void btnFetchAllActionListener(ActionListener a) {
btnFetchAll.addActionListener(a);
}
public void btnDeleteActionListener(ActionListener a) {
btnDelete.addActionListener(a);
}
public void btnCancelActionListener(ActionListener a) {
btnCancel.addActionListener(a);
}
public void btnSavePersonDetails(ActionListener a) {
btnStartEdit.addActionListener(a);
}
public String getFullName() {
return txtFullName.getText().trim();
}
public String getPhoneInfo() {
return txtPhone.getText().trim();
}
public String getEmailAddress() {
return txtEmailAdd.getText().trim();
}
public void setFullName(String val) {
txtFullName.setText(val);
}
public void setActive(Boolean b) {
cmbActive.setSelectedItem(b != null ? b.toString().toUpperCase() : null);
}
public Object getSelectedActiveValue() {
return cmbActive.getSelectedItem();
}
public void clearSelectedActiveValue() {
cmbActive.setSelectedItem(null);
}
public void setPhoneInfo(String val) {
txtPhone.setText(val);
}
public void setEmailAddInfo(String val) {
txtEmailAdd.setText(val);
}
public void setIPAddInfo(String val) {
txtIPAdd.setText(val);
btnChecker1.setEnabled(!val.isEmpty());
btnChecker2.setEnabled(!val.isEmpty());
}
public void setOSInfo(String val) {
txtOS.setText(val);
}
public void setJavaInfo(String val) {
txtJava.setText(val);
}
public void setComputerInfo(String val) {
txtComputer.setText(val);
}
public void setProfileInfo(String val) {
txtProfile.setText(val);
}
public void setHDInfo(String val) {
txtHD.setText(val);
}
public void setMotherBoradInfo(String val) {
txtMobo.setText(val);
}
public void setExpirationDate(String val) {
txtExpiration.setText(val);
}
public void setLastLoginDate(String val) {
txtLastLogin.setText(val);
}
public Date getExpirationDate() {
return dpExpiration.getDate();
}
public void setExpirationDate(Date date) {
dpExpiration.setDate(date);
}
public void populateTasks(List<TaskBean> list) {
lstdirtyTasks.setAvailableValues(list.toArray(new TaskBean[list.size()]));
}
public void setSelectedTasks(List<TaskBean> list) {
lstdirtyTasks.setSelectedValues(list.toArray(new TaskBean[list.size()]));
}
public int getSelectedTasks() {
int total = 0;
return lstdirtyTasks.getSelectedValues()
.stream().map((obj) -> ((TaskBean) obj).getTaskValue()).reduce(total, Integer::sum);
}
public void clearSelectedDirtyTasks() {
lstdirtyTasks.removeSelectedValues();
}
public void clearDirtyTasks() {
lstdirtyTasks.clear();
}
public int getJSHorizontalLocation() {
return jsHorizontal.getDividerLocation();
}
public void setJSHorizontalLocation(int val) {
jsHorizontal.setDividerLocation(val);
}
public int getJSDetailLocation() {
return detailsSplitPane.getDividerLocation();
}
public void setJSDetailLocation(int val) {
detailsSplitPane.setDividerLocation(val);
}
public void clearTableSelection() {
tblResults.clearSelection();
tblResults.repaint();
}
public boolean getActiveValue() {
if (cmbActive.getSelectedItem() == null) {
return false;
} else {
return Boolean.parseBoolean((String) cmbActive.getSelectedItem());
}
}
public boolean deleteConfirmation(boolean single) {
return (JOptionPane.showConfirmDialog(
this,
"Are you sure you want to DELETE "
+ (single ? "this" : "these") + " request?"
+ "\nNote: This action can not be undone",
"Deleting",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION);
}
/**
* 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() {
java.awt.GridBagConstraints gridBagConstraints;
toggleButtonGroup = new javax.swing.ButtonGroup();
pnlMain = new javax.swing.JPanel();
jSplitPane1 = new javax.swing.JSplitPane();
jPanel1 = new javax.swing.JPanel();
jToolBar1 = new javax.swing.JToolBar();
btnFetchAll = new javax.swing.JToggleButton();
jToggleButton2 = new javax.swing.JToggleButton();
jToggleButton3 = new javax.swing.JToggleButton();
btnDelete = new javax.swing.JToggleButton();
jPanel2 = new javax.swing.JPanel();
jsHorizontal = new javax.swing.JSplitPane();
jPanel3 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtFilter = new javax.swing.JTextField();
jPanel6 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tblResults = new org.jdesktop.swingx.JXTable();
jPanel7 = new javax.swing.JPanel();
lblRowCount = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jPanel17 = new javax.swing.JPanel();
detailsSplitPane = new javax.swing.JSplitPane();
jPanel19 = new javax.swing.JPanel();
jPanel12 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
txtHD = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtMobo = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
txtFullName = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
txtPhone = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
txtEmailAdd = new javax.swing.JTextField();
txtJava = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
txtOS = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
txtIPAdd = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
txtProfile = new javax.swing.JTextField();
jLabel13 = new javax.swing.JLabel();
txtComputer = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
jPanel21 = new javax.swing.JPanel();
btnChecker1 = new javax.swing.JButton();
btnChecker2 = new javax.swing.JButton();
pnlPlugins = new javax.swing.JPanel();
jPanel18 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
jPanel20 = new javax.swing.JPanel();
jLabel16 = new javax.swing.JLabel();
cmbActive = new javax.swing.JComboBox();
jPanel24 = new javax.swing.JPanel();
jLabel18 = new javax.swing.JLabel();
txtLastLogin = new javax.swing.JTextField();
pnlExpiration = new javax.swing.JPanel();
jPanel22 = new javax.swing.JPanel();
jLabel17 = new javax.swing.JLabel();
txtExpiration = new javax.swing.JTextField();
jPanel23 = new javax.swing.JPanel();
jLabel19 = new javax.swing.JLabel();
dpExpiration = new com.hccs.forms.components.ZDatePicker("MM-dd-yyyy","##-##-####",'_');
lstdirtyTasks = new com.hccs.forms.components.ListSelectorPanel();
jPanel25 = new javax.swing.JPanel();
btnCancel = new javax.swing.JButton();
btnStartEdit = new javax.swing.JButton();
pnlStatus = new javax.swing.JPanel();
lblStatus = new javax.swing.JLabel();
jPanel8 = new javax.swing.JPanel();
jToolBar2 = new javax.swing.JToolBar();
jToggleButton4 = new javax.swing.JToggleButton();
jToggleButton5 = new javax.swing.JToggleButton();
jToggleButton6 = new javax.swing.JToggleButton();
mnuBar = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
miExit = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
mnuSettings = new javax.swing.JMenu();
mnuCommands = new javax.swing.JMenuItem();
miAbout = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
pnlMain.setLayout(new java.awt.BorderLayout());
jPanel1.setLayout(new java.awt.BorderLayout());
jToolBar1.setFloatable(false);
jToolBar1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jToolBar1.setRollover(true);
toggleButtonGroup.add(btnFetchAll);
btnFetchAll.setText("Fetch All Device");
btnFetchAll.setFocusable(false);
btnFetchAll.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnFetchAll.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(btnFetchAll);
toggleButtonGroup.add(jToggleButton2);
jToggleButton2.setText("Newly Added Device");
jToggleButton2.setEnabled(false);
jToggleButton2.setFocusable(false);
jToggleButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jToggleButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(jToggleButton2);
toggleButtonGroup.add(jToggleButton3);
jToggleButton3.setText("Expiring Account");
jToggleButton3.setEnabled(false);
jToggleButton3.setFocusable(false);
jToggleButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jToggleButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(jToggleButton3);
toggleButtonGroup.add(btnDelete);
btnDelete.setText("Delete Account");
btnDelete.setFocusable(false);
btnDelete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(btnDelete);
jPanel1.add(jToolBar1, java.awt.BorderLayout.CENTER);
jSplitPane1.setLeftComponent(jPanel1);
jPanel2.setLayout(new java.awt.BorderLayout());
jsHorizontal.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
jPanel3.setLayout(new java.awt.BorderLayout());
jPanel5.setLayout(new java.awt.BorderLayout());
jLabel1.setText("Search");
jPanel5.add(jLabel1, java.awt.BorderLayout.WEST);
txtFilter.setMinimumSize(new java.awt.Dimension(160, 28));
jPanel5.add(txtFilter, java.awt.BorderLayout.CENTER);
jPanel3.add(jPanel5, java.awt.BorderLayout.NORTH);
jPanel6.setLayout(new java.awt.BorderLayout());
tblResults.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane1.setViewportView(tblResults);
jPanel6.add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel3.add(jPanel6, java.awt.BorderLayout.CENTER);
jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
lblRowCount.setText("Row Count: ");
jPanel7.add(lblRowCount);
jPanel3.add(jPanel7, java.awt.BorderLayout.SOUTH);
jsHorizontal.setLeftComponent(jPanel3);
jPanel4.setLayout(new java.awt.BorderLayout());
jPanel17.setLayout(new java.awt.BorderLayout());
jPanel19.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
jPanel19.setLayout(new java.awt.BorderLayout());
jPanel12.setLayout(new java.awt.GridBagLayout());
jLabel5.setText("HardDisk SN:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 1;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(jLabel5, gridBagConstraints);
txtHD.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 10;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 20;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(txtHD, gridBagConstraints);
jLabel6.setText("MotherBoard SN:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 11;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 1;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(jLabel6, gridBagConstraints);
txtMobo.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 11;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 20;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(txtMobo, gridBagConstraints);
jLabel7.setText("Full Name:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 1;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(jLabel7, gridBagConstraints);
txtFullName.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 20;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(txtFullName, gridBagConstraints);
jLabel8.setText("Phone Number:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 1;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(jLabel8, gridBagConstraints);
txtPhone.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 20;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(txtPhone, gridBagConstraints);
jLabel9.setText("Email Address:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 1;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(jLabel9, gridBagConstraints);
txtEmailAdd.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 20;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(txtEmailAdd, gridBagConstraints);
txtJava.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 7;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 20;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(txtJava, gridBagConstraints);
jLabel10.setText("Java Version:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 1;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(jLabel10, gridBagConstraints);
txtOS.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 20;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(txtOS, gridBagConstraints);
jLabel11.setText("Operating System:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 1;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(jLabel11, gridBagConstraints);
txtIPAdd.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 12;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 20;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(txtIPAdd, gridBagConstraints);
jLabel12.setText("Public IP:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 12;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 1;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(jLabel12, gridBagConstraints);
txtProfile.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 9;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 20;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(txtProfile, gridBagConstraints);
jLabel13.setText("Profile Name:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 9;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 1;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(jLabel13, gridBagConstraints);
txtComputer.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 20;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(txtComputer, gridBagConstraints);
jLabel14.setText("Computer Name:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipadx = 1;
gridBagConstraints.ipady = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel12.add(jLabel14, gridBagConstraints);
jPanel21.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 5, 0));
btnChecker1.setText("IP Checker 1");
btnChecker1.setEnabled(false);
btnChecker1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChecker1ActionPerformed(evt);
}
});
jPanel21.add(btnChecker1);
btnChecker2.setText("IP Checker 2");
btnChecker2.setEnabled(false);
btnChecker2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChecker2ActionPerformed(evt);
}
});
jPanel21.add(btnChecker2);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 13;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
jPanel12.add(jPanel21, gridBagConstraints);
jPanel19.add(jPanel12, java.awt.BorderLayout.NORTH);
detailsSplitPane.setLeftComponent(jPanel19);
pnlPlugins.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
pnlPlugins.setLayout(new java.awt.BorderLayout(5, 10));
jPanel18.setLayout(new java.awt.BorderLayout(5, 5));
jPanel9.setLayout(new java.awt.GridLayout(1, 0, 5, 5));
jPanel20.setLayout(new java.awt.GridLayout(0, 1));
jLabel16.setText("Active");
jPanel20.add(jLabel16);
cmbActive.setEnabled(false);
jPanel20.add(cmbActive);
jPanel9.add(jPanel20);
jPanel24.setLayout(new java.awt.GridLayout(0, 1));
jLabel18.setText("Last Seen");
jPanel24.add(jLabel18);
txtLastLogin.setEditable(false);
jPanel24.add(txtLastLogin);
jPanel9.add(jPanel24);
jPanel18.add(jPanel9, java.awt.BorderLayout.NORTH);
pnlExpiration.setLayout(new java.awt.GridLayout(1, 0, 5, 5));
jPanel22.setLayout(new java.awt.GridLayout(0, 1));
jLabel17.setText("Expiration Date");
jPanel22.add(jLabel17);
txtExpiration.setEditable(false);
jPanel22.add(txtExpiration);
pnlExpiration.add(jPanel22);
jPanel23.setLayout(new java.awt.GridLayout(0, 1));
jLabel19.setText("New Expiration Date");
jPanel23.add(jLabel19);
jPanel23.add(dpExpiration);
pnlExpiration.add(jPanel23);
jPanel18.add(pnlExpiration, java.awt.BorderLayout.CENTER);
pnlPlugins.add(jPanel18, java.awt.BorderLayout.NORTH);
pnlPlugins.add(lstdirtyTasks, java.awt.BorderLayout.CENTER);
jPanel25.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 5, 0));
btnCancel.setText("Cancel");
btnCancel.setEnabled(false);
btnCancel.setMaximumSize(new java.awt.Dimension(100, 25));
btnCancel.setMinimumSize(new java.awt.Dimension(80, 25));
btnCancel.setPreferredSize(new java.awt.Dimension(90, 25));
btnCancel.setVisible(false);
btnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
jPanel25.add(btnCancel);
btnStartEdit.setText("Start Edit");
btnStartEdit.setEnabled(false);
btnStartEdit.setMaximumSize(new java.awt.Dimension(100, 25));
btnStartEdit.setMinimumSize(new java.awt.Dimension(80, 25));
btnStartEdit.setPreferredSize(new java.awt.Dimension(90, 25));
jPanel25.add(btnStartEdit);
pnlPlugins.add(jPanel25, java.awt.BorderLayout.SOUTH);
detailsSplitPane.setRightComponent(pnlPlugins);
jPanel17.add(detailsSplitPane, java.awt.BorderLayout.CENTER);
jPanel4.add(jPanel17, java.awt.BorderLayout.CENTER);
jsHorizontal.setRightComponent(jPanel4);
jPanel2.add(jsHorizontal, java.awt.BorderLayout.CENTER);
jSplitPane1.setRightComponent(jPanel2);
pnlMain.add(jSplitPane1, java.awt.BorderLayout.CENTER);
getContentPane().add(pnlMain, java.awt.BorderLayout.CENTER);
pnlStatus.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
lblStatus.setText("...");
pnlStatus.add(lblStatus);
getContentPane().add(pnlStatus, java.awt.BorderLayout.SOUTH);
jPanel8.setLayout(new java.awt.BorderLayout());
jToolBar2.setRollover(true);
jToggleButton4.setText("Fetch All");
jToggleButton4.setFocusable(false);
jToggleButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jToggleButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(jToggleButton4);
jToggleButton5.setText("Deny");
jToggleButton5.setFocusable(false);
jToggleButton5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jToggleButton5.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(jToggleButton5);
jToggleButton6.setText("Delete");
jToggleButton6.setFocusable(false);
jToggleButton6.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jToggleButton6.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(jToggleButton6);
jPanel8.add(jToolBar2, java.awt.BorderLayout.CENTER);
getContentPane().add(jPanel8, java.awt.BorderLayout.NORTH);
jMenu1.setText("File");
miExit.setText("Exit");
jMenu1.add(miExit);
mnuBar.add(jMenu1);
jMenu2.setText("Edit");
mnuBar.add(jMenu2);
mnuSettings.setText("Settings");
mnuCommands.setText("Commands");
mnuSettings.add(mnuCommands);
mnuBar.add(mnuSettings);
miAbout.setText("Help");
jMenuItem1.setText("About");
miAbout.add(jMenuItem1);
mnuBar.add(miAbout);
setJMenuBar(mnuBar);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnChecker1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChecker1ActionPerformed
ActivatorUtility.openLink("http://geoiplookup.net/ip/" + txtIPAdd.getText());
}//GEN-LAST:event_btnChecker1ActionPerformed
private void btnChecker2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChecker2ActionPerformed
ActivatorUtility.openLink("http://www.ip-tracker.org/locator/ip-lookup.php?ip=" + txtIPAdd.getText());
}//GEN-LAST:event_btnChecker2ActionPerformed
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
toggleComponents(false);
}//GEN-LAST:event_btnCancelActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnChecker1;
private javax.swing.JButton btnChecker2;
private javax.swing.JToggleButton btnDelete;
private javax.swing.JToggleButton btnFetchAll;
private javax.swing.JButton btnStartEdit;
private javax.swing.JComboBox cmbActive;
private javax.swing.JSplitPane detailsSplitPane;
private com.hccs.forms.components.ZDatePicker dpExpiration;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel19;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel20;
private javax.swing.JPanel jPanel21;
private javax.swing.JPanel jPanel22;
private javax.swing.JPanel jPanel23;
private javax.swing.JPanel jPanel24;
private javax.swing.JPanel jPanel25;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JToggleButton jToggleButton2;
private javax.swing.JToggleButton jToggleButton3;
private javax.swing.JToggleButton jToggleButton4;
private javax.swing.JToggleButton jToggleButton5;
private javax.swing.JToggleButton jToggleButton6;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JToolBar jToolBar2;
private javax.swing.JSplitPane jsHorizontal;
private javax.swing.JLabel lblRowCount;
private javax.swing.JLabel lblStatus;
private com.hccs.forms.components.ListSelectorPanel lstdirtyTasks;
private javax.swing.JMenu miAbout;
private javax.swing.JMenuItem miExit;
private javax.swing.JMenuBar mnuBar;
private javax.swing.JMenuItem mnuCommands;
private javax.swing.JMenu mnuSettings;
private javax.swing.JPanel pnlExpiration;
private javax.swing.JPanel pnlMain;
private javax.swing.JPanel pnlPlugins;
private javax.swing.JPanel pnlStatus;
private org.jdesktop.swingx.JXTable tblResults;
private javax.swing.ButtonGroup toggleButtonGroup;
private javax.swing.JTextField txtComputer;
private javax.swing.JTextField txtEmailAdd;
private javax.swing.JTextField txtExpiration;
private javax.swing.JTextField txtFilter;
private javax.swing.JTextField txtFullName;
private javax.swing.JTextField txtHD;
private javax.swing.JTextField txtIPAdd;
private javax.swing.JTextField txtJava;
private javax.swing.JTextField txtLastLogin;
private javax.swing.JTextField txtMobo;
private javax.swing.JTextField txtOS;
private javax.swing.JTextField txtPhone;
private javax.swing.JTextField txtProfile;
// End of variables declaration//GEN-END:variables
public void setRowCountLabel() {
lblRowCount.setText("Row Count: " + sorter.getViewRowCount());
lblStatus.setText("");
}
public void toggleForm(boolean b) {
}
public void setlabelStatus(String status) {
lblStatus.setText(status);
}
public String getSearchString() {
return txtFilter.getText().trim();
}
public void clearSearchBox() {
txtFilter.setText("");
}
public void setSearchPanelFocus() {
txtFilter.requestFocus();
}
public void showConnectionError() {
JOptionPane.showMessageDialog(
this, "Connection Error Occured", "Error",
JOptionPane.ERROR_MESSAGE);
}
public void initActivatorTable(RegistrationTableModel model, TableRowSorter tblSorter) {
tblResults.setModel(model);
tblResults.setRowSorter(sorter = tblSorter);
}
public void toggleComponents(boolean b) {
lstdirtyTasks.toggleForm(b);
btnStartEdit.setText(b ? "Save" : "Start Edit");
txtFullName.setEditable(b);
txtPhone.setEditable(b);
txtEmailAdd.setEditable(b);
btnCancel.setVisible(b);
btnCancel.setEnabled(b);
cmbActive.setEnabled(b);
}
public List<Integer> getSelectedRowsModel() {
List<Integer> rows = new ArrayList<>();
int[] xy = tblResults.getSelectedRows();
if (xy.length > 0) {
for (int i = 0; i < xy.length; i++) {
rows.add(tblResults.convertRowIndexToModel(xy[i]));
}
}
return rows;
}
public void setSaveButtonEnable(boolean b) {
btnStartEdit.setEnabled(b);
}
public String getSaveButtonText() {
return btnStartEdit.getText();
}
}
<file_sep>/SkunkWorks-Task/src/com/hccs/skunkworks/task/TaskController.java
package com.hccs.skunkworks.task;
import com.hccs.skunkworks.model.TaskBean;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author DCSalenga
*/
public enum TaskController {
INSTANCE;
private final List<TaskBean> works = new ArrayList<>();
public List<TaskBean> getAllDirtyTasks() {
if (!works.isEmpty()) {
return works;
}
TaskBean dw = new TaskBean();
dw.setTaskName("Sample A");
dw.setTaskValue(1);
dw.setActive(true);
works.add(dw);
dw = new TaskBean();
dw.setTaskName("Sample B");
dw.setTaskValue(2);
dw.setActive(true);
works.add(dw);
dw = new TaskBean();
dw.setTaskName("Sample C");
dw.setTaskValue(4);
dw.setActive(true);
works.add(dw);
dw = new TaskBean();
dw.setTaskName("Sample D");
dw.setTaskValue(8);
dw.setActive(true);
works.add(dw);
dw = new TaskBean();
dw.setTaskName("Sample E");
dw.setTaskValue(0x10);
dw.setActive(true);
works.add(dw);
dw = new TaskBean();
dw.setTaskName("Sample F");
dw.setTaskValue(0x20);
dw.setActive(true);
works.add(dw);
return works;
}
}
<file_sep>/SkunkWorks-Core/src/com/hccs/skunkworks/jpa/models/PersonBean.java
package com.hccs.skunkworks.jpa.models;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author DCSalenga
*/
@Entity
@Table(name = "persons")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "PersonBean.findAll", query = "SELECT p FROM PersonBean p")
, @NamedQuery(name = "PersonBean.findByPersonid", query = "SELECT p FROM PersonBean p WHERE p.personid = :personid")
, @NamedQuery(name = "PersonBean.findByName", query = "SELECT p FROM PersonBean p WHERE p.name = :name")
, @NamedQuery(name = "PersonBean.findByPhonenumber", query = "SELECT p FROM PersonBean p WHERE p.phonenumber = :phonenumber")
, @NamedQuery(name = "PersonBean.findByEmail", query = "SELECT p FROM PersonBean p WHERE p.email = :email")
, @NamedQuery(name = "PersonBean.findByLocation", query = "SELECT p FROM PersonBean p WHERE p.location = :location")})
public class PersonBean implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "person_sequence", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "person_sequence", sequenceName = "person_sequence", allocationSize = 1)
@Basic(optional = false)
@Column(name = "personid")
private Integer personid;
@Column(name = "name")
private String name;
@Column(name = "phonenumber")
private String phonenumber;
@Column(name = "email")
private String email;
@Column(name = "location")
private String location;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "personid")
private List<RegistrationBean> registrationBeanList;
public PersonBean() {
}
public PersonBean(Integer personid) {
this.personid = personid;
}
public Integer getPersonid() {
return personid;
}
public void setPersonid(Integer personid) {
this.personid = personid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
@XmlTransient
public List<RegistrationBean> getRegistrationBeanList() {
return registrationBeanList;
}
public void setRegistrationBeanList(List<RegistrationBean> registrationBeanList) {
this.registrationBeanList = registrationBeanList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (personid != null ? personid.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PersonBean)) {
return false;
}
PersonBean other = (PersonBean) object;
if ((this.personid == null && other.personid != null) || (this.personid != null && !this.personid.equals(other.personid))) {
return false;
}
return true;
}
@Override
public String toString() {
return name;
}
}
<file_sep>/SQL/sql_2.sql
ALTER TABLE registrations ADD taskvalue integer;<file_sep>/SQL/sql_4.sql
CREATE SEQUENCE command_sequence INCREMENT 1 CYCLE;
CREATE TABLE commands
(
commandid integer NOT NULL,
name character varying(100),
extension character varying(10),
command character varying(250),
description character varying(250),
active Boolean DEFAULT NULL,
CONSTRAINT command_pkey PRIMARY KEY (commandid)
);
|
2a7bab03c0b5336fabac4585841ee461d1cdf3bd
|
[
"Markdown",
"Java",
"SQL",
"INI"
] | 16 |
Java
|
SCCS-PH/Skunkworks
|
c8e9134b7206f239d6b9c8465b5aa4ab3e5a6d79
|
5f3504b565eb245d85e81dfcdfbbb36e18fead38
|
refs/heads/master
|
<file_sep>var app_history = [];
function gotoLink(view) {
app_history.push(view);
$('.container').html($(view).children());
// $(view).show();
}
function goBack() {
}
w3IncludeHTML();
gotoLink('#home');
// goto register page
$('#imageBtn').click(function(event) {
gotoLink('#image');
});
$('#videoBtn').click(function(event) {
gotoLink('#video');
});
$('#audioBtn').click(function(event) {
gotoLink('#audio');
});
|
6fbafe39a23f90032151c551693e0341c29bcf07
|
[
"JavaScript"
] | 1 |
JavaScript
|
dawoodahmed/nasain
|
08d31a11c3a06db4a96712f6fc9cec820131ea04
|
f9cb4381465635d31111c04d26035d51db8b7106
|
refs/heads/main
|
<file_sep><section>
<div class="container">
<div class="sistema_titulo text-center">
<h1 class="">Consulta De Lista Estudantil Camaçari Card</h1>
</div> <br/>
<div class="sistema_formulario_busca p-5">
<h3 class="text-center">Cadastre Seu E-mail Para Ser Notificado</h3><br/>
<form method="POST">
<?php if (isset($email['success']) && !empty($email['success'])): ?>
<div class="alert alert-success"><?php echo $email['success']; ?></div>
<?php endif ?>
<?php if (isset($email['error']) && !empty($email['error'])): ?>
<div class="alert alert-danger"><?php echo $email['error']; ?></div>
<?php endif ?>
<div class="form-row">
<div class="form-group col-md-8">
<label for="inputEmail4">Instituição de Ensino</label>
<input type="text" class="form-control" id="instituicao" name="instituicao" placeholder="Informe sua Instituição" required>
</div>
<div class="form-group col-md-3">
<label for="inputPassword4">Última Atualização</label>
<input type="text" id="atualizacao" disabled class="form-control" id="inputPassword4" placeholder="" readonly="true">
</div>
<div class="form-group col-md-2">
<label for="inputAddress">Nome:</label>
<input type="text" class="form-control" placeholder="Informe seu nome" name="nome" required>
</div>
<div class="form-group col-md-4">
<label for="inputAddress">E-mail:</label>
<input type="email" class="form-control" placeholder="Informe seu email" name="email" required>
</div>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck1" required>
<label class="form-check-label" for="gridCheck1"><p class="text-primary">
Desejo Receber Notificações Sobre Listas Atualizadas</p></label>
</div><br/>
<div class="form-row">
<button type="submit" class="form_botao btn btn-outline-warning">Cadastre-se</button>
</div>
</form>
</div>
</div>
</section>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('email');
$this->load->library('pdf');
}
public function index() {
$data = array();
$instituicoes = $this->Alunos->getInstituicoes();
foreach ($instituicoes as $instituicao) {
$data['instituicoes'][] = $instituicao['nome'];
}
if (!empty($_POST['instituicao'])) {
$dados = array(
'instituicao' => (!empty($_POST['instituicao'])
?addslashes($_POST['instituicao']):NULL),
'nome' => (!empty($_POST['nome'])?addslashes($_POST['nome']):NULL),
'documento' => (!empty($_POST['info'])?addslashes($_POST['info']):NULL),
'atendimento' => (!empty($_POST['atendimento'])?addslashes($_POST['atendimento']):NULL),
'autenticidade' => md5(time().rand(0,999))
);
$auth = $this->Alunos->autenticar($dados);
if($auth !== false) {
$dados['matricula'] = $auth['matricula'];
$dados['curso'] = $auth['curso'];
$_SESSION['data'] = $dados;
$_SESSION['success'] = "Re3atório gerado com sucesso!
";
redirect('home/gerarRelatorio');
} else {
$data['erro'] = "Documento Inválido!";
}
}
if ((isset($_POST['especifica_cpf']) && !empty($_POST['especifica_cpf'])) || (isset($_POST['especifica_matricula']) && !empty($_POST['especifica_matricula']))) {
$data = array();
$cpf = null;
$matricula = null;
if (isset($_POST['especifica_cpf']) && !empty($_POST['especifica_cpf'])) {
$cpf = addslashes($_POST['especifica_cpf']);
} else {
$matricula = addslashes($_POST['especifica_matricula']);
}
$retorno = $this->Alunos->consultaEspecifica($cpf,$matricula);
if (is_array($retorno)) {
$retorno['autenticidade'] = md5(time().rand(0,999));
$retorno['especifica'] = true;
$_SESSION['data'] = $retorno;
redirect(base_url('gerarrelatorio'));
} elseif ($retorno == 'duplicado') {
$data['erro'] = "Matricula duplicada, favor entrar em contato no e-mail: <EMAIL>";
unset($_SESSION['success']);
}
elseif($retorno == false) {
$data['erro'] = "CPF invalido ou Matricula inexistente!";
unset($_SESSION['success']);
}
}
$this->load->view('header', $data);
$this->load->view('home', $data);
$this->load->view('footer', $data);
}
public function gerarRelatorio() {
if(isset($_SESSION['data']) &&!empty($_SESSION['data'])) {
$data = $_SESSION['data'];
$this->dompdf->output(['isRemoteEnabled' => true]);
$this->load->view('relatorio',$data);
// Get output html
$html = $this->output->get_output();
// Load HTML content
$this->dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation
$this->dompdf->setPaper('A4', 'portrait');
// Render the HTML as PDF
$this->dompdf->render();
// Output the generated PDF (1 = download and 0 = preview)
$this->dompdf->stream(md5(time().rand(0,9999)).".pdf");
}
}
/* FUNÇÃO DE NOTIFICÃO VIA EMAIL */
public function notificacao(){
$data = array();
$instituicoes = $this->Alunos->getInstituicoes();
foreach ($instituicoes as $instituicao) {
$data['instituicoes'][] = $instituicao['nome'];
}
if(isset($_POST['email']) && !empty($_POST['email'])) {
$email = addslashes($_POST['email']);
$nome = addslashes($_POST['nome']);
$instituicao = addslashes($_POST['instituicao']);
if (!$this->Alunos->verificarEmail($email,$instituicao)) {
/*
$this->email->from('<EMAIL>', 'Name');
$this->email->to('<EMAIL>');
$this->email->subject('subject');
$this->email->message('message');
$this->email->send();
*/
$this->Alunos->cadastrarEmail($nome,$email,$instituicao);
$data['email']['success'] = "Email cadastrado com sucesso! Você será notificado.";
} else {
//$this->Alunos->atualizarEmail($nome,$email,$instituicao);
$data['email']['error'] = "Email já cadastrado!";
}
}
$this->load->view('header', $data);
$this->load->view('notificacao', $data);
$this->load->view('footer', $data);
}
// FUNÇÃO PRA BUSCAR ATUALIZAÇÃO DA INSTITUICAO
public function buscarAtualizacao(){
if (isset($_POST['instituicao']) && !empty($_POST['instituicao'])) {
$instituicao = addslashes($_POST['instituicao']);
$data = $this->Alunos->buscarAtualizacao($instituicao);
if ($data) {
echo date("d/m/Y H:i:s", strtotime($data));
}
}
}
// FUNÇÃO QUE BUSCA OS ALUNOS PELA INSTITUIÇÃO
public function buscarAlunos(){
if (isset($_POST['inst']) && !empty($_POST['inst'])) {
$instituicao = addslashes($_POST['inst']);
$data = $this->Alunos->buscarAlunos($instituicao);
if ($data) {
foreach ($data as $a) {
$alunos[] = array($a['nome']);
}
echo json_encode($alunos);
}
}
}
// FUNÇÃO PRA PEGAR OS DADOS PESSOAIS DISPONÍVEIS PRA CARREGÁ-LOS NOS CAMPOS
public function carregarDados(){
if(isset($_POST['aluno']) && !empty($_POST['aluno']) && isset($_POST['inst']) && !empty($_POST['inst'])) {
$aluno = addslashes($_POST['aluno']);
$inst = addslashes($_POST['inst']);
$dados = $this->Alunos->carregarDados($aluno,$inst);
$dados = array(
'cpf' => (isset($dados['cpf']) && !empty($dados['cpf']))?true:false,
'rg' => (isset($dados['rg']) && !empty($dados['rg']))?true:false,
'dn' => (isset($dados['data_nascimento']) && !empty($dados['data_nascimento']))?true:false
);
echo json_encode($dados);
$dados = array('cpf' => (isset($dados['cpf']) && !empty($dados['cpf'])));
}
}
}
<file_sep>
<footer class="row">
<div class="container">
<hr>
<a href="javascript:alert('Contato: <EMAIL>')" class="mjd" >DESENVOLVIDO PELA MJD DESENVOLVIMENTO</a>
<div class="mjd">MJD © 2019</div>
</div>
</footer>
<!-- JQUERY 3.3.1 // POPPER // BOOTSTRAP JS -->
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery-3.3.1.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/popper.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/bootstrap.min.js"></script>
<!-- AUTO COMPLETE -->
<script src="<?php echo base_url();?>assets/js/jquery.autocomplete.js"></script>
<!-- JQUERY MASK PLUGIN -->
<script type="text/javascript" src="<?php echo base_url('assets/js/jquery.mask.js');?>"></script>
<!-- SCRIPT AUTO COMPLETE -->
<script>
var url = $('body').attr('data-url');
var states = <?php echo json_encode($instituicoes); ?>
$(function(){
var url = $('body').attr('data-url');
$(function(){
$("#instituicao").autocomplete({
source:[states]
});
});
});
$('#instituicao').change(function(){
var inst = $('#instituicao').val();
$.ajax({
method:'POST',
url:url+'buscaralunos',
dataType:'JSON',
data: {inst:inst},
beforeSend: function(){
$('#inputNome').val('');
},
success: function(json){
var alunos = json;
$('#inputNome').remove();
// insere ele depois do label que está antes do nome só isso // ta tranquilo mano, o brother ja entendeu , ficou filé !
$('label[for="inputNome"]').after('<input id="inputNome" type="text" onchange="definirDados(this);" class="form-control" name="nome" placeholder="Informe seu nome" required>');
$('#inputNome').autocomplete({
source:alunos
})
}
});
});
</script>
<!-- SCRIPT DO SISTEMA -->
<script src="<?php echo base_url();?>assets/js/script.js"></script>
<script>
$(function(){
if (location.protocol != 'https:')
{
location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}
});
</script>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Alunos extends CI_Model {
// FUNÇÃO CADASTRO DE EMAIL PARA NOTIFICAÇÕES
public function cadastrarEmail($nome,$email,$instituicao){
$id = $this->buscarId($instituicao);
$sql = "INSERT INTO email SET nome = '$nome', email = '$email', id_instituicao = '$id'";
$this->db->query($sql);
}
/*public function atualizarEmail($nome,$email,$instituicao){
$id = $this->buscarId($instituicao);
$sql = "UPDATE email SET nome = '$nome', email = '$email', id_instituicao = '$id' WHERE email = '$email'";
$this->db->query($sql);
}
*/
/* FIM DOS EMAILS */
public function verificarEmail($email,$instituicao) {
$id = $this->buscarId($instituicao);
$sql = "SELECT * from email WHERE email = '$email' AND id_instituicao = '$id'";
$sql = $this->db->query($sql);
if($sql->num_rows() > 0) {
return $sql->result_array();
} else {
return false;
}
}
public function getInstituicoes() {
$array = array();
$sql = "SELECT * FROM instituicao";
$sql = $this->db->query($sql);
if($sql->num_rows() > 0) {
$array = $sql->result_array();
}
return $array;
}
public function buscarAtualizacao($instituicao){
$sql = "SELECT uptime FROM instituicao WHERE nome = '$instituicao'";
$sql = $this->db->query($sql);
$sql = $sql->row_array();
return $sql['uptime'];
}
public function buscarAlunos($instituicao){
$sql = "SELECT id FROM instituicao WHERE nome = '$instituicao' ";
$sql = $this->db->query($sql);
if ($sql->num_rows()>0) {
$sql = $sql->row_array();
$id = $sql['id'];
$sql = "SELECT * FROM lista WHERE id_instituicao = '$id' AND status = '1'";
$sql = $this->db->query($sql);
return $sql->result_array();
}
}
// BUSCAR O ID DA INSTITUICAO PELO NOME
public function buscarId($inst){
$sql = "SELECT id FROM instituicao WHERE nome = '$inst'";
$sql = $this->db->query($sql);
$sql = $sql->row_array();
return $sql['id'];
$id_inst = $this->buscarId($inst);
}
public function carregarDados($alunos,$inst){
$id_inst = $this->buscarId($inst);
$sql = "SELECT cpf,rg,data_nascimento FROM lista WHERE nome = '$alunos' AND id_instituicao = '$id_inst'";
$sql = $this->db->query($sql);
if ($sql->num_rows()>0) {
return $sql->row_array();
}
}
// CONSULTA ESPECÍFICA
public function consultaEspecifica($cpf,$matricula){
$sql = "SELECT *,(select instituicao.nome from instituicao where lista.id_instituicao = instituicao.id) as instituicao FROM lista ";
if ($cpf !== NULL) {
$sql.= " WHERE cpf = '$cpf' ";
} else {
$sql.= " WHERE matricula = '$matricula' ";
}
$sql.= " AND status = '1' ";
$sql = $this->db->query($sql);
if ($sql->num_rows() == 1) {
return $sql->row_array();
} elseif($sql->num_rows() > 1){
return 'duplicado';
} elseif($sql->num_rows() == 0){
return false;
}
}
/* ================================================ AUTENTICANDO O ALUNO ==========================================================*/
public function autenticar($dados) {
if(strpos($dados['documento'],'/') !=0){
$data = implode("-",array_reverse(explode("/",$dados['documento'])));
}
$sql = "SELECT curso, matricula FROM lista WHERE (nome = '".$dados["nome"]."') AND (cpf = '".$dados['documento']."' OR rg = '".$dados['documento']."'
";
if (isset($data) && !empty($data)) {
$sql.= " OR data_nascimento = '".$data."'";
}
$sql.= ")";
$sql = $this->db->query($sql);
if ($sql->num_rows() > 0) {
return $sql->row_array();
}
return false;
}
}
/* End of file Alunos.php */
/* Location: ./application/models/Alunos.php */<file_sep><h1 align="center">:books: CLESCC :books:</h1>
<p align="center">O Sistema CLESCC é um sistema para consulta de lista estudantil na cidade de Camaçari-BA desenvolvido com o intuito de solucionar a demanda de digitalização na renovação do passe estudantil naquela localidade, sendo minha primeira pratica profissional.</p>
## :camera: Demonstração
<div align="center" >
<img src="./git_img/img1.png"><br/><br/>
<img src="./git_img/img2.png"><br/><br/>
</div><br/>
## :tv: Video Demonstrativo
<a href="https://youtu.be/uYLZqfUKoNg">
<img src="https://img.shields.io/badge/Assista_o_video_demonstrativo_do_sistema-FF0000?style=for-the-badge&logo=youtube&logoColor=white"/>
</a>
# Site
### - [CLESCC](https://clescc.com.br/)
---
## 🚀 Tecnologias
Este projeto foi desenvolvido com as seguintes tecnologias:
- ✔️ CodeIgniter
- ✔️ Bootstrap
- ✔️ Jquery
- ✔️ Html
- ✔️ Css
- ✔️ DomPdf
Feito com 💜 por <NAME> 👋 [Veja meu Linkedin](https://www.linkedin.com/in/joao-php/)
<br>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>::CLESCC::</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- BOOTSTRAP 4 -->
<link rel="stylesheet" type="text/css" href="https://clescc.com.br/assets/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://clescc.com.br/assets/css/style.css">
<link rel="icon" href="assets/images/miniatura.png" type="image/x-icon"/>
<link rel="shortcut icon" href="https://clescc.com.br/assets/images/miniatura.png" type="image/x-icon" />
</head>
<body>
<section class="section_relatorio" >
<img src="https://clescc.com.br/assets/images/timbrado1.jpg" class="img_header">
<!-- HTML QUE FICA COM AS INFORMAÇÕES DOS ALUNOS -->
<div class="titulo_relatorio">
<h4>RELATÓRIO CLESCC</h4>
</div><br/><br/>
<div class="row">
<div class="text_relatorio ">
<h6 ><strong>Instituição:</strong> <?php echo $instituicao; ?></h6>
</div>
</div><br/>
<div class="row">
<div class="text_relatorio ">
<h6 ><strong>Nome: </strong> <?php echo $nome; ?> </h6>
</div>
</div><br/>
<div class="row">
<div class="text_relatorio ">
<h6 ><strong>Matricula:</strong> <?php echo $matricula ?></h6>
</div>
</div><br/>
<div class="row">
<div class="text_relatorio ">
<h6 ><strong>Curso/Série:</strong> <?php echo $curso; ?></h6>
</div>
</div><br/>
<?php if (!isset($especifica) && empty($especifica)):?>
<div class="row">
<div class="text_relatorio ">
<h6 ><strong>Tipo de atendimento:</strong> <?php echo strtoupper($atendimento);?></h6>
</div>
</div><br/><br/>
<?php endif; ?>
<!-- LOGO DA MJD E CODIGO DE AUTENTICIDADE -->
<div class="logo_mjd">
<img src="https://clescc.com.br/assets/images/logo-2.png" class="">
</div><br/>
<div class="autenticidade_relatorio">
<h5>CODIGO DE AUTENTICIDADE</h5>
<div class="codigo_autenticador">
<?php echo $autenticidade; ?>
</div>
</div>
<div class="linha_autenticidade">
<hr>
</div>
<div class="row ">
<div class="titulo_cadastro">
<h5>O QUE FAZER AGORA ?</h5>
</div>
<div class="emoticon_cadastro">
<img src="https://clescc.com.br/assets/images/emoticon.png" class="">
</div>
</div><br/><br>
<div class="img_fazer">
<img src="https://clescc.com.br/assets/images/recad.png" >
</div>
<div class="observacao_relatorio">
<strong>*EM CASO DE CADASTRO TODOS OS DOCUMENTOS SUPRACITADOS DEVEM SER ORIGINAIS E XEROX, NO CASO DE RECADASTRAMENTO DEVE SER SOMENTE DOCUMENTOS ORIGINAIS.</strong>
</div>
<img src="https://clescc.com.br/assets/images/timbrado2.jpg" class="img_footer">
</section>
</body>
</html>
<script>
$(function(){
location.reload();
});
</script>
<file_sep><section id="sistema">
<div class="container ">
<div class="sistema_titulo text-center">
<h1 class="">Consulta De Lista Estudantil Camaçari Card</h1>
</div><br/>
<div class="sistema_formulario_busca p-5">
<form method="POST">
<h3 class="text-center">Consulta Por Instituição</h3><br/>
<?php if (isset($erro) && !empty($erro)): ?>
<div class="alert alert-danger"><?php echo $erro; ?></div>
<?php endif; ?>
<!--
<?php if (isset($_SESSION['success']) && !empty($_SESSION['success'])): ?>
<div class="alert alert-success"><?php echo$_SESSION['success']; ?></div>
<?php unset($_SESSION['success']); ?>
<?php endif; ?> -->
<div class="form-row">
<div class="form-group col-md-8">
<label for="instituicao">Instituição de Ensino</label>
<input type="text" class="form-control" id="instituicao" name="instituicao" placeholder="Informe sua Instituição" required>
</div>
<div class="form-group col-md-3">
<label for="inputPassword4">Última Atualização</label>
<input type="text" class="form-control" disabled id="atualizacao" placeholder="">
</div>
<div class="form-group col-md-8">
<label for="inputNome">Nome</label>
<input id="inputNome" type="text" class="form-control" name="nome" placeholder="Informe seu nome" required>
</div>
<div class="nome_naoconsta align-self-center mt-lg-3 mt-md-3 ml-2 mb-2">
<!--<a class="text-warning" href="<?php echo base_url('notificacao');?>"> Seu nome não consta? Clique aqui.</a> -->
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="inputCity">Selecione</label>
<select id="selectDocumentos" name="documento" class="form-control" required>
<option value="">Escolha uma Opção:</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputAddress">Informação Pessoal </label>
<input type="text" class="form-control" id="documento" name="info" placeholder="Informe seus dados.." required>
</div>
<div class="form-group col-md-3">
<label for="inputCity">Tipo de Atendimento</label>
<select id="inputEstado" name="atendimento" class="form-control" required>
<option value="">Escolha uma Opção: </option>
<option value="cadastro">CADASTRO</option>
<option value="recadastramento">RECADASTRAMENTO</option>
</select>
</div>
</div><br/>
<div class="form-row">
<button type="submit" class="form_botao btn btn-outline-warning">Buscar</button>
</div><br/>
</form>
<h3 class="text-center ">Consulta Específica</h3><br/>
<div class="form-row">
<form method="POST" class="form-row col-md-5">
<div class="mr-3">
<label for="inputAddress">CPF</label>
<input type="text" class="form-control" name="especifica_cpf" id="consulta_cpf" placeholder="Informe seu CPF" required>
</div>
<div class="mt-2">
<label for="inputAddress"></label><br/>
<button type="submit" class="form_botao btn btn-outline-warning mr-5">Buscar</button>
</div>
</form>
<form method="POST" class="form-row col-md-5">
<div class="mr-3">
<label for="inputAddress">Matricula</label>
<input type="text" class="form-control" name="especifica_matricula" placeholder="Informe sua Matricula" required>
</div>
<div class="mt-2 ">
<label for="inputAddress"></label><br/>
<button type="submit" class="form_botao btn btn-outline-warning">Buscar</button>
</div>
</form>
</div>
</section>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>::CLESCC::</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script>
$(function(){
if (location.protocol != 'https:')
{
location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}
});
</script>
<!-- BOOTSTRAP 4 -->
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/css/bootstrap.min.css">
<!-- CSS DO SITE -->
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/css/style.css">
<!-- AUTO COMPLETE CSS -->
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/jquery.autocomplete.css">
<!-- AUTO COMPLETE JS -->
<link rel="stylesheet" href="<?php echo base_url();?>assets/js/jquery.autocomplete.js">
<link rel="icon" href="assets/images/miniatura.png" type="image/x-icon"/>
<link rel="shortcut icon" href="<?php echo base_url();?>assets/images/miniatura.png" type="image/x-icon" />
</head>
<body data-url="<?php echo base_url();?>">
<header class="header container-fluid row justify-content-center align-self-center">
<div class="header_corpo container">
<div class="col header_logo text-center ">
<img class="img-fluid" src="<?php echo base_url();?>assets/images/certa.png" alt="">
</div>
</div>
</header>
|
66ab2f6f4e33aaa00fad05f77ecb290247f7f670
|
[
"Markdown",
"PHP"
] | 8 |
PHP
|
joao-oliveira-dev-php/clescc
|
40a74790741e97c6f66c759babf4d155cdbc3440
|
077b63dd6e7d11f5f46380090824461b8d47e4bd
|
refs/heads/master
|
<repo_name>gsgill112/SbSr_E14<file_sep>/SbSr_V1/main.cpp
/*
******************************************************************************
* @file main.cpp
* @author <NAME>
* @version V1.0.0
* @date 14-SEP-2017
* @brief Smart Bike Smart Rider Source for NUCLEO-L476RG using
* MEMS Inertial & Environmental Sensor Nucleo expansion board and
* BLE Expantion Board.
******************************************************************************
*
* Smart Bike Smart Rider Source for NUCLEO-L476RG
* Please refer <> for further information and build instructions.
*
* Requires [SHIELD]
* +-- Nucleo IDB0XA1 BLE Shield
* +-- Nucleo IKS01A2 Motion Sensing Shield
*
* Requires [External]
* +-- Nextion 3.2" Enhanced Diaplsy
* +-- Hall Effect Sensors
* +-- Battery Module with Solar Charging
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbed.h"
#include "ble/BLE.h"
#include "LEDService.h"
#include "BatteryService.h"
#include "DeviceInformationService.h"
#include "XNucleoIKS01A2.h"
#define M_PI 3.14
#define cycleTyreRadius 0.2
//#define oneRevolutionDist 2*M_PI*cycleTyreRadius
//#define DEBUG 1 //Enable Debug Statements
// PIN Maps
DigitalOut actuatedLED(LED1, 0);
DigitalOut errorLed(LED1, 0); // error indicator
InterruptIn mybutton(USER_BUTTON); // TESTING STATEMENT test
InterruptIn hallSensor(PA_12); // Using st Morpho Connectors as all arduino pins are used by shields.
DigitalIn dispBoot(PC_4); // Connected to D4 :: Display Boot Sucessful
DigitalIn mPnP(PB_1); // Connected to D10 :: Music PLay n Pause
DigitalIn mRt(PB_2); // Connected to D11 :: Music Rt
DigitalIn rideS(PB_11); // Connected to D5 :: Ride Screen
DigitalIn bumpP(PB_12); // Connected to D6 :: Bump Pressed
DigitalIn scS(PB_13); // Connected to D7 :: Self Check Screen
DigitalIn musicS(PB_14); // Connected to D8 :: Music Screen
DigitalIn mLt(PB_15); // Connected to D9 :: Music Left
// Objects
//Serial nextion(PC_4, PC_5); // Sending Data to Nextion Display
Serial nextion(SERIAL_TX, SERIAL_RX);
Timer tick;
//Static Variables
static const char* ver="SbSr_V00";
static const char terminator = 0xFF; // Nextion termination sequence
char* dispSpeed = "n0.val="; // Nextion RIDE screen commands
char* dispAvg = "n2.val=";
char* dispDist = "n1.val=";
char* accl_check = "t1.txt=\"Acc "; // Nextion Self Check screen
char* hx_check = "t2.txt=\"Hx ";
char* temp_check = "t3.txt=\"Temp ";
char* gyro_check = "t4.txt=\"Gyro ";
char* bx_check = "t5.txt=\"Bk ";
char* ble_check = "t6.txt=\"BLE ";
char* wifi_check = "t7.txt=\"WiFi ";
char* pass = "<PASSWORD>\"";
char* fail = "FAIL\"";
const static float seaLevelPressure = 1013.25;
const static float declinationAngle = 0.003839724;
float alt, LPS22HB_p, LPS22HB_p_previous, LPS22HB_t, HTS221_h, HTS221_t;
float angle;
int32_t LSM303AGR_a[3],LSM303AGR_m[3];
int32_t LSM6DSL_a[3],LSM6DSL_g[3];
// for Debug of sensors
uint8_t id;
float value1, value2;
char buffer1[32], buffer2[32];
int32_t axes[3];
// Message Bank
// To
/* Var Bank Msg
* greatingMessages 1 0-2
* pressureMessages 2 0-1
* ridingMessages 3 0-2
* weatherMessages 4 0-5
*/
const char* greatingMessages[3] = {
"Good Morning",
"Good Evening",
"Good Day"
};
const char* pressureMessages[2] = {
"Up Up Up the hill we go",
"Down we goooooo.... Yeeaahhh....."
};
const char* ridingMessages[3] = {
"Com'on its a Pleasent Fine AWESOME day :)",
"Hey Its a Holiday ! I will pickup dirt :(",
"I know you are sleeping :| "
};
const char* weatherMessages[6] = {
"Its pleasent to ride bike :)",
"Its not to bad :) a bit Humid :)",
"Its HUMID !! :|",
"Not Today, Its very Humid :\\",
"Its Chilling :O",
"Its Hot :<"
};
/* Instantiate the expansion board */
static XNucleoIKS01A2 *mems_expansion_board = XNucleoIKS01A2::instance(D14, D15, D4, D5);
/* Retrieve the composing elements of the expansion board */
static LSM303AGRMagSensor *magnetometer = mems_expansion_board->magnetometer;
static HTS221Sensor *hum_temp = mems_expansion_board->ht_sensor;
static LPS22HBSensor *press_temp = mems_expansion_board->pt_sensor;
static LSM6DSLSensor *acc_gyro = mems_expansion_board->acc_gyro;
static LSM303AGRAccSensor *accelerometer = mems_expansion_board->accelerometer;
//Variables
static volatile bool triggerSensorPolling = false; // one sec delay for BL sensor Data
char nextionScreen = '0'; // Nextion Screen indicator
char nextionMusic = '0'; // Nextion Music controls indicator
bool nextionBoot = false; // Nextion Sucessful Boot indicator
float totalDist, dist, ridingSpeed, avgSpeed[5], avgSpeedF;
uint8_t avgCtr, hallSensorCounter, timeP, timeN, timex, stopC;
char* dispMsg = "";
uint8_t messageInUse, BLEStat;
const static char DEVICE_NAME[] = "IoToWSbSr";
static const uint16_t uuid16_list[] = {LEDService::LED_SERVICE_UUID,
//GattService::UUID_BATTERY_SERVICE,
GattService::UUID_DEVICE_INFORMATION_SERVICE};
LEDService *ledServicePtr;
void pressed(void) // TESTING STATEMENT test
{
nextion.printf("Test Sucessful\n");
}
void irqcallback_hallSensor(void)
{
#ifdef DEBUG
nextion.printf("In Hall Callback\n");
#endif
errorLed = !errorLed;
//hallSensor.disable_irq();
stopC = 0; // enables calculation of Speed
timex = tick.read_ms();
hallSensorCounter++;
tick.reset();
//hallSensor.enable_irq();
}
/* Helper function for printing floats & doubles */
static char *print_double(char* str, double v, int decimalDigits=2)
{
int i = 1;
int intPart, fractPart;
int len;
char *ptr;
/* prepare decimal digits multiplicator */
for (;decimalDigits!=0; i*=10, decimalDigits--);
/* calculate integer & fractinal parts */
intPart = (int)v;
fractPart = (int)((v-(double)(int)v)*i);
/* fill in integer part */
sprintf(str, "%i.", intPart);
/* prepare fill in of fractional part */
len = strlen(str);
ptr = &str[len];
/* fill in leading fractional zeros */
for (i/=10;i>1; i/=10, ptr++) {
if (fractPart >= i) {
break;
}
*ptr = '0';
}
/* fill in (rest of) fractional part */
sprintf(ptr, "%i", fractPart);
return str;
}
void updateMessage(void){
hum_temp->get_temperature(&HTS221_t);
hum_temp->get_humidity(&HTS221_h);
// printf("HTS221: [temp] %7s C, [hum] %s%%\r\n", print_double(buffer1, value1), print_double(buffer2, value2));
// Use this in another function
if(HTS221_h < 70){
messageInUse=0;
}else if(HTS221_h > 70 && HTS221_h < 80){
messageInUse=1;
}else if(HTS221_h > 80 && HTS221_h < 90){
messageInUse=2;
}
else{
messageInUse=3;
}
if(HTS221_t < 20){
messageInUse=4;
}else if(HTS221_t > 20 && HTS221_t < 35){
messageInUse=0;
}else{
messageInUse=5;
}
press_temp->get_temperature(&LPS22HB_t);
press_temp->get_pressure(&LPS22HB_p);
//printf("LPS22HB: [temp] %7s C, [press] %s mbar\r\n", print_double(buffer1, value1), print_double(buffer2, value2));
if(LPS22HB_p_previous > LPS22HB_p){
messageInUse=0;
}else{
messageInUse=1;
}
if(LPS22HB_t < 20){
messageInUse=4;
}else if(LPS22HB_t > 20 && LPS22HB_t < 35){
messageInUse=0;
}else{
messageInUse=5;
}
//#ifdef DEBUG
nextion.printf("%s\n",weatherMessages[messageInUse]);
//#endif
}
void perodic(void)
{
#ifdef DEBUG
nextion.printf("In perodic\n Start Speed Calc\n");
#endif
if (tick.read_ms() > 10000) { //(tick.read_ms() < 100 || tick.read_ms() > 10000 ) // check if bike is ideal standing ..
stopC = 1;
//tick.reset();
} else stopC = 0;
if (stopC == 0) {
timex = timex * 100 * 60; //min
ridingSpeed = (2 * M_PI * cycleTyreRadius) / timex ; // in mtr/sec
} else if(stopC == 1) {
ridingSpeed = 0;
}
#ifdef DEBUG
nextion.printf("Riding Speed = %f\n",ridingSpeed);
#endif
totalDist = 2* M_PI * cycleTyreRadius * hallSensorCounter; // calculating total distance
#ifdef DEBUG
nextion.printf("Total Distance = %f\n",totalDist);
#endif
avgSpeed[avgCtr] = ridingSpeed;
avgCtr++;
if(avgCtr == 4) avgCtr = 0;
for(int i = 0; i == 4; i++) { // calculation of avg speed
avgSpeedF += avgSpeed[i];
}
avgSpeedF = avgSpeedF/5;
#ifdef DEBUG
nextion.printf("Average Speed = %f\n",avgSpeedF);
#endif
triggerSensorPolling = true;
#ifdef DEBUG
nextion.printf("Speedy Calc Over ---- \n Sensor Data Polling Begin\n");
#endif
hum_temp->get_temperature(&HTS221_t);
hum_temp->get_humidity(&HTS221_h);
#ifdef DEBUG
printf("HTS221: [temp] %7s C, [hum] %s%%\r\n", print_double(buffer1, value1), print_double(buffer2, value2));
#endif
press_temp->get_temperature(&LPS22HB_t);
press_temp->get_pressure(&LPS22HB_p_previous);
//wait(5);
#ifdef DEBUG
printf("LPS22HB: [temp] %7s C, [press] %s mbar\r\n", print_double(buffer1, value1), print_double(buffer2, value2));
printf("---\r\n");
#endif
magnetometer->get_m_axes(LSM303AGR_m);
#ifdef DEBUG
printf("LSM303AGR [mag/mgauss]: %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
#endif
accelerometer->get_x_axes(LSM303AGR_a);
#ifdef DEBUG
printf("LSM303AGR [acc/mg]: %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
#endif
acc_gyro->get_x_axes(LSM6DSL_a);
#ifdef DEBUG
printf("LSM6DSL [acc/mg]: %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
#endif
acc_gyro->get_g_axes(LSM6DSL_g);
#ifdef DEBUG
printf("LSM6DSL [gyro/mdps]: %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
#endif
//Altitude computation based on http://keisan.casio.com/exec/system/1224585971 formula
alt = pow((double)(seaLevelPressure/LPS22HB_p),(double)(1/5.257)) - 1;
alt = alt * (LPS22HB_t + 273.15);
alt = alt / 0.0065;
angle -= declinationAngle;
// Correct for when signs are reversed.
if(angle < 0){
angle += 2*M_PI;
}
// Check for wrap due to addition of declination.
if(angle > 2*M_PI){
angle -= 2*M_PI;
}
angle = angle * 180/M_PI;
updateMessage();
// Screen and Controlls Checks
if(dispBoot){
nextionBoot = true;
nextionScreen ='B';
}else if(rideS){
nextionScreen ='R';
}else if(bumpP){
nextionScreen ='B';
}else if(musicS){
nextionScreen ='M';
}else if(scS){
nextionScreen ='S';
}
if(mPnP){
nextionMusic ='P';
}else if(mLt){
nextionMusic ='L';
}else if(mRt){
nextionMusic ='R';
}
//Update the Display Screen
if(nextionScreen =='R') { // checking if nextio display is on rise screen
nextion.printf(dispSpeed); // updating Speed Value on Nextion Display
nextion.printf("%d",(int)(ridingSpeed));
nextion.printf("%c%c%c",terminator,terminator,terminator);
nextion.printf(dispAvg); // updating Avg Speed Value on Nextion Display
nextion.printf("%d",(int)(avgSpeedF));
nextion.printf("%c%c%c",terminator,terminator,terminator);
nextion.printf(dispDist); // updating Distance Value on Nextion Display
nextion.printf("%d",(int)(totalDist));
nextion.printf("%c%c%c",terminator,terminator,terminator);
}else if(nextionScreen =='S' && scS){
if(hum_temp->read_id(&id)){
nextion.printf(hx_check);
nextion.printf(pass);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}else {
nextion.printf(hx_check);
nextion.printf(fail);
nextion.printf("%c%c%c",terminator,terminator,terminator);
nextion.printf(temp_check);
nextion.printf(fail);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}
if(press_temp->read_id(&id)){
nextion.printf(bx_check);
nextion.printf(pass);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}else{
nextion.printf(bx_check);
nextion.printf(fail);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}
if(magnetometer->read_id(&id)){
nextion.printf(temp_check);
nextion.printf(pass);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}else {
nextion.printf(temp_check);
nextion.printf(fail);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}
if(accelerometer->read_id(&id)){
nextion.printf(accl_check);
nextion.printf(pass);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}else {
nextion.printf(accl_check);
nextion.printf(fail);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}
if(acc_gyro->read_id(&id)){
nextion.printf(gyro_check);
nextion.printf(pass);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}else{
nextion.printf(gyro_check);
nextion.printf(fail);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}
if(BLEStat){
nextion.printf(ble_check);
nextion.printf(pass);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}else{
nextion.printf(ble_check);
nextion.printf(fail);
nextion.printf("%c%c%c",terminator,terminator,terminator);
}
while(scS);
}
#ifdef DEBUG
nextion.printf("sensor Collection Over \n perodic over\n");
#endif
}
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
{
(void)params;
BLE::Instance().gap().startAdvertising(); // restart advertising
}
/**
* This callback allows the LEDService to receive updates to the ledState Characteristic.
*
* @param[in] params
* Information about the characterisitc being updated.
*/
void onDataWrittenCallback(const GattWriteCallbackParams *params) {
if ((params->handle == ledServicePtr->getValueHandle()) && (params->len == 1)) {
actuatedLED = *(params->data);
}
}
/**
* This function is called when the ble initialization process has failled
*/
void onBleInitError(BLE &ble, ble_error_t error)
{
/* Initialization error handling should go here */
BLEStat = 1;
}
/**
* Callback triggered when the ble initialization process has finished
*/
void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
BLE& ble = params->ble;
ble_error_t error = params->error;
if (error != BLE_ERROR_NONE) {
/* In case of error, forward the error handling to onBleInitError */
onBleInitError(ble, error);
return;
}
/* Ensure that it is the default instance of BLE */
if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
return;
}
ble.gap().onDisconnection(disconnectionCallback);
ble.gattServer().onDataWritten(onDataWrittenCallback);
/* Setup Device Identification service. */
DeviceInformationService devInfoService(ble, "ST Micro", "NUCLEO-L476RG", "XXXX", "v1.0", "v1.0", "v1.0");
bool initialValueForLEDCharacteristic = true;
ledServicePtr = new LEDService(ble, initialValueForLEDCharacteristic);
/* setup advertising */
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
ble.gap().setAdvertisingInterval(1000); /* 1000ms. */
ble.gap().startAdvertising();
while (true) {
ble.waitForEvent();
}
}
int main(void)
{
stopC = 1; // skips calculation of speed if set to : 1
BLEStat = 0;
hallSensorCounter = 0;
nextion.baud(9600); //Setting Up nextion Display see the Issues.txt for more info
errorLed = 1; //To confirm System has Started :: Loading Screen on the Display
wait(0.5);
errorLed = 0;
#ifdef DEBUG
nextion.printf("Welcome To SbSr Version %s\n",ver); // Serial Print only Debug MODE as serial is shared with Nextion Display
#endif
wait(0.1);
/* Enable all sensors */
hum_temp->enable();
press_temp->enable();
magnetometer->enable();
accelerometer->enable();
acc_gyro->enable_x();
acc_gyro->enable_g();
mybutton.fall(&pressed); // TESTING STATEMENT test
hallSensor.fall(&irqcallback_hallSensor);
Ticker ticToc;
ticToc.attach(perodic, 0.2f); // blink LED every second
BLE &ble = BLE::Instance();
ble.init(bleInitComplete);
}
<file_sep>/SbSr_Arduino_Nextion_Interface/SbSr_Arduino_Nextion_Interface.ino
/*
<NAME>
<EMAIL>
http://crcibernetica.com
This example code is in public domain
*/
#include <SoftwareSerial.h>
#include "Timer.h"
#include <Nextion.h>
SoftwareSerial nextion(2, 3);// Nextion TX to pin 2 and RX to pin 3 of Arduino
Nextion myNextion(nextion, 9600); //create a Nextion object named myNextion using the nextion serial port @ 9600bps
Timer t;
void setup() {
Serial.begin(9600);
myNextion.init();
pinMode(4,OUTPUT); // Display Boot Successful
digitalWrite(4,LOW);
pinMode(5,OUTPUT); // Ride Screen
digitalWrite(5,LOW);
pinMode(6,OUTPUT); // Bump Pressed
digitalWrite(6,LOW);
pinMode(7,OUTPUT); // Self Check Screen
digitalWrite(7,LOW);
pinMode(8,OUTPUT); // Music Screen
digitalWrite(8,LOW);
pinMode(9,OUTPUT); // Music Left
digitalWrite(9,LOW);
pinMode(10,OUTPUT); // Music Play Pause
digitalWrite(10,LOW);
pinMode(11,OUTPUT); // Music Right
digitalWrite(11,LOW);
t.every(1000, resetAll);
}
void loop() {
String message = myNextion.listen(); //check for message
if(message != ""){ // if a message is received...
if( message == "6"){
Serial.println("Booted");
digitalWrite(6,HIGH);
}else if (message == '0xFF'){
Serial.println("Off");
digitalWrite(4,LOW);
// Ride Screen
digitalWrite(5,LOW);
// Options Screen
digitalWrite(6,LOW);
// Self Check Screen
digitalWrite(7,LOW);
// Music Screen
digitalWrite(8,LOW);
// Music Left
digitalWrite(9,LOW);
// Music Play Pause
digitalWrite(10,LOW);
// Music Right
digitalWrite(11,LOW);
}else if (message == "7"){
Serial.println("Riding Screen");
digitalWrite(5,HIGH);
}else if (message == "65 7 6 0 ffff ffff ffff"){
Serial.println("Bump Pressed");
digitalWrite(6,HIGH);
}else if (message == "8"){
Serial.println("Music Controls");
digitalWrite(8,HIGH);
}else if (message == "65 8 4 0 ffff ffff ffff"){
Serial.println("Left Button");
digitalWrite(9,HIGH);
}else if (message == "65 8 5 0 ffff ffff ffff"){
Serial.println("Play Pause Button");
digitalWrite(10,HIGH);
}else if (message == "65 8 3 0 ffff ffff ffff"){
Serial.println("Right Button");
digitalWrite(11,HIGH);
}else if (message == "3"){
Serial.println("Self Check Page");
digitalWrite(7,HIGH);
}else {
Serial.println("INVALID INPUT");
digitalWrite(4,LOW);
// Ride Screen
digitalWrite(5,LOW);
// Options Screen
digitalWrite(6,LOW);
// Self Check Screen
digitalWrite(7,LOW);
// Music Screen
digitalWrite(8,LOW);
// Music Left
digitalWrite(9,LOW);
// Music Play Pause
digitalWrite(10,LOW);
// Music Right
digitalWrite(11,LOW);
}
Serial.println(message); //...print it out
}
}
void resetAll(void){
digitalWrite(4,LOW);
// Ride Screen
digitalWrite(5,LOW);
// Options Screen
digitalWrite(6,LOW);
// Self Check Screen
digitalWrite(7,LOW);
// Music Screen
digitalWrite(8,LOW);
// Music Left
digitalWrite(9,LOW);
// Music Play Pause
digitalWrite(10,LOW);
// Music Right
digitalWrite(11,LOW);
Serial.println("Reset All Lines");
}
|
f6f4f42ce582182bbb3bf4c860a7791ce20ec66e
|
[
"C++"
] | 2 |
C++
|
gsgill112/SbSr_E14
|
c8763c978da1b388841f677f30d081a4d0f4fdcc
|
71fbfa9945118062c512fdb385cee28c47810d13
|
refs/heads/master
|
<file_sep>import {
configure, // set some global mobx config settings
action,
observable,
runInAction, // inlining an action within another function
flow, // using generators and yield to run in action
decorate // not needing to use decorators to decorate functions
} from "mobx";
// this is now `flow` from mobx
// import { asyncAction } from "mobx-utils";
// removed as of MobX 4
// useStrict(true);
configure({ enforceActions: true });
class WeatherStore {
weatherData = {};
loadWeather = city => {
fetch(
`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`
)
.then(response => response.json())
.then(data => {
this.setWeather(data);
});
};
setWeather = data => {
this.weatherData = data;
};
loadWeatherInline = city => {
fetch(
`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`
)
.then(response => response.json())
.then(data => {
runInAction(() => {
this.weatherData = data;
});
});
};
loadWeatherAsync = async city => {
const response = await fetch(
`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`
);
const data = await response.json();
runInAction(() => {
this.weatherData = data;
});
};
loadWeatherGenerator = flow(function*(city) {
const response = yield fetch(
`https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`
);
const data = yield response.json();
this.weatherData = data;
});
}
decorate(WeatherStore, {
weatherData: observable,
setWeather: action
});
export default new WeatherStore();
|
d00ead679469bed385929925ba5705e5783f3f00
|
[
"JavaScript"
] | 1 |
JavaScript
|
rahulsyal2512/mobx-async-actions
|
f7e6ad83ef8c9d67cd52a4fcf2250d84dbb75a3a
|
92121849f084115ac50aecb67b0da111ab8ce70b
|
refs/heads/main
|
<file_sep>import streamlit as st
import pandas as pd
import pydeck as pdk
import numpy as np
import matplotlib.pyplot as plt
def load_data(loadna):
df=pd.read_csv("rileydata.csv")
if loadna==False:
df=df.dropna()
return df
def chart_options(index):
st.header("Chart Options")
c1,c2,c3,c4,c5=st.beta_columns(5)
alpha=c2.slider("Select Transparency",0.0,1.0,.5,key=index)
ascending=c3.selectbox("Ascending or Descending?",["Ascending","Descending"],key=index)
color=c1.selectbox("Select Color for Charts",["purple","red","blue","green","yellow","orange","black","grey"],key=index)
filter_by=c4.selectbox("Filter by Largest or Smallest",["Largest # of schools","Smallest # of schools"],key=index)
keep=int(c5.number_input("How many records would you like to see?",key=index))
return color,alpha,ascending,filter_by,keep
def filter_by_state(use,index):
try:
dfn=pd.read_csv("FilterbyState.csv")
except:
df=load_data(True)
states=pd.unique(df["STATE"])
d1=[]
for state in states:
d2=[]
count=len(df[df["STATE"]==state])
d2.append(state)
d2.append(count)
d2.append(df[df["STATE"]==state]["LON"].mean())
d2.append(df[df["STATE"]==state]["LAT"].mean())
d1.append(d2)
dfn=pd.DataFrame(d1)
dfn.columns=["state","number_of_schools","lon","lat"]
dfn.to_csv("FilterbyState.csv")
if use=="Maps":
st.header("Map of Schools by State")
view=pdk.ViewState(latitude=dfn["lat"].mean(),longitude=dfn["lon"].mean(),pitch=20,zoom=5)
map = pdk.Layer("ColumnLayer",data=dfn,get_position=["lon", "lat"],get_elevation="number_of_schools",elevation_scale=1000,radius=10000,pickable=True,auto_highlight=True,get_fill_color=[225,225,225,225])
tooltip = {"html": "<b>{state}</b>: {number_of_schools} schools","style": {"background": "grey", "color": "white", "font-family": '"Helvetica Neue", Arial', "z-index": "10000"}}
map=pdk.Deck(map_provider='carto',layers=[map],initial_view_state=view,api_keys=None,tooltip=tooltip)
st.pydeck_chart(map)
if use=="Charts":
color,alpha,ascending,filter_by,num_to_keep=chart_options(index)
if filter_by=="Largest # of schools":
dfn=dfn.nlargest(num_to_keep,columns=["number_of_schools"])
else:
dfn=dfn.nsmallest(num_to_keep,columns=["number_of_schools"])
if ascending=="Ascending":
dfn=dfn.sort_values(by="number_of_schools",ascending=True)
else:
dfn=dfn.sort_values(by="number_of_schools",ascending=False)
objects = dfn["state"]
y_pos = np.arange(len(objects))
performance = dfn["number_of_schools"]
plt.barh(y_pos, performance, align='center', alpha=alpha,color=color)
plt.yticks(y_pos, objects)
plt.xlabel('Number of Schools')
plt.ylabel("States")
plt.title('Number of Schools by State')
st.pyplot(plt)
plt.clf()
def filter_by_town(use,index):
try:
dfn=pd.read_csv("FilterbyTown.csv")
except:
df=load_data(True)
df["st"]=df["STATE"]+","+df["CITY"]
states=pd.unique(df["st"])
d1=[]
for state in states:
d2=[]
count=len(df[df["st"]==state])
d2.append(state)
d2.append(count)
d2.append(df[df["st"]==state]["LON"].mean())
d2.append(df[df["st"]==state]["LAT"].mean())
d1.append(d2)
dfn=pd.DataFrame(d1)
dfn.columns=["town","number_of_schools","lon","lat"]
dfn.to_csv("FilterbyTown.csv")
if use=="Maps":
st.header("Map of Schools by Town")
view=pdk.ViewState(latitude=dfn["lat"].mean(),longitude=dfn["lon"].mean(),pitch=20,zoom=5)
map = pdk.Layer("ColumnLayer",data=dfn,get_position=["lon", "lat"],get_elevation="number_of_schools",elevation_scale=1000,radius=1000,pickable=True,auto_highlight=True,get_fill_color=[225,225,225,225])
tooltip = {"html": "<b>{town}</b>: {number_of_schools} schools","style": {"background": "grey", "color": "white", "font-family": '"Helvetica Neue", Arial', "z-index": "10000"}}
map=pdk.Deck(map_provider='carto',layers=[map],initial_view_state=view,api_keys=None,tooltip=tooltip)
st.pydeck_chart(map)
if use=="Charts":
color,alpha,ascending,filter_by,num_to_keep=chart_options(index)
if filter_by=="Largest # of schools":
dfn=dfn.nlargest(num_to_keep,columns=["number_of_schools"])
else:
dfn=dfn.nsmallest(num_to_keep,columns=["number_of_schools"])
if ascending=="Ascending":
dfn=dfn.sort_values(by="number_of_schools",ascending=True)
else:
dfn=dfn.sort_values(by="number_of_schools",ascending=False)
objects = dfn["town"]
y_pos = np.arange(len(objects))
performance = dfn["number_of_schools"]
plt.barh(y_pos, performance, align='center', alpha=alpha,color=color)
plt.yticks(y_pos, objects)
plt.xlabel('Number of Schools')
plt.ylabel("Towns")
plt.title('Number of Town')
st.pyplot(plt)
plt.clf()
def all_colleges(use,index):
df=load_data(True)
if use=="Maps":
st.header("Map of all Schools")
view=pdk.ViewState(latitude=df["LAT"].mean(),longitude=df["LON"].mean(),pitch=20,zoom=5)
map = pdk.Layer("ColumnLayer",data=df,get_position=["LON", "LAT"],get_elevation=100,elevation_scale=1000,radius=500,pickable=True,auto_highlight=True,get_fill_color=[225,225,225,225])
tooltip = {"html": "<b>{NAME}</b>: {STREET}, {CITY} {STATE}","style": {"background": "grey", "color": "white", "font-family": '"Helvetica Neue", Arial', "z-index": "10000"}}
map=pdk.Deck(map_provider='carto',layers=[map],initial_view_state=view,api_keys=None,tooltip=tooltip)
st.pydeck_chart(map)
def main():
st.title("College Explorer")
mm=st.sidebar.radio("What do you want to see?",["Maps","Charts"])
if mm=="Maps":
sm=st.multiselect("Which maps would you like to see? (can select more than 1)",["Colleges by State","All Colleges","Colleges by Town"])
for i,x in enumerate(sm):
if x=="Colleges by State":
filter_by_state(mm,i)
if x=="All Colleges":
all_colleges(mm,i)
if x=="Colleges by Town":
filter_by_town(mm,i)
if mm=="Charts":
sm=st.multiselect("Which Chart would you like to see? (can select more than 1)",["Colleges by State","Colleges by Town"])
for i,x in enumerate(sm):
if x=="Colleges by State":
filter_by_state(mm,i)
for i,x in enumerate(sm):
if x=="Colleges by Town":
filter_by_town(mm,i)
main()
|
145d8587bc9a6b19f786963cc7a13a0a9df23ca9
|
[
"Python"
] | 1 |
Python
|
DrinkElixr/Streamlit
|
2b32ef3a1554eccee8be41b069f80a6582a4639f
|
f805f7edb7104bfb6c136e2952c0accfdded8754
|
refs/heads/master
|
<repo_name>rupindermonga/euler58SpiralPrimes<file_sep>/euler58SpiralPrimes.py
'''
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.
If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?
'''
def isPrime(n):
result = True
if n == 1:
result = False
for i in range(2,int(n**0.5)+1):
if n % i == 0:
result = False
break
return result
def SideLength(n):
# n is the %age
final_percent = 1
side_length = 5
no_primes = 5
while final_percent > n:
side_length += 2
for i in range(4):
number = side_length**2 - (side_length - 1)*i
no_primes += isPrime(number)
final_percent = no_primes/(2*side_length - 1)
return side_length
final = SideLength(0.1)
print(final)
|
8fe74c84e942c42a0ea6d1f14b8e94081dd3cd3f
|
[
"Python"
] | 1 |
Python
|
rupindermonga/euler58SpiralPrimes
|
fa19f5eeb4fcb54a32a18e69873c643700be8371
|
050759197bb4ff67364896816719b44822a6f261
|
refs/heads/main
|
<file_sep>//Dustbin Class
class Dustbin{
constructor(){
var options = {
isStatic: true
}
this.rec1 = Bodies.rectangle(907,560,20,190,options)
this.rec2 = Bodies.rectangle(960,655,150,20,options)
this.image = loadImage("dustbingreen.png");
this.rec3 = Bodies.rectangle(1015,560,20,190,options)
this.rec1.width = 20;
this.rec1.height = 190;
this.rec2.width = 100;
this.rec2.height = 20;
this.width = 140;
this.height = 200;
this.rec3.width = 20;
this.rec3.height = 190;
World.add(world,this.rec1);
World.add(world,this.rec2);
World.add(world,this.rec3);
}
display(){
var pos1 = this.rec1.position;
var pos2 = this.rec2.position;
var pos3 = this.rec3.position;
rectMode(CENTER);
fill("white");
stroke(0);
rect(pos1.x,pos1.y,this.rec1.width,this.rec1.height);
rect(pos2.x,pos2.y,this.rec2.width,this.rec2.height);
rect(pos3.x,pos3.y,this.rec3.width,this.rec3.height);
image(this.image,pos2.x+1,pos2.y-90.5,this.width,this.height);
}
}
|
e14b3fb1383d7cce0c01f551f24d6df48c6e479d
|
[
"JavaScript"
] | 1 |
JavaScript
|
PrayasP/Project-25
|
6b13b2a5674728d302bb51ab50f5478a31f69fab
|
e7e310be6363824982ac5f9d4d409f8f8fe910a9
|
refs/heads/master
|
<file_sep>package co.flagly.utils;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
public final class ZDT {
public static ZonedDateTime now() {
return ZonedDateTime.now().withFixedOffsetZone().withNano(0);
}
public static String toString(ZonedDateTime zdt) {
return zdt.withFixedOffsetZone().withNano(0).format(formatter);
}
public static ZonedDateTime fromString(String zdt) {
return ZonedDateTime.parse(zdt, formatter).withFixedOffsetZone().withNano(0);
}
private static DateTimeFormatter formatter =
new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.optionalStart()
.appendOffsetId()
.toFormatter();
}
<file_sep>package co.flagly.utils;
import com.google.gson.*;
import dev.akif.e.E;
import dev.akif.e.gson.EGsonAdapter;
import java.lang.reflect.Type;
import java.time.ZonedDateTime;
public final class JsonUtils {
public static <A> String toJson(A a) {
return gson.toJson(a);
}
public static <A> A fromJson(String json, Class<A> c) {
return gson.fromJson(json, c);
}
private static class ZonedDateTimeAdapter implements JsonSerializer<ZonedDateTime>, JsonDeserializer<ZonedDateTime> {
@Override public JsonElement serialize(ZonedDateTime zdt, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(ZDT.toString(zdt));
}
@Override public ZonedDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return ZDT.fromString(json.getAsString());
}
}
private static Gson gson = new GsonBuilder()
.registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeAdapter())
.registerTypeAdapter(E.class, new EGsonAdapter())
.create();
}
<file_sep>package co.flagly.core;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.time.ZonedDateTime;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import co.flagly.utils.ZDT;
public class FlagTest {
@Test void testFlagCreation() {
UUID applicationId = UUID.randomUUID();
ZonedDateTime now = ZDT.now();
Flag flag1 = Flag.of(applicationId, "test-flag-1", "Test Flag 1", true);
Flag flag2 = Flag.of(UUID.randomUUID(), applicationId, "test-flag-2", "Test Flag 2", false, now, now);
assertNotEquals(flag1.id(), flag2.id());
assertEquals(flag1.applicationId(), flag2.applicationId());
assertNotEquals(flag1.name(), flag2.name());
assertNotEquals(flag1.description(), flag2.description());
assertNotEquals(flag1.value(), flag2.value());
}
}
|
c97b2b0d9c3c5c9fb3e9069547f8a7f27b0370e3
|
[
"Java"
] | 3 |
Java
|
flaglyco/flagly-core
|
a973d1f1b80b5ba91fc8452fc2cfecef5675b5f5
|
a50b9a21fbb6800da6843e67d21f03b59b9584ed
|
refs/heads/master
|
<repo_name>minmin0530/multi-puzzle<file_sep>/README.md
# multi-puzzle
<img src="Cooperation.png" width="50%"><img src="nekoneko-online.png" width="50%">
## concept
### 協力して遊ぶオンライン落ちゲーです。
これは各プレイヤーが落ちるブロックの色と落ちる場所を選んでブロックを落とします。同じ色のブロックが並ぶと消えて得点になります。ブロックの消滅が連鎖すると高得点になります。誰が何色のブロックをどこに落とすかで、連鎖具合が変わってきます。ランキングを作っておき、1つのステージに何人関わったかの人数ランキング、ブロックの消滅の連鎖ランキング。これらの記録を目指す協力型パズルゲームです。
## コントリビュータ、共同制作者募集
### contributors
@minmin0530
## 環境
プラットフォーム:iOS
言語:Swift
サーバ:Node.js、もしくはDeno
## その他
仮称:nekoneko-online
<file_sep>/nekoneko-online/Neko.swift
//
// Neko.swift
// nekoneko-online
//
// Created by <NAME> on 2020/06/03.
// Copyright © 2020 <NAME>. All rights reserved.
//
import SpriteKit
class Neko: SKSpriteNode {
var time: CGFloat = 0.0
var timeSpeed: CGFloat = 0.1
var eyeRight: SKShapeNode = SKShapeNode(circleOfRadius: 10.0)
var eyeFrameRight: SKShapeNode = SKShapeNode(circleOfRadius: 50.0)
var eyeLeft: SKShapeNode = SKShapeNode(circleOfRadius: 10.0)
var eyeFrameLeft: SKShapeNode = SKShapeNode(circleOfRadius: 50.0)
}
<file_sep>/nekoneko-online/GameScene.swift
//
// GameScene.swift
// nekoneko-online
//
// Created by <NAME> on 2020/06/03.
// Copyright © 2020 <NAME>. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
// private var label : SKLabelNode?
// private var spinnyNode : SKShapeNode?
var snArray: [Neko] = [] //= Neko(texture: SKTexture(imageNamed: "nekoneko-orange"))
let scale: CGFloat = 0.6
override func didMove(to view: SKView) {
for _ in 0...22 {
let r = Int.random(in: 0...9)
if r % 3 == 0 {
snArray.append(Neko(texture: SKTexture(imageNamed: "nekoneko-pink")))
}
if r % 3 == 1 {
snArray.append(Neko(texture: SKTexture(imageNamed: "nekoneko-green")))
}
if r % 3 == 2 {
snArray.append(Neko(texture: SKTexture(imageNamed: "nekoneko-orange")))
}
}
var z: CGFloat = 1.0
let backroundImage = SKSpriteNode(texture: SKTexture(imageNamed: "major"))
backroundImage.zPosition = z
backroundImage.xScale = 0.6
backroundImage.yScale = 0.6
z += 1
addChild(backroundImage)
var x: CGFloat = -300.0
var y: CGFloat = -500.0
for sn in snArray {
sn.xScale = scale
sn.yScale = scale
sn.eyeFrameRight.xScale = scale
sn.eyeFrameLeft.xScale = scale
sn.eyeRight.xScale = scale
sn.eyeLeft.xScale = scale
sn.eyeFrameRight.yScale = scale
sn.eyeFrameLeft.yScale = scale
sn.eyeRight.yScale = scale
sn.eyeLeft.yScale = scale
sn.time = CGFloat.random(in: 0.0...360.0)
sn.timeSpeed = CGFloat.random(in: 0.0...0.05)
sn.position.x = x//CGFloat.random(in: -400.0...400.0)
sn.position.y = y//CGFloat.random(in: -400.0...400.0)
x += 150
if x >= 450.0 {
x = -450.0
y += 150.0
}
sn.eyeRight.fillColor = UIColor.white
sn.eyeRight.strokeColor = UIColor.black
sn.eyeRight.lineWidth = 10
sn.eyeRight.position.x = 50 * scale
sn.eyeRight.position.y = -20 * scale
sn.eyeLeft.fillColor = UIColor.white
sn.eyeLeft.strokeColor = UIColor.black
sn.eyeLeft.lineWidth = 10
sn.eyeLeft.position.x = -50 * scale
sn.eyeLeft.position.y = -20 * scale
sn.eyeFrameRight.fillColor = UIColor.white
sn.eyeFrameRight.strokeColor = UIColor.black
sn.eyeFrameRight.lineWidth = 10
sn.eyeFrameRight.position.x = 50 * scale
sn.eyeFrameRight.position.y = -30 * scale
sn.eyeFrameLeft.fillColor = UIColor.white
sn.eyeFrameLeft.strokeColor = UIColor.black
sn.eyeFrameLeft.lineWidth = 10
sn.eyeFrameLeft.position.x = -50 * scale
sn.eyeFrameLeft.position.y = -30 * scale
sn.zPosition = z
z += 1
sn.eyeFrameRight.zPosition = z
sn.eyeFrameLeft.zPosition = z
z += 1
sn.eyeRight.zPosition = z
sn.eyeLeft.zPosition = z
z += 1
addChild(sn.eyeRight)
addChild(sn.eyeFrameRight)
addChild(sn.eyeLeft)
addChild(sn.eyeFrameLeft)
addChild(sn)
}
// // Get label node from scene and store it for use later
// self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
// if let label = self.label {
// label.alpha = 0.0
// label.run(SKAction.fadeIn(withDuration: 2.0))
// }
//
// // Create shape node to use during mouse interaction
// let w = (self.size.width + self.size.height) * 0.05
// self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.3)
//
// if let spinnyNode = self.spinnyNode {
// spinnyNode.lineWidth = 2.5
//
// spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
// spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
// SKAction.fadeOut(withDuration: 0.5),
// SKAction.removeFromParent()]))
// }
}
func touchDown(atPoint pos : CGPoint) {
}
func touchMoved(toPoint pos : CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
for sn in snArray {
// sn.time += sn.timeSpeed
//
// sn.position.y += 5 * cos(sn.time)
sn.eyeFrameRight.position.x = sn.position.x + 50.0 * scale
sn.eyeFrameRight.position.y = sn.position.y - 30.0 * scale
sn.eyeFrameLeft.position.x = sn.position.x - 50.0 * scale
sn.eyeFrameLeft.position.y = sn.position.y - 30.0 * scale
sn.eyeRight.position.x = 30.0 * scale * cos(sn.time) + 50.0 * scale + sn.position.x
sn.eyeRight.position.y = 30.0 * scale * sin(sn.time) - 30.0 * scale + sn.position.y
sn.eyeLeft.position.x = 30.0 * scale * cos(sn.time) - 50.0 * scale + sn.position.x
sn.eyeLeft.position.y = 30.0 * scale * sin(sn.time) - 30.0 * scale + sn.position.y
}
}
}
|
b074bd3ea1e78e0a0486226886a7ccb660b85598
|
[
"Markdown",
"Swift"
] | 3 |
Markdown
|
minmin0530/multi-puzzle
|
722220cee5ab9ecff7fc8e4cd9abaf1fafaccfe0
|
06c51a8c44c97207f5d522749a5e1b806ae2d77a
|
refs/heads/master
|
<repo_name>italocolpal/refresherGit<file_sep>/hangman.py
import random
from words import word_list
def get_word():
word = random.choice(word_list)
return word.upper()
def play(word):
print('hello lets play')
word_completion = '_'*len(word)
guessed = False
guessed_letters = []
guessed_words = []
tries = 6
print('Lets play hangman')
print(display_hangman(tries))
print(word_completion)
print('\n')
while not guessed and tries > 0 :
guess = input('Please guess a letter or word').upper()
# length has to be equal to one (char) and it has to a letter--> isalpha()
if len(guess) == 1 and guess.isalpha():
#char already in list of guessed letters
if guess in guessed_letters:
print('You are ready guess the letter' , guess)
# if (char) not in the character of the word
elif guess not in word:
print(guess, ' is not in the word')
tries -= 1
guessed_letters.append(guess)
else:
print('Good job', guess , 'is in the word!')
guessed_letters.append (guess)
word_as_list = list(word_completion)
def display_hangman(tries):
stages = [ # final state: head, torso, both arms, and both legs
"""
--------
| |
| O
| \\|/
| |
| / \\
-
""",
# head, torso, both arms, and one leg
"""
--------
| |
| O
| \\|/
| |
| /
-
""",
# head, torso, and both arms
"""
--------
| |
| O
| \\|/
| |
|
-
""",
# head, torso, and one arm
"""
--------
| |
| O
| \\|
| |
|
-
""",
# head and torso
"""
--------
| |
| O
| |
| |
|
-
""",
# head
"""
--------
| |
| O
|
|
|
-
""",
# initial empty state
"""
--------
| |
|
|
|
|
-
"""
]
return stages[tries]
def main():
word = get_word()
play(word)
if __name__ == '__main__':
main()
|
eab372052066ce089a19532081837937950b02b2
|
[
"Python"
] | 1 |
Python
|
italocolpal/refresherGit
|
520502dac881c8f493fd1c6a4338e8ff87f7d9ce
|
dbfba87b8a565efcf1d83a25d70b91e6f99c4816
|
refs/heads/master
|
<repo_name>NO8LESIX/Carmen-Bot<file_sep>/commands/dndgen.js
const fs = require("fs");
let student = {
name: "Mike",
age: 23,
gender: "Male",
department: "English",
car: "Honda",
};
let data = JSON.stringify(student, null, 2);
module.exports = (message) => {
fs.writeFile("dndCampaigns.json", data, (err) => {
if (err) throw err;
console.log("Data written to file");
});
console.log("This is after the write call");
return message.reply("Creating D&D JSON Demo");
};
<file_sep>/functions/dndFunctions.ts
const RollDice = (num) => {
let init = Math.floor(Math.random() * (num - 1 + 1)) + 1;
if (init == 1 && num == 20) {
return `Critical Failure! Rolled: ${init}`;
}
else if (init == 20) {
return `Rolled a Natural ${init}!`
}
return `Rolled: ${init}`;
}
const RollInitiative = () => {
let init = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
if (init == 1) {
return `Critical Failure! Rolled: ${init}`;
}
else if (init == 20) {
return `Rolled a Natural ${init}!`
}
return `Rolled: ${init}`;
};
const DiceRoller = (diceType) => {
switch (diceType) {
case "d100":
return RollDice(100);
case "d20":
return RollDice(20);
case "d12":
return RollDice(12);
case "d10":
return RollDice(10);
case "d8":
return RollDice(8);
case "d6":
return RollDice(6);
case "d4":
return RollDice(4);
case "initiative":
return RollInitiative();
default:
return "*Bad Dice Input*. Try again with a d20 or somth'n kiddo."
}
};
exports.RollInitiative = RollInitiative;
exports.DiceRoller = DiceRoller;<file_sep>/events/message.js
require("dotenv").config();
const prefix = process.env.prefix;
const kick = require("../commands/kick");
const help = require("../commands/help");
const music = require("../commands/music");
const dnd = require("../commands/dnd");
const dndgen = require("../commands/dndgen");
const dndFunctions = require("../functions/dndFunctions.ts");
const _new = require("../commands/new");
module.exports = (client, message) => {
if (message.author.id == 7<PASSWORD>0<PASSWORD>) {
return;
}
if (message.content.startsWith(prefix)) {
return music(message);
} else if (
message.content.includes("<@!753100404534935622>") ||
message.content.includes("<@&755871336139718768>") ||
message.content.includes("<@753100404534935622>")
) {
//console.log(message.content);
msg = message;
msg.content = msg.content.split(" ").slice(1).join(" ");
if (msg.content.toLowerCase().startsWith("roll")) {
return msg.reply(
dndFunctions.DiceRoller(msg.content.split(" ").slice(1).join(" ").toLowerCase())
);
}
//Gotta be a better way to do this.
//We are working blind with types here
key = msg.content.split(" ").slice(0);
switch (key[0]) {
case "":
return msg.reply("What'cha need hun?");
case "dnd":
msg.content = msg.content.split(" ").slice(1).join(" ");
return dnd(msg);
case "dndgen":
return dndgen(msg);
case "kick":
return kick(msg);
case "help":
return help(msg);
case "ping":
return msg.reply("Pong!");
case "hello":
return msg.reply("Hiya!");
case "new":
console.log("new")
return _new(msg)
case "say":
return msg.channel.send(`${msg.content.split(" ").slice(1).join(" ")}`);
case "are you up?":
return msg.reply("Yup!");
case "what are you?":
return msg.reply("My name is Carmen and I am a Bot! :yum: ");
default:
console.log("command not implemented");
return;
}
} //end of check
}; //end of module
// npm rm ytdl-core-discord
// npm i ytdl-core@latest
<file_sep>/interfaces/dndTypes.ts
export enum CreatureSize {
Fine,
Diminutive,
Tiny,
Small,
Medium,
Large,
Huge,
Gargantuan,
Colossal
}
export enum DamageType {
Acid,
Fire,
Lightning,
}
export interface DNDCampaign {
CampaignId: number
CampaignName: string
Players: Player
Scenarios: Scenario[]
}
export interface Scenario {
Description: string
Encounters: Encounter[]
}
export interface Encounter {
Enemy?: AI[]
Friendly?: AI[]
}
export interface Player {
Armor?: Armor
CreatureSize: CreatureSize
Description: string
HP: number
Level: number
Name: string
Shield?: boolean
Spells?: Spell
Stats: Stats
Weapon?: Weapon
}
export interface AI {
Armor?: Armor
CreatureSize: CreatureSize
Description: string
HP: number
Name: string
SavingThrows?: SavingThrows
Shield?: boolean
Skills?: Skills
Spells?: Spell
Stats: Stats
Weapon?: Weapon
}
export interface Stats {
AC: number
CHA: number
CON: number
DEX: number
INT: number
STR: number
WIS: number
}
export interface Skills {
}
export interface SavingThrows {
}
export enum WeaponClass {
Martial,
MartialRanged,
SimpleMelee,
SimpleRanged,
}
export interface Weapon {
Name: string
WeaponClass: WeaponClass
DamageMax: number
DamageMin: number
Range: number
RequiresAmmo: boolean
AmmoCount?: number
}
export enum ArmorClass {
Light,
Medium,
Heavy
}
export enum ArmorMaterial {
Breastplate,
ChainMail,
ChainShirt,
Halfplate,
Hide,
Leather,
Padded,
Plate,
RingMail,
ScaleMail,
Splint,
StuddedLeather,
}
export interface Armor {
ArmorClass: ArmorClass
ArmorMaterial: ArmorMaterial
Name: string
Stealthy?: boolean
}
export interface Effect {
DamageMax: number
DamageMin: number
Name: string
RemainingDuration: number
}
export enum School {
Abjuration,
Conjuration,
Divination,
Enchantment,
Evocation,
Illusion,
Necromancy,
Transmutation
}
export interface Spell {
DamageMax: number
DamageMin: number
Descritpion: string
CastTime: number
Name: string
Range: number
School: School
StatusEffect?: Effect
Type: DamageType
Components?: string[]
}<file_sep>/events/disconnect.js
module.exports = (client) => {
console.log(`Disconnected!`)
}<file_sep>/index.js
require("dotenv").config();
const Discord = require("discord.js");
const fs = require("fs");
const client = new Discord.Client();
client.on('ready', () => {
console.log('Carmen is ready!');
});
process.on('unhandledRejection', error => console.error('Uncaught Promise Rejection', error));
client.once("reconnecting", () => {
console.log("Carmen is finding her way back!");
});
client.once("disconnect", () => {
console.log("Carmen has Disconnected!");
});
fs.readdir("./events/", (err, files) => {
files.forEach((file) => {
const eventHandler = require(`./events/${file}`)
const eventName = file.split(".")[0]
client.on(eventName, (...args) => eventHandler(client, ...args))
})
});
client.login(process.env.BOT_TOKEN);<file_sep>/README.md
# Carmen-Bot
<file_sep>/commands/dnd.js
const Discord = require("discord.js");
module.exports = (message) => {
message.channel.send("Start ***New*** or ***Continue***?");
const collector = new Discord.MessageCollector(
message.channel,
(m) => m.author.id === message.author.id,
{ time: 10000 }
);
//console.log(collector);
collector.on("collect", (message) => {
if (message.content == "New") {
message.channel.send("Time to start a new tale!");
} else if (message.content == "Continue") {
message.channel.send("From what tale are we reading from today?");
}
});
return;
};
|
6a282161462afe962e57486de53a00e9331c9ef2
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 8 |
JavaScript
|
NO8LESIX/Carmen-Bot
|
1709ae69978f46f3526db5caac421f15d67febf0
|
6a73025796216e2f34d918f750e423f261dbb4d8
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.